fix(security): outbound URL 내부주소·host 검증 전수 강화
서버가 외부 입력으로 목적지가 제어되는 outbound HTTP 요청을 보내는 지점을 전수 조사해, 내부망(사설 IP·루프백·링크로컬·메타데이터)과 host 위조를 차단한다. KVE-2026-1546(이니시스 인증 URL 접두사 매칭 우회)과 동일 클래스의 지점(언어팩 URL 설치, 스케줄 URL 호출, 배송비 계산 API, GitHub URL 판정)을 코어 공용 유틸 App\Support\OutboundUrlValidator 로 수렴시켰다. - 접두사 매칭을 host 완전일치로 교체 — userinfo(@) 위장과 접미사 확장 도메인 우회 벡터 차단. - 사내 서버 호출이 정당한 관리자 지점(스케줄·외부 API)은 신규 설정 security.allow_internal_outbound_urls(기본 off)로 옵트인. - 언어팩 URL 설치는 원격 코드 다운로드라 옵트인과 무관하게 내부 주소 항상 차단. - 웹소켓 연결 테스트는 localhost·사설 IP 가 정상 구성이므로 구조적 위조만 차단. 각 지점에 red 재현 → 수정 → green 회귀 테스트 + 실브라우저 E2E 로 검증. 수기 API 문서가 자동 재생성으로 소실되는 사고를 막는 PreToolUse 훅을 함께 추가한다.
This commit is contained in:
1 parent
f848086fd6
commit
c4beb116ad
46 files changed
+1297
-55
No files matched your search
@@ -2,6 +2,8 @@
|
||||
|
||||
namespace App\Http\Requests\LanguagePack;
|
||||
|
||||
use App\Extension\HookManager;
|
||||
use App\Rules\PublicOutboundUrl;
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
|
||||
/**
|
||||
@@ -26,11 +28,15 @@ class InstallFromUrlRequest extends FormRequest
|
||||
*/
|
||||
public function rules(): array
|
||||
{
|
||||
return [
|
||||
'url' => ['required', 'url', 'max:500'],
|
||||
$rules = [
|
||||
// 원격 코드를 내려받는 지점이므로 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'],
|
||||
];
|
||||
|
||||
// 모듈/플러그인이 validation rules 를 동적으로 추가할 수 있도록 훅 제공
|
||||
return HookManager::applyFilters('core.language_packs.install_from_url_validation_rules', $rules, $this);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -6,13 +6,18 @@ use App\Enums\ExtensionOwnerType;
|
||||
use App\Enums\ScheduleFrequency;
|
||||
use App\Enums\ScheduleType;
|
||||
use App\Extension\HookManager;
|
||||
use App\Rules\PublicOutboundUrl;
|
||||
use Illuminate\Contracts\Validation\ValidationRule;
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Illuminate\Validation\Rule;
|
||||
|
||||
class CreateScheduleRequest extends FormRequest
|
||||
{
|
||||
/**
|
||||
* Determine if the user is authorized to make this request.
|
||||
*
|
||||
* @return bool 권한 검사는 라우트의 permission 미들웨어가 담당하므로 항상 true
|
||||
*/
|
||||
public function authorize(): bool
|
||||
{
|
||||
@@ -22,7 +27,7 @@ class CreateScheduleRequest extends FormRequest
|
||||
/**
|
||||
* Get the validation rules that apply to the request.
|
||||
*
|
||||
* @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
|
||||
* @return array<string, ValidationRule|array<mixed>|string>
|
||||
*/
|
||||
public function rules(): array
|
||||
{
|
||||
@@ -33,7 +38,16 @@ class CreateScheduleRequest extends FormRequest
|
||||
'name' => 'required|string|max:255',
|
||||
'description' => 'nullable|string|max:1000',
|
||||
'type' => "required|string|in:{$types}",
|
||||
'command' => 'required|string|max:2000',
|
||||
// URL 호출 스케줄이면 command 가 곧 서버의 outbound 목적지가 되므로 내부망 주소를 차단한다
|
||||
'command' => [
|
||||
'required',
|
||||
'string',
|
||||
'max:2000',
|
||||
Rule::when(
|
||||
$this->input('type') === ScheduleType::Url->value,
|
||||
[new PublicOutboundUrl],
|
||||
),
|
||||
],
|
||||
'expression' => 'required|string|max:100',
|
||||
'frequency' => "required|string|in:{$frequencies}",
|
||||
'without_overlapping' => 'boolean',
|
||||
@@ -86,7 +100,9 @@ class CreateScheduleRequest extends FormRequest
|
||||
}
|
||||
|
||||
/**
|
||||
* 검증된 데이터 반환
|
||||
* 검증된 데이터에 생성자(created_by)를 덧붙여 반환합니다.
|
||||
*
|
||||
* @return array<string, mixed> 검증된 입력 + created_by
|
||||
*/
|
||||
public function validatedWithCreator(): array
|
||||
{
|
||||
|
||||
@@ -6,12 +6,18 @@ use App\Enums\ExtensionOwnerType;
|
||||
use App\Enums\ScheduleFrequency;
|
||||
use App\Enums\ScheduleType;
|
||||
use App\Extension\HookManager;
|
||||
use App\Models\Schedule;
|
||||
use App\Rules\PublicOutboundUrl;
|
||||
use Illuminate\Contracts\Validation\ValidationRule;
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
use Illuminate\Validation\Rule;
|
||||
|
||||
class UpdateScheduleRequest extends FormRequest
|
||||
{
|
||||
/**
|
||||
* Determine if the user is authorized to make this request.
|
||||
*
|
||||
* @return bool 권한 검사는 라우트의 permission 미들웨어가 담당하므로 항상 true
|
||||
*/
|
||||
public function authorize(): bool
|
||||
{
|
||||
@@ -21,7 +27,7 @@ class UpdateScheduleRequest extends FormRequest
|
||||
/**
|
||||
* Get the validation rules that apply to the request.
|
||||
*
|
||||
* @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
|
||||
* @return array<string, ValidationRule|array<mixed>|string>
|
||||
*/
|
||||
public function rules(): array
|
||||
{
|
||||
@@ -32,7 +38,14 @@ class UpdateScheduleRequest extends FormRequest
|
||||
'name' => 'sometimes|required|string|max:255',
|
||||
'description' => 'nullable|string|max:1000',
|
||||
'type' => "sometimes|required|string|in:{$types}",
|
||||
'command' => 'sometimes|required|string|max:2000',
|
||||
// URL 호출 스케줄이면 command 가 곧 서버의 outbound 목적지가 되므로 내부망 주소를 차단한다
|
||||
'command' => [
|
||||
'sometimes',
|
||||
'required',
|
||||
'string',
|
||||
'max:2000',
|
||||
Rule::when($this->resolvesToUrlSchedule(), [new PublicOutboundUrl]),
|
||||
],
|
||||
'expression' => 'sometimes|required|string|max:100',
|
||||
'frequency' => "sometimes|required|string|in:{$frequencies}",
|
||||
'without_overlapping' => 'boolean',
|
||||
@@ -47,6 +60,25 @@ class UpdateScheduleRequest extends FormRequest
|
||||
return HookManager::applyFilters('core.schedule.update_validation_rules', $rules, $this);
|
||||
}
|
||||
|
||||
/**
|
||||
* 이번 수정 결과 URL 호출 스케줄이 되는지 판정합니다.
|
||||
*
|
||||
* PATCH 라 `type` 이 요청에 없을 수 있으므로, 없으면 저장된 스케줄의 타입을 기준으로
|
||||
* 판정한다 — 그렇지 않으면 기존 url 스케줄의 command 만 바꾸는 요청이 검증을 비껴간다.
|
||||
*
|
||||
* @return bool URL 호출 스케줄이면 true
|
||||
*/
|
||||
protected function resolvesToUrlSchedule(): bool
|
||||
{
|
||||
if ($this->has('type')) {
|
||||
return $this->input('type') === ScheduleType::Url->value;
|
||||
}
|
||||
|
||||
$schedule = $this->route('schedule');
|
||||
|
||||
return $schedule instanceof Schedule && $schedule->type === ScheduleType::Url;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get custom messages for validator errors.
|
||||
*
|
||||
|
||||
@@ -231,6 +231,8 @@ class SaveSettingsRequest extends FormRequest
|
||||
'security.auth_token_lifetime' => $this->getSecurityTabAuthTokenRules($tab),
|
||||
'security.max_login_attempts' => ['nullable', 'integer', 'min:0', 'max:100'],
|
||||
'security.login_lockout_time' => ['nullable', 'integer', 'min:0', 'max:1440'],
|
||||
// 신규 설정이므로 미전송(기존 클라이언트)을 허용한다 — 미전송 시 기본값 false 유지
|
||||
'security.allow_internal_outbound_urls' => ['nullable', 'boolean'],
|
||||
|
||||
// 캐시 설정 (advanced 탭)
|
||||
'advanced.cache_enabled' => $this->getTabRules($tab, 'advanced', 'boolean'),
|
||||
@@ -614,6 +616,7 @@ class SaveSettingsRequest extends FormRequest
|
||||
'security.auth_token_lifetime.integer' => __('validation.settings.auth_token_lifetime_integer'),
|
||||
'security.auth_token_lifetime.min' => __('validation.settings.auth_token_lifetime_min'),
|
||||
'security.auth_token_lifetime.max' => __('validation.settings.auth_token_lifetime_max'),
|
||||
'security.allow_internal_outbound_urls.boolean' => __('validation.settings.allow_internal_outbound_urls_boolean'),
|
||||
'security.max_login_attempts.integer' => __('validation.settings.max_login_attempts_integer'),
|
||||
'security.max_login_attempts.min' => __('validation.settings.max_login_attempts_min'),
|
||||
'security.max_login_attempts.max' => __('validation.settings.max_login_attempts_max'),
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
<?php
|
||||
|
||||
namespace App\Rules;
|
||||
|
||||
use App\Support\OutboundUrlValidator;
|
||||
use Closure;
|
||||
use Illuminate\Contracts\Validation\ValidationRule;
|
||||
|
||||
/**
|
||||
* 서버가 대신 호출하게 될 URL 이 내부망을 가리키지 않는지 검증하는 Custom Rule.
|
||||
*
|
||||
* 외부 API 엔드포인트·스케줄 URL 처럼 저장된 값이 나중에 서버의 outbound 요청 목적지가
|
||||
* 되는 입력에 적용한다. 사설/루프백/링크로컬 IP 와 내부 도메인을 입력 시점에 차단해,
|
||||
* 서버가 내부망 정찰 도구로 쓰이는 것을 막는다(SSRF).
|
||||
*
|
||||
* 사내 서버를 호출하는 것이 정당한 용도(외부 API 연동, 스케줄 URL 호출)에 한해, 관리자
|
||||
* 환경설정의 `security.allow_internal_outbound_urls` 로 내부 주소를 허용할 수 있다.
|
||||
* 원격 코드(언어팩 ZIP 등)를 내려받는 지점은 `allowInternalOptIn: false` 로 두어 이
|
||||
* 설정과 무관하게 항상 차단한다.
|
||||
*/
|
||||
class PublicOutboundUrl implements ValidationRule
|
||||
{
|
||||
/**
|
||||
* @param array<int, string> $schemes 허용 scheme (기본 http/https — 사내 API 는 http 인 경우가 있다)
|
||||
* @param bool $allowInternalOptIn 관리자 설정으로 내부 주소를 허용할 수 있는 지점인지 (기본 true)
|
||||
*/
|
||||
public function __construct(
|
||||
private readonly array $schemes = ['http', 'https'],
|
||||
private readonly bool $allowInternalOptIn = true,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* 값이 공개 인터넷 URL 인지 검증합니다.
|
||||
*
|
||||
* @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.outbound_url.invalid'));
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$options = ['schemes' => $this->schemes];
|
||||
|
||||
// 내부 주소 허용이 켜져 있으면 구조 검증(scheme/userinfo)만 하고 내부망 차단은 건너뛴다
|
||||
if ($this->allowInternalOptIn && (bool) g7_core_settings('security.allow_internal_outbound_urls', false)) {
|
||||
if (! OutboundUrlValidator::isStructurallySafeUrl($value, $options)) {
|
||||
$fail(__('validation.outbound_url.invalid'));
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if (! OutboundUrlValidator::isPublicHttpUrl($value, $options)) {
|
||||
$fail(__('validation.outbound_url.internal_not_allowed'));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2,8 +2,13 @@
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Support\OutboundUrlValidator;
|
||||
use Aws\S3\Exception\S3Exception;
|
||||
use Aws\S3\S3Client;
|
||||
use Illuminate\Http\Client\ConnectionException;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Predis\Client;
|
||||
|
||||
/**
|
||||
* 드라이버 연결 테스트 서비스
|
||||
@@ -89,7 +94,7 @@ class DriverConnectionTester
|
||||
}
|
||||
|
||||
// AWS SDK가 설치되어 있는지 확인
|
||||
if (! class_exists(\Aws\S3\S3Client::class)) {
|
||||
if (! class_exists(S3Client::class)) {
|
||||
return [
|
||||
'success' => false,
|
||||
'message' => __('settings.s3_sdk_missing'),
|
||||
@@ -98,7 +103,7 @@ class DriverConnectionTester
|
||||
|
||||
$startTime = microtime(true);
|
||||
|
||||
$client = new \Aws\S3\S3Client([
|
||||
$client = new S3Client([
|
||||
'version' => 'latest',
|
||||
'region' => $region,
|
||||
'credentials' => [
|
||||
@@ -121,7 +126,7 @@ class DriverConnectionTester
|
||||
'message' => __('settings.s3_test_success'),
|
||||
'latency' => $latency.'ms',
|
||||
];
|
||||
} catch (\Aws\S3\Exception\S3Exception $e) {
|
||||
} catch (S3Exception $e) {
|
||||
$errorMessage = match ($e->getAwsErrorCode()) {
|
||||
'NoSuchBucket' => __('settings.s3_bucket_not_found'),
|
||||
'AccessDenied' => __('settings.s3_access_denied'),
|
||||
@@ -165,7 +170,7 @@ class DriverConnectionTester
|
||||
// PHP Redis 확장 확인
|
||||
if (! extension_loaded('redis')) {
|
||||
// Predis 사용 시도
|
||||
if (! class_exists(\Predis\Client::class)) {
|
||||
if (! class_exists(Client::class)) {
|
||||
return [
|
||||
'success' => false,
|
||||
'message' => __('settings.redis_extension_missing'),
|
||||
@@ -177,7 +182,7 @@ class DriverConnectionTester
|
||||
|
||||
$startTime = microtime(true);
|
||||
|
||||
$redis = new \Redis();
|
||||
$redis = new \Redis;
|
||||
$connected = @$redis->connect($host, $port, 3.0);
|
||||
|
||||
if (! $connected) {
|
||||
@@ -259,7 +264,7 @@ class DriverConnectionTester
|
||||
$options['password'] = $password;
|
||||
}
|
||||
|
||||
$client = new \Predis\Client($options);
|
||||
$client = new Client($options);
|
||||
$pong = $client->ping();
|
||||
|
||||
if ($pong->getPayload() !== 'PONG') {
|
||||
@@ -307,7 +312,7 @@ class DriverConnectionTester
|
||||
|
||||
$startTime = microtime(true);
|
||||
|
||||
$memcached = new \Memcached();
|
||||
$memcached = new \Memcached;
|
||||
$memcached->setOption(\Memcached::OPT_CONNECT_TIMEOUT, 3000);
|
||||
$memcached->addServer($host, $port);
|
||||
|
||||
@@ -376,6 +381,17 @@ class DriverConnectionTester
|
||||
// Reverb 서버 상태 확인 (기본 HTTP 엔드포인트)
|
||||
$url = sprintf('%s://%s:%d', $scheme, $host, $port);
|
||||
|
||||
// Reverb 는 통상 localhost·사내 IP 에서 동작하므로 사설 주소 자체는 정상 구성이다.
|
||||
// 다만 이 진단 요청을 임의 목적지 탐색에 전용하지 못하도록, 정상 설정에서는 나올 수
|
||||
// 없는 값(userinfo 위장, http/https 이외 scheme, 제어문자 주입)은 거부한다.
|
||||
if (! OutboundUrlValidator::isStructurallySafeUrl($url, ['schemes' => ['http', 'https']])) {
|
||||
return [
|
||||
'success' => false,
|
||||
'message' => __('settings.websocket_test_failed'),
|
||||
'error' => __('settings.websocket_invalid_host'),
|
||||
];
|
||||
}
|
||||
|
||||
$startTime = microtime(true);
|
||||
|
||||
// HTTP 요청으로 서버 응답 확인
|
||||
@@ -402,7 +418,7 @@ class DriverConnectionTester
|
||||
'message' => __('settings.websocket_test_failed'),
|
||||
'error' => "HTTP {$response->status()}",
|
||||
];
|
||||
} catch (\Illuminate\Http\Client\ConnectionException $e) {
|
||||
} catch (ConnectionException $e) {
|
||||
return [
|
||||
'success' => false,
|
||||
'message' => __('settings.websocket_connection_refused'),
|
||||
|
||||
@@ -6,6 +6,7 @@ use App\Contracts\Extension\CacheInterface;
|
||||
use App\Contracts\Repositories\LanguagePackRepositoryInterface;
|
||||
use App\Enums\LanguagePackScope;
|
||||
use App\Enums\LanguagePackStatus;
|
||||
use App\Exceptions\LanguagePackOperationException;
|
||||
use App\Exceptions\LanguagePackSlotConflictException;
|
||||
use App\Extension\Helpers\ExtensionBackupHelper;
|
||||
use App\Extension\Helpers\GithubHelper;
|
||||
@@ -16,6 +17,7 @@ use App\Models\LanguagePack;
|
||||
use App\Services\LanguagePack\LanguagePackBaseLocales;
|
||||
use App\Services\LanguagePack\LanguagePackManifestValidator;
|
||||
use App\Services\LanguagePack\LanguagePackRegistry;
|
||||
use App\Support\OutboundUrlValidator;
|
||||
use Illuminate\Http\UploadedFile;
|
||||
use Illuminate\Pagination\LengthAwarePaginator;
|
||||
use Illuminate\Pagination\Paginator;
|
||||
@@ -25,7 +27,6 @@ use Illuminate\Support\Facades\File;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Illuminate\Support\Str;
|
||||
use App\Exceptions\LanguagePackOperationException;
|
||||
use RuntimeException;
|
||||
use Throwable;
|
||||
|
||||
@@ -340,7 +341,6 @@ class LanguagePackService
|
||||
*
|
||||
* @param LanguagePack $pack 가상 행
|
||||
* @param array<string, mixed> $filters 필터
|
||||
* @return bool
|
||||
*/
|
||||
private function matchesBuiltInFilters(LanguagePack $pack, array $filters): bool
|
||||
{
|
||||
@@ -600,7 +600,7 @@ class LanguagePackService
|
||||
ZipInstallHelper::extractZip($zipPath, $extractPath);
|
||||
|
||||
return $this->finalizeInstall($extractPath, 'zip', $file->getClientOriginalName(), $autoActivate, $installedBy);
|
||||
} catch (\Throwable $e) {
|
||||
} catch (Throwable $e) {
|
||||
$this->cleanupPending($extractPath);
|
||||
throw $e;
|
||||
}
|
||||
@@ -632,7 +632,7 @@ class LanguagePackService
|
||||
ZipInstallHelper::extractZip($zipPath, $extractPath);
|
||||
|
||||
return $this->finalizeInstall($extractPath, 'github', $githubUrl, $autoActivate, $installedBy, $force);
|
||||
} catch (\Throwable $e) {
|
||||
} catch (Throwable $e) {
|
||||
$this->cleanupPending($extractPath);
|
||||
File::deleteDirectory($tempPath);
|
||||
throw $e;
|
||||
@@ -653,6 +653,11 @@ class LanguagePackService
|
||||
*/
|
||||
public function installFromUrl(string $url, ?string $checksum, bool $autoActivate = false, ?int $installedBy = null, bool $force = false): LanguagePack
|
||||
{
|
||||
// 서버가 이 URL 을 대신 내려받으므로, 내부 네트워크 주소가 목적지가 되지 않도록 차단한다.
|
||||
if (! OutboundUrlValidator::isPublicHttpUrl($url)) {
|
||||
throw new LanguagePackOperationException('language_packs.errors.download_url_not_public');
|
||||
}
|
||||
|
||||
$this->assertInstallDirectoriesWritable();
|
||||
|
||||
$tempId = (string) Str::uuid();
|
||||
@@ -679,7 +684,7 @@ class LanguagePackService
|
||||
ZipInstallHelper::extractZip($zipPath, $extractPath);
|
||||
|
||||
return $this->finalizeInstall($extractPath, 'url', $url, $autoActivate, $installedBy, $force);
|
||||
} catch (\Throwable $e) {
|
||||
} catch (Throwable $e) {
|
||||
$this->cleanupPending($extractPath);
|
||||
File::deleteDirectory($tempPath);
|
||||
throw $e;
|
||||
@@ -718,7 +723,7 @@ class LanguagePackService
|
||||
File::copyDirectory($bundledPath, $extractPath);
|
||||
|
||||
return $this->finalizeInstall($extractPath, 'bundled', $identifier, $autoActivate, $installedBy, $force);
|
||||
} catch (\Throwable $e) {
|
||||
} catch (Throwable $e) {
|
||||
$this->cleanupPending($extractPath);
|
||||
throw $e;
|
||||
}
|
||||
@@ -901,6 +906,7 @@ class LanguagePackService
|
||||
$pack = $this->repository->findById((int) $id);
|
||||
if (! $pack) {
|
||||
$failed[] = ['id' => $id, 'reason' => 'not_found'];
|
||||
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
@@ -955,7 +961,6 @@ class LanguagePackService
|
||||
*
|
||||
* @param LanguagePack $pack 대상 언어팩
|
||||
* @param bool $cascade 코어 제거 시 하위(module/plugin/template) 동일 locale 팩도 함께 제거
|
||||
* @return void
|
||||
*/
|
||||
public function uninstall(LanguagePack $pack, bool $cascade = false): void
|
||||
{
|
||||
@@ -1000,7 +1005,6 @@ class LanguagePackService
|
||||
* 슬롯 비활성화 후 다음 후보를 active 로 승격합니다.
|
||||
*
|
||||
* @param LanguagePack $pack 방금 비활성화된 언어팩
|
||||
* @return void
|
||||
*/
|
||||
private function promoteSlotSuccessor(LanguagePack $pack): void
|
||||
{
|
||||
@@ -1056,7 +1060,6 @@ class LanguagePackService
|
||||
*
|
||||
* @param string $packageRoot 패키지 루트 디렉토리
|
||||
* @param array<string, mixed> $manifest manifest 데이터
|
||||
* @return void
|
||||
*
|
||||
* @throws RuntimeException 보안 위반 발견 시
|
||||
*/
|
||||
@@ -1103,7 +1106,6 @@ class LanguagePackService
|
||||
* 모듈/플러그인/템플릿 install 과 동일 수준의 가드 — 권한 부족 시 chmod 안내 메시지가
|
||||
* 포함된 `RuntimeException` 을 던집니다. 컨트롤러는 본 예외를 422 응답으로 변환합니다.
|
||||
*
|
||||
* @return void
|
||||
*
|
||||
* @throws RuntimeException 디렉토리 미존재/쓰기 불가 시
|
||||
*/
|
||||
@@ -1126,7 +1128,6 @@ class LanguagePackService
|
||||
* 의존성 검증 — depends_on_core_locale 이 true 면 코어 언어팩 active 여부 확인.
|
||||
*
|
||||
* @param array<string, mixed> $manifest manifest 데이터
|
||||
* @return void
|
||||
*
|
||||
* @throws RuntimeException 의존성 미충족 시
|
||||
*/
|
||||
@@ -1146,7 +1147,6 @@ class LanguagePackService
|
||||
* 모듈/플러그인 시스템과 동일한 강도로 — 비활성 확장에도 언어팩이 들러붙지 않게 차단합니다.
|
||||
*
|
||||
* @param array<string, mixed> $manifest manifest 데이터
|
||||
* @return void
|
||||
*
|
||||
* @throws RuntimeException 대상 확장 미설치/비활성 시
|
||||
*/
|
||||
@@ -1256,7 +1256,6 @@ class LanguagePackService
|
||||
*
|
||||
* @param LanguagePack $existing 기존 언어팩
|
||||
* @param array<string, mixed> $manifest 새 manifest
|
||||
* @return void
|
||||
*
|
||||
* @throws RuntimeException 다운그레이드 시도 시
|
||||
*/
|
||||
@@ -1301,7 +1300,6 @@ class LanguagePackService
|
||||
* _pending 임시 디렉토리를 정리합니다.
|
||||
*
|
||||
* @param string $path 정리 대상 경로
|
||||
* @return void
|
||||
*/
|
||||
private function cleanupPending(string $path): void
|
||||
{
|
||||
@@ -1309,7 +1307,7 @@ class LanguagePackService
|
||||
if (File::isDirectory($path)) {
|
||||
File::deleteDirectory($path);
|
||||
}
|
||||
} catch (\Throwable $e) {
|
||||
} catch (Throwable $e) {
|
||||
Log::warning('lang-pack pending cleanup failed', ['path' => $path, 'error' => $e->getMessage()]);
|
||||
}
|
||||
}
|
||||
@@ -1421,19 +1419,33 @@ class LanguagePackService
|
||||
$manifest = $pack->manifest;
|
||||
if (is_array($manifest)) {
|
||||
$manifestUrl = $manifest['github_url'] ?? null;
|
||||
if (is_string($manifestUrl) && Str::startsWith($manifestUrl, 'https://github.com/')) {
|
||||
if (is_string($manifestUrl) && self::isGithubUrl($manifestUrl)) {
|
||||
return $manifestUrl;
|
||||
}
|
||||
}
|
||||
|
||||
$sourceUrl = (string) $pack->source_url;
|
||||
if (Str::startsWith($sourceUrl, 'https://github.com/')) {
|
||||
if (self::isGithubUrl($sourceUrl)) {
|
||||
return $sourceUrl;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* URL 이 실제 GitHub host 를 가리키는지 판정합니다.
|
||||
*
|
||||
* 접두사 매칭은 `https://github.com@evil.example/` 같은 userinfo 위장을 통과시키므로
|
||||
* host 를 완전 일치로 검증합니다.
|
||||
*
|
||||
* @param string $url 판정 대상 URL
|
||||
* @return bool GitHub URL 이면 true
|
||||
*/
|
||||
private static function isGithubUrl(string $url): bool
|
||||
{
|
||||
return OutboundUrlValidator::isHostAllowed($url, ['github.com', 'www.github.com']);
|
||||
}
|
||||
|
||||
/**
|
||||
* 번들 manifest 로부터 최신 버전을 조회합니다 (요구사항 #4 폴백 경로).
|
||||
*
|
||||
|
||||
@@ -10,6 +10,7 @@ use App\Enums\ScheduleType;
|
||||
use App\Extension\HookManager;
|
||||
use App\Models\Schedule;
|
||||
use App\Models\ScheduleHistory;
|
||||
use App\Support\OutboundUrlValidator;
|
||||
use Exception;
|
||||
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
|
||||
use Illuminate\Database\Eloquent\Collection;
|
||||
@@ -19,6 +20,7 @@ use Illuminate\Support\Facades\Http;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Illuminate\Support\Facades\Process;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
use Symfony\Component\Console\Output\BufferedOutput;
|
||||
|
||||
class ScheduleService
|
||||
{
|
||||
@@ -250,7 +252,7 @@ class ScheduleService
|
||||
{
|
||||
$output = '';
|
||||
|
||||
Artisan::call($schedule->command, [], new \Symfony\Component\Console\Output\BufferedOutput);
|
||||
Artisan::call($schedule->command, [], new BufferedOutput);
|
||||
|
||||
return [
|
||||
'output' => Artisan::output(),
|
||||
@@ -292,6 +294,12 @@ class ScheduleService
|
||||
*/
|
||||
private function executeUrlCall(Schedule $schedule): array
|
||||
{
|
||||
// 저장된 URL 이 그대로 서버의 outbound 목적지가 되므로, 실행 직전에도 내부망 주소를 차단한다
|
||||
// (저장 시점 검증 도입 이전 데이터나 DB 직접 수정으로 들어온 값 방어).
|
||||
if (! $this->isUrlCallAllowed($schedule->command)) {
|
||||
throw new Exception(__('schedule.url_not_public'));
|
||||
}
|
||||
|
||||
$timeout = $schedule->timeout ?? 30;
|
||||
|
||||
$response = Http::timeout($timeout)->get($schedule->command);
|
||||
@@ -306,6 +314,27 @@ class ScheduleService
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 스케줄의 URL 호출이 허용되는 목적지인지 판정합니다.
|
||||
*
|
||||
* 사설 IP·localhost 등 내부 네트워크 주소는 기본 차단하되, 사내 엔드포인트를 주기 호출하는
|
||||
* 정당한 운영을 위해 `security.allow_internal_outbound_urls` 로 허용할 수 있습니다.
|
||||
* 허용하더라도 userinfo 위장·비 HTTP scheme 은 계속 거부합니다.
|
||||
*
|
||||
* @param string $url 스케줄에 저장된 호출 URL
|
||||
* @return bool 호출을 허용하면 true
|
||||
*/
|
||||
private function isUrlCallAllowed(string $url): bool
|
||||
{
|
||||
$options = ['schemes' => ['http', 'https']];
|
||||
|
||||
if ((bool) g7_core_settings('security.allow_internal_outbound_urls', false)) {
|
||||
return OutboundUrlValidator::isStructurallySafeUrl($url, $options);
|
||||
}
|
||||
|
||||
return OutboundUrlValidator::isPublicHttpUrl($url, $options);
|
||||
}
|
||||
|
||||
/**
|
||||
* 스케줄을 복제합니다.
|
||||
*
|
||||
|
||||
@@ -0,0 +1,213 @@
|
||||
<?php
|
||||
|
||||
namespace App\Support;
|
||||
|
||||
/**
|
||||
* 서버가 외부로 나가는(outbound) HTTP 요청의 목적지 URL 을 검증하는 순수 유틸.
|
||||
*
|
||||
* 사용자·관리자·외부 콜백이 제어할 수 있는 값이 그대로 목적지가 되면 서버는
|
||||
* 내부망(사설 IP, 루프백, 클라우드 메타데이터 169.254.169.254)으로 요청을 대신
|
||||
* 보내는 도구가 된다(SSRF). 본 유틸은 두 계층의 판정을 제공한다:
|
||||
*
|
||||
* 1. `isHostAllowed()` — 신뢰 도메인 목록이 정해진 경우(결제/본인인증 게이트웨이 등).
|
||||
* host 를 **완전 일치**로 검증한다. 접두사 매칭(`str_starts_with`)은 금지 —
|
||||
* `https://trusted.example@127.0.0.1/`(userinfo)와
|
||||
* `https://trusted.example.attacker.com/`(접미사 확장)이 모두 통과하기 때문이다.
|
||||
*
|
||||
* 2. `isPublicHttpUrl()` — 신뢰 목록이 없고 "임의의 공개 URL 은 허용하되 내부망
|
||||
* 타격만 막는" 경우(외부 API 연동, 원격 다운로드 등).
|
||||
*
|
||||
* 두 메서드 모두 예외를 던지지 않고 bool 만 반환한다. 차단 시 어떤 예외/응답을
|
||||
* 낼지는 각 호출 지점이 자신의 반환 계약에 맞춰 결정한다.
|
||||
*
|
||||
* 방어 범위: **host 레벨**이다. DNS rebinding(검증 시점과 실제 연결 시점 사이에
|
||||
* 같은 호스트명이 내부 IP 로 재해석되는 공격)은 막지 못한다. 이를 막으려면 요청
|
||||
* 직전에 실제 해석된 IP 를 재검증해야 하며, 이는 본 유틸의 범위 밖이다.
|
||||
*/
|
||||
class OutboundUrlValidator
|
||||
{
|
||||
/** 공개 인터넷 호스트로 취급하지 않는 내부 도메인 접미사 */
|
||||
private const INTERNAL_HOST_SUFFIXES = [
|
||||
'.local',
|
||||
'.localhost',
|
||||
'.internal',
|
||||
'.intranet',
|
||||
'.lan',
|
||||
'.home.arpa',
|
||||
];
|
||||
|
||||
/** 그 자체로 내부를 가리키는 호스트명 */
|
||||
private const INTERNAL_HOST_NAMES = [
|
||||
'localhost',
|
||||
'ip6-localhost',
|
||||
'ip6-loopback',
|
||||
];
|
||||
|
||||
/**
|
||||
* URL 의 host 가 화이트리스트와 완전 일치하는지 검증한다.
|
||||
*
|
||||
* scheme 허용 목록·userinfo 부재·포트 표기까지 함께 강제하므로, 호출부는
|
||||
* 이 메서드 하나만 통과시키면 목적지 위조를 막을 수 있다.
|
||||
*
|
||||
* @param string $url 검증 대상 URL (외부 입력)
|
||||
* @param array<int, string> $allowedHosts 허용 host 목록 (예: ['kssa.inicis.com'])
|
||||
* @param array{schemes?: array<int, string>, allowPort?: bool} $options
|
||||
* schemes: 허용 scheme (기본 ['https'])
|
||||
* allowPort: 명시 포트 허용 여부 (기본 false)
|
||||
* @return bool 화이트리스트 host 와 완전 일치하면 true
|
||||
*/
|
||||
public static function isHostAllowed(string $url, array $allowedHosts, array $options = []): bool
|
||||
{
|
||||
$host = self::extractSafeHost($url, $options);
|
||||
|
||||
if ($host === null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
foreach ($allowedHosts as $allowed) {
|
||||
if ($host === strtolower(trim($allowed))) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* URL 의 host 가 공개 인터넷 주소인지(= 내부망이 아닌지) 검증한다.
|
||||
*
|
||||
* 사설 IP(10/172.16/192.168), 루프백(127.0.0.1, ::1), 링크로컬 및 클라우드
|
||||
* 메타데이터(169.254.169.254), `localhost`·`*.local` 등 내부 도메인을 차단한다.
|
||||
*
|
||||
* @param string $url 검증 대상 URL (외부 입력)
|
||||
* @param array{schemes?: array<int, string>, allowPort?: bool} $options
|
||||
* schemes: 허용 scheme (기본 ['https'])
|
||||
* allowPort: 명시 포트 허용 여부 (기본 true — 외부 API 는 비표준 포트를 쓸 수 있다)
|
||||
* @return bool 공개 인터넷 host 이면 true
|
||||
*/
|
||||
public static function isPublicHttpUrl(string $url, array $options = []): bool
|
||||
{
|
||||
$host = self::extractSafeHost($url, $options + ['allowPort' => true]);
|
||||
|
||||
if ($host === null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return self::isPublicHost($host);
|
||||
}
|
||||
|
||||
/**
|
||||
* URL 이 구조적으로 안전한지만 판정한다 (내부망 여부는 보지 않는다).
|
||||
*
|
||||
* 내부 주소 호출을 의도적으로 허용한 환경에서도 userinfo(`@`) 위장·미허용 scheme·
|
||||
* 제어문자 주입은 여전히 막아야 하므로, 그 최소 방어선을 제공한다.
|
||||
*
|
||||
* @param string $url 검증 대상 URL
|
||||
* @param array{schemes?: array<int, string>, allowPort?: bool} $options 검증 옵션
|
||||
* @return bool 구조적으로 안전하면 true
|
||||
*/
|
||||
public static function isStructurallySafeUrl(string $url, array $options = []): bool
|
||||
{
|
||||
return self::extractSafeHost($url, $options + ['allowPort' => true]) !== null;
|
||||
}
|
||||
|
||||
/**
|
||||
* host 문자열(URL 이 아닌 host 단독)이 공개 인터넷 주소인지 판정한다.
|
||||
*
|
||||
* @param string $host host 문자열 (예: 'example.com', '127.0.0.1', '[::1]')
|
||||
* @return bool 공개 인터넷 host 이면 true
|
||||
*/
|
||||
public static function isPublicHost(string $host): bool
|
||||
{
|
||||
$host = strtolower(trim($host));
|
||||
|
||||
// parse_url 이 IPv6 를 대괄호째 반환하므로 벗겨낸다
|
||||
if (str_starts_with($host, '[') && str_ends_with($host, ']')) {
|
||||
$host = substr($host, 1, -1);
|
||||
}
|
||||
|
||||
if ($host === '' || in_array($host, self::INTERNAL_HOST_NAMES, true)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// IP 리터럴 — 사설/예약 대역 차단 (루프백·링크로컬·메타데이터 포함)
|
||||
if (filter_var($host, FILTER_VALIDATE_IP) !== false) {
|
||||
return filter_var(
|
||||
$host,
|
||||
FILTER_VALIDATE_IP,
|
||||
FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE,
|
||||
) !== false;
|
||||
}
|
||||
|
||||
// 10진수·8진수·16진수로 인코딩된 IP 우회(예: http://2130706433/ = 127.0.0.1) 차단.
|
||||
// 공개 도메인은 최상위 라벨이 숫자로만 이루어질 수 없다.
|
||||
$lastLabel = substr(strrchr('.'.$host, '.') ?: '', 1);
|
||||
if ($lastLabel === '' || ctype_digit($lastLabel) || str_starts_with($host, '0x')) {
|
||||
return false;
|
||||
}
|
||||
|
||||
foreach (self::INTERNAL_HOST_SUFFIXES as $suffix) {
|
||||
if (str_ends_with($host, $suffix)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* URL 을 파싱해 구조적으로 안전한 host 를 소문자로 반환한다.
|
||||
*
|
||||
* scheme 미허용, userinfo(`@`) 포함, 미허용 포트, host 부재이면 null 을 반환해
|
||||
* 상위 판정을 즉시 실패시킨다.
|
||||
*
|
||||
* @param string $url 검증 대상 URL
|
||||
* @param array{schemes?: array<int, string>, allowPort?: bool} $options 검증 옵션
|
||||
* @return string|null 소문자 host, 구조적으로 안전하지 않으면 null
|
||||
*/
|
||||
private static function extractSafeHost(string $url, array $options): ?string
|
||||
{
|
||||
$schemes = $options['schemes'] ?? ['https'];
|
||||
$allowPort = $options['allowPort'] ?? false;
|
||||
|
||||
$url = trim($url);
|
||||
|
||||
if ($url === '') {
|
||||
return null;
|
||||
}
|
||||
|
||||
// 개행·제어문자가 섞인 URL 은 헤더/요청 분리 시도로 간주하고 즉시 거부
|
||||
if (preg_match('/[\x00-\x1F\x7F]/', $url) === 1) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$parts = parse_url($url);
|
||||
|
||||
if ($parts === false || ! isset($parts['scheme'], $parts['host'])) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// userinfo(`user:pass@host`) 는 host 위조의 핵심 벡터 — 존재만으로 거부
|
||||
if (isset($parts['user']) || isset($parts['pass'])) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$scheme = strtolower($parts['scheme']);
|
||||
$normalizedSchemes = array_map(
|
||||
static fn (string $s): string => strtolower(trim($s)),
|
||||
$schemes,
|
||||
);
|
||||
|
||||
if (! in_array($scheme, $normalizedSchemes, true)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (! $allowPort && isset($parts['port'])) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$host = strtolower(trim($parts['host']));
|
||||
|
||||
return $host === '' ? null : $host;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user