fix(security): 스케줄러 Shell/Artisan 명령 실행 하드닝

미출시 예약 작업 기능에서 스케줄 권한만 위임받은 계정이 Shell/Artisan
명령으로 임의 코드를 실행할 수 있던 문제를 선제적으로 차단(KVE-2026-1567).
Shell 은 기본 차단 + 실행 파일 화이트리스트 + 셸 미경유 인자배열 실행,
Artisan 은 차단목록. 저장 시점(FormRequest)과 실행 시점(Service) 이중 검증.

아울러 공개 release 보다 앞선 미출시 버전들의 CHANGELOG 출시 날짜를
2026-07-14 로 통일.
This commit is contained in:
HeuJung committed 2026-07-14 14:48:33 +09:00
1 parent 4c73db2e91
commit ce8e55b390
23 files changed
+957 -25

No files matched your search

@@ -6,6 +6,8 @@ use App\Enums\ExtensionOwnerType;
use App\Enums\ScheduleFrequency;
use App\Enums\ScheduleType;
use App\Extension\HookManager;
use App\Rules\AllowedArtisanCommand;
use App\Rules\AllowedShellCommand;
use App\Rules\PublicOutboundUrl;
use Illuminate\Contracts\Validation\ValidationRule;
use Illuminate\Foundation\Http\FormRequest;
@@ -38,7 +40,8 @@ class CreateScheduleRequest extends FormRequest
'name' => 'required|string|max:255',
'description' => 'nullable|string|max:1000',
'type' => "required|string|in:{$types}",
// URL 호출 스케줄이면 command 가 곧 서버의 outbound 목적지가 되므로 내부망 주소를 차단한다
// command 는 타입별로 서버의 outbound 목적지(URL)·OS 명령(Shell)·PHP 코드(Artisan)가 되므로
// 각 타입에 맞는 실행 허용 검증을 저장 시점에 건다
'command' => [
'required',
'string',
@@ -47,6 +50,14 @@ class CreateScheduleRequest extends FormRequest
$this->input('type') === ScheduleType::Url->value,
[new PublicOutboundUrl],
),
Rule::when(
$this->input('type') === ScheduleType::Shell->value,
[new AllowedShellCommand],
),
Rule::when(
$this->input('type') === ScheduleType::Artisan->value,
[new AllowedArtisanCommand],
),
],
'expression' => 'required|string|max:100',
'frequency' => "required|string|in:{$frequencies}",
@@ -7,6 +7,8 @@ use App\Enums\ScheduleFrequency;
use App\Enums\ScheduleType;
use App\Extension\HookManager;
use App\Models\Schedule;
use App\Rules\AllowedArtisanCommand;
use App\Rules\AllowedShellCommand;
use App\Rules\PublicOutboundUrl;
use Illuminate\Contracts\Validation\ValidationRule;
use Illuminate\Foundation\Http\FormRequest;
@@ -38,13 +40,16 @@ class UpdateScheduleRequest extends FormRequest
'name' => 'sometimes|required|string|max:255',
'description' => 'nullable|string|max:1000',
'type' => "sometimes|required|string|in:{$types}",
// URL 호출 스케줄이면 command 가 곧 서버의 outbound 목적지가 되므로 내부망 주소를 차단한다
// command 는 타입별로 서버의 outbound 목적지(URL)·OS 명령(Shell)·PHP 코드(Artisan)가 되므로
// 각 타입에 맞는 실행 허용 검증을 저장 시점에 건다
'command' => [
'sometimes',
'required',
'string',
'max:2000',
Rule::when($this->resolvesToUrlSchedule(), [new PublicOutboundUrl]),
Rule::when($this->resolvesToScheduleType(ScheduleType::Url), [new PublicOutboundUrl]),
Rule::when($this->resolvesToScheduleType(ScheduleType::Shell), [new AllowedShellCommand]),
Rule::when($this->resolvesToScheduleType(ScheduleType::Artisan), [new AllowedArtisanCommand]),
],
'expression' => 'sometimes|required|string|max:100',
'frequency' => "sometimes|required|string|in:{$frequencies}",
@@ -61,22 +66,23 @@ class UpdateScheduleRequest extends FormRequest
}
/**
* 이번 수정 결과 URL 호출 스케줄이 되는지 판정합니다.
* 이번 수정 결과 스케줄이 주어진 타입이 되는지 판정합니다.
*
* PATCH 라 `type` 이 요청에 없을 수 있으므로, 없으면 저장된 스케줄의 타입을 기준으로
* 판정한다 — 그렇지 않으면 기존 url 스케줄의 command 만 바꾸는 요청이 검증을 비껴간다.
* 판정한다 — 그렇지 않으면 기존 스케줄의 command 만 바꾸는 요청이 검증을 비껴간다.
*
* @return bool URL 호출 스케줄이면 true
* @param ScheduleType $type 판정할 스케줄 타입
* @return bool 해당 타입의 스케줄이면 true
*/
protected function resolvesToUrlSchedule(): bool
protected function resolvesToScheduleType(ScheduleType $type): bool
{
if ($this->has('type')) {
return $this->input('type') === ScheduleType::Url->value;
return $this->input('type') === $type->value;
}
$schedule = $this->route('schedule');
return $schedule instanceof Schedule && $schedule->type === ScheduleType::Url;
return $schedule instanceof Schedule && $schedule->type === $type;
}
/**
+41
View File
@@ -0,0 +1,41 @@
<?php
namespace App\Rules;
use App\Support\ScheduleCommandValidator;
use Closure;
use Illuminate\Contracts\Validation\ValidationRule;
/**
* Artisan 타입 스케줄의 command 가 차단목록에 걸리지 않는지 검증하는 Custom Rule.
*
* `tinker` 처럼 임의 PHP 코드를 실행하거나 `db:wipe` 처럼 파괴적인 명령을 스케줄로 등록하는 것을
* 저장 시점에 차단한다. 차단목록은 `config/schedule_security.php` 가 소유하며 관리자 환경설정에
* 노출되지 않는다.
*/
class AllowedArtisanCommand implements ValidationRule
{
/**
* 값이 실행 허용된 artisan 명령인지 검증합니다.
*
* @param string $attribute 검증 대상 필드명
* @param mixed $value 검증 대상 값
* @param Closure $fail 실패 콜백
*/
public function validate(string $attribute, mixed $value, Closure $fail): void
{
if ($value === null || $value === '') {
return;
}
if (! is_string($value)) {
$fail(__('validation.schedule_command.artisan_denied'));
return;
}
if (! ScheduleCommandValidator::isArtisanCommandAllowed($value)) {
$fail(__('validation.schedule_command.artisan_denied'));
}
}
}
+41
View File
@@ -0,0 +1,41 @@
<?php
namespace App\Rules;
use App\Support\ScheduleCommandValidator;
use Closure;
use Illuminate\Contracts\Validation\ValidationRule;
/**
* Shell 타입 스케줄의 command 가 실행 허용된 명령인지 검증하는 Custom Rule.
*
* 스케줄 생성 권한만 위임받은 계정이 임의 OS 명령을 서버에서 실행하는 것을 저장 시점에 차단한다.
* 허용 여부는 `config/schedule_security.php` 의 opt-in 게이트와 실행 파일 화이트리스트가 결정하며,
* 관리자 환경설정에 노출되지 않으므로 위임 관리자가 스스로 범위를 넓힐 수 없다.
*/
class AllowedShellCommand implements ValidationRule
{
/**
* 값이 실행 허용된 shell 명령인지 검증합니다.
*
* @param string $attribute 검증 대상 필드명
* @param mixed $value 검증 대상 값
* @param Closure $fail 실패 콜백
*/
public function validate(string $attribute, mixed $value, Closure $fail): void
{
if ($value === null || $value === '') {
return;
}
if (! is_string($value)) {
$fail(__('validation.schedule_command.shell_not_allowed'));
return;
}
if (! ScheduleCommandValidator::isShellCommandAllowed($value)) {
$fail(__('validation.schedule_command.shell_not_allowed'));
}
}
}
+29 -7
View File
@@ -11,8 +11,8 @@ use App\Extension\HookManager;
use App\Models\Schedule;
use App\Models\ScheduleHistory;
use App\Support\OutboundUrlValidator;
use App\Support\ScheduleCommandValidator;
use Exception;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\DB;
@@ -207,10 +207,13 @@ class ScheduleService
'output' => $result['output'] ?? null,
]);
// 스케줄 상태 업데이트
// 스케줄 상태 업데이트 (다음 실행 시각은 모델이 계산, 영속화는 Repository 경유)
$schedule->last_result = ScheduleResultStatus::Success;
$schedule->calculateNextRunAt();
$schedule->save();
$this->scheduleRepository->update($schedule, [
'last_result' => ScheduleResultStatus::Success,
'next_run_at' => $schedule->next_run_at,
]);
// after_run 훅 실행
HookManager::doAction('core.schedule.after_run', $schedule, $history);
@@ -226,10 +229,13 @@ class ScheduleService
'error_output' => $e->getMessage(),
]);
// 스케줄 상태 업데이트
// 스케줄 상태 업데이트 (다음 실행 시각은 모델이 계산, 영속화는 Repository 경유)
$schedule->last_result = ScheduleResultStatus::Failed;
$schedule->calculateNextRunAt();
$schedule->save();
$this->scheduleRepository->update($schedule, [
'last_result' => ScheduleResultStatus::Failed,
'next_run_at' => $schedule->next_run_at,
]);
Log::error('Schedule execution failed', [
'schedule_id' => $schedule->id,
@@ -247,10 +253,16 @@ class ScheduleService
*
* @param Schedule $schedule 스케줄
* @return array 실행 결과
*
* @throws Exception 차단목록에 걸린 명령일 때
*/
private function executeArtisanCommand(Schedule $schedule): array
{
$output = '';
// 저장 시점 검증 도입 이전 데이터나 DB 직접 수정으로 들어온 값을 방어한다
// (isUrlCallAllowed 와 동일 사유 — 실행 직전이 마지막 방어선).
if (! ScheduleCommandValidator::isArtisanCommandAllowed($schedule->command)) {
throw new Exception(__('schedule.artisan_not_allowed'));
}
Artisan::call($schedule->command, [], new BufferedOutput);
@@ -270,9 +282,19 @@ class ScheduleService
*/
private function executeShellCommand(Schedule $schedule): array
{
// 저장 시점 검증 도입 이전 데이터나 DB 직접 수정으로 들어온 값을 방어한다
// (isUrlCallAllowed 와 동일 사유 — 실행 직전이 마지막 방어선).
$arguments = ScheduleCommandValidator::tokenizeShellCommand($schedule->command);
if ($arguments === null || ! ScheduleCommandValidator::isShellCommandAllowed($schedule->command)) {
throw new Exception(__('schedule.shell_not_allowed'));
}
$timeout = $schedule->timeout ?? 60;
$result = Process::timeout($timeout)->run($schedule->command);
// 문자열이 아닌 인자 배열로 넘겨 `/bin/sh -c` 를 경유하지 않는다 —
// 파이프·`;`·`$()` 같은 셸 메타문자가 명령으로 해석될 여지를 없앤다.
$result = Process::timeout($timeout)->run($arguments);
if ($result->failed()) {
throw new Exception($result->errorOutput() ?: __('schedule.shell_command_failed'), $result->exitCode());
+149
View File
@@ -0,0 +1,149 @@
<?php
namespace App\Support;
/**
* 스케줄 Shell/Artisan command 가 실행 가능한 안전 명령인지 판정하는 순수 유틸.
*
* 스케줄 command 는 저장된 문자열이 그대로 서버에서 실행되는 값이므로, 스케줄 생성 권한을
* 위임받은 계정이 임의 OS 명령·임의 PHP 코드를 실행하는 통로가 될 수 있다(권한 상승형 RCE).
* 본 유틸은 두 축의 판정을 제공한다:
*
* 1. Shell — 기본 차단. `config/schedule_security.php` 의 opt-in 게이트가 켜져 있고,
* 셸 메타문자가 없으며, 첫 토큰의 basename 이 허용 실행 파일 목록과 완전 일치할 때만 허용.
* 허용되더라도 호출부는 `tokenizeShellCommand()` 로 얻은 인자 배열로 실행해야 한다
* (`/bin/sh -c` 를 경유하지 않으므로 파이프·`;`·`$()` 가 무력화된다).
*
* 2. Artisan — 기본 허용, 차단목록만 거부. `tinker` 처럼 임의 PHP 코드를 실행하거나
* `db:wipe` 처럼 파괴적인 명령을 스케줄로 실행하지 못하게 막는다.
*
* 예외를 던지지 않고 bool/배열만 반환한다 — 차단 시 어떤 응답/예외를 낼지는 호출부가 결정한다.
*/
class ScheduleCommandValidator
{
/** 셸 해석을 유발하는 메타문자 — 하나라도 있으면 인자 배열 실행이 불가하므로 거부 */
private const SHELL_METACHARACTERS = [
'|', '&', ';', '$', '`', '>', '<', '(', ')', '{', '}',
'*', '?', '!', '\\', '"', "'", "\n", "\r", "\t",
];
/**
* Shell 타입 command 를 실행해도 되는지 판정합니다.
*
* 게이트가 켜져 있고, 화이트리스트가 비어있지 않으며, 메타문자가 없고,
* 첫 토큰의 basename 이 화이트리스트와 완전 일치할 때만 true.
*
* @param string $command 스케줄에 저장된 shell command 문자열
* @return bool 실행을 허용하면 true
*/
public static function isShellCommandAllowed(string $command): bool
{
if (! (bool) config('schedule_security.shell.enabled', false)) {
return false;
}
$allowed = array_values(array_filter(array_map(
static fn ($binary): string => trim((string) $binary),
(array) config('schedule_security.shell.allowed_binaries', []),
)));
if ($allowed === []) {
return false;
}
$tokens = self::tokenize($command);
if ($tokens === null || $tokens === []) {
return false;
}
return in_array(basename($tokens[0]), $allowed, true);
}
/**
* Shell command 를 `Process::run(array)` 에 넘길 안전한 인자 배열로 변환합니다.
*
* 메타문자가 섞여 있으면 셸 미경유 실행이 불가하므로 null 을 반환한다.
*
* @param string $command 스케줄에 저장된 shell command 문자열
* @return array<int, string>|null 인자 배열, 안전하게 토큰화할 수 없으면 null
*/
public static function tokenizeShellCommand(string $command): ?array
{
return self::tokenize($command);
}
/**
* Artisan command 문자열에서 명령명(첫 토큰)을 추출합니다.
*
* @param string $command 스케줄에 저장된 artisan command 문자열
* @return string|null 명령명, 빈 문자열이면 null
*/
public static function extractArtisanCommandName(string $command): ?string
{
$trimmed = trim($command);
if ($trimmed === '') {
return null;
}
$tokens = preg_split('/\s+/', $trimmed);
return ($tokens === false || $tokens === []) ? null : $tokens[0];
}
/**
* Artisan command 가 차단목록에 걸리지 않는지 판정합니다.
*
* @param string $command 스케줄에 저장된 artisan command 문자열
* @return bool 실행을 허용하면 true
*/
public static function isArtisanCommandAllowed(string $command): bool
{
$name = self::extractArtisanCommandName($command);
if ($name === null) {
return false;
}
$denylist = array_map(
static fn ($denied): string => strtolower(trim((string) $denied)),
(array) config('schedule_security.artisan.denylist', []),
);
return ! in_array(strtolower($name), $denylist, true);
}
/**
* 메타문자 없는 공백 구분 토큰화. 메타문자가 있으면 null 을 반환합니다.
*
* 따옴표 escape 처리 버그를 원천 회피하기 위해, 따옴표를 포함한 복잡한 명령은
* 지원하지 않고 거부하는 보수적 구현이다(복합 명령은 래퍼 스크립트로 유도).
*
* @param string $command command 문자열
* @return array<int, string>|null 토큰 배열, 안전하지 않으면 null
*/
private static function tokenize(string $command): ?array
{
$command = trim($command);
if ($command === '') {
return null;
}
// 제어문자(개행 포함)가 섞인 명령은 즉시 거부
if (preg_match('/[\x00-\x1F\x7F]/', $command) === 1) {
return null;
}
foreach (self::SHELL_METACHARACTERS as $meta) {
if (str_contains($command, $meta)) {
return null;
}
}
$tokens = preg_split('/\s+/', $command);
return ($tokens === false || $tokens === []) ? null : $tokens;
}
}