fix(core,extensions): 보안 결함 3건과 이중저장소·레이아웃 중복키 결함군 폐쇄

KISA 제보 3건(KVE-2026-2010/2011/2018)과 그 동일 계열 형제 결함을 전수 조치하고,
그 과정에서 드러난 두 결함군을 함께 닫는다.

- 검증 시점과 연결 시점이 host 를 다르게 읽던 SSRF 통로를 정규화 SSoT 한 곳으로 모았다
- 세션을 여는 지점(2FA 완료·토큰 재발급)이 잠금 검사를 거치지 않아 계정 잠금이 우회됐다
- 인증도 서명도 없는 브라우저 리턴 콜백이 주문 상태를 바꾸던 통로를 4 PG 전부에서 닫고,
 소유권을 대조하는 close-report 를 토스에도 신설했다. 그 결과 정리 주체를 잃는
 결제창 미완료 주문은 만료 자동취소가 거둔다
- 저장소 A(_local)에만 쓰는 경로가 B 의 값을 조용히 덮던 회귀를 정본 writer 로 닫았다
 (engine-v1.63.5). 한 방향만 보던 정적 검사에 반대 방향 축과 양방향 계약 테스트를 더했다
- 레이아웃 JSON 의 같은 객체 중복 키가 앞선 선언을 오류 없이 삼키던 결함군을 닫았다
This commit is contained in:
HeuJung committed 2026-09-02 17:36:11 +09:00
1 parent d4439ea30a
commit 21fc114f37
137 files changed
+6470 -829

No files matched your search

@@ -110,6 +110,19 @@ class AuthController extends AdminBaseController
}
return $this->success('common.success', $data);
} catch (AccountLockedException $e) {
// 재발급도 세션을 여는 지점이다 — 사용자 경로와 같은 423 계약을 따른다.
// 이 catch 가 없으면 잠긴 계정의 재발급 시도가 500 으로 새어 나간다.
return $this->error(
$e->isPermanent() ? 'auth.account_locked_permanently' : 'auth.account_locked',
423,
[
'locked_until' => $e->lockedUntil?->toIso8601String(),
'retry_after_seconds' => $e->remainingMinutes === null ? null : $e->remainingMinutes * 60,
'permanent' => $e->isPermanent(),
],
['minutes' => $e->remainingMinutes]
);
} catch (ValidationException $e) {
return $this->unauthorized('auth.unauthenticated');
}
@@ -60,17 +60,7 @@ class AuthController extends AuthBaseController
return $this->success('auth.login_success', $data);
} catch (AccountLockedException $e) {
// 영구 잠금(무한대 설정)은 해제 시각·잔여 시간이 없다 — null 그대로 노출.
return $this->error(
$e->isPermanent() ? 'auth.account_locked_permanently' : 'auth.account_locked',
423,
[
'locked_until' => $e->lockedUntil?->toIso8601String(),
'retry_after_seconds' => $e->remainingMinutes === null ? null : $e->remainingMinutes * 60,
'permanent' => $e->isPermanent(),
],
['minutes' => $e->remainingMinutes]
);
return $this->lockedResponse($e);
} catch (ValidationException $e) {
return $this->unauthorized('auth.login_failed');
}
@@ -98,11 +88,38 @@ class AuthController extends AuthBaseController
$data['user'] = new UserResource($data['user']);
return $this->success('auth.login_success', $data);
} catch (AccountLockedException $e) {
// 세션을 여는 지점이므로 `login` 과 같은 423 계약을 따른다 — 화면은 두 경로를
// 구분하지 않으므로 한쪽만 다른 모양이면 잠금 안내가 깨진다.
return $this->lockedResponse($e);
} catch (ValidationException $e) {
return $this->unauthorized('auth.two_factor_failed');
}
}
/**
* 계정 잠금 응답(423)을 구성합니다.
*
* 세션을 발급하는 모든 엔드포인트가 같은 페이로드를 돌려주도록 단일 지점에서 만든다.
*
* @param AccountLockedException $e 잠금 예외
* @return JsonResponse 423 응답
*/
private function lockedResponse(AccountLockedException $e): JsonResponse
{
// 영구 잠금(무한대 설정)은 해제 시각·잔여 시간이 없다 — null 그대로 노출.
return $this->error(
$e->isPermanent() ? 'auth.account_locked_permanently' : 'auth.account_locked',
423,
[
'locked_until' => $e->lockedUntil?->toIso8601String(),
'retry_after_seconds' => $e->remainingMinutes === null ? null : $e->remainingMinutes * 60,
'permanent' => $e->isPermanent(),
],
['minutes' => $e->remainingMinutes]
);
}
/**
* 새로운 사용자를 등록시킵니다.
*
@@ -178,7 +195,11 @@ class AuthController extends AuthBaseController
*/
public function refresh(AuthenticatedRequest $request): JsonResponse
{
$data = $this->authService->refreshToken($request->user());
try {
$data = $this->authService->refreshToken($request->user());
} catch (AccountLockedException $e) {
return $this->lockedResponse($e);
}
// 사용자 정보는 Resource로, 토큰은 그대로
if (isset($data['user'])) {
+45 -14
View File
@@ -100,20 +100,7 @@ class AuthService
// 사전 잠금 체크 — 잠긴 계정은 Auth::attempt 자체를 시도하지 않는다.
// (실패 카운트가 0 으로 리셋된 잠금 상태에서 Failed 이벤트가 다시
// 카운트를 올려 재잠금 시각을 갱신하는 부작용 방지)
if ((bool) g7_core_settings('security.login_attempt_enabled', true)) {
$candidate = $this->userRepository->findByEmail($email);
if ($candidate !== null && $this->userRepository->isLocked($candidate)) {
// 영구 잠금은 해제 시각이 없다 — diffInSeconds(null) 로 폭발하지 않도록 분기.
$remaining = $candidate->locked_until === null
? null
: max(1, (int) ceil(now()->diffInSeconds($candidate->locked_until, false) / 60));
throw new AccountLockedException(
lockedUntil: $candidate->locked_until,
remainingMinutes: $remaining,
);
}
}
$this->assertNotLocked($this->userRepository->findByEmail($email));
if (! Auth::attempt(['email' => $email, 'password' => $password])) {
// 실패 카운트 증가/잠금 처리는 HandleFailedLoginListener 에서 담당
@@ -158,6 +145,40 @@ class AuthService
return $this->issueLoginSession($user, $email);
}
/**
* 계정이 잠겨 있으면 예외를 던집니다.
*
* 세션(토큰)을 발급하는 지점은 전부 이 검사를 거쳐야 합니다. 2단계 인증이 켜져 있으면
* 비밀번호 확인(`login`)은 challenge 만 돌려주고 실제 세션은 `completeTwoFactor()` 가
* 발급하므로, 한쪽에만 검사가 있으면 잠기기 전에 받아 둔 challenge 를 잠긴 뒤 완료하는
* 것만으로 잠금이 통째로 우회됩니다. 그 뒤 로그인 완료 훅이 실패 횟수·잠금 시각까지
* 초기화해 흔적도 남지 않습니다.
*
* @param User|null $user 검사 대상 사용자 (없으면 검사 대상 아님)
*
* @throws AccountLockedException 계정이 잠겨 있을 때
*/
private function assertNotLocked(?User $user): void
{
if (! (bool) g7_core_settings('security.login_attempt_enabled', true)) {
return;
}
if ($user === null || ! $this->userRepository->isLocked($user)) {
return;
}
// 영구 잠금은 해제 시각이 없다 — diffInSeconds(null) 로 폭발하지 않도록 분기.
$remaining = $user->locked_until === null
? null
: max(1, (int) ceil(now()->diffInSeconds($user->locked_until, false) / 60));
throw new AccountLockedException(
lockedUntil: $user->locked_until,
remainingMinutes: $remaining,
);
}
/**
* 이 사용자에게 2단계 인증을 요구해야 하는지 판정합니다.
*
@@ -268,6 +289,10 @@ class AuthService
]);
}
// 세션을 여는 것은 이 지점이다 — challenge 발급 이후에 잠겼을 수 있으므로 재검사한다.
// Auth::login() 앞에 두어야 로그인 완료 훅이 잠금 필드를 초기화하지 못한다.
$this->assertNotLocked($user);
Auth::login($user);
return $this->issueLoginSession($user, (string) $user->email);
@@ -446,9 +471,15 @@ class AuthService
*
* @param User $user 토큰을 갱신할 사용자
* @return array 새로운 토큰 정보
*
* @throws AccountLockedException 계정이 잠겨 있을 때
*/
public function refreshToken(User $user): array
{
// 재발급도 세션을 여는 지점이다. 유효한 기존 세션이 전제라 신규 로그인 우회는
// 아니지만, 관리자가 계정을 잠근 뒤에도 그 세션이 무기한 연장되면 잠금이 실효를 잃는다.
$this->assertNotLocked($user);
// 현재 토큰 삭제 (다른 디바이스는 유지)
$currentToken = $user->currentAccessToken();
+84 -1
View File
@@ -111,6 +111,75 @@ class OutboundUrlValidator
return self::extractSafeHost($url, $options + ['allowPort' => true]) !== null;
}
/**
* host 문자열을 실제 연결 계층과 같은 규칙으로 정규화한다.
*
* 이 메서드가 정규화의 SSoT 다. 검증기 밖에서 host 를 대조하는 소비자(결제 콜백
* URL 의 도메인 접미사 확인 등)도 이 메서드를 거쳐야 판정이 갈리지 않는다.
*
* 정규화 내용:
* - 점(.) 동등 유니코드 문자(U+3002·U+FF0E·U+FF61)를 ASCII 점으로 치환.
* 검증기가 ASCII 점만 구분자로 보면 `localhost。` 는 단일 라벨(공개 도메인)로
* 읽히지만 libcurl/libidn2 는 UTS#46 정규화로 `localhost` 에 연결한다.
* - IDNA/UTS#46 A-label(punycode) 변환 — 유니코드 표기와 ASCII 표기를 한 형태로 모은다.
* - 소문자화 및 완전한 DNS 이름의 후행 점 제거.
*
* @param string $host 정규화할 host 문자열 (IPv6 는 대괄호 없이)
* @return string|null 정규화된 host, 정규화할 수 없으면 null
*/
public static function normalizeHost(string $host): ?string
{
$host = strtolower(trim($host));
if ($host === '') {
return null;
}
// 점 동등 문자 사전 치환 — idn_to_ascii 는 구현에 따라 이들을 남길 수 있으므로
// 라벨 분리 자체를 여기서 확정한다.
$host = strtr($host, [
"\u{3002}" => '.', // IDEOGRAPHIC FULL STOP
"\u{FF0E}" => '.', // FULLWIDTH FULL STOP
"\u{FF61}" => '.', // HALFWIDTH IDEOGRAPHIC FULL STOP
]);
if (function_exists('idn_to_ascii')) {
$ascii = idn_to_ascii($host, IDNA_NONTRANSITIONAL_TO_ASCII, INTL_IDNA_VARIANT_UTS46);
if (is_string($ascii) && $ascii !== '') {
$host = $ascii;
} elseif (preg_match('/[^\x20-\x7E]/', $host) === 1) {
// 변환에 실패했는데 비-ASCII 가 남아 있으면 연결 계층이 어떤 host 로
// 해석할지 알 수 없다 — 판정 불가는 거부로 처리한다.
return null;
}
} elseif (preg_match('/[^\x20-\x7E]/', $host) === 1) {
// polyfill 부재 환경 fail-safe: 비-ASCII host 는 판정 불가로 보고 거부.
return null;
}
$host = strtolower($host);
// 완전한 DNS 이름 표기(`example.com.`)의 후행 점 제거 — 남겨 두면 최상위 라벨이
// 빈 문자열이 되어 정상 도메인이 차단되고, `localhost.` 가 내부 이름 대조를 빠져나간다.
while (str_ends_with($host, '.')) {
$host = substr($host, 0, -1);
}
// 정규화 결과가 host 로 성립하는지 확인한다. UTS#46 은 전각 문자를 ASCII 로
// 매핑하므로 `127.0.0.1/.example.com`(U+FF0F) 은 `127.0.0.1/.example.com` 이 된다.
// parse_url 은 전각 문자를 구분자로 보지 않아 이 전체를 host 로 넘기지만, 연결
// 계층은 정규화 후 첫 구분자 앞(`127.0.0.1`)까지만 host 로 읽는다. 즉 접미사·
// 화이트리스트 대조는 뒤쪽 도메인으로 통과하는데 실제 접속은 앞쪽 주소로 간다.
// punycode(A-label)와 IP 리터럴은 항상 letter/digit/hyphen/dot 뿐이므로, 그 밖의
// 문자가 남았다면 어느 host 로 해석될지 알 수 없다 — 판정 불가는 거부로 처리한다.
if (preg_match('/^[a-z0-9._-]+$/', $host) !== 1) {
return null;
}
return $host === '' ? null : $host;
}
/**
* host 문자열(URL 이 아닌 host 단독)이 공개 인터넷 주소인지 판정한다.
*
@@ -126,6 +195,13 @@ class OutboundUrlValidator
$host = substr($host, 1, -1);
}
// 직접 호출자(URL 을 거치지 않는 경로)도 같은 정규화를 받아야 한다.
// 단 IP 리터럴은 IDNA 라벨 구조가 없어 정규화 대상이 아니다 — 특히 IPv6 의 ':' 는
// 정규화의 호스트명 문자 집합 검사에 걸려 공개 IPv6 까지 차단된다.
if (filter_var($host, FILTER_VALIDATE_IP) === false) {
$host = self::normalizeHost($host) ?? '';
}
if ($host === '' || in_array($host, self::INTERNAL_HOST_NAMES, true)) {
return false;
}
@@ -208,6 +284,13 @@ class OutboundUrlValidator
$host = strtolower(trim($parts['host']));
return $host === '' ? null : $host;
// IPv6 리터럴은 대괄호째 유지한다 — 라벨 구조가 없어 IDNA 정규화 대상이 아니다.
if (str_starts_with($host, '[') && str_ends_with($host, ']')) {
return $host === '[]' ? null : $host;
}
// 실제 연결 계층(libcurl/libidn2)과 같은 규칙으로 정규화한 뒤 상위 판정에 넘긴다.
// 정규화 없이 넘기면 `localhost。` 처럼 검증 시점과 연결 시점의 host 가 달라진다.
return self::normalizeHost($host);
}
}