fix(security): KVE-2026-1914/1915/1919 remediation 전건

위임 관리자(부관리자)가 권한·역할·표현식·비밀 콘텐츠 경계를 우회하던
결함군을 계층 대칭성 원칙으로 전건 차단한다. 약한 경로가 정상 응답을
내보내는 것이 유일한 증상이라, 게이트를 생산 지점 한 곳(SSoT)에 두고
같은 데이터를 내보내는 소비 경로 전부가 그 게이트를 경유하도록 맞췄다.

- 등급 상한(rank ceiling): 슈퍼관리자 보호·역할/사용자 역할 배정(추가·제거
 대칭)·일괄 상태변경·순서변경을 상세 경로와 동일 강도로 재적용. 가드는
 DB 쓰기에 선행하여 거부 시 상태 불변.
- 레이아웃 표현식: new Function/with 실행을 AST 화이트리스트 평가기로 교체.
 비-문자열 computed 키 정규화(normalizeKey)·Object facade(리플렉션 static
 제거)·legacy 접근자 차단. 저장측 검증·정적 검사와 3계층 동형.
- secret 게이트: 비밀글의 댓글·첨부·문의 독립 경로 재적용, hash 파일서빙
 소유권·비밀·발행 상태 검사 통일.
- 신뢰 스크립트 호스트: 확장 선언 기반 + same-origin 브라우저 정규화를
 런타임·저장측·정적검사 3층 동형화.
- 회귀 감지: 단위·Feature·E2E·시나리오 매니페스트 전축 + audit 룰 4종 신설.
This commit is contained in:
HeuJung committed 2026-08-17 01:45:09 +09:00
1 parent cd84b63d2b
commit 71abdeaf60
249 files changed
+14354 -1134

No files matched your search

+57 -3
View File
@@ -1138,7 +1138,8 @@ class ApiDocScaffolder
// 종료 마커를 표의 끝 경계로 삼는데, 전자는 그 마커를 잘라내고 돌려준다.
$merged .= $this->applyPreservedErrorTable(
$withErrors,
$this->exactGeneratedBlock($existing, $key)
$this->exactGeneratedBlock($existing, $key),
$section
)."\n";
}
@@ -1252,7 +1253,44 @@ class ApiDocScaffolder
* @param string|null $previous 기존 문서의 같은 엔드포인트 생성 블록
* @return string 에러 표가 보존된 섹션
*/
private function applyPreservedErrorTable(string $section, ?string $previous): string
/**
* 403 행의 요구 권한 식별자를 이번 재생성 산출값으로 갱신합니다.
*
* 에러 표 병합은 같은 상태코드에서 기존(사람) 행을 이기게 두는데, 403 의 권한 식별자는
* 라우트 정의에서 파생된 사실이라 사람 서술과 같은 취급을 하면 안 된다. 두 행이 모두
* 백틱 식별자를 가질 때만 그 부분을 치환하고, 나머지 문구(사람이 덧붙인 도메인 조건)는
* 건드리지 않는다. 식별자가 없는 형태(관리자 게이트만 걸린 라우트)는 갱신 대상이 아니다.
*
* @param string $preserved 병합 결과로 살아남은 기존 403 행
* @param string $generated 이번 재생성이 만든 403 행
* @return string 식별자만 갱신된 403 행
*/
private function refreshPermissionIdentifier(string $preserved, string $generated): string
{
if (! preg_match('/`([^`]+)`/', $generated, $new)) {
return $preserved;
}
if (! preg_match('/`([^`]+)`/', $preserved, $old)) {
return $preserved;
}
if ($old[1] === $new[1]) {
return $preserved;
}
$needle = '`'.$old[1].'`';
$pos = strpos($preserved, $needle);
if ($pos === false) {
return $preserved;
}
// preg_replace 는 대체 문자열의 `$`·`\` 를 역참조로 해석하므로 쓰지 않는다.
return substr_replace($preserved, '`'.$new[1].'`', $pos, strlen($needle));
}
private function applyPreservedErrorTable(string $section, ?string $previous, ?string $generated = null): string
{
if ($previous === null) {
return $section;
@@ -1285,12 +1323,28 @@ class ApiDocScaffolder
// 상태코드 키로 병합. `+` 는 왼쪽 우선이므로 기존 행을 먼저 둬서, 같은 상태코드면
// 사람이 쓴 구체적 조건이 자동 문구를 이긴다. 자동 추론에만 있는 상태코드는 새로 편입된다.
$merged = $previousRows + $this->errorTableRows($section);
$currentRows = $this->errorTableRows($section);
$merged = $previousRows + $currentRows;
if ($merged === []) {
return $section;
}
// 403 행의 권한 식별자만은 예외다 — 그것은 사람 서술이 아니라 라우트에서 파생된
// 사실이라, 위 병합 규칙을 그대로 두면 라우트의 요구 권한을 바꿔도 옛 식별자가
// 영구히 남아 문서가 조용히 틀린 권한을 안내한다. 사람이 보강한 조건 문구는 그대로
// 두고 백틱 식별자만 갱신한다.
//
// 대조 원본은 반드시 **이번 회차가 생성한 원본 섹션**이어야 한다. 여기 들어오는
// $section 은 restoreTableDescriptions 를 이미 거쳐 403 행의 설명 셀이 기존 문서
// 값으로 되돌아가 있으므로(에러 표도 상태코드를 행 키로 갖는 표라 그 복원 대상에
// 걸린다), 그것을 기준으로 삼으면 갱신이 언제나 no-op 이 된다.
$generatedRows = $generated === null ? $currentRows : $this->errorTableRows($generated);
if (isset($merged['403'], $generatedRows['403'])) {
$merged['403'] = $this->refreshPermissionIdentifier($merged['403'], $generatedRows['403']);
}
ksort($merged, SORT_NUMERIC);
$table = "| 상태코드 | 의미 | 발생 조건 |\n| --- | --- | --- |\n".implode("\n", $merged);
+177
View File
@@ -0,0 +1,177 @@
<?php
namespace App\Support;
use App\Contracts\Repositories\PermissionRepositoryInterface;
use App\Contracts\Repositories\RoleRepositoryInterface;
use App\Exceptions\PermissionEscalationException;
use App\Models\User;
use Illuminate\Support\Facades\Auth;
/**
* 권한 상승(escalation) 상한 가드 (SSoT)
*
* 비-슈퍼관리자 액터가 "자신이 보유하지 않았거나 자신의 범위(scope)보다 넓은" 권한을
* 부여하는 것을 차단합니다(KVE-2026-1919). 권한을 직접 역할에 부여하는 경로(RoleService)와
* 역할 자체를 사용자에게 붙여 그 역할의 권한을 통째로 넘기는 경로(UserService)가 **동일한
* 상한 규칙**을 공유하도록, 판정을 한 지점에 모읍니다. 한 경로만 막으면 다른 경로가 우회로가
* 됩니다(역할 부여는 곧 그 역할의 전 권한 부여이므로 권한 부여와 같은 상한을 받아야 합니다).
*/
class PermissionEscalationGuard
{
/**
* @param PermissionRepositoryInterface $permissionRepository 권한 조회
* @param RoleRepositoryInterface $roleRepository 역할 조회
*/
public function __construct(
private PermissionRepositoryInterface $permissionRepository,
private RoleRepositoryInterface $roleRepository
) {}
/**
* 부여하려는 권한이 액터의 상한(보유 + 범위)을 넘지 않는지 확인합니다.
*
* 슈퍼 관리자와 내부/Artisan 경로는 상한 검사 없이 통과합니다. 비-슈퍼관리자
* 액터는 자신이 보유한 권한만, 그리고 자신의 effective scope 보다 넓지 않은
* 범위로만 부여할 수 있습니다(권한 상승 차단).
*
* @param array<int, array{id?: int, scope_type?: string|null}> $permissions 부여 권한 배열
*
* @throws PermissionEscalationException 상한 위반 시
*/
public function assertGrantWithinActorCeiling(array $permissions): void
{
$actor = Auth::user();
// 인증 액터 부재 = 내부/Artisan 신뢰 경로 → 상한 미적용
if (! $actor instanceof User) {
return;
}
// 슈퍼 관리자는 상한 없음
if ($actor->isSuperAdmin()) {
return;
}
if (empty($permissions)) {
return;
}
// 부여 대상 권한 ID → 식별자 매핑
$ids = array_values(array_filter(array_map(
static fn ($p) => $p['id'] ?? null,
$permissions
)));
$identifierById = $this->permissionRepository->getByIds($ids)
->keyBy('id')
->map(static fn ($permission) => $permission->identifier);
foreach ($permissions as $permission) {
$id = $permission['id'] ?? null;
$identifier = $id !== null ? ($identifierById[$id] ?? null) : null;
// 식별자를 해석할 수 없는 권한은 안전하게 거부
if ($identifier === null) {
throw new PermissionEscalationException;
}
// 액터가 보유하지 않은 권한은 부여 불가
if (! $actor->hasPermission($identifier)) {
throw new PermissionEscalationException;
}
// 부여 범위가 액터의 effective scope 보다 넓으면 불가
$requestedScope = $permission['scope_type'] ?? null;
$actorScope = $actor->getEffectiveScopeForPermission($identifier);
if ($this->scopeRank($requestedScope) > $this->scopeRank($actorScope)) {
throw new PermissionEscalationException;
}
}
}
/**
* 사용자에게 부여하려는 역할들이 액터의 상한을 넘지 않는지 확인합니다.
*
* 역할을 붙이는 것은 그 역할이 담은 권한 전부를 부여하는 것과 같으므로, 각 역할의
* 권한을 그 pivot scope 와 함께 펼쳐 권한 부여 상한(assertGrantWithinActorCeiling)을
* 그대로 적용합니다. 호출측은 **이번 조작으로 변경되는(추가·제거) 역할만** 전달해야 합니다 —
* 기존 유지 역할은 변경이 아니므로 제외합니다. 제거 방향도 같은 상한을 받는 이유는, 상위
* 역할을 박탈하는 하향 조작 역시 액터가 권한을 갖지 못한 역할 구성에 대한 조작이기 때문입니다.
*
* @param array<int, int> $roleIds 이번 조작으로 변경되는(추가·제거) 역할 ID 목록
*
* @throws PermissionEscalationException 상한 위반 시
*/
public function assertRoleAssignmentWithinActorCeiling(array $roleIds): void
{
$actor = Auth::user();
if (! $actor instanceof User) {
return;
}
if ($actor->isSuperAdmin()) {
return;
}
$roleIds = array_values(array_filter($roleIds, static fn ($id) => $id !== null));
if (empty($roleIds)) {
return;
}
// 시스템 baseline 역할('user')은 상한에서 면제한다.
//
// 'user' 는 모든 회원이 갖는 기본 역할로, core.permissions.update 가 없는 액터의
// 생성 경로가 상한 검사 없이 자동 배정하는 바로 그 역할이다(UserService::createUser).
// 그 역할의 권한은 알림 self-service·본인인증 등 회원 baseline 뿐이라 액터가
// 그것을 "부여" 해도 권한 상승 벡터가 되지 않는다. baseline 을 검사에 넣으면
// core.permissions.update 를 가진(=더 권한 있는) 액터가 baseline 을 명시 지정했을 때만
// 403 이 되어, 권한 낮은 액터의 auto-assign 경로와 비대칭으로 정상 회원 생성/수정이
// 깨진다. 비-baseline 역할은 여전히 전량 상한 검사를 받는다.
$baselineRoleId = $this->roleRepository->findByIdentifier('user')?->id;
// 부여 역할들의 권한을 [{id, scope_type}] 로 펼친다
$permissions = [];
foreach ($roleIds as $roleId) {
if ($baselineRoleId !== null && (int) $roleId === (int) $baselineRoleId) {
continue;
}
$role = $this->roleRepository->findById((int) $roleId);
// 존재하지 않는 역할은 안전하게 거부
if ($role === null) {
throw new PermissionEscalationException;
}
foreach ($role->permissions as $permission) {
$permissions[] = [
'id' => $permission->id,
'scope_type' => $permission->pivot->scope_type ?? null,
];
}
}
$this->assertGrantWithinActorCeiling($permissions);
}
/**
* scope_type 의 넓이 순위를 반환합니다 (클수록 넓음).
*
* null(전체) > 'role'(소유역할) > 'self'(본인) 순으로, User::getEffectiveScopeForPermission
* 의 union 우선순위와 동일한 서열을 사용합니다.
*
* @param string|null $scope 범위 문자열
* @return int 넓이 순위 (2=전체, 1=role, 0=self)
*/
private function scopeRank(?string $scope): int
{
return match ($scope) {
null => 2,
'role' => 1,
default => 0,
};
}
}
+180
View File
@@ -0,0 +1,180 @@
<?php
namespace App\Support;
use App\Extension\HookManager;
use App\Extension\ModuleManager;
use App\Extension\PluginManager;
use App\Extension\TemplateManager;
use Illuminate\Support\Facades\Log;
/**
* 신뢰하는 외부 스크립트 호스트 집계 (KVE-2026-1915 신뢰 출처 허용목록)
*
* 레이아웃 `scripts[].src` 는 기본적으로 same-origin path-only 만 허용한다(원격 코드 로드
* 차단). 그러나 CKEditor5(cdn.ckeditor.com)·Daum 우편번호(t1.daumcdn.net)처럼 외부 CDN
* 스크립트를 정당하게 로드하는 번들 확장이 있다. 그 확장이 manifest 의
* `trusted_script_hosts` 로 자기 호스트를 **선언**하고, 코어가 활성 확장 전수에서 이 목록을
* 집계한다. 런타임 스크립트 로더(TemplateApp)·저장측 검증(SafeLayoutExpressions)·정적 검사
* (audit)가 모두 이 집계 결과만 신뢰 호스트로 허용한다.
*
* 신뢰 경계: 편집기가 저장하는 레이아웃(저권한 액터)에는 외부 스크립트를 허용하지 않는
* 것이 기본이고, 여기서 허용되는 것은 **확장이 코드로 선언한 호스트**뿐이다.
*/
class TrustedScriptHosts
{
/**
* 확장이 동적으로 신뢰 호스트를 추가할 수 있는 필터 훅 이름.
*/
public const FILTER_HOOK = 'core.layout.trusted_script_hosts';
/**
* 활성 모듈·플러그인·템플릿이 선언한 신뢰 호스트 전체를 집계합니다.
*
* @return array<int, string> 중복 제거된 호스트명 목록 (소문자)
*/
public static function hosts(): array
{
$hosts = [];
try {
foreach (app(ModuleManager::class)->getActiveModules() as $module) {
if (method_exists($module, 'getTrustedScriptHosts')) {
$hosts = array_merge($hosts, $module->getTrustedScriptHosts());
}
}
} catch (\Throwable $e) {
Log::warning('TrustedScriptHosts: 모듈 집계 실패 - '.$e->getMessage());
}
try {
foreach (app(PluginManager::class)->getActivePlugins() as $plugin) {
if (method_exists($plugin, 'getTrustedScriptHosts')) {
$hosts = array_merge($hosts, $plugin->getTrustedScriptHosts());
}
}
} catch (\Throwable $e) {
Log::warning('TrustedScriptHosts: 플러그인 집계 실패 - '.$e->getMessage());
}
// 템플릿은 모듈/플러그인과 달리 PHP 확장 클래스가 없고 manifest 배열로 다뤄지므로,
// 활성 템플릿의 template.json 에서 직접 읽는다. 타입별 활성 템플릿은 각각 하나뿐이다.
try {
$templateManager = app(TemplateManager::class);
foreach (['admin', 'user'] as $type) {
$template = $templateManager->getActiveTemplate($type);
if (! is_array($template) || ! isset($template['trusted_script_hosts'])) {
continue;
}
$declared = $template['trusted_script_hosts'];
if (! is_array($declared)) {
continue;
}
$hosts = array_merge($hosts, $declared);
}
} catch (\Throwable $e) {
Log::warning('TrustedScriptHosts: 템플릿 집계 실패 - '.$e->getMessage());
}
// 확장이 훅으로 동적 추가할 수 있는 경로 (manifest 외 경로)
$hosts = HookManager::applyFilters(self::FILTER_HOOK, $hosts);
if (! is_array($hosts)) {
$hosts = [];
}
// 정규화: 문자열·비어있지 않음·소문자·중복 제거
$normalized = [];
foreach ($hosts as $host) {
if (! is_string($host)) {
continue;
}
$host = strtolower(trim($host));
if ($host !== '') {
$normalized[$host] = true;
}
}
return array_keys($normalized);
}
/**
* URL 에서 호스트명을 추출합니다.
*
* `//host/path`(protocol-relative)·`https://host/path`(scheme 포함) 모두 처리합니다.
* same-origin 경로(`/path`)는 호스트가 없으므로 null 을 반환합니다.
*
* @param string $url 검사 대상 URL
* @return string|null 소문자 호스트명 (없으면 null)
*/
public static function hostOf(string $url): ?string
{
$host = parse_url(self::normalizeForOriginCheck(trim($url)), PHP_URL_HOST);
return is_string($host) && $host !== '' ? strtolower($host) : null;
}
/**
* origin 판정 전에 URL 을 브라우저 URL 파서와 동일하게 정규화합니다.
*
* 브라우저(WHATWG URL)는 파싱 전에 ASCII tab·LF·CR 을 제거하고, special scheme
* (http/https)에서 백슬래시를 슬래시와 동등하게 처리합니다. 이 정규화 없이 판정하면
* 같은 문자열을 계층마다 다른 출처로 읽습니다:
*
* - `https://evil.com\@cdn.ckeditor.com/x.js` — 정규화 없이는 호스트가
* `cdn.ckeditor.com`(userinfo 해석)이지만 브라우저는 `evil.com` 에서 로드합니다.
* - `/\/cdn.ckeditor.com/x.js` — 문자열상 path 지만 브라우저는 authority 로 읽습니다.
*
* 정규화 후 판정하면 경로 중간의 백슬래시·탭(`/js/a\b.js`)은 authority 를 만들지
* 않으므로 그대로 통과합니다(과차단 없음).
*
* 이 메서드가 origin 판정 정규화의 SSoT 입니다 — 저장측 규칙
* (`App\Rules\SafeLayoutExpressions`)이 위임하고, 클라이언트
* (`TemplateApp.normalizeScriptSrcForOriginCheck`)·정적 검사
* (`layout-scripts-src-same-origin`)가 동형 구현을 갖습니다. 한 계층만 바꾸면
* 그 계층만 다른 출처를 보게 되며, 예외도 경고도 없이 판정만 갈립니다.
*
* @param string $url 원본 URL
* @return string 정규화된 URL
*/
public static function normalizeForOriginCheck(string $url): string
{
// ASCII tab / LF / CR 제거 (브라우저 파서가 파싱 전에 제거하는 문자)
$stripped = str_replace(["\t", "\n", "\r"], '', $url);
// 백슬래시를 슬래시로 (special scheme 에서 등가)
$slashed = str_replace('\\', '/', $stripped);
// 선행 슬래시가 3개 이상이어도 브라우저는 authority 시작으로 접는다
// (`///host/x` ≡ `//host/x`, `https:///host/x` ≡ `https://host/x`).
// 접지 않으면 `/\/host/x` 가 정규화 후 `///host/x` 가 되어 parse_url 은
// 호스트를 못 찾는데 브라우저는 host 에서 로드하는 갈림이 생긴다.
// 경로 중간의 연속 슬래시(`/js//a.js`)는 브라우저도 경로로 두므로 건드리지 않는다.
return preg_replace('#^([a-z][a-z0-9+.\-]*:)?/{2,}#i', '$1//', $slashed) ?? $slashed;
}
/**
* URL 의 호스트가 신뢰 목록에 있는지 판정합니다.
*
* @param string $url 검사 대상 URL
* @param array<int, string>|null $hosts 신뢰 호스트 목록 (미지정 시 self::hosts())
* @return bool 신뢰 호스트면 true (호스트 없는 same-origin 경로는 false)
*/
public static function isTrustedUrl(string $url, ?array $hosts = null): bool
{
$host = self::hostOf($url);
if ($host === null) {
return false;
}
$hosts ??= self::hosts();
return in_array($host, $hosts, true);
}
}
+83
View File
@@ -0,0 +1,83 @@
<?php
namespace App\Support;
use App\Exceptions\CannotModifySuperAdminException;
use App\Models\User;
use Illuminate\Support\Facades\Auth;
/**
* 사용자 등급 상한(rank ceiling) 가드 (SSoT)
*
* 슈퍼 관리자 보호는 그동안 삭제/탈퇴 경로에만 있었고 수정·상태변경·권한부여
* 경로에는 없어 비대칭이었습니다(KVE-2026-1919). 이 가드는 "비-슈퍼관리자
* 액터는 슈퍼 관리자를 수정할 수 없다"는 규칙을 단일 지점에서 강제해 모든
* 쓰기 경로가 동일한 상한을 공유하도록 합니다.
*
* 인증된 액터가 없는 경우(Artisan, 내부 시더/호출)는 신뢰 경로로 간주해
* 가드를 적용하지 않습니다. HTTP 관리 경로는 인증·권한 미들웨어를 통과하므로
* 이 지점에서는 항상 액터가 존재합니다.
*/
class UserGradeGuard
{
/**
* 액터가 대상 사용자를 수정할 수 있는지 판정합니다.
*
* @param User $target 수정 대상 사용자
* @param User|null $actor 행위자(미지정 시 현재 인증 사용자)
* @return bool 수정 가능 여부
*/
public static function mayModify(User $target, ?User $actor = null): bool
{
$actor ??= Auth::user();
// 인증 액터 부재 = 내부/Artisan 신뢰 경로 → 가드 미적용
if (! $actor instanceof User) {
return true;
}
// 대상이 슈퍼 관리자가 아니면 등급 상한과 무관
if (! $target->isSuperAdmin()) {
return true;
}
// 슈퍼 관리자 대상은 슈퍼 관리자 액터만 수정 가능
return $actor->isSuperAdmin();
}
/**
* 액터가 대상을 수정할 수 없으면 예외를 던집니다.
*
* @param User $target 수정 대상 사용자
* @param User|null $actor 행위자(미지정 시 현재 인증 사용자)
*
* @throws CannotModifySuperAdminException 상한 위반 시
*/
public static function assertActorMayModify(User $target, ?User $actor = null): void
{
if (! self::mayModify($target, $actor)) {
throw new CannotModifySuperAdminException;
}
}
/**
* 액터가 수정 가능한 대상만 남긴 배열을 반환합니다(일괄 작업용).
*
* @param iterable<User> $targets 대상 사용자 목록
* @param User|null $actor 행위자(미지정 시 현재 인증 사용자)
* @return array<User> 수정 가능한 대상 목록
*/
public static function filterModifiable(iterable $targets, ?User $actor = null): array
{
$actor ??= Auth::user();
$allowed = [];
foreach ($targets as $target) {
if (self::mayModify($target, $actor)) {
$allowed[] = $target;
}
}
return $allowed;
}
}