fix(security): 예약 작업·언어팩·인스톨러의 차단목록을 허용목록으로 전환
KISA 신고포상제 접수 3건(KVE-2026-1677/1678/1679)의 공통 원인은 하나다 — "위험한 것을 골라 막았고, 목록 밖으로 우회됐다". 세 지점 모두 판정을 뒤집는다. 예약 작업 Artisan (KVE-2026-1679) 차단 9개 / 허용 229개였던 구조를 허용목록으로 바꾸고 명령마다 허용 옵션을 선언한다. 검증 과정에서 보고서보다 짧은 경로를 추가로 발견했다 — 검증기는 preg_split 의 첫 토큰을 명령명으로 봤지만 실행부는 문자열째 넘겼고, parameters 가 비면 Laravel 이 StringInput 으로 재파싱한다. 따옴표 한 쌍이면 차단목록의 tinker 가 그대로 실행됐다 (마커 파일로 확인). 파서를 엄격 형태 하나로 고정하고 실행은 (명령명, 인자배열)로 넘겨 재해석 지점 자체를 없앴다. 언어팩 (KVE-2026-1678) 위험 함수 11개를 정규식으로 나열하던 검사를 토큰 상태기계로 교체해 "번역 배열만" 통과시킨다. 목록에 없는 함수도, 함수 이름을 아예 쓰지 않는 형태도 원리적으로 막힌다. 파일 형식·PHP 위치·심볼릭 링크도 화이트리스트로 뒤집었다. 활성 승격이 require 배선의 필수 조건이므로 설치와 활성화의 권한 경계를 네 설치 경로 전부에 같은 강도로 건다 — 경로별 면제는 곧 우회로가 되기 때문이다. 화면은 운영자의 활성화 권한을 보고 auto_activate 를 실을지 결정하므로 재설치 흐름은 그대로 동작한다. 인스톨러 (KVE-2026-1677) 실행 바이너리 자리에 인자가 들어가는 것을 형태 규칙으로 차단한다. escapeshellarg 는 "하나의 인자" 임만 보장할 뿐 그 인자가 실행 파일인지 스크립트인지는 보장하지 않는다. 판정을 의존성 0 공용 정책으로 모아 진단 API·설치 워커·저장 시점이 같은 규칙을 쓴다. stat 은 호출하지 않는다 — 접근이 제한된 서버에서 정상 경로가 거부되던 회귀를 재발시키지 않기 위함이다. 검증: 백엔드 392건 + 프론트 7건 green(skip 1, symlink 미지원 환경). PoC 마커로 red 를 먼저 확보하고, 수정 후 stash 역회귀로 다시 red 가 되는 것까지 확인했다.
This commit is contained in:
1 parent
30867e0e0b
commit
4b6adf4788
45 files changed
+4382
-301
No files matched your search
@@ -12,14 +12,27 @@ use Exception;
|
||||
*/
|
||||
class ScheduleExecutionException extends Exception
|
||||
{
|
||||
/**
|
||||
* 거부 사유 코드 (`ScheduleCommandValidator::ARTISAN_REASON_*`).
|
||||
*
|
||||
* 관리자에게 보이는 메시지는 사유와 무관하게 동일하지만, 운영 진단 로그에는
|
||||
* 어느 규칙에 걸렸는지가 남아야 한다 — 업그레이드 점검 스텝을 두지 않기로 했으므로
|
||||
* 실행 이력과 로그가 유일한 통로다.
|
||||
*/
|
||||
public ?string $reasonCode = null;
|
||||
|
||||
/**
|
||||
* 허용되지 않은 Artisan 명령
|
||||
*
|
||||
* @param string|null $reasonCode 거부 사유 코드 (`ScheduleCommandValidator::ARTISAN_REASON_*`)
|
||||
* @return self 생성된 예외
|
||||
*/
|
||||
public static function artisanNotAllowed(): self
|
||||
public static function artisanNotAllowed(?string $reasonCode = null): self
|
||||
{
|
||||
return new self(__('schedule.artisan_not_allowed'));
|
||||
$exception = new self(__('schedule.artisan_not_allowed'));
|
||||
$exception->reasonCode = $reasonCode;
|
||||
|
||||
return $exception;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -2,6 +2,8 @@
|
||||
|
||||
namespace App\Http\Requests\LanguagePack;
|
||||
|
||||
use App\Extension\HookManager;
|
||||
use App\Rules\LanguagePack\RequiresActivationPermission;
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
|
||||
/**
|
||||
@@ -29,15 +31,27 @@ class InstallFromBundledRequest extends FormRequest
|
||||
*/
|
||||
public function rules(): array
|
||||
{
|
||||
return [
|
||||
$rules = [
|
||||
'identifier' => [
|
||||
'required',
|
||||
'string',
|
||||
'max:200',
|
||||
'regex:/^[a-zA-Z0-9._\-]+$/',
|
||||
],
|
||||
'auto_activate' => ['nullable', 'boolean'],
|
||||
/*
|
||||
* 외부 소스(파일·URL·GitHub)와 동일하게 활성화 권한 게이트를 건다 (PO 결정, 2026-08-04).
|
||||
* 설치(install)와 활성화(manage)를 별도 권한으로 두는 정책을 네 경로 전부에 같은 강도로
|
||||
* 적용해, "어느 경로로 들어오느냐" 가 권한 경계를 바꾸지 않게 한다.
|
||||
*
|
||||
* 부수 효과: 관리자 화면에서 auto_activate 를 보내는 곳이 번들 재설치 모달 하나뿐이므로,
|
||||
* 설치 권한만 가진 운영자가 활성 팩을 재설치하면 그 팩이 installed 로 내려간다.
|
||||
* 다시 켜려면 언어팩 관리 권한이 필요하다 — 의도된 동작이다.
|
||||
*/
|
||||
'auto_activate' => ['nullable', 'boolean', new RequiresActivationPermission],
|
||||
];
|
||||
|
||||
// 모듈/플러그인이 validation rules 를 동적으로 추가할 수 있도록 훅 제공
|
||||
return HookManager::applyFilters('core.language_packs.install_from_bundled_validation_rules', $rules, $this);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -2,6 +2,8 @@
|
||||
|
||||
namespace App\Http\Requests\LanguagePack;
|
||||
|
||||
use App\Extension\HookManager;
|
||||
use App\Rules\LanguagePack\RequiresActivationPermission;
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
|
||||
/**
|
||||
@@ -26,10 +28,14 @@ class InstallFromFileRequest extends FormRequest
|
||||
*/
|
||||
public function rules(): array
|
||||
{
|
||||
return [
|
||||
$rules = [
|
||||
'file' => ['required', 'file', 'max:10240', 'mimetypes:application/zip,application/x-zip-compressed,application/octet-stream'],
|
||||
'auto_activate' => ['nullable', 'boolean'],
|
||||
// 설치 권한만으로 활성화까지 수행하지 못하게 한다 — 활성 팩만 require 경로에 배선된다.
|
||||
'auto_activate' => ['nullable', 'boolean', new RequiresActivationPermission],
|
||||
];
|
||||
|
||||
// 모듈/플러그인이 validation rules 를 동적으로 추가할 수 있도록 훅 제공
|
||||
return HookManager::applyFilters('core.language_packs.install_from_file_validation_rules', $rules, $this);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -2,6 +2,8 @@
|
||||
|
||||
namespace App\Http\Requests\LanguagePack;
|
||||
|
||||
use App\Extension\HookManager;
|
||||
use App\Rules\LanguagePack\RequiresActivationPermission;
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
|
||||
/**
|
||||
@@ -26,14 +28,18 @@ class InstallFromGithubRequest extends FormRequest
|
||||
*/
|
||||
public function rules(): array
|
||||
{
|
||||
return [
|
||||
$rules = [
|
||||
'github_url' => [
|
||||
'required',
|
||||
'url',
|
||||
'regex:/^https?:\/\/(www\.)?github\.com\/[a-zA-Z0-9\-_]+\/[a-zA-Z0-9\-_]+\/?$/',
|
||||
],
|
||||
'auto_activate' => ['nullable', 'boolean'],
|
||||
// 설치 권한만으로 활성화까지 수행하지 못하게 한다 — 활성 팩만 require 경로에 배선된다.
|
||||
'auto_activate' => ['nullable', 'boolean', new RequiresActivationPermission],
|
||||
];
|
||||
|
||||
// 모듈/플러그인이 validation rules 를 동적으로 추가할 수 있도록 훅 제공
|
||||
return HookManager::applyFilters('core.language_packs.install_from_github_validation_rules', $rules, $this);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
namespace App\Http\Requests\LanguagePack;
|
||||
|
||||
use App\Extension\HookManager;
|
||||
use App\Rules\LanguagePack\RequiresActivationPermission;
|
||||
use App\Rules\PublicOutboundUrl;
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
|
||||
@@ -32,7 +33,8 @@ class InstallFromUrlRequest extends FormRequest
|
||||
// 원격 코드를 내려받는 지점이므로 https 고정 + 내부 주소 허용 설정과 무관하게 항상 차단
|
||||
'url' => ['required', 'url', 'max:500', new PublicOutboundUrl(schemes: ['https'], allowInternalOptIn: false)],
|
||||
'checksum' => ['nullable', 'string', 'regex:/^[a-f0-9]{64}$/i'],
|
||||
'auto_activate' => ['nullable', 'boolean'],
|
||||
// 설치 권한만으로 활성화까지 수행하지 못하게 한다 — 활성 팩만 require 경로에 배선된다.
|
||||
'auto_activate' => ['nullable', 'boolean', new RequiresActivationPermission],
|
||||
];
|
||||
|
||||
// 모듈/플러그인이 validation rules 를 동적으로 추가할 수 있도록 훅 제공
|
||||
|
||||
@@ -7,14 +7,25 @@ use Closure;
|
||||
use Illuminate\Contracts\Validation\ValidationRule;
|
||||
|
||||
/**
|
||||
* Artisan 타입 스케줄의 command 가 차단목록에 걸리지 않는지 검증하는 Custom Rule.
|
||||
* Artisan 타입 스케줄의 command 가 실행 허용 목록 안인지 검증하는 Custom Rule.
|
||||
*
|
||||
* `tinker` 처럼 임의 PHP 코드를 실행하거나 `db:wipe` 처럼 파괴적인 명령을 스케줄로 등록하는 것을
|
||||
* 저장 시점에 차단한다. 차단목록은 `config/schedule_security.php` 가 소유하며 관리자 환경설정에
|
||||
* 노출되지 않는다.
|
||||
* 허용목록에 없는 명령, 선언되지 않은 옵션, 위치 인자, 그리고 Symfony 가 다르게 해석할 수 있는
|
||||
* 형태(따옴표·백슬래시·단축 옵션)를 저장 시점에 차단한다. 정책은 `config/schedule_security.php`
|
||||
* 가 소유하며 관리자 환경설정에 노출되지 않는다.
|
||||
*
|
||||
* 어느 항목이 왜 막혔는지 드러나도록 거부 사유별로 메시지를 분기한다.
|
||||
*/
|
||||
class AllowedArtisanCommand implements ValidationRule
|
||||
{
|
||||
/** 거부 사유 코드 → 다국어 키 */
|
||||
private const REASON_MESSAGES = [
|
||||
ScheduleCommandValidator::ARTISAN_REASON_DENIED => 'validation.schedule_command.artisan_denied',
|
||||
ScheduleCommandValidator::ARTISAN_REASON_NOT_ALLOWED => 'validation.schedule_command.artisan_not_allowlisted',
|
||||
ScheduleCommandValidator::ARTISAN_REASON_MALFORMED => 'validation.schedule_command.artisan_malformed',
|
||||
ScheduleCommandValidator::ARTISAN_REASON_OPTION => 'validation.schedule_command.artisan_option_denied',
|
||||
ScheduleCommandValidator::ARTISAN_REASON_ARGUMENT => 'validation.schedule_command.artisan_argument_denied',
|
||||
];
|
||||
|
||||
/**
|
||||
* 값이 실행 허용된 artisan 명령인지 검증합니다.
|
||||
*
|
||||
@@ -29,13 +40,19 @@ class AllowedArtisanCommand implements ValidationRule
|
||||
}
|
||||
|
||||
if (! is_string($value)) {
|
||||
$fail(__('validation.schedule_command.artisan_denied'));
|
||||
$fail(__('validation.schedule_command.artisan_malformed'));
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if (! ScheduleCommandValidator::isArtisanCommandAllowed($value)) {
|
||||
$fail(__('validation.schedule_command.artisan_denied'));
|
||||
$verdict = ScheduleCommandValidator::inspectArtisanCommand($value);
|
||||
|
||||
if ($verdict['allowed']) {
|
||||
return;
|
||||
}
|
||||
|
||||
$key = self::REASON_MESSAGES[$verdict['reason']] ?? 'validation.schedule_command.artisan_not_allowlisted';
|
||||
|
||||
$fail(__($key));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
<?php
|
||||
|
||||
namespace App\Rules\LanguagePack;
|
||||
|
||||
use App\Enums\PermissionType;
|
||||
use Closure;
|
||||
use Illuminate\Contracts\Validation\ValidationRule;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
|
||||
/**
|
||||
* `auto_activate` 로 설치 직후 활성화를 요청할 때 활성화 권한을 추가로 요구하는 Custom Rule.
|
||||
*
|
||||
* 언어팩 설치(`core.language_packs.install`)와 활성화(`core.language_packs.manage`)는 원래
|
||||
* 별도 권한이다. 그런데 설치 요청의 `auto_activate` 플래그는 install 권한만으로 활성 상태를
|
||||
* 만들 수 있어 경계가 무너져 있었다. 활성 팩만 fallback 경로에 배선되어 `require` 되므로,
|
||||
* 이 경계가 임의 PHP 실행의 마지막 관문이다.
|
||||
*
|
||||
* `authorize()` 가 아니라 필드 단위 Rule 이어야 한다 — `authorize()` 로 처리하면
|
||||
* `auto_activate` 를 보내지 않은 정상 설치 요청까지 403 이 된다. 필드 단위로 두면
|
||||
* 그 항목만 422 로 거부되고, 항목을 빼면 설치는 그대로 진행된다.
|
||||
*
|
||||
* 판정 기준은 활성화 라우트가 쓰는 권한과 같다(`core.language_packs.manage`, admin 타입) —
|
||||
* 두 경로가 다른 기준을 쓰면 한쪽이 우회로가 된다.
|
||||
*/
|
||||
class RequiresActivationPermission implements ValidationRule
|
||||
{
|
||||
/** 활성화에 필요한 권한 식별자 */
|
||||
public const PERMISSION = 'core.language_packs.manage';
|
||||
|
||||
/**
|
||||
* 활성화를 요청했다면 활성화 권한을 가지고 있는지 검증합니다.
|
||||
*
|
||||
* @param string $attribute 검증 대상 필드명
|
||||
* @param mixed $value 검증 대상 값
|
||||
* @param Closure $fail 실패 콜백
|
||||
*/
|
||||
public function validate(string $attribute, mixed $value, Closure $fail): void
|
||||
{
|
||||
if (! filter_var($value, FILTER_VALIDATE_BOOLEAN)) {
|
||||
return;
|
||||
}
|
||||
|
||||
$user = Auth::user();
|
||||
|
||||
if ($user === null || ! $user->hasPermission(self::PERMISSION, PermissionType::Admin)) {
|
||||
$fail(__('language_packs.errors.auto_activate_requires_manage'));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,403 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\LanguagePack;
|
||||
|
||||
use ParseError;
|
||||
|
||||
/**
|
||||
* 언어팩에 동봉된 PHP 파일이 "번역 배열만" 담고 있는지 문법으로 검사하는 순수 유틸.
|
||||
*
|
||||
* 언어팩의 PHP 파일은 활성화되면 `LanguagePackTranslator` 가 `require` 하므로 그 내용이
|
||||
* 그대로 실행된다. 위험 함수 이름을 나열해 막는 방식은 목록에 없는 함수(`file_put_contents`,
|
||||
* `fopen`, `call_user_func`, 백틱 등)로 언제든 우회되므로, 반대로 **허용된 문법만 통과**시킨다.
|
||||
*
|
||||
* 허용 문법:
|
||||
*
|
||||
* 파일 := "<?php" declare? "return" 값 ";" 닫는태그? EOF
|
||||
* declare := declare(strict_types=1);
|
||||
* 값 := 배열 | 스칼라
|
||||
* 배열 := "[" 항목들? "]" | array( 항목들? )
|
||||
* 항목 := 값 ("=>" 값)?
|
||||
* 스칼라 := 문자열리터럴 ("." 문자열리터럴)* | 부호? 숫자 | true | false | null
|
||||
* (공백·주석은 어디서나 허용)
|
||||
*
|
||||
* 토큰 집합만 검사해서는 안 된다 — "허용 토큰 목록에 없으면 거부" 로 구현하면
|
||||
* `<?php return [('system')('id')];` 가 통과한다. 여기 쓰인 토큰은 문자열 리터럴과
|
||||
* 괄호뿐이기 때문이다. 따라서 토큰의 **등장 위치와 순서를 강제하는 상태기계**로 구현하고,
|
||||
* `(` 는 `array` 바로 뒤와 `declare` 프리픽스에서만 허용한다.
|
||||
*
|
||||
* 블록리스트보다 나은 점은 빠뜨림이 원리적으로 불가능하다는 것이다. 함수 호출은 이름과
|
||||
* 무관하게 전부 거부되고, 변수·가변변수·백틱·heredoc 보간·`?>` 뒤 인라인 코드·속성·`new`·
|
||||
* `match` 도 전부 문법에 없다. PHP 에 새 위험 함수가 추가되어도 목록을 갱신할 필요가 없다.
|
||||
*
|
||||
* `nikic/php-parser` 를 쓰지 않는다 — 개발 의존성이라 배포본에서 사라질 수 있다.
|
||||
* `token_get_all()` 은 별도 확장 없이 항상 쓸 수 있다.
|
||||
*/
|
||||
class LanguagePackPhpArrayValidator
|
||||
{
|
||||
/** 검사 대상 파일 크기 상한 (파서 자원 소모 방지) */
|
||||
public const MAX_BYTES = 2 * 1024 * 1024;
|
||||
|
||||
/** 배열 중첩 깊이 상한 (파서 자원 소모 방지) */
|
||||
public const MAX_DEPTH = 30;
|
||||
|
||||
/** @var array<int, array{type: int|string, text: string, line: int}> 공백·주석을 제거한 토큰 목록 */
|
||||
private array $tokens = [];
|
||||
|
||||
/** @var int 현재 토큰 위치 */
|
||||
private int $position = 0;
|
||||
|
||||
/**
|
||||
* 소스가 번역 배열만 담고 있는지 판정합니다.
|
||||
*
|
||||
* @param string $source PHP 소스 문자열
|
||||
* @return bool 안전하면 true
|
||||
*/
|
||||
public static function isSafe(string $source): bool
|
||||
{
|
||||
return self::inspect($source) === null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 소스를 검사해 위반 지점을 돌려줍니다.
|
||||
*
|
||||
* @param string $source PHP 소스 문자열
|
||||
* @return array{line: int, reason: string}|null 안전하면 null
|
||||
*/
|
||||
public static function inspect(string $source): ?array
|
||||
{
|
||||
if (strlen($source) > self::MAX_BYTES) {
|
||||
return ['line' => 0, 'reason' => 'file_too_large'];
|
||||
}
|
||||
|
||||
try {
|
||||
$raw = token_get_all($source, TOKEN_PARSE);
|
||||
} catch (ParseError) {
|
||||
return ['line' => 0, 'reason' => 'parse_error'];
|
||||
}
|
||||
|
||||
return (new self)->run($raw);
|
||||
}
|
||||
|
||||
/**
|
||||
* 파일을 읽어 검사합니다.
|
||||
*
|
||||
* @param string $path 절대 경로
|
||||
* @return array{line: int, reason: string}|null 안전하면 null
|
||||
*/
|
||||
public static function inspectFile(string $path): ?array
|
||||
{
|
||||
// 크기 상한은 읽기 **전에** 본다 — 내용을 먼저 메모리에 올리면 압축률 높은 ZIP 으로
|
||||
// 반입한 거대 파일이 2MB 컷에 걸리기 전에 메모리를 소모한다.
|
||||
$size = @filesize($path);
|
||||
|
||||
if ($size !== false && $size > self::MAX_BYTES) {
|
||||
return ['line' => 0, 'reason' => 'file_too_large'];
|
||||
}
|
||||
|
||||
$source = @file_get_contents($path, false, null, 0, self::MAX_BYTES + 1);
|
||||
|
||||
if ($source === false) {
|
||||
return ['line' => 0, 'reason' => 'unreadable'];
|
||||
}
|
||||
|
||||
return self::inspect($source);
|
||||
}
|
||||
|
||||
/**
|
||||
* 토큰 목록을 문법에 따라 검사합니다.
|
||||
*
|
||||
* @param array<int, array{0: int, 1: string, 2: int}|string> $raw token_get_all 결과
|
||||
* @return array{line: int, reason: string}|null 안전하면 null
|
||||
*/
|
||||
private function run(array $raw): ?array
|
||||
{
|
||||
$line = 1;
|
||||
|
||||
foreach ($raw as $token) {
|
||||
if (is_array($token)) {
|
||||
$line = $token[2];
|
||||
|
||||
if (in_array($token[0], [T_WHITESPACE, T_COMMENT, T_DOC_COMMENT], true)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$this->tokens[] = ['type' => $token[0], 'text' => $token[1], 'line' => $token[2]];
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$this->tokens[] = ['type' => $token, 'text' => $token, 'line' => $line];
|
||||
}
|
||||
|
||||
if (! $this->expectType(T_OPEN_TAG)) {
|
||||
return $this->violation('missing_open_tag');
|
||||
}
|
||||
|
||||
if ($this->peekType() === T_DECLARE && ! $this->consumeStrictTypesDeclare()) {
|
||||
return $this->violation('unsupported_declare');
|
||||
}
|
||||
|
||||
if (! $this->expectType(T_RETURN)) {
|
||||
return $this->violation('missing_return');
|
||||
}
|
||||
|
||||
if (! $this->consumeValue(0)) {
|
||||
return $this->violation('not_a_literal_value');
|
||||
}
|
||||
|
||||
if (! $this->expectText(';')) {
|
||||
return $this->violation('missing_semicolon');
|
||||
}
|
||||
|
||||
if ($this->peekType() === T_CLOSE_TAG) {
|
||||
$this->position++;
|
||||
|
||||
/*
|
||||
* PHP 는 닫는 태그 직후 개행 하나를 삼킨다. 그 이상 남은 것은 인라인 출력이므로
|
||||
* 공백만 허용한다 (닫는 태그 `?>` 뒤의 임의 코드·두 번째 여는 태그를 여기서 막는다).
|
||||
* 한 줄 주석에 닫는 태그를 쓰면 그 지점에서 PHP 모드가 끝나므로 블록 주석을 쓴다.
|
||||
*/
|
||||
if ($this->peekType() === T_INLINE_HTML) {
|
||||
if (trim($this->tokens[$this->position]['text']) !== '') {
|
||||
return $this->violation('code_after_close_tag');
|
||||
}
|
||||
|
||||
$this->position++;
|
||||
}
|
||||
}
|
||||
|
||||
if ($this->position !== count($this->tokens)) {
|
||||
return $this->violation('trailing_tokens');
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* `declare(strict_types=1);` 프리픽스를 소비합니다.
|
||||
*
|
||||
* @return bool 정확히 이 형태였으면 true
|
||||
*/
|
||||
private function consumeStrictTypesDeclare(): bool
|
||||
{
|
||||
$this->position++; // T_DECLARE
|
||||
|
||||
if (! $this->expectText('(')) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$directive = $this->tokens[$this->position] ?? null;
|
||||
|
||||
if ($directive === null || $directive['type'] !== T_STRING || strtolower($directive['text']) !== 'strict_types') {
|
||||
return false;
|
||||
}
|
||||
|
||||
$this->position++;
|
||||
|
||||
return $this->expectText('=')
|
||||
&& $this->expectType(T_LNUMBER)
|
||||
&& $this->expectText(')')
|
||||
&& $this->expectText(';');
|
||||
}
|
||||
|
||||
/**
|
||||
* 값(배열 또는 스칼라) 하나를 소비합니다.
|
||||
*
|
||||
* @param int $depth 현재 중첩 깊이
|
||||
* @return bool 소비했으면 true
|
||||
*/
|
||||
private function consumeValue(int $depth): bool
|
||||
{
|
||||
if ($depth > self::MAX_DEPTH) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$token = $this->tokens[$this->position] ?? null;
|
||||
|
||||
if ($token === null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if ($token['type'] === '[') {
|
||||
$this->position++;
|
||||
|
||||
return $this->consumeArrayItems(']', $depth + 1);
|
||||
}
|
||||
|
||||
// `(` 는 `array` 바로 뒤에서만 허용한다 — 그 외 위치의 괄호는 호출·그룹화이므로 거부.
|
||||
if ($token['type'] === T_ARRAY) {
|
||||
$this->position++;
|
||||
|
||||
return $this->expectText('(') && $this->consumeArrayItems(')', $depth + 1);
|
||||
}
|
||||
|
||||
return $this->consumeScalar();
|
||||
}
|
||||
|
||||
/**
|
||||
* 배열 항목들과 닫는 기호를 소비합니다.
|
||||
*
|
||||
* @param string $closer 닫는 기호 (`]` 또는 `)`)
|
||||
* @param int $depth 현재 중첩 깊이
|
||||
* @return bool 소비했으면 true
|
||||
*/
|
||||
private function consumeArrayItems(string $closer, int $depth): bool
|
||||
{
|
||||
if ($depth > self::MAX_DEPTH) {
|
||||
return false;
|
||||
}
|
||||
|
||||
while (true) {
|
||||
if ($this->peekText() === $closer) {
|
||||
$this->position++;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
if (! $this->consumeValue($depth)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if ($this->peekType() === T_DOUBLE_ARROW) {
|
||||
$this->position++;
|
||||
|
||||
if (! $this->consumeValue($depth)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
if ($this->peekText() === ',') {
|
||||
$this->position++;
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if ($this->peekText() === $closer) {
|
||||
$this->position++;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 스칼라 하나를 소비합니다.
|
||||
*
|
||||
* @return bool 소비했으면 true
|
||||
*/
|
||||
private function consumeScalar(): bool
|
||||
{
|
||||
$token = $this->tokens[$this->position] ?? null;
|
||||
|
||||
if ($token === null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if ($token['type'] === T_CONSTANT_ENCAPSED_STRING) {
|
||||
$this->position++;
|
||||
|
||||
// 문자열 리터럴 연결만 허용한다 (변수 보간은 T_ENCAPSED_AND_WHITESPACE 라 여기 오지 않는다).
|
||||
while ($this->peekText() === '.') {
|
||||
$this->position++;
|
||||
|
||||
if (! $this->expectType(T_CONSTANT_ENCAPSED_STRING)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
if ($token['type'] === '-' || $token['type'] === '+') {
|
||||
$this->position++;
|
||||
|
||||
return $this->expectType(T_LNUMBER) || $this->expectType(T_DNUMBER);
|
||||
}
|
||||
|
||||
if ($token['type'] === T_LNUMBER || $token['type'] === T_DNUMBER) {
|
||||
$this->position++;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
if ($token['type'] === T_STRING && in_array(strtolower($token['text']), ['true', 'false', 'null'], true)) {
|
||||
$this->position++;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 다음 토큰이 지정한 타입이면 소비합니다.
|
||||
*
|
||||
* @param int $type 토큰 타입
|
||||
* @return bool 소비했으면 true
|
||||
*/
|
||||
private function expectType(int $type): bool
|
||||
{
|
||||
if (($this->tokens[$this->position]['type'] ?? null) !== $type) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$this->position++;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 다음 토큰이 지정한 기호면 소비합니다.
|
||||
*
|
||||
* @param string $text 기호
|
||||
* @return bool 소비했으면 true
|
||||
*/
|
||||
private function expectText(string $text): bool
|
||||
{
|
||||
if (($this->tokens[$this->position]['type'] ?? null) !== $text) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$this->position++;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 다음 토큰의 타입을 봅니다 (소비하지 않음).
|
||||
*
|
||||
* @return int|string|null 토큰 타입
|
||||
*/
|
||||
private function peekType(): int|string|null
|
||||
{
|
||||
return $this->tokens[$this->position]['type'] ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 다음 토큰이 기호일 때 그 기호를 봅니다 (소비하지 않음).
|
||||
*
|
||||
* @return string|null 기호, 기호가 아니면 null
|
||||
*/
|
||||
private function peekText(): ?string
|
||||
{
|
||||
$type = $this->peekType();
|
||||
|
||||
return is_string($type) ? $type : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 현재 위치를 위반 지점으로 보고합니다.
|
||||
*
|
||||
* @param string $reason 위반 사유 코드
|
||||
* @return array{line: int, reason: string} 위반 정보
|
||||
*/
|
||||
private function violation(string $reason): array
|
||||
{
|
||||
$token = $this->tokens[$this->position] ?? $this->tokens[count($this->tokens) - 1] ?? null;
|
||||
|
||||
return ['line' => $token['line'] ?? 0, 'reason' => $reason];
|
||||
}
|
||||
}
|
||||
@@ -16,6 +16,7 @@ use App\Extension\Traits\ClearsTemplateCaches;
|
||||
use App\Models\LanguagePack;
|
||||
use App\Services\LanguagePack\LanguagePackBaseLocales;
|
||||
use App\Services\LanguagePack\LanguagePackManifestValidator;
|
||||
use App\Services\LanguagePack\LanguagePackPhpArrayValidator;
|
||||
use App\Services\LanguagePack\LanguagePackRegistry;
|
||||
use App\Support\OutboundUrlValidator;
|
||||
use Illuminate\Http\UploadedFile;
|
||||
@@ -875,34 +876,37 @@ class LanguagePackService
|
||||
File::deleteDirectory($extractPath);
|
||||
}
|
||||
|
||||
$pack = DB::transaction(function () use ($existing, $manifest, $sourceType, $sourceUrl, $autoActivate, $installedBy) {
|
||||
// 재설치(update path) 시 자기 자신을 슬롯 충돌로 오인하지 않도록 $existing->id 를 제외.
|
||||
// 이전엔 재설치 시 자기가 active 였더라도 $shouldActivate 가 false 가 되어
|
||||
// status 가 active → installed 로 강등 → 의존하는 확장 언어팩이 'core_locale_missing'
|
||||
// 으로 차단되는 회귀가 발생.
|
||||
$shouldActivate = $autoActivate
|
||||
&& ! $this->repository->findActiveForSlot(
|
||||
$manifest['scope'],
|
||||
$manifest['target_identifier'] ?? null,
|
||||
$manifest['locale'],
|
||||
$existing?->id
|
||||
);
|
||||
|
||||
$pack = DB::transaction(function () use ($existing, $manifest, $sourceType, $sourceUrl, $installedBy) {
|
||||
$data = $this->buildPackData($manifest, $sourceType, $sourceUrl, $installedBy);
|
||||
|
||||
// 재설치(update path) 시 자기 자신을 슬롯 충돌로 오인하지 않도록 $existing->id 를 제외.
|
||||
// 이전엔 재설치 시 자기가 active 였더라도 $shouldActivate 가 false 가 되어
|
||||
// status 가 active → installed 로 강등 → 의존하는 확장 언어팩이 'core_locale_missing'
|
||||
// 으로 차단되는 회귀가 발생.
|
||||
$shouldActivate = $autoActivate
|
||||
&& ! $this->repository->findActiveForSlot(
|
||||
$manifest['scope'],
|
||||
$manifest['target_identifier'] ?? null,
|
||||
$manifest['locale'],
|
||||
$existing?->id
|
||||
);
|
||||
// 설치 트랜잭션은 항상 installed 로만 기록한다. 활성화는 아래에서 activate() 를
|
||||
// 경유해야 의존성 검사·대상 확장 존재 확인·슬롯 충돌 검사가 반드시 수행되고,
|
||||
// activated 훅도 한 곳에서만 발화한다.
|
||||
//
|
||||
// 이 규칙의 부수 효과로, 이미 active 인 팩을 auto_activate 없이 덮어쓰면
|
||||
// active → installed 로 강등된다. 겉보기엔 버그지만 의도된 안전장치다 —
|
||||
// 활성 팩만 require 경로에 배선되므로, 방금 외부에서 반입된 내용이
|
||||
// 활성화 권한자의 동의 없이 그 자리를 이어받는 일이 없어야 한다.
|
||||
// (설치 권한만 가진 사용자가 활성 팩을 덮어쓰는 방식으로 활성화 권한 게이트를
|
||||
// 우회하는 경로를 닫는다. 정상 운영자는 auto_activate 로 활성 상태를 유지하며,
|
||||
// 그 플래그는 RequiresActivationPermission 이 지킨다.)
|
||||
$data['status'] = LanguagePackStatus::Installed->value;
|
||||
|
||||
$data['status'] = $shouldActivate
|
||||
? LanguagePackStatus::Active->value
|
||||
: LanguagePackStatus::Installed->value;
|
||||
|
||||
if ($shouldActivate) {
|
||||
$data['activated_at'] = now();
|
||||
}
|
||||
|
||||
$pack = $existing
|
||||
return $existing
|
||||
? $this->repository->update($existing, $data)
|
||||
: $this->repository->create($data);
|
||||
|
||||
return $pack;
|
||||
});
|
||||
|
||||
// 캐시 전 계층 무효화 (registry + translator + template-lang)
|
||||
@@ -913,8 +917,9 @@ class LanguagePackService
|
||||
$pack
|
||||
);
|
||||
|
||||
if ($pack->status === LanguagePackStatus::Active->value) {
|
||||
HookManager::doAction('core.language_packs.activated', $pack);
|
||||
if ($shouldActivate) {
|
||||
// activate() 내부에서 상태 기록·캐시 무효화·activated 훅 발화를 모두 담당한다.
|
||||
$pack = $this->activate($pack, false);
|
||||
}
|
||||
|
||||
return $pack;
|
||||
@@ -1145,7 +1150,20 @@ class LanguagePackService
|
||||
}
|
||||
|
||||
/**
|
||||
* 보안 규칙 검사 — backend/ 외의 PHP 파일 차단, eval/include 패턴 차단.
|
||||
* 보안 규칙 검사 — 허용된 파일 형식·위치·내용만 통과시킵니다.
|
||||
*
|
||||
* 언어팩의 PHP 파일은 활성화되면 `LanguagePackTranslator` 가 `require` 하므로 그 내용이
|
||||
* 그대로 실행된다. 과거에는 위험 함수 11개를 정규식으로 나열해 막았으나 목록에 없는
|
||||
* 함수(`file_put_contents` `fopen` `call_user_func` `assert` 백틱 등)로 전부 우회됐다.
|
||||
* 따라서 판정을 뒤집어, 아래 네 가지를 모두 만족하는 것만 통과시킨다.
|
||||
*
|
||||
* 1. 확장자 화이트리스트 — `.json` / `.php` / `.md` (대소문자 무관)
|
||||
* 2. PHP 파일 위치 강제 — `backend/{manifest locale}/{group}.php` 또는 `backend/{group}.php`
|
||||
* 3. 심볼릭 링크 거부 — 패키지 밖 파일을 끌어들이는 통로 차단
|
||||
* 4. PHP 내용은 "번역 배열만" (LanguagePackPhpArrayValidator 문법 검사)
|
||||
*
|
||||
* 번들 여부와 무관하게 같은 경로로 검사한다 — 예외를 두면 "동봉된 것으로 위장하면 통과"
|
||||
* 라는 틈이 생기고, 앞으로 언어팩을 만들 때 기준이 둘로 갈린다.
|
||||
*
|
||||
* @param string $packageRoot 패키지 루트 디렉토리
|
||||
* @param array<string, mixed> $manifest manifest 데이터
|
||||
@@ -1154,41 +1172,111 @@ class LanguagePackService
|
||||
*/
|
||||
private function assertSecurityRules(string $packageRoot, array $manifest): void
|
||||
{
|
||||
$finder = function (string $directory) use (&$finder) {
|
||||
if (! File::isDirectory($directory)) {
|
||||
return [];
|
||||
}
|
||||
$files = [];
|
||||
foreach (File::allFiles($directory) as $file) {
|
||||
$files[] = $file->getRealPath();
|
||||
$locale = (string) ($manifest['locale'] ?? '');
|
||||
|
||||
// `backend/{locale}/{group}.php` 와 평면형 `backend/{group}.php` 만 허용.
|
||||
$phpLocationPattern = '#^backend/(?:'.preg_quote($locale, '#').'/)?[A-Za-z0-9_-]+\.php$#';
|
||||
|
||||
foreach ($this->collectPackageEntries($packageRoot) as $relative => $absolute) {
|
||||
if (is_link($absolute)) {
|
||||
throw new LanguagePackOperationException('language_packs.errors.symlink_not_allowed', [
|
||||
'file' => $relative,
|
||||
]);
|
||||
}
|
||||
|
||||
return $files;
|
||||
};
|
||||
|
||||
$allFiles = $finder($packageRoot);
|
||||
$backendDir = realpath($packageRoot.DIRECTORY_SEPARATOR.'backend') ?: null;
|
||||
|
||||
foreach ($allFiles as $absolute) {
|
||||
if (! str_ends_with($absolute, '.php')) {
|
||||
if (is_dir($absolute)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (! $backendDir || ! str_starts_with($absolute, $backendDir)) {
|
||||
throw new LanguagePackOperationException('language_packs.errors.php_outside_backend', [
|
||||
'file' => str_replace($packageRoot, '', $absolute),
|
||||
]);
|
||||
$extension = strtolower(pathinfo($relative, PATHINFO_EXTENSION));
|
||||
|
||||
if ($extension === 'php') {
|
||||
if ($locale === '' || preg_match($phpLocationPattern, $relative) !== 1) {
|
||||
throw new LanguagePackOperationException('language_packs.errors.php_outside_backend', [
|
||||
'file' => $relative,
|
||||
]);
|
||||
}
|
||||
|
||||
$violation = LanguagePackPhpArrayValidator::inspectFile($absolute);
|
||||
|
||||
if ($violation !== null) {
|
||||
throw new LanguagePackOperationException('language_packs.errors.php_file_not_literal_array', [
|
||||
'file' => $relative,
|
||||
'line' => $violation['line'],
|
||||
]);
|
||||
}
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$contents = File::get($absolute);
|
||||
if (preg_match('/\b(eval|include|include_once|require|require_once|exec|shell_exec|passthru|system|popen|proc_open)\s*\(/i', $contents)) {
|
||||
throw new LanguagePackOperationException('language_packs.errors.unsafe_php_pattern', [
|
||||
'file' => str_replace($packageRoot, '', $absolute),
|
||||
// 압축 도구가 끼워 넣는 OS 메타데이터는 형식 검사에서 제외한다.
|
||||
// PHP 는 위 분기에서 이미 위치 규칙에 걸리므로 이 예외로 새는 실행 경로가 없다.
|
||||
if ($this->isOsMetadataEntry($relative)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (! in_array($extension, ['json', 'md'], true)) {
|
||||
throw new LanguagePackOperationException('language_packs.errors.unsupported_file_type', [
|
||||
'file' => $relative,
|
||||
'extension' => $extension === '' ? '(none)' : $extension,
|
||||
]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 패키지 안의 모든 엔트리(디렉토리 포함)를 상대경로 ⇒ 절대경로로 수집합니다.
|
||||
*
|
||||
* 심볼릭 링크를 따라 들어가지 않는다 — 링크는 호출부가 거부 대상으로 판정하며,
|
||||
* 따라 들어가면 순환 링크로 무한 재귀에 빠질 수 있다.
|
||||
*
|
||||
* @param string $packageRoot 패키지 루트 디렉토리
|
||||
* @param string $prefix 현재 상대경로 접두사
|
||||
* @return array<string, string> 상대경로(슬래시 구분) ⇒ 절대경로
|
||||
*/
|
||||
private function collectPackageEntries(string $packageRoot, string $prefix = ''): array
|
||||
{
|
||||
$base = $prefix === '' ? $packageRoot : $packageRoot.DIRECTORY_SEPARATOR.str_replace('/', DIRECTORY_SEPARATOR, $prefix);
|
||||
|
||||
if (! is_dir($base)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$entries = [];
|
||||
|
||||
foreach (scandir($base) ?: [] as $name) {
|
||||
if ($name === '.' || $name === '..') {
|
||||
continue;
|
||||
}
|
||||
|
||||
$relative = $prefix === '' ? $name : $prefix.'/'.$name;
|
||||
$absolute = $base.DIRECTORY_SEPARATOR.$name;
|
||||
|
||||
$entries[$relative] = $absolute;
|
||||
|
||||
if (is_dir($absolute) && ! is_link($absolute)) {
|
||||
$entries += $this->collectPackageEntries($packageRoot, $relative);
|
||||
}
|
||||
}
|
||||
|
||||
return $entries;
|
||||
}
|
||||
|
||||
/**
|
||||
* 압축 도구가 생성하는 OS 메타데이터 엔트리인지 판정합니다.
|
||||
*
|
||||
* @param string $relative 패키지 루트 기준 상대경로
|
||||
* @return bool 메타데이터면 true
|
||||
*/
|
||||
private function isOsMetadataEntry(string $relative): bool
|
||||
{
|
||||
if (str_starts_with($relative, '__MACOSX/') || $relative === '__MACOSX') {
|
||||
return true;
|
||||
}
|
||||
|
||||
return in_array(basename($relative), ['.DS_Store', 'Thumbs.db', '.gitkeep', '.gitignore'], true);
|
||||
}
|
||||
|
||||
/**
|
||||
* 언어팩 설치 디렉토리(`lang-packs/`, `lang-packs/_pending/`) 의 쓰기 권한을 사전 검증합니다.
|
||||
*
|
||||
|
||||
@@ -239,8 +239,13 @@ class ScheduleService
|
||||
'next_run_at' => $schedule->next_run_at,
|
||||
]);
|
||||
|
||||
// 거부 사유는 error 레벨 한 줄만 보는 알림 파이프라인에서도 보여야 한다 —
|
||||
// 별도 warning 로그에만 남기면 그 경로에서는 "왜 막혔는지" 가 유실된다.
|
||||
Log::error('Schedule execution failed', [
|
||||
'schedule_id' => $schedule->id,
|
||||
'type' => $schedule->type->value,
|
||||
'command' => $schedule->command,
|
||||
'reason' => $e instanceof ScheduleExecutionException ? $e->reasonCode : null,
|
||||
'error' => $e->getMessage(),
|
||||
]);
|
||||
|
||||
@@ -262,11 +267,23 @@ class ScheduleService
|
||||
{
|
||||
// 저장 시점 검증 도입 이전 데이터나 DB 직접 수정으로 들어온 값을 방어한다
|
||||
// (isUrlCallAllowed 와 동일 사유 — 실행 직전이 마지막 방어선).
|
||||
if (! ScheduleCommandValidator::isArtisanCommandAllowed($schedule->command)) {
|
||||
throw ScheduleExecutionException::artisanNotAllowed();
|
||||
$verdict = ScheduleCommandValidator::inspectArtisanCommand($schedule->command);
|
||||
|
||||
if (! $verdict['allowed']) {
|
||||
// 업그레이드 점검 스텝을 두지 않으므로, 거부 사유는 이 로그가 유일한 운영 진단 통로다.
|
||||
Log::warning('Schedule artisan command rejected', [
|
||||
'schedule_id' => $schedule->id,
|
||||
'command' => $schedule->command,
|
||||
'reason' => $verdict['reason'],
|
||||
]);
|
||||
|
||||
throw ScheduleExecutionException::artisanNotAllowed($verdict['reason']);
|
||||
}
|
||||
|
||||
Artisan::call($schedule->command, [], new BufferedOutput);
|
||||
// 문자열이 아닌 (명령명, 인자배열) 로 넘겨 StringInput 재파싱을 경유하지 않는다 —
|
||||
// parameters 가 비어 있으면 Laravel 이 문자열 전체를 다시 파싱해
|
||||
// 검증한 이름과 다른 명령이 실행될 수 있다.
|
||||
Artisan::call($verdict['name'], $verdict['parameters'], new BufferedOutput);
|
||||
|
||||
return [
|
||||
'output' => Artisan::output(),
|
||||
|
||||
@@ -2,6 +2,11 @@
|
||||
|
||||
namespace App\Support;
|
||||
|
||||
use Illuminate\Support\Facades\Artisan;
|
||||
use Symfony\Component\Console\Command\Command as SymfonyCommand;
|
||||
use Symfony\Component\Console\Input\InputDefinition;
|
||||
use Throwable;
|
||||
|
||||
/**
|
||||
* 스케줄 Shell/Artisan command 가 실행 가능한 안전 명령인지 판정하는 순수 유틸.
|
||||
*
|
||||
@@ -14,13 +19,34 @@ namespace App\Support;
|
||||
* 허용되더라도 호출부는 `tokenizeShellCommand()` 로 얻은 인자 배열로 실행해야 한다
|
||||
* (`/bin/sh -c` 를 경유하지 않으므로 파이프·`;`·`$()` 가 무력화된다).
|
||||
*
|
||||
* 2. Artisan — 기본 허용, 차단목록만 거부. `tinker` 처럼 임의 PHP 코드를 실행하거나
|
||||
* `db:wipe` 처럼 파괴적인 명령을 스케줄로 실행하지 못하게 막는다.
|
||||
* 2. Artisan — 기본 차단, 허용목록만 통과. `config/schedule_security.php` 의 허용목록에
|
||||
* 명령명이 있고 그 항목이 선언한 옵션만 쓰였을 때 통과한다. 설치된 확장이 소유한 명령은
|
||||
* 게이트가 켜져 있으면 자동으로 허용된다. 차단목록은 최종 거부권으로 가장 먼저 평가된다.
|
||||
*
|
||||
* 명령 문자열은 엄격 파서로만 해석한다 — 따옴표·백슬래시·단축 옵션이 있으면 거부하고,
|
||||
* 호출부는 `resolveArtisanCommand()` 가 돌려준 (명령명, 인자배열) 로 실행해야 한다.
|
||||
* 문자열째 `Artisan::call()` 에 넘기면 Symfony 가 따옴표를 다시 해석해
|
||||
* 검증한 이름과 실행되는 이름이 갈린다(`"tinker" --execute=…`).
|
||||
*
|
||||
* 예외를 던지지 않고 bool/배열만 반환한다 — 차단 시 어떤 응답/예외를 낼지는 호출부가 결정한다.
|
||||
*/
|
||||
class ScheduleCommandValidator
|
||||
{
|
||||
/** 파싱 불가 — 따옴표·백슬래시·제어문자·단축 옵션 등 정규 형태가 아님 */
|
||||
public const ARTISAN_REASON_MALFORMED = 'malformed';
|
||||
|
||||
/** 차단목록(최종 거부권)에 걸림 */
|
||||
public const ARTISAN_REASON_DENIED = 'denied';
|
||||
|
||||
/** 허용목록에도 없고 확장 소유 명령도 아님 */
|
||||
public const ARTISAN_REASON_NOT_ALLOWED = 'not_allowlisted';
|
||||
|
||||
/** 명령은 허용되나 선언되지 않은 옵션이 쓰임 */
|
||||
public const ARTISAN_REASON_OPTION = 'option_denied';
|
||||
|
||||
/** 허용 개수를 넘는 위치 인자가 쓰임 */
|
||||
public const ARTISAN_REASON_ARGUMENT = 'argument_denied';
|
||||
|
||||
/** 셸 해석을 유발하는 메타문자 — 하나라도 있으면 인자 배열 실행이 불가하므로 거부 */
|
||||
private const SHELL_METACHARACTERS = [
|
||||
'|', '&', ';', '$', '`', '>', '<', '(', ')', '{', '}',
|
||||
@@ -74,44 +100,386 @@ class ScheduleCommandValidator
|
||||
}
|
||||
|
||||
/**
|
||||
* Artisan command 문자열에서 명령명(첫 토큰)을 추출합니다.
|
||||
* Artisan command 문자열에서 명령명을 추출합니다.
|
||||
*
|
||||
* 엄격 파서를 경유하므로, Symfony 가 다르게 해석할 수 있는 형태(따옴표·백슬래시·
|
||||
* 선행 옵션)는 명령명을 돌려주지 않고 null 이 된다 — 여기서 반환된 이름은
|
||||
* 실제 실행되는 이름과 반드시 같다.
|
||||
*
|
||||
* @param string $command 스케줄에 저장된 artisan command 문자열
|
||||
* @return string|null 명령명, 빈 문자열이면 null
|
||||
* @return string|null 명령명, 정규 형태가 아니면 null
|
||||
*/
|
||||
public static function extractArtisanCommandName(string $command): ?string
|
||||
{
|
||||
$trimmed = trim($command);
|
||||
$parsed = self::parseArtisanCommand($command);
|
||||
|
||||
if ($trimmed === '') {
|
||||
return null;
|
||||
}
|
||||
|
||||
$tokens = preg_split('/\s+/', $trimmed);
|
||||
|
||||
return ($tokens === false || $tokens === []) ? null : $tokens[0];
|
||||
return $parsed === null ? null : $parsed['name'];
|
||||
}
|
||||
|
||||
/**
|
||||
* Artisan command 가 차단목록에 걸리지 않는지 판정합니다.
|
||||
* Artisan command 를 실행 가능한지 판정하고 사유·실행 계획을 함께 돌려줍니다.
|
||||
*
|
||||
* @param string $command 스케줄에 저장된 artisan command 문자열
|
||||
* @return array{allowed: bool, reason: string|null, name: string|null, parameters: array<string, mixed>}
|
||||
*/
|
||||
public static function inspectArtisanCommand(string $command): array
|
||||
{
|
||||
$parsed = self::parseArtisanCommand($command);
|
||||
|
||||
if ($parsed === null) {
|
||||
return self::artisanVerdict(false, self::ARTISAN_REASON_MALFORMED);
|
||||
}
|
||||
|
||||
$name = $parsed['name'];
|
||||
|
||||
// ① 최종 거부권 — 허용목록·확장 자동 허용보다 먼저 평가한다.
|
||||
// 확장이 코어 명령 이름을 가로채 등록하는 경우도 여기서 걸린다.
|
||||
if (self::isArtisanCommandDenied($name)) {
|
||||
return self::artisanVerdict(false, self::ARTISAN_REASON_DENIED, $name);
|
||||
}
|
||||
|
||||
$allowlist = (array) config('schedule_security.artisan.allowlist', []);
|
||||
$spec = self::findArtisanAllowlistSpec($allowlist, $name);
|
||||
|
||||
if ($spec !== null) {
|
||||
return self::verifyArtisanUsage(
|
||||
$name,
|
||||
$parsed,
|
||||
static fn (string $option): bool => in_array($option, $spec['options'], true),
|
||||
$spec['max_arguments'],
|
||||
);
|
||||
}
|
||||
|
||||
// ③ 확장 소유 명령 — 자기 정의(getDefinition)에 있는 옵션만 허용한다.
|
||||
$definition = self::resolveExtensionCommandDefinition($name);
|
||||
|
||||
if ($definition === null) {
|
||||
return self::artisanVerdict(false, self::ARTISAN_REASON_NOT_ALLOWED, $name);
|
||||
}
|
||||
|
||||
return self::verifyArtisanUsage(
|
||||
$name,
|
||||
$parsed,
|
||||
static fn (string $option): bool => $definition->hasOption($option),
|
||||
0,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 실행 허용 시 (명령명, 인자배열) 실행 계획을 돌려줍니다.
|
||||
*
|
||||
* 호출부는 반드시 이 계획으로 `Artisan::call($name, $parameters, ...)` 를 호출해야 한다.
|
||||
* 문자열째 넘기면 Symfony 가 재파싱해 검증한 이름과 다른 명령이 실행될 수 있다.
|
||||
*
|
||||
* 코어의 두 호출부(FormRequest Rule · 실행부)는 거부 사유 코드가 필요해
|
||||
* `inspectArtisanCommand()` 를 직접 쓴다. 이 메서드는 사유가 필요 없는 호출부
|
||||
* (확장의 자체 스케줄러 등)를 위한 형태이며, 판정은 전적으로 위임하므로
|
||||
* 두 경로의 결과가 갈릴 여지가 없다.
|
||||
*
|
||||
* @param string $command 스케줄에 저장된 artisan command 문자열
|
||||
* @return array{name: string, parameters: array<string, mixed>}|null 허용되지 않으면 null
|
||||
*/
|
||||
public static function resolveArtisanCommand(string $command): ?array
|
||||
{
|
||||
$verdict = self::inspectArtisanCommand($command);
|
||||
|
||||
if (! $verdict['allowed'] || $verdict['name'] === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return ['name' => $verdict['name'], 'parameters' => $verdict['parameters']];
|
||||
}
|
||||
|
||||
/**
|
||||
* Artisan command 를 실행해도 되는지 판정합니다.
|
||||
*
|
||||
* @param string $command 스케줄에 저장된 artisan command 문자열
|
||||
* @return bool 실행을 허용하면 true
|
||||
*/
|
||||
public static function isArtisanCommandAllowed(string $command): bool
|
||||
{
|
||||
$name = self::extractArtisanCommandName($command);
|
||||
return self::inspectArtisanCommand($command)['allowed'];
|
||||
}
|
||||
|
||||
if ($name === null) {
|
||||
return false;
|
||||
/**
|
||||
* Artisan command 문자열을 엄격 규칙으로 파싱합니다.
|
||||
*
|
||||
* 규칙(순서대로, 하나라도 걸리면 null):
|
||||
* 1. trim 후 빈 문자열
|
||||
* 2. 제어문자 포함
|
||||
* 3. 따옴표(`"` `'`)·백슬래시 포함 — Symfony 가 재해석하는 형태를 원천 배제
|
||||
* 4. 첫 토큰이 명령명 형태가 아님 (`-` 로 시작 불가)
|
||||
* 5. 나머지 토큰이 `--이름` / `--이름=값` 롱옵션이 아니거나 옵션 이름이 중복
|
||||
*
|
||||
* @param string $command artisan command 문자열
|
||||
* @return array{name: string, options: array<string, mixed>, arguments: array<int, string>}|null
|
||||
*/
|
||||
private static function parseArtisanCommand(string $command): ?array
|
||||
{
|
||||
$command = trim($command);
|
||||
|
||||
if ($command === '') {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (preg_match('/[\x00-\x1F\x7F]/', $command) === 1) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// 따옴표·백슬래시가 있으면 Symfony 의 재해석 여지가 생긴다 (`"tinker"` → `tinker`).
|
||||
if (preg_match('/["\'\\\\]/', $command) === 1) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$tokens = preg_split('/\s+/', $command);
|
||||
|
||||
if ($tokens === false || $tokens === []) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$name = array_shift($tokens);
|
||||
|
||||
if (preg_match('/^[A-Za-z][A-Za-z0-9_.-]*(?::[A-Za-z0-9_.-]+)*$/', $name) !== 1) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$options = [];
|
||||
$arguments = [];
|
||||
|
||||
foreach ($tokens as $token) {
|
||||
if ($token === '--' || $token === '-') {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (str_starts_with($token, '--')) {
|
||||
$body = substr($token, 2);
|
||||
$separator = strpos($body, '=');
|
||||
|
||||
$optionName = $separator === false ? $body : substr($body, 0, $separator);
|
||||
$optionValue = $separator === false ? true : substr($body, $separator + 1);
|
||||
|
||||
if (preg_match('/^[A-Za-z][A-Za-z0-9-]*$/', $optionName) !== 1) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// 중복 옵션은 어느 값이 이기는지가 파서에 좌우되므로 거부한다.
|
||||
if (array_key_exists($optionName, $options)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$options[$optionName] = $optionValue;
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
// 단축 옵션(`-v`)은 이름이 정의에 따라 달라져 화이트리스트 대조가 불가능하다.
|
||||
if (str_starts_with($token, '-')) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$arguments[] = $token;
|
||||
}
|
||||
|
||||
return ['name' => $name, 'options' => $options, 'arguments' => $arguments];
|
||||
}
|
||||
|
||||
/**
|
||||
* 파싱된 명령의 옵션·위치 인자가 허용 범위 안인지 확인합니다.
|
||||
*
|
||||
* @param string $name 명령명
|
||||
* @param array{name: string, options: array<string, mixed>, arguments: array<int, string>} $parsed 파싱 결과
|
||||
* @param callable(string): bool $optionAllowed 옵션 허용 판정
|
||||
* @param int $maxArguments 허용 위치 인자 개수
|
||||
* @return array{allowed: bool, reason: string|null, name: string|null, parameters: array<string, mixed>}
|
||||
*/
|
||||
private static function verifyArtisanUsage(string $name, array $parsed, callable $optionAllowed, int $maxArguments): array
|
||||
{
|
||||
foreach (array_keys($parsed['options']) as $option) {
|
||||
if (! $optionAllowed((string) $option)) {
|
||||
return self::artisanVerdict(false, self::ARTISAN_REASON_OPTION, $name);
|
||||
}
|
||||
}
|
||||
|
||||
if (count($parsed['arguments']) > $maxArguments) {
|
||||
return self::artisanVerdict(false, self::ARTISAN_REASON_ARGUMENT, $name);
|
||||
}
|
||||
|
||||
$parameters = [];
|
||||
|
||||
foreach ($parsed['options'] as $option => $value) {
|
||||
$parameters['--'.$option] = $value;
|
||||
}
|
||||
|
||||
// 위치 인자는 이름이 있어야 ArrayInput 으로 넘길 수 있다. 허용 개수가 0 인 현재
|
||||
// 설정에서는 도달하지 않지만, 상한을 넓히면 이름을 해석할 수 없는 인자는 거부한다.
|
||||
if ($parsed['arguments'] !== []) {
|
||||
$names = self::resolveArtisanArgumentNames($name, count($parsed['arguments']));
|
||||
|
||||
if ($names === null) {
|
||||
return self::artisanVerdict(false, self::ARTISAN_REASON_ARGUMENT, $name);
|
||||
}
|
||||
|
||||
foreach ($parsed['arguments'] as $index => $value) {
|
||||
$parameters[$names[$index]] = $value;
|
||||
}
|
||||
}
|
||||
|
||||
return self::artisanVerdict(true, null, $name, $parameters);
|
||||
}
|
||||
|
||||
/**
|
||||
* 명령명이 차단목록(정확 일치 또는 접두사)에 걸리는지 판정합니다.
|
||||
*
|
||||
* @param string $name 명령명
|
||||
* @return bool 차단 대상이면 true
|
||||
*/
|
||||
private static function isArtisanCommandDenied(string $name): bool
|
||||
{
|
||||
$normalized = strtolower($name);
|
||||
|
||||
$denylist = array_map(
|
||||
static fn ($denied): string => strtolower(trim((string) $denied)),
|
||||
(array) config('schedule_security.artisan.denylist', []),
|
||||
);
|
||||
|
||||
return ! in_array(strtolower($name), $denylist, true);
|
||||
if (in_array($normalized, $denylist, true)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
foreach ((array) config('schedule_security.artisan.denylist_prefixes', []) as $prefix) {
|
||||
$prefix = strtolower(trim((string) $prefix));
|
||||
|
||||
if ($prefix !== '' && str_starts_with($normalized, $prefix)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 허용목록에서 명령 항목을 찾아 정규화합니다 (대소문자 무관).
|
||||
*
|
||||
* @param array<string, mixed> $allowlist 허용목록 설정
|
||||
* @param string $name 명령명
|
||||
* @return array{options: array<int, string>, max_arguments: int}|null 미등재면 null
|
||||
*/
|
||||
private static function findArtisanAllowlistSpec(array $allowlist, string $name): ?array
|
||||
{
|
||||
$normalized = strtolower($name);
|
||||
|
||||
foreach ($allowlist as $key => $spec) {
|
||||
if (strtolower(trim((string) $key)) !== $normalized) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$spec = (array) $spec;
|
||||
|
||||
return [
|
||||
'options' => array_map('strval', (array) ($spec['options'] ?? [])),
|
||||
'max_arguments' => (int) ($spec['max_arguments'] ?? 0),
|
||||
];
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 확장이 소유한 명령이면 그 정의를 돌려줍니다.
|
||||
*
|
||||
* 이름이 아니라 등록된 명령 인스턴스의 클래스 네임스페이스로 소유자를 판정한다 —
|
||||
* Symfony 가 실제 실행에 쓰는 레지스트리이므로 이름만으로 위조할 수 없다.
|
||||
*
|
||||
* @param string $name 명령명
|
||||
* @return InputDefinition|null 확장 소유가 아니면 null
|
||||
*/
|
||||
private static function resolveExtensionCommandDefinition(string $name): ?InputDefinition
|
||||
{
|
||||
if (! (bool) config('schedule_security.artisan.allow_extension_commands', true)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$namespaces = array_filter(array_map(
|
||||
static fn ($namespace): string => trim((string) $namespace),
|
||||
(array) config('schedule_security.artisan.extension_namespaces', []),
|
||||
));
|
||||
|
||||
if ($namespaces === []) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$command = self::findRegisteredCommand($name);
|
||||
|
||||
if ($command === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$class = get_class($command);
|
||||
|
||||
foreach ($namespaces as $namespace) {
|
||||
if (str_starts_with($class, $namespace)) {
|
||||
return $command->getDefinition();
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 등록된 artisan 명령 인스턴스를 찾습니다.
|
||||
*
|
||||
* 콘솔 부트스트랩 비용이 있으므로 허용목록에서 찾지 못했을 때만 호출한다.
|
||||
* 조회 자체가 실패하면 "허용되지 않음" 으로 취급한다(fail-closed).
|
||||
*
|
||||
* @param string $name 명령명
|
||||
* @return SymfonyCommand|null 없으면 null
|
||||
*/
|
||||
private static function findRegisteredCommand(string $name): ?SymfonyCommand
|
||||
{
|
||||
try {
|
||||
$commands = Artisan::all();
|
||||
} catch (Throwable) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return $commands[$name] ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 위치 인자에 대응하는 인자 이름을 순서대로 해석합니다.
|
||||
*
|
||||
* @param string $name 명령명
|
||||
* @param int $count 위치 인자 개수
|
||||
* @return array<int, string>|null 해석 불가하면 null
|
||||
*/
|
||||
private static function resolveArtisanArgumentNames(string $name, int $count): ?array
|
||||
{
|
||||
$command = self::findRegisteredCommand($name);
|
||||
|
||||
if ($command === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$names = array_values(array_filter(
|
||||
array_keys($command->getDefinition()->getArguments()),
|
||||
static fn (string $argument): bool => $argument !== 'command',
|
||||
));
|
||||
|
||||
return count($names) >= $count ? $names : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 판정 결과 배열을 만듭니다.
|
||||
*
|
||||
* @param bool $allowed 허용 여부
|
||||
* @param string|null $reason 거부 사유 코드
|
||||
* @param string|null $name 명령명
|
||||
* @param array<string, mixed> $parameters 실행 인자 배열
|
||||
* @return array{allowed: bool, reason: string|null, name: string|null, parameters: array<string, mixed>}
|
||||
*/
|
||||
private static function artisanVerdict(bool $allowed, ?string $reason = null, ?string $name = null, array $parameters = []): array
|
||||
{
|
||||
return ['allowed' => $allowed, 'reason' => $reason, 'name' => $name, 'parameters' => $parameters];
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
Reference in new issue
Block a user