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
@@ -0,0 +1,279 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Unit\Installer;
|
||||
|
||||
use PHPUnit\Framework\Attributes\DataProvider;
|
||||
use PHPUnit\Framework\Attributes\Test;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
|
||||
/**
|
||||
* 인스톨러 실행 바이너리 경로 정책 테스트 (KVE-2026-1677).
|
||||
*
|
||||
* 정책 파일은 의존성이 없어야 한다 — 인스톨러 API(라이브러리 모드)와 설치 워커 양쪽에서
|
||||
* 단독으로 `require_once` 되므로, 이 테스트도 BASE_PATH·lang 스텁 없이 파일만 로드한다.
|
||||
* 로드에 다른 것이 필요해지면 이 테스트가 먼저 깨진다.
|
||||
*
|
||||
* 판정 축:
|
||||
* - 인자 자리 차단 (하이픈 선두 · 인터프리터+임의 스크립트)
|
||||
* - 자리별 비대칭 (PHP 자리는 이름 무제한 / Composer 자리는 이름 형태 제한)
|
||||
* - stat 미사용 (존재하지 않는 절대경로도 형태만 맞으면 통과 — open_basedir 회귀 가드)
|
||||
*/
|
||||
class BinaryPathPolicyTest extends TestCase
|
||||
{
|
||||
public static function setUpBeforeClass(): void
|
||||
{
|
||||
require_once dirname(__DIR__, 3).'/public/install/includes/binary-path-policy.php';
|
||||
}
|
||||
|
||||
/**
|
||||
* 형태 규칙을 통과해야 하는 토큰.
|
||||
*
|
||||
* @param string $token 경로 토큰
|
||||
* @param string $reason 통과 사유 (실패 메시지용)
|
||||
*
|
||||
* @scenario vector=validatePhpPath, payload_class=normal, expected_outcome=accept_normal
|
||||
*
|
||||
* @effects legitimate_paths_still_reach_exec
|
||||
*/
|
||||
#[Test]
|
||||
#[DataProvider('shapeAllowedProvider')]
|
||||
public function it_accepts_tokens_with_a_valid_shape(string $token, string $reason): void
|
||||
{
|
||||
$this->assertTrue(
|
||||
installer_binary_path_shape_ok($token),
|
||||
"통과해야 하는 경로가 거부됨 ({$reason}): {$token}"
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 형태 규칙에 걸려야 하는 토큰.
|
||||
*
|
||||
* @param string $token 경로 토큰
|
||||
* @param string $reason 거부 사유 (실패 메시지용)
|
||||
*
|
||||
* @scenario vector=validatePhpPath, payload_class=argument_injection_dash_r, expected_outcome=return_invalid_message
|
||||
*
|
||||
* @effects leading_hyphen_token_is_rejected
|
||||
* @effects php_slot_rejects_leading_hyphen
|
||||
* @effects relative_and_traversal_paths_are_rejected
|
||||
*/
|
||||
#[Test]
|
||||
#[DataProvider('shapeRejectedProvider')]
|
||||
public function it_rejects_tokens_with_an_invalid_shape(string $token, string $reason): void
|
||||
{
|
||||
$this->assertFalse(
|
||||
installer_binary_path_shape_ok($token),
|
||||
"거부해야 하는 경로가 통과함 ({$reason}): {$token}"
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Composer 자리는 이름 형태까지 제한한다.
|
||||
*
|
||||
* @param string $token 경로 토큰
|
||||
* @param bool $expected 기대 판정
|
||||
* @param string $reason 사유 (실패 메시지용)
|
||||
*
|
||||
* @scenario vector=validateComposerPath, payload_class=interpreter_plus_script, expected_outcome=return_invalid_message
|
||||
*
|
||||
* @effects getComposerCommand_rejects_interpreter_plus_arbitrary_script
|
||||
*/
|
||||
#[Test]
|
||||
#[DataProvider('composerSlotProvider')]
|
||||
public function it_restricts_the_composer_slot_by_name(string $token, bool $expected, string $reason): void
|
||||
{
|
||||
$this->assertSame(
|
||||
$expected,
|
||||
installer_is_composer_binary_path($token),
|
||||
"Composer 자리 판정이 기대와 다름 ({$reason}): {$token}"
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* PHP 자리는 이름을 제한하지 않는다.
|
||||
*
|
||||
* 래퍼 스크립트·버전이 붙은 이름·커스텀 이름을 모두 허용해야 한다. 이 자리는
|
||||
* 인자가 `--version` 으로 고정된 실행 파일 자리라 이름 제한이 이번 공격과 무관하고,
|
||||
* 제한하면 설치 환경 다양성을 해친다.
|
||||
*
|
||||
* @param string $token PHP 실행 경로
|
||||
*
|
||||
* @scenario vector=validatePhpPath, payload_class=wrapper_script_name, expected_outcome=accept_normal
|
||||
*
|
||||
* @effects legitimate_paths_still_reach_exec
|
||||
*/
|
||||
#[Test]
|
||||
#[DataProvider('phpSlotNameProvider')]
|
||||
public function it_does_not_restrict_the_php_slot_by_name(string $token): void
|
||||
{
|
||||
$this->assertTrue(
|
||||
installer_binary_path_shape_ok($token),
|
||||
"PHP 자리 이름 제한이 생겨 정상 환경이 거부됨: {$token}"
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 2토큰 입력은 자리별 규칙을 모두 만족할 때만 해석된다.
|
||||
*
|
||||
* @param string $raw 원본 입력
|
||||
* @param array{php: string, composer: string}|null $expected 기대 해석 결과
|
||||
* @param string $reason 사유 (실패 메시지용)
|
||||
*
|
||||
* @scenario vector=validateComposerPath, payload_class=argument_injection_dash_r, expected_outcome=return_invalid_message
|
||||
*
|
||||
* @effects argument_injection_never_reaches_exec
|
||||
* @effects getComposerCommand_keeps_multi_php_pair_support
|
||||
*/
|
||||
#[Test]
|
||||
#[DataProvider('pairProvider')]
|
||||
public function it_resolves_only_well_formed_php_composer_pairs(string $raw, ?array $expected, string $reason): void
|
||||
{
|
||||
$this->assertSame(
|
||||
$expected,
|
||||
installer_resolve_php_composer_pair($raw),
|
||||
"2토큰 해석이 기대와 다름 ({$reason}): {$raw}"
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 파일 시스템 stat 에 의존하지 않는다 (open_basedir 회귀 가드).
|
||||
*
|
||||
* `#361` 은 `is_file()`/`is_executable()` 가드가 시놀로지 DSM 등에서 정상 절대경로를
|
||||
* false negative 로 거부하는 회귀를 되돌린 이력이다. 존재하지 않는 절대경로가
|
||||
* 형태 검사만으로 통과해야 그 회귀가 구조적으로 재발하지 않는다.
|
||||
*
|
||||
* @scenario vector=getPhpBinary, payload_class=normal, expected_outcome=accept_normal
|
||||
*
|
||||
* @effects getPhpBinary_passes_through_legitimate_paths
|
||||
*/
|
||||
#[Test]
|
||||
public function it_does_not_depend_on_filesystem_stat(): void
|
||||
{
|
||||
$missing = '/usr/local/php99/bin/php';
|
||||
|
||||
$this->assertFileDoesNotExist($missing);
|
||||
$this->assertTrue(installer_binary_path_shape_ok($missing));
|
||||
$this->assertTrue(installer_is_composer_binary_path('/usr/local/php99/bin/composer'));
|
||||
}
|
||||
|
||||
/**
|
||||
* 통과해야 하는 토큰 목록.
|
||||
*
|
||||
* @return array<string, array{string, string}>
|
||||
*/
|
||||
public static function shapeAllowedProvider(): array
|
||||
{
|
||||
return [
|
||||
'bare php' => ['php', '시스템 기본'],
|
||||
'bare composer' => ['composer', '시스템 기본'],
|
||||
'POSIX 절대경로' => ['/usr/bin/php', '일반 설치'],
|
||||
'버전 붙은 이름' => ['/usr/bin/php8.3', '멀티 PHP'],
|
||||
'Plesk 경로' => ['/opt/plesk/php/8.2/bin/php', '패널 환경'],
|
||||
'Windows 드라이브' => ['C:\\php\\php.exe', 'Windows'],
|
||||
'Windows 슬래시' => ['C:/php/php.exe', 'Windows 정방향 슬래시'],
|
||||
'UNC 경로' => ['\\\\server\\share\\php.exe', '네트워크 공유'],
|
||||
'점 포함 디렉토리' => ['/usr/local/php.d/bin/php', '단일 점은 상위 참조가 아님'],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 거부해야 하는 토큰 목록.
|
||||
*
|
||||
* @return array<string, array{string, string}>
|
||||
*/
|
||||
public static function shapeRejectedProvider(): array
|
||||
{
|
||||
return [
|
||||
'빈 문자열' => ['', '입력 없음'],
|
||||
'하이픈 선두 (-r)' => ['-rphpinfo();', '코드 실행 플래그 — 이번 취약점'],
|
||||
'하이픈 선두 (-d)' => ['-dauto_prepend_file=/tmp/x', 'ini 주입'],
|
||||
'롱옵션' => ['--define=x', '옵션'],
|
||||
'상대경로' => ['bin/composer', 'CWD 의존'],
|
||||
'단순 이름' => ['evilbinary', 'bare 허용은 php/composer 뿐'],
|
||||
'부모 참조' => ['/usr/local/../../tmp/composer', '.. 세그먼트'],
|
||||
'부모 참조 (윈도우 구분자)' => ['C:\\php\\..\\..\\tmp\\evil.exe', '.. 세그먼트'],
|
||||
'해시 주석' => ['/usr/bin/php#.phar', '접미사 위장'],
|
||||
'공백 포함' => ['/usr/bin/my php', '토큰 분리 불가'],
|
||||
'세미콜론' => ['/usr/bin/php;id', '셸 메타문자'],
|
||||
'백틱' => ['/usr/bin/`id`', '셸 메타문자'],
|
||||
'달러 괄호' => ['/usr/bin/$(id)', '셸 메타문자'],
|
||||
'따옴표' => ['/usr/bin/"php"', '셸 메타문자'],
|
||||
'개행' => ["/usr/bin/php\nid", '제어문자'],
|
||||
'NUL 바이트' => ["/usr/bin/php\x00", '제어문자'],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Composer 자리 판정 목록.
|
||||
*
|
||||
* @return array<string, array{string, bool, string}>
|
||||
*/
|
||||
public static function composerSlotProvider(): array
|
||||
{
|
||||
return [
|
||||
'composer' => ['composer', true, 'bare 기본'],
|
||||
'절대경로 composer' => ['/usr/local/bin/composer', true, '일반 설치'],
|
||||
'composer2' => ['/usr/local/bin/composer2', true, '버전 붙은 이름'],
|
||||
'composer.phar' => ['/opt/composer.phar', true, 'phar 아카이브'],
|
||||
'임의 이름 phar' => ['/opt/tools/mytool.phar', true, 'phar 는 이름 무관 허용'],
|
||||
'composer.bat' => ['C:\\laragon\\bin\\composer\\composer.bat', true, 'Windows 배치'],
|
||||
'composer.exe' => ['C:\\tools\\composer.exe', true, 'Windows 실행 파일'],
|
||||
'임의 스크립트' => ['/tmp/evil.py', false, '인터프리터가 실행할 임의 스크립트 — 이번 취약점'],
|
||||
'임의 PHP 스크립트' => ['/tmp/evil.php', false, '임의 PHP 스크립트'],
|
||||
'셸 스크립트' => ['/tmp/evil.sh', false, '임의 스크립트'],
|
||||
'composer 접두 위장' => ['/tmp/composer-evil.sh', false, 'basename 완전 일치가 아님'],
|
||||
'하이픈 선두' => ['-rphpinfo();', false, '옵션'],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* PHP 자리에 허용되어야 하는 이름 목록.
|
||||
*
|
||||
* @return array<string, array{string}>
|
||||
*/
|
||||
public static function phpSlotNameProvider(): array
|
||||
{
|
||||
return [
|
||||
'래퍼 스크립트' => ['/usr/local/bin/php-8.2-wrapper.sh'],
|
||||
'커스텀 이름' => ['/opt/mycompany/run-php'],
|
||||
'버전 접미사' => ['/usr/bin/php8.3'],
|
||||
'DSM 경로' => ['/usr/local/php84/bin/php'],
|
||||
'Windows exe' => ['C:\\php\\php.exe'],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 2토큰 해석 목록.
|
||||
*
|
||||
* @return array<string, array{string, array{php: string, composer: string}|null, string}>
|
||||
*/
|
||||
public static function pairProvider(): array
|
||||
{
|
||||
return [
|
||||
'멀티 PHP 정상' => [
|
||||
'/usr/local/php84/bin/php /usr/local/bin/composer.phar',
|
||||
['php' => '/usr/local/php84/bin/php', 'composer' => '/usr/local/bin/composer.phar'],
|
||||
'운영 패턴',
|
||||
],
|
||||
'래퍼 + composer' => [
|
||||
'/usr/local/bin/php-8.2-wrapper.sh /usr/local/bin/composer',
|
||||
['php' => '/usr/local/bin/php-8.2-wrapper.sh', 'composer' => '/usr/local/bin/composer'],
|
||||
'PHP 자리 이름 무제한',
|
||||
],
|
||||
'Windows 2토큰' => [
|
||||
'C:\\php\\php.exe D:\\composer\\composer.phar',
|
||||
['php' => 'C:\\php\\php.exe', 'composer' => 'D:\\composer\\composer.phar'],
|
||||
'Windows',
|
||||
],
|
||||
'인자 주입 (-r)' => ['/usr/bin/php -rphpinfo();', null, '둘째 토큰이 코드 실행 플래그'],
|
||||
'인터프리터 + 스크립트' => ['/usr/bin/python3 /tmp/evil.py', null, '둘째 토큰이 임의 스크립트'],
|
||||
'PHP 자리 옵션' => ['-rphpinfo(); /usr/bin/composer', null, '첫 토큰이 옵션'],
|
||||
'공백 없음' => ['/usr/bin/composer', null, '2토큰 입력이 아님'],
|
||||
'공백 포함 디렉토리' => [
|
||||
'C:\\Program Files\\PHP\\php.exe C:\\composer\\composer.phar',
|
||||
null,
|
||||
'#361 이 명시한 기존 known_limitation — 악화가 아님',
|
||||
],
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
namespace Tests\Unit\Installer;
|
||||
|
||||
use PHPUnit\Framework\Attributes\DataProvider;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
use ReflectionClass;
|
||||
use ValidationApi;
|
||||
@@ -30,7 +31,7 @@ class ComposerPathValidationTest extends TestCase
|
||||
|
||||
// ValidationApi 는 글로벌 네임스페이스이므로 \lang() 으로 조회됨 →
|
||||
// 글로벌 스코프에 정의된 스텁이 필요.
|
||||
require_once __DIR__ . '/stubs/lang_stub.php';
|
||||
require_once __DIR__.'/stubs/lang_stub.php';
|
||||
|
||||
if (! defined('MIN_PHP_VERSION')) {
|
||||
define('MIN_PHP_VERSION', '8.2.0');
|
||||
@@ -48,14 +49,14 @@ class ComposerPathValidationTest extends TestCase
|
||||
define('BASE_PATH', $projectRoot);
|
||||
}
|
||||
if (! defined('STATE_PATH')) {
|
||||
define('STATE_PATH', BASE_PATH . '/storage/installer-state.json');
|
||||
define('STATE_PATH', BASE_PATH.'/storage/installer-state.json');
|
||||
}
|
||||
|
||||
require_once $projectRoot . '/public/install/api/check-configuration.php';
|
||||
require_once $projectRoot.'/public/install/api/check-configuration.php';
|
||||
// applyInstallerComposerEnvVars() 는 functions.php 에 정의. stat 가드 완화 회복
|
||||
// 이후 시스템 기본 'composer' 또는 정상 절대경로 입력이 exec 단계까지 도달하면서
|
||||
// 이 함수를 호출하므로 사전 로드 필요.
|
||||
require_once $projectRoot . '/public/install/includes/functions.php';
|
||||
require_once $projectRoot.'/public/install/includes/functions.php';
|
||||
self::$loaded = true;
|
||||
}
|
||||
|
||||
@@ -64,7 +65,7 @@ class ComposerPathValidationTest extends TestCase
|
||||
*/
|
||||
private function invoke(string $method, array $args): array
|
||||
{
|
||||
$api = new ValidationApi();
|
||||
$api = new ValidationApi;
|
||||
$ref = new ReflectionClass($api);
|
||||
$m = $ref->getMethod($method);
|
||||
|
||||
@@ -74,8 +75,8 @@ class ComposerPathValidationTest extends TestCase
|
||||
|
||||
public function test_composer_path_with_shell_injection_is_rejected_before_exec(): void
|
||||
{
|
||||
$marker = sys_get_temp_dir() . '/g7_kve_test_' . bin2hex(random_bytes(4));
|
||||
$payload = 'sh -c "id > ' . $marker . '"';
|
||||
$marker = sys_get_temp_dir().'/g7_kve_test_'.bin2hex(random_bytes(4));
|
||||
$payload = 'sh -c "id > '.$marker.'"';
|
||||
|
||||
$result = $this->invoke('validateComposerPath', [$payload, 'php']);
|
||||
|
||||
@@ -86,8 +87,8 @@ class ComposerPathValidationTest extends TestCase
|
||||
|
||||
public function test_composer_path_with_semicolon_injection_is_rejected(): void
|
||||
{
|
||||
$marker = sys_get_temp_dir() . '/g7_kve_test_' . bin2hex(random_bytes(4));
|
||||
$payload = '/bin/sh; touch ' . $marker;
|
||||
$marker = sys_get_temp_dir().'/g7_kve_test_'.bin2hex(random_bytes(4));
|
||||
$payload = '/bin/sh; touch '.$marker;
|
||||
|
||||
$result = $this->invoke('validateComposerPath', [$payload, 'php']);
|
||||
|
||||
@@ -112,14 +113,14 @@ class ComposerPathValidationTest extends TestCase
|
||||
|
||||
public function test_phar_path_with_invalid_php_path_is_rejected_before_exec(): void
|
||||
{
|
||||
$marker = sys_get_temp_dir() . '/g7_kve_test_' . bin2hex(random_bytes(4));
|
||||
$marker = sys_get_temp_dir().'/g7_kve_test_'.bin2hex(random_bytes(4));
|
||||
|
||||
$tmpPhar = tempnam(sys_get_temp_dir(), 'g7-fake-composer-') . '.phar';
|
||||
$tmpPhar = tempnam(sys_get_temp_dir(), 'g7-fake-composer-').'.phar';
|
||||
file_put_contents($tmpPhar, '');
|
||||
chmod($tmpPhar, 0755);
|
||||
|
||||
try {
|
||||
$payload = 'sh -c "id > ' . $marker . '"';
|
||||
$payload = 'sh -c "id > '.$marker.'"';
|
||||
$result = $this->invoke('validateComposerPath', [$tmpPhar, $payload]);
|
||||
|
||||
$this->assertFalse($result['valid']);
|
||||
@@ -131,8 +132,8 @@ class ComposerPathValidationTest extends TestCase
|
||||
|
||||
public function test_php_path_with_shell_injection_is_rejected_before_exec(): void
|
||||
{
|
||||
$marker = sys_get_temp_dir() . '/g7_kve_test_' . bin2hex(random_bytes(4));
|
||||
$payload = 'sh -c "id > ' . $marker . '"';
|
||||
$marker = sys_get_temp_dir().'/g7_kve_test_'.bin2hex(random_bytes(4));
|
||||
$payload = 'sh -c "id > '.$marker.'"';
|
||||
|
||||
$result = $this->invoke('validatePhpPath', [$payload]);
|
||||
|
||||
@@ -161,4 +162,171 @@ class ComposerPathValidationTest extends TestCase
|
||||
// shell injection 메시지 패턴이 들어가지 않는지 확인.
|
||||
$this->assertIsString($result['message']);
|
||||
}
|
||||
|
||||
// ========================================================================
|
||||
// 인자 주입 (KVE-2026-1677)
|
||||
// ========================================================================
|
||||
|
||||
/**
|
||||
* 둘째 토큰이 임의 스크립트면 exec 에 도달하지 않는다.
|
||||
*
|
||||
* KVE-2026-1677 의 실제 실행 경로다. escapeshellarg 는 "이 문자열이 하나의 인자" 임만
|
||||
* 보장할 뿐, 그 인자가 실행 파일인지 인터프리터가 실행할 스크립트인지는 보장하지 않는다.
|
||||
* 기존 문자 블랙리스트는 `-` `(` `)` `.` `/` 를 모두 허용해 인자 자리를 열어 두었다.
|
||||
*
|
||||
* 실측 근거: 명령 끝에 붙는 ` --version` 은 스크립트 인자로 넘어갈 뿐이라
|
||||
* `php <스크립트> --version` 은 그 스크립트를 그대로 실행한다. 실행되면 마커가
|
||||
* 만들어지므로 마커 부재가 곧 미도달의 증거다.
|
||||
*
|
||||
* @scenario vector=validateComposerPath, payload_class=interpreter_plus_script
|
||||
*
|
||||
* @effects argument_injection_never_reaches_exec
|
||||
*/
|
||||
public function test_interpreter_with_arbitrary_script_never_reaches_exec(): void
|
||||
{
|
||||
$marker = $this->argumentInjectionMarkerPath();
|
||||
@unlink($marker);
|
||||
|
||||
// 실행 파일 자리에는 이 환경에 실제로 존재하는 PHP 를 쓴다 — 검증을 통과하면
|
||||
// 실제로 실행되므로 "환경에 없어서 실패" 로 초록이 되는 가짜 통과를 배제한다.
|
||||
$script = sys_get_temp_dir().DIRECTORY_SEPARATOR.'g7i527_evil.php';
|
||||
file_put_contents(
|
||||
$script,
|
||||
'<?php file_put_contents('.var_export($marker, true).", '1');"
|
||||
);
|
||||
|
||||
try {
|
||||
$result = $this->invoke('validateComposerPath', [PHP_BINARY.' '.$script, 'php']);
|
||||
|
||||
$this->assertFalse($result['valid'], '인자 자리에 임의 스크립트를 넣은 입력이 유효로 판정됨');
|
||||
$this->assertFileDoesNotExist($marker, '페이로드가 exec 에 도달해 임의 스크립트가 실행됨');
|
||||
} finally {
|
||||
@unlink($marker);
|
||||
@unlink($script);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 둘째 토큰이 코드 실행 플래그면 형태 검사에서 거부된다.
|
||||
*
|
||||
* 이 호출 지점은 명령 끝에 ` --version` 을 붙이는데, PHP CLI 는 `--version` 을 만나면
|
||||
* 버전만 출력하고 종료하므로 `-r` 코드가 실행되지 않는다(실측 확인). 즉 여기서는
|
||||
* 실행까지 가지 않지만, ` --version` 을 붙이지 않는 호출 지점(설치 워커의 실제 명령
|
||||
* 실행)에서는 그대로 실행된다. 따라서 자리 자체를 닫아 두 지점을 같은 규칙으로 막는다.
|
||||
*
|
||||
* @scenario vector=validateComposerPath, payload_class=argument_injection_dash_r
|
||||
*
|
||||
* @effects leading_hyphen_token_is_rejected
|
||||
*/
|
||||
public function test_leading_hyphen_token_is_rejected_in_the_argument_slot(): void
|
||||
{
|
||||
$result = $this->invoke('validateComposerPath', [PHP_BINARY.' -rphpinfo();', 'php']);
|
||||
|
||||
$this->assertFalse($result['valid'], '하이픈 선두 인자가 유효로 판정됨');
|
||||
}
|
||||
|
||||
/**
|
||||
* PHP 자리(첫 토큰·단일 토큰)에도 하이픈 선두 토큰은 올 수 없다.
|
||||
*
|
||||
* @scenario vector=validatePhpPath, payload_class=argument_injection_dash_r
|
||||
*
|
||||
* @effects php_slot_rejects_leading_hyphen
|
||||
*/
|
||||
public function test_php_path_rejects_leading_hyphen_token(): void
|
||||
{
|
||||
$result = $this->invoke('validatePhpPath', ['-rphpinfo();']);
|
||||
|
||||
$this->assertFalse($result['valid']);
|
||||
}
|
||||
|
||||
/**
|
||||
* 상대경로·`..` 세그먼트는 거부된다 (CWD 의존 실행 차단).
|
||||
*
|
||||
* @param string $payload 거부되어야 하는 경로
|
||||
* @param string $reason 거부 사유 (실패 메시지용)
|
||||
*
|
||||
* @scenario vector=validateComposerPath, payload_class=relative_path
|
||||
*
|
||||
* @effects relative_and_traversal_paths_are_rejected
|
||||
*/
|
||||
#[DataProvider('rejectedShapeProvider')]
|
||||
public function test_rejects_paths_outside_the_allowed_shape(string $payload, string $reason): void
|
||||
{
|
||||
$result = $this->invoke('validateComposerPath', [$payload, 'php']);
|
||||
|
||||
$this->assertFalse($result['valid'], "거부되어야 하는 입력이 통과함 ({$reason}): {$payload}");
|
||||
}
|
||||
|
||||
/**
|
||||
* 정상 입력은 계속 통과한다 (stat 미사용 — open_basedir 환경 회귀 가드).
|
||||
*
|
||||
* 존재하지 않는 절대경로도 사전 거부되지 않고 exec 까지 도달해야 한다. `#361` 이
|
||||
* `is_file()`/`is_executable()` 가드로 시놀로지 DSM 등에서 정상 경로를 false negative
|
||||
* 로 거부한 회귀를 되돌린 이력이 있다.
|
||||
*
|
||||
* @param string $payload 통과해야 하는 경로
|
||||
* @param string $reason 통과 사유 (실패 메시지용)
|
||||
*
|
||||
* @scenario vector=validateComposerPath, payload_class=wrapper_script_name
|
||||
*
|
||||
* @effects legitimate_paths_still_reach_exec
|
||||
*/
|
||||
#[DataProvider('acceptedShapeProvider')]
|
||||
public function test_legitimate_paths_are_not_rejected_before_exec(string $payload, string $reason): void
|
||||
{
|
||||
$result = $this->invoke('validateComposerPath', [$payload, 'php']);
|
||||
|
||||
// 실행 결과는 환경 의존이므로 "사전 거부 메시지" 가 아닌지로 판정한다.
|
||||
$this->assertStringNotContainsString(
|
||||
'not_allowed',
|
||||
(string) $result['message'],
|
||||
"정상 입력이 형태 검사에서 사전 거부됨 ({$reason}): {$payload}"
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 형태 규칙에 걸려야 하는 입력 목록.
|
||||
*
|
||||
* @return array<string, array{string, string}>
|
||||
*/
|
||||
public static function rejectedShapeProvider(): array
|
||||
{
|
||||
return [
|
||||
'상대경로' => ['bin/composer', 'bare 명령이 아닌 상대경로'],
|
||||
'부모 참조' => ['/usr/local/../../tmp/composer', '.. 세그먼트'],
|
||||
'해시 주석 위장' => ['-rphpinfo()#.phar', '# + 하이픈 선두'],
|
||||
'인터프리터 + 스크립트' => ['/usr/bin/python3 /tmp/evil.py', 'Composer 자리 형태 위반'],
|
||||
'Composer 자리 임의 이름' => ['/usr/bin/php /tmp/evil.sh', 'composer 계열도 .phar 도 아님'],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 형태 규칙을 통과해야 하는 정상 입력 목록.
|
||||
*
|
||||
* @return array<string, array{string, string}>
|
||||
*/
|
||||
public static function acceptedShapeProvider(): array
|
||||
{
|
||||
return [
|
||||
'bare composer' => ['composer', '시스템 기본'],
|
||||
'절대경로 composer' => ['/usr/local/bin/composer', '일반 설치'],
|
||||
'버전 붙은 이름' => ['/usr/local/bin/composer2', 'composer 계열'],
|
||||
'phar' => ['/opt/composer.phar', 'phar 아카이브'],
|
||||
'Windows bat' => ['C:\\laragon\\bin\\composer\\composer.bat', 'Windows 배치'],
|
||||
'존재하지 않는 절대경로' => ['/usr/local/php99/bin/composer', 'stat 미사용 회귀 가드'],
|
||||
'2토큰 멀티 PHP' => ['/usr/local/php84/bin/php /usr/local/bin/composer.phar', '멀티 PHP 운영 패턴'],
|
||||
'래퍼 스크립트 PHP' => ['/usr/local/bin/php-8.2-wrapper.sh /usr/local/bin/composer.phar', 'PHP 자리 이름 무제한'],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 인자 주입 페이로드가 실행되었을 때 만들어지는 마커 경로.
|
||||
*
|
||||
* 페이로드에는 따옴표를 넣을 수 없어(셸 메타문자 차단) 같은 경로를 `chr()` 연결로
|
||||
* 조립한다. 두 값이 어긋나면 증명이 성립하지 않으므로 여기서 한 번만 정의한다.
|
||||
*/
|
||||
private function argumentInjectionMarkerPath(): string
|
||||
{
|
||||
return sys_get_temp_dir().chr(47).chr(103).chr(55).chr(105).chr(53).chr(50).chr(55);
|
||||
}
|
||||
}
|
||||
@@ -19,7 +19,9 @@ use ValidationApi;
|
||||
class InstallerSecurityHardeningTest extends TestCase
|
||||
{
|
||||
private static bool $loaded = false;
|
||||
|
||||
private static string $tempBase = '';
|
||||
|
||||
private static string $skipReason = '';
|
||||
|
||||
public static function setUpBeforeClass(): void
|
||||
@@ -28,7 +30,7 @@ class InstallerSecurityHardeningTest extends TestCase
|
||||
return;
|
||||
}
|
||||
|
||||
require_once __DIR__ . '/stubs/lang_stub.php';
|
||||
require_once __DIR__.'/stubs/lang_stub.php';
|
||||
|
||||
if (! defined('MIN_PHP_VERSION')) {
|
||||
define('MIN_PHP_VERSION', '8.2.0');
|
||||
@@ -45,11 +47,11 @@ class InstallerSecurityHardeningTest extends TestCase
|
||||
define('BASE_PATH', $projectRoot);
|
||||
}
|
||||
// STATE_PATH 는 테스트 격리용 임시 경로로 분리 — 운영 storage/installer-state.json 미오염.
|
||||
self::$tempBase = sys_get_temp_dir() . '/g7-installer-hardening-' . bin2hex(random_bytes(4));
|
||||
@mkdir(self::$tempBase . '/storage/app', 0755, true);
|
||||
self::$tempBase = sys_get_temp_dir().'/g7-installer-hardening-'.bin2hex(random_bytes(4));
|
||||
@mkdir(self::$tempBase.'/storage/app', 0755, true);
|
||||
|
||||
if (! defined('STATE_PATH')) {
|
||||
define('STATE_PATH', self::$tempBase . '/storage/installer-state.json');
|
||||
define('STATE_PATH', self::$tempBase.'/storage/installer-state.json');
|
||||
}
|
||||
|
||||
// 안전 가드: STATE_PATH 는 PHP 상수라 한 프로세스에서 단 한 번만 정의된다.
|
||||
@@ -59,18 +61,18 @@ class InstallerSecurityHardeningTest extends TestCase
|
||||
$tempPrefix = realpath(sys_get_temp_dir()) ?: sys_get_temp_dir();
|
||||
$resolvedState = realpath(dirname((string) STATE_PATH)) ?: dirname((string) STATE_PATH);
|
||||
if (strpos($resolvedState, $tempPrefix) !== 0) {
|
||||
self::$skipReason = 'STATE_PATH (' . STATE_PATH . ') 가 시스템 temp 하위가 아님 — '
|
||||
. '다른 Installer 테스트의 상수 정의가 선행됨. 실제 installer-state.json 파괴 방지를 위해 skip. '
|
||||
. '격리 실행: php vendor/bin/phpunit --filter=InstallerSecurityHardeningTest';
|
||||
self::$skipReason = 'STATE_PATH ('.STATE_PATH.') 가 시스템 temp 하위가 아님 — '
|
||||
.'다른 Installer 테스트의 상수 정의가 선행됨. 실제 installer-state.json 파괴 방지를 위해 skip. '
|
||||
.'격리 실행: php vendor/bin/phpunit --filter=InstallerSecurityHardeningTest';
|
||||
self::$loaded = true;
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
require_once $projectRoot . '/public/install/api/check-configuration.php';
|
||||
require_once $projectRoot . '/public/install/includes/installer-state.php';
|
||||
require_once $projectRoot . '/public/install/includes/functions.php';
|
||||
require_once $projectRoot . '/public/install/includes/task-runner.php';
|
||||
require_once $projectRoot.'/public/install/api/check-configuration.php';
|
||||
require_once $projectRoot.'/public/install/includes/installer-state.php';
|
||||
require_once $projectRoot.'/public/install/includes/functions.php';
|
||||
require_once $projectRoot.'/public/install/includes/task-runner.php';
|
||||
|
||||
self::$loaded = true;
|
||||
}
|
||||
@@ -88,6 +90,7 @@ class InstallerSecurityHardeningTest extends TestCase
|
||||
{
|
||||
$ref = new ReflectionClass($obj);
|
||||
$m = $ref->getMethod($method);
|
||||
|
||||
return $m->invokeArgs($obj, $args);
|
||||
}
|
||||
|
||||
@@ -123,7 +126,7 @@ class InstallerSecurityHardeningTest extends TestCase
|
||||
// Critical-1 — getComposerCommand 공백 분기 RCE 차단
|
||||
// ========================================================================
|
||||
|
||||
public function test_getComposerCommand_rejects_space_containing_input_falls_back_to_composer(): void
|
||||
public function test_get_composer_command_rejects_space_containing_input_falls_back_to_composer(): void
|
||||
{
|
||||
$this->writeState(['composer_binary' => 'sh -c "id > /tmp/g7_should_not_run"']);
|
||||
|
||||
@@ -133,7 +136,7 @@ class InstallerSecurityHardeningTest extends TestCase
|
||||
$this->clearState();
|
||||
}
|
||||
|
||||
public function test_getComposerCommand_rejects_shell_metachars_falls_back_to_composer(): void
|
||||
public function test_get_composer_command_rejects_shell_metachars_falls_back_to_composer(): void
|
||||
{
|
||||
foreach ([
|
||||
'/bin/sh; touch /tmp/x',
|
||||
@@ -149,7 +152,7 @@ class InstallerSecurityHardeningTest extends TestCase
|
||||
$this->clearState();
|
||||
}
|
||||
|
||||
public function test_getComposerCommand_passes_through_safe_absolute_path(): void
|
||||
public function test_get_composer_command_passes_through_safe_absolute_path(): void
|
||||
{
|
||||
// open_basedir 같은 PHP 런타임 제약 환경의 false negative 를 피하기 위해
|
||||
// stat 의존 가드가 제거됨. 메타문자 없는 단일 절대경로는 escape 후 그대로 사용.
|
||||
@@ -162,7 +165,7 @@ class InstallerSecurityHardeningTest extends TestCase
|
||||
$this->clearState();
|
||||
}
|
||||
|
||||
public function test_getComposerCommand_empty_returns_default(): void
|
||||
public function test_get_composer_command_empty_returns_default(): void
|
||||
{
|
||||
$this->writeState(['composer_binary' => '']);
|
||||
|
||||
@@ -170,7 +173,7 @@ class InstallerSecurityHardeningTest extends TestCase
|
||||
$this->clearState();
|
||||
}
|
||||
|
||||
public function test_getComposerCommandForDisplay_does_not_leak_shell_payload(): void
|
||||
public function test_get_composer_command_for_display_does_not_leak_shell_payload(): void
|
||||
{
|
||||
$this->writeState(['composer_binary' => 'rm -rf /']);
|
||||
|
||||
@@ -181,15 +184,15 @@ class InstallerSecurityHardeningTest extends TestCase
|
||||
$this->clearState();
|
||||
}
|
||||
|
||||
public function test_isInstallerExecutablePath_rejects_metachars(): void
|
||||
public function test_is_installer_executable_path_rejects_metachars(): void
|
||||
{
|
||||
// 백슬래시는 Windows 경로 구분자이므로 차단 대상 아님 (escapeshellarg 가 셸 인젝션 차단)
|
||||
foreach (['foo bar', 'a;b', 'a`b', 'a$b', 'a|b', "a\nb", 'a"b', "a'b", "a\0b", "a\x01b", "a\rb"] as $bad) {
|
||||
$this->assertFalse(isInstallerExecutablePath($bad), "메타문자 거부: " . bin2hex($bad));
|
||||
$this->assertFalse(isInstallerExecutablePath($bad), '메타문자 거부: '.bin2hex($bad));
|
||||
}
|
||||
}
|
||||
|
||||
public function test_isInstallerExecutablePath_accepts_windows_paths(): void
|
||||
public function test_is_installer_executable_path_accepts_windows_paths(): void
|
||||
{
|
||||
// Windows 절대경로는 백슬래시 포함이지만 공백·메타문자 없으면 통과.
|
||||
// 공백 포함 디렉토리(예: 'C:\\Program Files\\...') 는 공백 분리 입력 형식의 토큰
|
||||
@@ -204,7 +207,7 @@ class InstallerSecurityHardeningTest extends TestCase
|
||||
}
|
||||
}
|
||||
|
||||
public function test_isInstallerExecutablePath_rejects_windows_path_with_space_known_limitation(): void
|
||||
public function test_is_installer_executable_path_rejects_windows_path_with_space_known_limitation(): void
|
||||
{
|
||||
// 'C:\\Program Files\\...' 같은 공백 포함 Windows 경로는 본 회복 범위 외.
|
||||
// 공백 분리 입력(PHP + Composer 합성) 형식 휴리스틱과 충돌 — escapeshellarg 단일 토큰
|
||||
@@ -221,7 +224,7 @@ class InstallerSecurityHardeningTest extends TestCase
|
||||
* stat 가드가 제거되어 시놀로지 DSM 등 open_basedir 환경에서도
|
||||
* 정상 절대경로 입력이 통과해야 함. 실제 실행 가능 여부는 exec 결과로 판정.
|
||||
*/
|
||||
public function test_isInstallerExecutablePath_accepts_safe_absolute_path_without_stat(): void
|
||||
public function test_is_installer_executable_path_accepts_safe_absolute_path_without_stat(): void
|
||||
{
|
||||
// 실제로 존재하지 않는 경로지만 메타문자 없음 — stat 가드 제거로 true
|
||||
$this->assertTrue(isInstallerExecutablePath('/usr/local/bin/php83'));
|
||||
@@ -233,7 +236,7 @@ class InstallerSecurityHardeningTest extends TestCase
|
||||
// Composer 공백 분리 입력 안전 복원 — 멀티 PHP 환경 호환성
|
||||
// ========================================================================
|
||||
|
||||
public function test_getComposerCommand_accepts_php_composer_space_separated_input(): void
|
||||
public function test_get_composer_command_accepts_php_composer_space_separated_input(): void
|
||||
{
|
||||
// 시놀로지/cPanel/Plesk 멀티 PHP 환경의 운영 패턴
|
||||
$this->writeState(['composer_binary' => '/usr/local/bin/php83 /usr/local/bin/composer']);
|
||||
@@ -241,12 +244,12 @@ class InstallerSecurityHardeningTest extends TestCase
|
||||
$cmd = getComposerCommand();
|
||||
|
||||
// 두 토큰 각각 escapeshellarg 적용 후 공백으로 합성
|
||||
$expected = escapeshellarg('/usr/local/bin/php83') . ' ' . escapeshellarg('/usr/local/bin/composer');
|
||||
$expected = escapeshellarg('/usr/local/bin/php83').' '.escapeshellarg('/usr/local/bin/composer');
|
||||
$this->assertSame($expected, $cmd);
|
||||
$this->clearState();
|
||||
}
|
||||
|
||||
public function test_getComposerCommand_rejects_space_separated_with_metachar_in_first_token(): void
|
||||
public function test_get_composer_command_rejects_space_separated_with_metachar_in_first_token(): void
|
||||
{
|
||||
// 첫 토큰에 메타문자 → 거부, composer 폴백
|
||||
$this->writeState(['composer_binary' => '/usr/local/bin/php$(id) /usr/local/bin/composer']);
|
||||
@@ -257,7 +260,7 @@ class InstallerSecurityHardeningTest extends TestCase
|
||||
$this->clearState();
|
||||
}
|
||||
|
||||
public function test_getComposerCommand_rejects_space_separated_with_metachar_in_second_token(): void
|
||||
public function test_get_composer_command_rejects_space_separated_with_metachar_in_second_token(): void
|
||||
{
|
||||
// 두 번째 토큰에 메타문자 → 거부, composer 폴백
|
||||
$this->writeState(['composer_binary' => '/usr/local/bin/php83 /usr/local/bin/composer;id']);
|
||||
@@ -268,7 +271,7 @@ class InstallerSecurityHardeningTest extends TestCase
|
||||
$this->clearState();
|
||||
}
|
||||
|
||||
public function test_getComposerCommand_rejects_three_or_more_tokens(): void
|
||||
public function test_get_composer_command_rejects_three_or_more_tokens(): void
|
||||
{
|
||||
// 3 토큰 이상은 두 번째 토큰에 공백이 남음 → 두 번째 토큰의 메타문자(공백) 로 거부
|
||||
$this->writeState(['composer_binary' => '/bin/php /bin/composer extra_arg']);
|
||||
@@ -279,7 +282,7 @@ class InstallerSecurityHardeningTest extends TestCase
|
||||
$this->clearState();
|
||||
}
|
||||
|
||||
public function test_getComposerCommandForDisplay_shows_human_friendly_space_separated_form(): void
|
||||
public function test_get_composer_command_for_display_shows_human_friendly_space_separated_form(): void
|
||||
{
|
||||
$this->writeState(['composer_binary' => '/usr/local/bin/php83 /usr/local/bin/composer']);
|
||||
|
||||
@@ -290,7 +293,7 @@ class InstallerSecurityHardeningTest extends TestCase
|
||||
$this->clearState();
|
||||
}
|
||||
|
||||
public function test_getComposerCommandForDisplay_does_not_leak_shell_payload_in_space_separated(): void
|
||||
public function test_get_composer_command_for_display_does_not_leak_shell_payload_in_space_separated(): void
|
||||
{
|
||||
// 두 토큰 중 하나라도 메타문자 포함이면 display 도 composer 폴백
|
||||
$this->writeState(['composer_binary' => '/bin/php `id`']);
|
||||
@@ -306,9 +309,9 @@ class InstallerSecurityHardeningTest extends TestCase
|
||||
// validatePhpPath / validateComposerPath stat 가드 완화 (인스톨러 검증 API)
|
||||
// ========================================================================
|
||||
|
||||
public function test_validatePhpPath_rejects_shell_metachars(): void
|
||||
public function test_validate_php_path_rejects_shell_metachars(): void
|
||||
{
|
||||
$api = new ValidationApi();
|
||||
$api = new ValidationApi;
|
||||
foreach ([
|
||||
'/usr/local/bin/php; id',
|
||||
'/usr/local/bin/php$(id)',
|
||||
@@ -321,28 +324,28 @@ class InstallerSecurityHardeningTest extends TestCase
|
||||
}
|
||||
}
|
||||
|
||||
public function test_validatePhpPath_rejects_empty(): void
|
||||
public function test_validate_php_path_rejects_empty(): void
|
||||
{
|
||||
$api = new ValidationApi();
|
||||
$api = new ValidationApi;
|
||||
$result = $this->invokePrivate($api, 'validatePhpPath', ['']);
|
||||
$this->assertFalse($result['valid']);
|
||||
}
|
||||
|
||||
public function test_validatePhpPath_safe_path_reaches_exec_phase(): void
|
||||
public function test_validate_php_path_safe_path_reaches_exec_phase(): void
|
||||
{
|
||||
// 메타문자 없는 절대경로는 stat 가드 없이 exec 단계까지 도달.
|
||||
// 존재하지 않으면 exec 실패 (return code != 0) 로 거부 — 단, 거부 메시지는
|
||||
// 'error_php_exec_failed' 로 stat 거부와 동일. 핵심: stat 가드가 사라졌다는 점.
|
||||
$api = new ValidationApi();
|
||||
$api = new ValidationApi;
|
||||
$result = $this->invokePrivate($api, 'validatePhpPath', ['/nonexistent/path/to/php']);
|
||||
|
||||
// 실제 실행 실패로 invalid 이지만, 그 판정이 exec 결과에 기반함을 의미적으로 검증.
|
||||
$this->assertFalse($result['valid']);
|
||||
}
|
||||
|
||||
public function test_validateComposerPath_rejects_shell_metachars(): void
|
||||
public function test_validate_composer_path_rejects_shell_metachars(): void
|
||||
{
|
||||
$api = new ValidationApi();
|
||||
$api = new ValidationApi;
|
||||
foreach ([
|
||||
'/usr/local/bin/composer; id',
|
||||
'/usr/local/bin/composer$(id)',
|
||||
@@ -354,10 +357,10 @@ class InstallerSecurityHardeningTest extends TestCase
|
||||
}
|
||||
}
|
||||
|
||||
public function test_validateComposerPath_rejects_space_separated_with_metachar(): void
|
||||
public function test_validate_composer_path_rejects_space_separated_with_metachar(): void
|
||||
{
|
||||
// 공백 분리 입력의 토큰별 메타문자 검증
|
||||
$api = new ValidationApi();
|
||||
$api = new ValidationApi;
|
||||
foreach ([
|
||||
'/bin/php$(id) /bin/composer',
|
||||
'/bin/php /bin/composer;id',
|
||||
@@ -369,23 +372,23 @@ class InstallerSecurityHardeningTest extends TestCase
|
||||
}
|
||||
}
|
||||
|
||||
public function test_splitPhpComposerTokens_helper_splits_into_two_tokens(): void
|
||||
public function test_split_php_composer_tokens_helper_splits_into_two_tokens(): void
|
||||
{
|
||||
$api = new ValidationApi();
|
||||
$api = new ValidationApi;
|
||||
$result = $this->invokePrivate($api, 'splitPhpComposerTokens', ['/usr/local/bin/php83 /usr/local/bin/composer']);
|
||||
$this->assertSame(['php' => '/usr/local/bin/php83', 'composer' => '/usr/local/bin/composer'], $result);
|
||||
}
|
||||
|
||||
public function test_splitPhpComposerTokens_helper_returns_null_for_single_token(): void
|
||||
public function test_split_php_composer_tokens_helper_returns_null_for_single_token(): void
|
||||
{
|
||||
$api = new ValidationApi();
|
||||
$api = new ValidationApi;
|
||||
$result = $this->invokePrivate($api, 'splitPhpComposerTokens', ['/usr/local/bin/composer']);
|
||||
$this->assertNull($result);
|
||||
}
|
||||
|
||||
public function test_isInstallerSafePathArg_helper_accepts_safe_paths(): void
|
||||
public function test_is_installer_safe_path_arg_helper_accepts_safe_paths(): void
|
||||
{
|
||||
$api = new ValidationApi();
|
||||
$api = new ValidationApi;
|
||||
|
||||
foreach ([
|
||||
'/usr/local/bin/php83',
|
||||
@@ -401,14 +404,14 @@ class InstallerSecurityHardeningTest extends TestCase
|
||||
}
|
||||
}
|
||||
|
||||
public function test_isInstallerSafePathArg_helper_rejects_metachars_and_empty(): void
|
||||
public function test_is_installer_safe_path_arg_helper_rejects_metachars_and_empty(): void
|
||||
{
|
||||
$api = new ValidationApi();
|
||||
$api = new ValidationApi;
|
||||
|
||||
$this->assertFalse($this->invokePrivate($api, 'isInstallerSafePathArg', ['']));
|
||||
// 백슬래시는 Windows 경로 구분자이므로 차단 대상이 아님 — 셸 인젝션 차단은 escapeshellarg 가 담당
|
||||
foreach (['foo bar', 'a;b', 'a`b', 'a$b', 'a|b', "a\nb", 'a"b', "a'b", "a\0b", "a\x01b", "a\rb"] as $bad) {
|
||||
$this->assertFalse($this->invokePrivate($api, 'isInstallerSafePathArg', [$bad]), "메타문자 거부: " . bin2hex($bad));
|
||||
$this->assertFalse($this->invokePrivate($api, 'isInstallerSafePathArg', [$bad]), '메타문자 거부: '.bin2hex($bad));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -416,7 +419,7 @@ class InstallerSecurityHardeningTest extends TestCase
|
||||
// 워커 정합 — 검증 통과한 입력이 워커에서도 silent fallback 없이 전달
|
||||
// ========================================================================
|
||||
|
||||
public function test_getComposerCommand_passes_through_single_absolute_path_without_silent_fallback(): void
|
||||
public function test_get_composer_command_passes_through_single_absolute_path_without_silent_fallback(): void
|
||||
{
|
||||
// 검증 단계에서 통과한 단일 절대경로가 워커에서도 그대로 사용됨을 보장.
|
||||
// stat 가드 제거 후 회귀 — 정상 입력이 silent fallback 으로 사라지지 않음.
|
||||
@@ -433,9 +436,9 @@ class InstallerSecurityHardeningTest extends TestCase
|
||||
// High-2 — checkCorePendingPath traversal 차단
|
||||
// ========================================================================
|
||||
|
||||
public function test_checkCorePendingPath_rejects_parent_traversal(): void
|
||||
public function test_check_core_pending_path_rejects_parent_traversal(): void
|
||||
{
|
||||
$api = new ValidationApi();
|
||||
$api = new ValidationApi;
|
||||
|
||||
foreach (['../../../etc', '..', 'foo/../bar', 'foo/..\\bar'] as $bad) {
|
||||
$_GET = ['path' => $bad];
|
||||
@@ -452,9 +455,9 @@ class InstallerSecurityHardeningTest extends TestCase
|
||||
$_GET = [];
|
||||
}
|
||||
|
||||
public function test_checkCorePendingPath_rejects_null_byte(): void
|
||||
public function test_check_core_pending_path_rejects_null_byte(): void
|
||||
{
|
||||
$api = new ValidationApi();
|
||||
$api = new ValidationApi;
|
||||
$_GET = ['path' => "valid\0../etc"];
|
||||
ob_start();
|
||||
$this->invokePrivate($api, 'checkCorePendingPath', []);
|
||||
@@ -465,10 +468,10 @@ class InstallerSecurityHardeningTest extends TestCase
|
||||
$_GET = [];
|
||||
}
|
||||
|
||||
public function test_checkCorePendingPath_returns_uniform_message_for_nonexistent(): void
|
||||
public function test_check_core_pending_path_returns_uniform_message_for_nonexistent(): void
|
||||
{
|
||||
$api = new ValidationApi();
|
||||
$_GET = ['path' => '/nonexistent/g7-test-' . bin2hex(random_bytes(4))];
|
||||
$api = new ValidationApi;
|
||||
$_GET = ['path' => '/nonexistent/g7-test-'.bin2hex(random_bytes(4))];
|
||||
ob_start();
|
||||
$this->invokePrivate($api, 'checkCorePendingPath', []);
|
||||
$body = ob_get_clean();
|
||||
@@ -484,7 +487,7 @@ class InstallerSecurityHardeningTest extends TestCase
|
||||
// Medium-1 — escapeEnvValue 개행 제거
|
||||
// ========================================================================
|
||||
|
||||
public function test_escapeEnvValue_strips_newlines(): void
|
||||
public function test_escape_env_value_strips_newlines(): void
|
||||
{
|
||||
$payload = "secret\nINJECTED=true";
|
||||
$result = escapeEnvValue($payload);
|
||||
@@ -499,21 +502,21 @@ class InstallerSecurityHardeningTest extends TestCase
|
||||
$this->assertStringEndsWith('"', $result);
|
||||
}
|
||||
|
||||
public function test_escapeEnvValue_strips_crlf(): void
|
||||
public function test_escape_env_value_strips_crlf(): void
|
||||
{
|
||||
$result = escapeEnvValue("a\r\nb");
|
||||
|
||||
$this->assertSame('"ab"', $result);
|
||||
}
|
||||
|
||||
public function test_escapeEnvValue_preserves_normal_password(): void
|
||||
public function test_escape_env_value_preserves_normal_password(): void
|
||||
{
|
||||
$result = escapeEnvValue('p@ssw0rd!#$%');
|
||||
|
||||
$this->assertSame('"p@ssw0rd!#$%"', $result);
|
||||
}
|
||||
|
||||
public function test_escapeEnvValue_escapes_quotes_and_backslashes(): void
|
||||
public function test_escape_env_value_escapes_quotes_and_backslashes(): void
|
||||
{
|
||||
$result = escapeEnvValue('a"b\\c');
|
||||
|
||||
@@ -524,7 +527,7 @@ class InstallerSecurityHardeningTest extends TestCase
|
||||
// Medium-2 — PDO DSN 파라미터 sanitize
|
||||
// ========================================================================
|
||||
|
||||
public function test_getDatabaseConnection_rejects_semicolon_in_host(): void
|
||||
public function test_get_database_connection_rejects_semicolon_in_host(): void
|
||||
{
|
||||
$this->expectException(\PDOException::class);
|
||||
|
||||
@@ -537,7 +540,7 @@ class InstallerSecurityHardeningTest extends TestCase
|
||||
], false);
|
||||
}
|
||||
|
||||
public function test_getDatabaseConnection_rejects_equals_in_database(): void
|
||||
public function test_get_database_connection_rejects_equals_in_database(): void
|
||||
{
|
||||
$this->expectException(\PDOException::class);
|
||||
|
||||
@@ -550,7 +553,7 @@ class InstallerSecurityHardeningTest extends TestCase
|
||||
], false);
|
||||
}
|
||||
|
||||
public function test_getDatabaseConnection_rejects_newline_in_port(): void
|
||||
public function test_get_database_connection_rejects_newline_in_port(): void
|
||||
{
|
||||
$this->expectException(\PDOException::class);
|
||||
|
||||
@@ -562,4 +565,102 @@ class InstallerSecurityHardeningTest extends TestCase
|
||||
'db_write_password' => '',
|
||||
], false);
|
||||
}
|
||||
|
||||
// ========================================================================
|
||||
// KVE-2026-1677 — 설치 워커의 실행 바이너리 경로
|
||||
// ========================================================================
|
||||
|
||||
/**
|
||||
* 저장된 php_binary 가 형태 규칙을 위반하면 시스템 기본값으로 폴백한다.
|
||||
*
|
||||
* 이 값은 설치 워커에서 실제 명령의 실행 바이너리가 된다(`--version` 이 붙지 않는
|
||||
* 호출 지점). 이전에는 아무 검증 없이 그대로 반환해, 저장만 되면 인자 자리가 열렸다.
|
||||
*
|
||||
* @scenario vector=getPhpBinary, payload_class=argument_injection_dash_r
|
||||
*
|
||||
* @effects getPhpBinary_falls_back_to_default_for_disallowed_shape
|
||||
*/
|
||||
public function test_get_php_binary_falls_back_to_default_for_disallowed_shape(): void
|
||||
{
|
||||
foreach ([
|
||||
'-rphpinfo();' => '코드 실행 플래그',
|
||||
'-dauto_prepend_file=/tmp/x' => 'ini 주입',
|
||||
'bin/php' => '상대경로',
|
||||
'/usr/local/../../tmp/php' => '.. 세그먼트',
|
||||
'/usr/bin/php$(id)' => '셸 메타문자',
|
||||
] as $payload => $reason) {
|
||||
$this->writeState(['php_binary' => $payload]);
|
||||
|
||||
$this->assertSame(
|
||||
'php',
|
||||
getPhpBinary(),
|
||||
"형태 위반 값이 그대로 실행 바이너리가 됨 ({$reason}): {$payload}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 정상 절대경로는 그대로 사용된다 (stat 미사용 — 존재하지 않아도 통과).
|
||||
*
|
||||
* @scenario vector=getPhpBinary, payload_class=wrapper_script_name
|
||||
*
|
||||
* @effects getPhpBinary_passes_through_legitimate_paths
|
||||
*/
|
||||
public function test_get_php_binary_passes_through_legitimate_paths(): void
|
||||
{
|
||||
foreach ([
|
||||
'/usr/local/php84/bin/php',
|
||||
'/usr/local/bin/php-8.2-wrapper.sh',
|
||||
'C:\\php\\php.exe',
|
||||
'/usr/local/php99/bin/php',
|
||||
] as $path) {
|
||||
$this->writeState(['php_binary' => $path]);
|
||||
|
||||
$this->assertSame($path, getPhpBinary(), "정상 경로가 폴백됨: {$path}");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Composer 자리에 인터프리터 + 임의 스크립트를 넣으면 기본값으로 폴백한다.
|
||||
*
|
||||
* 하이픈 선두만 막으면 `PHP경로 /tmp/올려둔파일` 형태가 남는다.
|
||||
*
|
||||
* @scenario vector=getComposerCommand, payload_class=interpreter_plus_script
|
||||
*
|
||||
* @effects getComposerCommand_rejects_interpreter_plus_arbitrary_script
|
||||
*/
|
||||
public function test_get_composer_command_rejects_interpreter_plus_arbitrary_script(): void
|
||||
{
|
||||
foreach ([
|
||||
'/usr/bin/php /tmp/evil.php',
|
||||
'/usr/bin/python3 /tmp/evil.py',
|
||||
'/usr/bin/php -rphpinfo();',
|
||||
'/usr/bin/php /tmp/composer-evil.sh',
|
||||
] as $payload) {
|
||||
$this->writeState(['composer_binary' => $payload]);
|
||||
|
||||
$this->assertSame(
|
||||
'composer',
|
||||
getComposerCommand(),
|
||||
"인자 자리에 임의 스크립트/옵션이 통과함: {$payload}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 정상 멀티 PHP 입력은 계속 두 토큰으로 실행된다 (비파괴).
|
||||
*
|
||||
* @scenario vector=getComposerCommand, payload_class=wrapper_script_name
|
||||
*
|
||||
* @effects getComposerCommand_keeps_multi_php_pair_support
|
||||
*/
|
||||
public function test_get_composer_command_keeps_multi_php_pair_support(): void
|
||||
{
|
||||
$this->writeState(['composer_binary' => '/usr/local/bin/php-8.2-wrapper.sh /usr/local/bin/composer.phar']);
|
||||
|
||||
$cmd = getComposerCommand();
|
||||
|
||||
$this->assertStringContainsString('php-8.2-wrapper.sh', $cmd);
|
||||
$this->assertStringContainsString('composer.phar', $cmd);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,165 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Unit\Installer;
|
||||
|
||||
use PHPUnit\Framework\Attributes\DataProvider;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
|
||||
/**
|
||||
* Step 3 저장 시점의 바이너리 경로 형태 강제 회귀 테스트 (KVE-2026-1677)
|
||||
*
|
||||
* `php_binary` / `composer_binary` 는 설치 워커에서 실제 명령의 실행 바이너리가 된다.
|
||||
* 실행 시점(task-runner)과 진단 시점(check-configuration)에도 같은 정책이 걸려 있지만,
|
||||
* 형태 위반 값이 애초에 `.env` / 설치 상태 파일에 기록되지 않도록 저장 시점에서도 막는다.
|
||||
* 세 지점 중 하나라도 빠지면 "저장은 되는데 실행만 폴백" 같은 어긋난 상태가 남는다.
|
||||
*
|
||||
* 본 테스트는 저장/리다이렉트 분기에 도달하지 않도록 DB 검증을 일부러 실패시켜
|
||||
* (`db_write_host` 공백) 상태 파일·세션을 건드리지 않는다. 그래서 `STATE_PATH` 를
|
||||
* 정의하지 않으며, 인접 Installer 테스트의 상수 선점과도 무관하다.
|
||||
*
|
||||
* @scenario vector=handleStep3Post, payload_class=argument_injection_dash_r, expected_outcome=return_invalid_message
|
||||
*
|
||||
* @effects step3_post_rejects_disallowed_binary_paths_before_save
|
||||
*/
|
||||
class InstallerStep3BinaryPathStoreGuardTest extends TestCase
|
||||
{
|
||||
public static function setUpBeforeClass(): void
|
||||
{
|
||||
require_once __DIR__.'/stubs/lang_stub.php';
|
||||
|
||||
$projectRoot = dirname(__DIR__, 3);
|
||||
if (! defined('BASE_PATH')) {
|
||||
define('BASE_PATH', $projectRoot);
|
||||
}
|
||||
if (! defined('SUPPORTED_LANGUAGES')) {
|
||||
define('SUPPORTED_LANGUAGES', ['ko' => '한국어', 'en' => 'English']);
|
||||
}
|
||||
|
||||
require_once $projectRoot.'/public/install/includes/functions.php';
|
||||
require_once $projectRoot.'/public/install/includes/binary-path-policy.php';
|
||||
require_once $projectRoot.'/public/install/includes/request-handler.php';
|
||||
}
|
||||
|
||||
protected function tearDown(): void
|
||||
{
|
||||
$_POST = [];
|
||||
parent::tearDown();
|
||||
}
|
||||
|
||||
/**
|
||||
* Step 3 POST 를 실행하고 에러 배열을 돌려줍니다.
|
||||
*
|
||||
* @param array<string, string> $post POST 본문 (DB 검증은 일부러 실패시킨다)
|
||||
* @return array<string, string> 에러 배열
|
||||
*/
|
||||
private function runStep3(array $post): array
|
||||
{
|
||||
// 저장/리다이렉트 분기에 도달하지 않도록 DB 검증을 실패시킨다.
|
||||
$_POST = $post + [
|
||||
'db_write_host' => '',
|
||||
'db_write_database' => '',
|
||||
'db_write_username' => '',
|
||||
'admin_email' => 'not-an-email',
|
||||
'admin_language' => 'ko',
|
||||
'admin_password' => '',
|
||||
'admin_password_confirm' => '',
|
||||
];
|
||||
|
||||
$formData = [];
|
||||
$errors = [];
|
||||
handleStep3Post('ko', $formData, $errors);
|
||||
|
||||
return $errors;
|
||||
}
|
||||
|
||||
/**
|
||||
* PHP 자리에 코드 실행 플래그를 넣으면 저장 시점에 거부된다.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function test_step3_rejects_php_binary_with_code_execution_flag(): void
|
||||
{
|
||||
$errors = $this->runStep3(['php_binary' => '-r file_put_contents("g7","x");']);
|
||||
|
||||
$this->assertArrayHasKey(
|
||||
'php_binary',
|
||||
$errors,
|
||||
'PHP 자리의 선두 하이픈 토큰이 저장 시점에 통과했다 — 형태 위반 값이 설치 상태에 기록된다'
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Composer 자리에 셸 메타문자가 있으면 저장 시점에 거부된다.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function test_step3_rejects_composer_binary_with_shell_metachars(): void
|
||||
{
|
||||
$errors = $this->runStep3(['composer_binary' => 'sh -c "id > /tmp/g7"']);
|
||||
|
||||
$this->assertArrayHasKey('composer_binary', $errors);
|
||||
}
|
||||
|
||||
/**
|
||||
* Composer 자리의 공백 분리 입력에서 둘째 토큰이 임의 스크립트면 거부된다.
|
||||
*
|
||||
* `escapeshellarg` 는 "하나의 인자" 임만 보장하므로, 인터프리터 + 임의 스크립트
|
||||
* 조합은 그 스크립트를 그대로 실행한다. 이 자리를 저장 시점에서도 닫는다.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function test_step3_rejects_interpreter_plus_arbitrary_script_pair(): void
|
||||
{
|
||||
$errors = $this->runStep3(['composer_binary' => '/usr/bin/php /tmp/evil.php']);
|
||||
|
||||
$this->assertArrayHasKey(
|
||||
'composer_binary',
|
||||
$errors,
|
||||
'Composer 자리의 둘째 토큰이 임의 스크립트인데 저장 시점에 통과했다'
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 정상 입력은 저장 시점 검증을 통과한다 (비파괴 확인).
|
||||
*
|
||||
* @param array<string, string> $post POST 본문
|
||||
* @param string $field 통과해야 하는 필드
|
||||
*
|
||||
* @scenario vector=handleStep3Post, payload_class=normal, expected_outcome=accept_normal
|
||||
*
|
||||
* @effects step3_post_accepts_legitimate_binary_paths
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
#[DataProvider('legitimateBinaryInputProvider')]
|
||||
public function test_step3_accepts_legitimate_binary_paths(array $post, string $field): void
|
||||
{
|
||||
$errors = $this->runStep3($post);
|
||||
|
||||
$this->assertArrayNotHasKey(
|
||||
$field,
|
||||
$errors,
|
||||
'정상 경로가 저장 시점에 거부됐다 — 설치가 불가능해진다: '.json_encode($post)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 저장 시점 검증을 통과해야 하는 정상 입력 목록.
|
||||
*
|
||||
* @return array<string, array{array<string, string>, string}>
|
||||
*/
|
||||
public static function legitimateBinaryInputProvider(): array
|
||||
{
|
||||
return [
|
||||
'PHP 미입력' => [[], 'php_binary'],
|
||||
'PHP 기본값' => [['php_binary' => 'php'], 'php_binary'],
|
||||
'PHP 절대경로' => [['php_binary' => '/usr/bin/php8.2'], 'php_binary'],
|
||||
'PHP Windows 절대경로' => [['php_binary' => 'C:\\php\\php.exe'], 'php_binary'],
|
||||
'Composer 미입력' => [[], 'composer_binary'],
|
||||
'Composer 기본값' => [['composer_binary' => 'composer'], 'composer_binary'],
|
||||
'Composer 절대경로' => [['composer_binary' => '/usr/local/bin/composer'], 'composer_binary'],
|
||||
'Composer phar' => [['composer_binary' => '/opt/composer.phar'], 'composer_binary'],
|
||||
'PHP+phar 쌍' => [['composer_binary' => '/usr/bin/php /opt/composer.phar'], 'composer_binary'],
|
||||
];
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user