Compare commits

...
Sign in to create a new pull request.

12 commits

Author SHA1 Message Date
김민곤
1e9a0f1aa0
Merge pull request #21 from whs-authz-authn-project/feature/access-token-detector
[DOCS] AccessToken findings 생성 시 reporter 추가
2025-06-04 22:40:19 +09:00
KMINGON
595d0e93a3 Merge branch 'main' into feature/access-token-detector 2025-06-04 22:37:39 +09:00
KMINGON
195be25c22 [DOCS] : findings 추가될 때 reporter 값 설정 2025-06-04 22:36:37 +09:00
김민곤
5a88570fe2
Merge pull request #19 from whs-authz-authn-project/feature/csrf
[Update] nonce 파라미터 감지 범위 확장 및 nonce 파라미터 재사용에대한 검증 로직 추가
2025-06-04 22:19:15 +09:00
James
d2c95cff2e
Merge pull request #20 from whs-authz-authn-project/feature/access-token-detector
[FIX] AccessToken 탐지 정확도 증가
2025-06-04 22:03:47 +09:00
KMINGON
ac53cd4be5 [FIX]: index의 response에 위치하던 request검사 함수 이동 2025-06-04 17:04:39 +09:00
KMINGON
ba98eef694 Merge branch 'main' into feature/access-token-detector 2025-06-04 17:02:13 +09:00
KMINGON
1bc442b1d3 [FIX]: tokenType까지 검사하여 OAuth Flow인지 확인 2025-06-04 17:01:32 +09:00
tv0924@icloud.com
efb89c668c [Update] nonce 파라미터 감지 범위 늘림 및 nonce 파라미터 재사용에대한 검증 로직 추가 2025-06-04 16:02:42 +09:00
gyuu04
c722adbe9d
Merge pull request #18 from whs-authz-authn-project/gyu
Update redirect_uriBypass.ts
2025-06-03 14:45:30 +09:00
gyuu04
14164ceb83
Merge pull request #17 from whs-authz-authn-project/gyu
[Add] RedirectBypassController 및 실행 로직 추가
2025-06-03 12:50:47 +09:00
gyuu04
e45124de21
Merge pull request #16 from whs-authz-authn-project/gyu
Create redirect_uriBypass.ts
2025-06-03 12:30:11 +09:00
5 changed files with 365 additions and 122 deletions

View file

@ -19,7 +19,7 @@ export class AccessTokenLeakController {
title: result.title, title: result.title,
description: result.description, description: result.description,
request, request,
reporter: "", reporter: "AccessTokenLeak",
}); });
} }
} }
@ -31,7 +31,7 @@ export class AccessTokenLeakController {
title: result.title, title: result.title,
description: result.description, description: result.description,
request, request,
reporter: "", reporter: "AccessTokenLeak",
}); });
} }
} }
@ -132,34 +132,53 @@ export class AccessTokenLeakController {
* @param text - * @param text -
* @returns , null * @returns , null
*/ */
private extractTokenFromText(text: string): string | null { private extractTokenFromText(text: string): string | null {
// 토큰 관련 키워드 리스트 // 토큰 관련 키워드 리스트
const tokenKeys = [ const tokenKeys = [
'access_token', 'access_token',
'accesstoken', 'accesstoken',
'Access-Token', 'Access-Token',
'Refresh_Token', 'Refresh_Token',
'Refresh-Token', 'Refresh-Token',
'RefreshToken', 'RefreshToken',
'Secret_Token', 'Secret_Token',
'Secret-Token', 'Secret-Token',
'SecretToken', 'SecretToken',
'SSO_Auth', 'SSO_Auth',
'SSO-Auth', 'SSO-Auth',
'SSOAuth', 'SSOAuth',
'auth_token', 'auth_token',
'session_token' 'session_token'
]; ];
// 정규표현식 패턴 리스트 생성 const tokenTypeKeys = [
'token_type',
'tokenType'
];
// 정규표현식 토큰 타입 유무 패턴 리스트 생성
const tokenTypeRegexes: RegExp[] = [];
for (const key of tokenTypeKeys) {
// JSON 형식: "token_type": "Bearer"
tokenTypeRegexes.push(new RegExp(`"${key}"\\s*:\\s*"bearer"`, 'i'));
// 일반 key=value 형식: token_type=Bearer
tokenTypeRegexes.push(new RegExp(`${key}[=:]\\s*bearer`, 'i'));
// 공백 있는 형식: token_type : Bearer
tokenTypeRegexes.push(new RegExp(`${key}\\s*:\\s*bearer`, 'i'));
}
// token_type=bearer 형태 중 하나라도 포함되는지 확인
const hasTokenTypeBearer = tokenTypeRegexes.some(rx => rx.test(text));
// 정규표현식 토큰 유무 패턴 리스트 생성
const tokenPatterns: RegExp[] = []; const tokenPatterns: RegExp[] = [];
for (const key of tokenKeys) { for (const key of tokenKeys) {
// 1. key=token 또는 key: token // 1. key=token 또는 key: token
tokenPatterns.push(new RegExp(`${key}[=:]\\s*([a-zA-Z0-9\\-._~+/]+=*)`, 'i')); tokenPatterns.push(new RegExp(`${key}[=:]\\s*([a-zA-Z0-9\\-._~+/]+=*)`, 'i'));
// 2. JSON 형태의 "key": "token" // 2. JSON 형태의 "key": "token"
tokenPatterns.push(new RegExp(`"${key}"\\s*:\\s*"([^"]+)"`, 'i')); tokenPatterns.push(new RegExp(`"${key}"\\s*:\\s*"([^"]+)"`, 'i'));
} }
// 3. Authorization: Bearer <token> 형태 // 3. Authorization: Bearer <token> 형태
@ -167,12 +186,14 @@ private extractTokenFromText(text: string): string | null {
// 모든 패턴에 대해 검사 // 모든 패턴에 대해 검사
for (const pattern of tokenPatterns) { for (const pattern of tokenPatterns) {
const match = pattern.exec(text); const match = pattern.exec(text);
if (match && match[1]) { if (match && match[1]) {
return match[1]; if(hasTokenTypeBearer){
return match[1];
} }
}
} }
return null; return null;
} }
} }

View file

@ -5,6 +5,15 @@ import { HttpUtils } from "../utils/http";
const httpUtils = new HttpUtils(); const httpUtils = new HttpUtils();
export class CsrfCheck { export class CsrfCheck {
private nonceParam = [
"state",
"nonce",
"as",
"frame_id",
"csrf_token",
"csrf",
];
private isTargetUri(uri: string): boolean { private isTargetUri(uri: string): boolean {
if ( if (
httpUtils.getQueryParamFromURI(uri, "client_id") !== null && httpUtils.getQueryParamFromURI(uri, "client_id") !== null &&
@ -43,105 +52,178 @@ export class CsrfCheck {
return false; return false;
} }
private isStateInQuery(request: Request): boolean { private isNonceInQuery(request: Request): boolean {
const query = request.getQuery(); const query = request.getQuery() || "";
const stateValue =
httpUtils.getQueryParam(query || "", "state") || for (const param of this.nonceParam) {
httpUtils.getQueryParam(query || "", "nonce"); if (httpUtils.getQueryParam(query, param) !== null) {
if (!stateValue) { return true; // Nonce parameter is present in the query
return false; }
} }
return true;
return false; // No nonce parameter found in the query
} }
private checkStateAtResponseLocationHeader( private getNonceParamName(url: string): string | null {
for (const param of this.nonceParam) {
if (httpUtils.getQueryParamFromURI(url, param) !== null) {
return param; // Return the first matching nonce parameter
}
}
return null; // No nonce parameter found
}
private checkNonceAtResponseLocationHeader(
request: Request, request: Request,
response: Response response: Response
): string[] | 0 { ): string[] | 0 {
const nonceParamName = this.getNonceParamName(request.getUrl() || "");
if ( if (
!( !this.isOauthUri(request) ||
this.isOauthUri(request) && !this.isNonceInQuery(request) ||
this.isStateInQuery(request) && !this.isOauthRedirectResponse(response) ||
this.isOauthRedirectResponse(response) !nonceParamName
)
) { ) {
return 0; // Not a target, no CSRF risk return 0; // Not a target, no CSRF risk
} }
// 요청에서 보낸 state 추출 // 요청에서 보낸 Nonce 추출
const query = request.getQuery() || ""; const query = request.getQuery() || "";
const originalState = const originalNonce = httpUtils.getQueryParam(query, nonceParamName);
httpUtils.getQueryParam(query, "state") ||
httpUtils.getQueryParam(query || "", "nonce");
// 리다이렉트 URL에서 쿼리 부분만 추출 // 리다이렉트 URL에서 쿼리 부분만 추출
const locationHeader = httpUtils.getHeaderValue( const locationHeader =
response.getHeaders(), httpUtils.getHeaderValue(response.getHeaders(), "location") || "";
"location"
);
const responseState =
httpUtils.getQueryParamFromURI(locationHeader || "", "state") ||
httpUtils.getQueryParamFromURI(locationHeader || "", "nonce");
// state가 없거나, 요청값과 다르면 CSRF 위험 const responseNonce = httpUtils.getQueryParamFromURI(
if (!responseState) { locationHeader || "",
nonceParamName
);
// Nonce가 없거나, 요청값과 다르면 CSRF 위험
if (!responseNonce) {
// missing state // missing state
return ["state parameter is missing in the response location header"]; return ["Nonce parameter is missing in the response location header"];
} }
if (originalState !== responseState) { if (originalNonce !== responseNonce) {
// mismatch // mismatch
return ["state parameter mismatch between request and response"]; return ["Nonce parameter mismatch between request and response"];
} }
return 0; // no CSRF risk detected return 0; // no CSRF risk detected
} }
// private async checkStateReuse( private async checkNonceReuse(
// request: Request, sdk: SDK<DefineAPI<{}>, {}>,
// originResponse: Response request: Request,
// ): Promise<string[] | 0> { originResponse: Response
// // uri에 oauth 관련 파라미터가 없지만, 응답이 oauth 리다이렉트 응답인지 확인 ): Promise<string[] | 0> {
// // 즉, 처음으로 state를 발급한 요청인지 확인 // uri에 oauth 관련 파라미터가 없지만, 응답이 oauth 리다이렉트 응답인지 확인
// if ( // 즉, 처음으로 Nonce를 발급한 요청인지 확인
// !( if (
// !this.isOauthUri(request) && this.isOauthUri(request) ||
// this.isOauthRedirectResponse(originResponse) !this.isOauthRedirectResponse(originResponse)
// ) ) {
// ) { return 0; // Not a target, no CSRF risk
// return 0; // Not a target, no CSRF risk }
// }
// const originResponseLocationHeader = httpUtils.getHeaderValue( // 기존 응답의 location 헤더의 url에서 Nonce 파라미터 이름, nonce 파라미터 값, 쿼리 추출
// originResponse.getHeaders(), const originResponseLocationHeader =
// "location" httpUtils.getHeaderValue(originResponse.getHeaders(), "location") || "";
// ); const nonceParamName =
// const originState = httpUtils.getQueryParamFromURI( this.getNonceParamName(originResponseLocationHeader || "") || "state";
// originResponseLocationHeader || "", const originLocationQuery =
// "state" httpUtils.getQueryFromURI(originResponseLocationHeader || "") || "";
// ); const originLocationNonce = httpUtils.getQueryParam(
originLocationQuery,
nonceParamName
);
// const requestHeaders = request.getHeaders(); // 쿠키가 없는 헤더로 새로운 nonce를 발급받기 위해 요청
// const noCookieHeaders = httpUtils.removeHeaders(requestHeaders, ["cookie"]); const noCookieHeaders = httpUtils.removeHeaders(request.getHeaders(), [
// const newResponse = await httpUtils.resend(request, { "cookie",
// headers: noCookieHeaders, ]);
// }); const noCookieResponse = await httpUtils.resend(sdk, request, {
// const newLocationHeader = httpUtils.getHeaderValue( headers: noCookieHeaders,
// newResponse.getHeaders(), });
// "location" if (!noCookieResponse || noCookieResponse?.getCode() >= 400) {
// ); return 0;
// const newState = httpUtils.getQueryParamFromURI( }
// newLocationHeader || "",
// "state"
// );
// if (originState === newState) { // 쿠키가 없는 응답의 location 헤더 추출 및 Nonce 추출
// return [ const noCookieLocationHeader = httpUtils.getHeaderValue(
// "State parameter reused in the response location header, indicating a potential CSRF risk", noCookieResponse?.getHeaders() || {},
// ]; "location"
// } );
const newNonce =
httpUtils.getQueryParamFromURI(
noCookieLocationHeader || "",
nonceParamName
) || "";
// return 0; // no CSRF risk detected if (originLocationNonce === newNonce) {
// } return [
"State parameter reused in the response location header, indicating a potential CSRF risk",
];
}
// 기존 쿠키와 함께 새로운 Nonce로 요청
const newQuery = httpUtils.setQueryParam(
originLocationQuery,
nonceParamName,
newNonce
);
// 기존 location 헤더의 uri 요청과 location 헤더에서 nonce값만 새로 발급한 값으로 바꾸어 요청한 결과를 비교
const res1 = await httpUtils.customFetch(
sdk,
originResponseLocationHeader,
"GET",
originLocationQuery,
request.getHeaders()
);
const res2 = await httpUtils.customFetch(
sdk,
originResponseLocationHeader,
"GET",
newQuery,
request.getHeaders()
);
if (
!res1 ||
!res2 ||
res1.getCode() >= 400 ||
res2.getCode() >= 400 ||
res1.getCode() !== res2.getCode()
) {
return 0;
}
if (
res1.getCode() === res2.getCode() &&
300 <= res1.getCode() &&
res1.getCode() < 400
) {
const res1LocationHeader =
httpUtils.getHeaderValue(res1.getHeaders(), "location") || "";
const res2LocationHeader =
httpUtils.getHeaderValue(res2.getHeaders(), "location") || "";
const res1ReirectPath = httpUtils.getPathFromURI(res1LocationHeader);
const res2ReirectPath = httpUtils.getPathFromURI(res2LocationHeader);
if (res1ReirectPath === res2ReirectPath) {
return [
"When nonce parameter reused in the response location header, it might not be verified. Indicating a potential CSRF risk",
];
}
}
return 0; // no CSRF risk detected
}
async checker( async checker(
sdk: SDK<DefineAPI<{}>, {}>, sdk: SDK<DefineAPI<{}>, {}>,
@ -152,7 +234,7 @@ export class CsrfCheck {
// 쿼리에 state 파라미터가 없으면 CSRF 위험 // 쿼리에 state 파라미터가 없으면 CSRF 위험
try { try {
if (this.isOauthUri(request) && !this.isStateInQuery(request)) { if (this.isOauthUri(request) && !this.isNonceInQuery(request)) {
result += "CSRF risk: missing state parameter"; // CSRF risk: missing state parameter result += "CSRF risk: missing state parameter"; // CSRF risk: missing state parameter
} }
} catch (error) { } catch (error) {
@ -162,7 +244,7 @@ export class CsrfCheck {
// location 헤더에 state 파라미터가 없거나, 요청에서 보낸 state와 다르면 CSRF 위험 // location 헤더에 state 파라미터가 없거나, 요청에서 보낸 state와 다르면 CSRF 위험
try { try {
const stateAtResponseLocationHeaderCheck = const stateAtResponseLocationHeaderCheck =
this.checkStateAtResponseLocationHeader(request, response); this.checkNonceAtResponseLocationHeader(request, response);
if (stateAtResponseLocationHeaderCheck !== 0) { if (stateAtResponseLocationHeaderCheck !== 0) {
result += `, ${stateAtResponseLocationHeaderCheck.join(", ")}`; result += `, ${stateAtResponseLocationHeaderCheck.join(", ")}`;
} }
@ -172,14 +254,14 @@ export class CsrfCheck {
); );
} }
// // 처음으로 state를 발급한 요청에서 state 파라미터를 바꿔서 보내기 // 처음으로 state를 발급한 요청에서 state 파라미터를 바꿔서 보내기
// const reusedStateCheck = await this.checkStateReuse(request, response); const reusedStateCheck = await this.checkNonceReuse(sdk, request, response);
// if (reusedStateCheck !== 0) { if (reusedStateCheck !== 0) {
// result += `, ${reusedStateCheck.join(", ")}`; result += `, ${reusedStateCheck.join(", ")}`;
// } }
result.replace(/^\s*,\s*|\s*$/, ""); // Remove leading/trailing commas
try { try {
result.replace(/^\s*,\s*|\s*$/, ""); // Remove leading/trailing commas
if (result) { if (result) {
await sdk.findings.create({ await sdk.findings.create({
title: "csrf vuln", title: "csrf vuln",
@ -187,7 +269,6 @@ export class CsrfCheck {
request, request,
reporter: "csrf reporter", reporter: "csrf reporter",
}); });
sdk.console.log("qq");
} }
} catch (error) { } catch (error) {
sdk.console.error(`Error creating finding: ${error}`); sdk.console.error(`Error creating finding: ${error}`);

View file

@ -22,7 +22,6 @@ export function init(sdk: SDK<API>) {
sdk.events.onInterceptResponse(async (sdk, req: Request, res: Response) => { sdk.events.onInterceptResponse(async (sdk, req: Request, res: Response) => {
await csrfCheck.checker(sdk, req, res); await csrfCheck.checker(sdk, req, res);
//await pkceCheckController.test(sdk, req); //await pkceCheckController.test(sdk, req);
await tokenCheck.testReq(sdk, req);
await tokenCheck.testResp(sdk, res, req); await tokenCheck.testResp(sdk, res, req);
await ScopeDetectionController.scan(sdk, req.getUrl()); await ScopeDetectionController.scan(sdk, req.getUrl());
await redirectBypassController.testAsync(sdk, req, res); await redirectBypassController.testAsync(sdk, req, res);
@ -38,6 +37,7 @@ export function init(sdk: SDK<API>) {
}); });
sdk.events.onInterceptRequest(async (sdk, req: Request) => { sdk.events.onInterceptRequest(async (sdk, req: Request) => {
await tokenCheck.testReq(sdk, req);
await pkceCheckController.test(sdk, req); await pkceCheckController.test(sdk, req);
}); });
/* /*

View file

@ -1,3 +1,6 @@
import type { SDK } from "caido:plugin";
import { Body, RequestSpec, type Request, type Response } from "caido:utils";
let instance: HttpUtils | null = null; let instance: HttpUtils | null = null;
export class HttpUtils { export class HttpUtils {
/** /**
@ -11,6 +14,14 @@ export class HttpUtils {
return instance; return instance;
} }
encodeAndLower(value: string): string {
try {
return encodeURIComponent(value).toLowerCase();
} catch {
return value.toLowerCase();
}
}
/** /**
* URI * URI
* @param value - * @param value -
@ -47,12 +58,35 @@ export class HttpUtils {
return result; return result;
} }
getPathFromURI(uri: string): string | null {
uri = uri.toLowerCase();
try {
const urlObj = new URL(uri);
const path = urlObj.pathname;
return path ? decodeURIComponent(path) : null; // 경로가 없으면 null 반환
} catch (e) {
return null; // URL 파싱 실패 시 null 반환
}
}
getQueryFromURI(uri: string): string | null {
uri = uri.toLowerCase();
try {
const urlObj = new URL(uri);
const query = urlObj.search;
return query ? decodeURIComponent(query.slice(1)) : null; // 쿼리 문자열에서 ? 제거
} catch (e) {
return null; // URL 파싱 실패 시 null 반환
}
}
getQueryParamFromURI(uri: string, key: string): string | null { getQueryParamFromURI(uri: string, key: string): string | null {
uri = this.decodeAndLower(uri); uri = uri.toLowerCase();
key = this.decodeAndLower(key); key = this.decodeAndLower(key);
try { try {
const urlObj = new URL(uri); const urlObj = new URL(uri);
return urlObj.searchParams.get(key); const param = urlObj.searchParams.get(key);
return param ? decodeURIComponent(param) : null;
} catch (e) { } catch (e) {
return null; return null;
} }
@ -66,11 +100,12 @@ export class HttpUtils {
* @returns - , null * @returns - , null
*/ */
getQueryParam(query: string, key: string): string | null { getQueryParam(query: string, key: string): string | null {
query = this.decodeAndLower(query); query = query.toLowerCase();
key = this.decodeAndLower(key); key = this.decodeAndLower(key);
const params = new URLSearchParams(query); const params = new URLSearchParams(query);
return params.get(key); const targetParam = params.get(key);
return targetParam ? decodeURIComponent(targetParam) : null;
} }
/** /**
@ -82,12 +117,12 @@ export class HttpUtils {
* @returns - "a=1&b=2&c=3..." * @returns - "a=1&b=2&c=3..."
*/ */
setQueryParam(query: string, key: string, value: string): string { setQueryParam(query: string, key: string, value: string): string {
query = this.decodeAndLower(query); query = query.toLowerCase();
key = this.decodeAndLower(key); key = this.decodeAndLower(key);
value = this.decodeAndLower(value); value = this.decodeAndLower(value);
const params = new URLSearchParams(query); const params = new URLSearchParams(query);
params.set(key, value); params.set(key, this.encodeAndLower(value));
return params.toString(); return params.toString();
} }
@ -99,7 +134,7 @@ export class HttpUtils {
* @returns - * @returns -
*/ */
removeQueryParam(query: string, key: string): string { removeQueryParam(query: string, key: string): string {
query = this.decodeAndLower(query); query = query.toLowerCase();
key = this.decodeAndLower(key); key = this.decodeAndLower(key);
const params = new URLSearchParams(query); const params = new URLSearchParams(query);
@ -109,6 +144,7 @@ export class HttpUtils {
// Headers // Headers
/** /**
* !! request.getHeader(`${key}`) .
* name에 . * name에 .
* @param headers - Response.getHeaders() * @param headers - Response.getHeaders()
* @param name - (: "location", "Content-Type") * @param name - (: "location", "Content-Type")
@ -207,4 +243,89 @@ export class HttpUtils {
} }
return filtered; return filtered;
} }
async resend(
sdk: SDK,
request: Request,
options?: {
headers?: Record<string, string | string[]>;
body?: Body;
method?: string;
query?: string;
}
): Promise<Response | null> {
try {
const spec = new RequestSpec(request.getUrl());
spec.setMethod(options?.method || request.getMethod() || "GET");
if (options?.query) {
spec.setQuery(options.query);
} else {
spec.setQuery(request.getQuery() || "");
}
const originBody = request.getBody();
if (options?.body) {
spec.setBody(options.body);
} else if (originBody) {
spec.setBody(originBody);
}
const headers = request.getHeaders();
if (options?.headers) {
// 기존 헤더에서 options.headers로 덮어쓰기
const newHeaders = this.lowerCaseAllHeaders({
...headers,
...options.headers,
});
for (const [key, value] of Object.entries(newHeaders)) {
spec.setHeader(key, Array.isArray(value) ? value.join(", ") : value);
}
} else {
// 기존 헤더 그대로 사용
for (const [key, value] of Object.entries(headers)) {
spec.setHeader(key, Array.isArray(value) ? value.join(", ") : value);
}
}
const result = await sdk.requests.send(spec);
return result.response ?? null;
} catch (error) {
sdk.console.error(
`Error resending request to ${request.getUrl()}: ${String(error)}`
);
return null;
}
}
async customFetch(
sdk: SDK,
url: string,
method?: string,
query?: string,
headers?: Record<string, string | string[]>,
body?: Body
): Promise<Response | null> {
try {
const spec = new RequestSpec(url);
spec.setMethod(method || "GET");
if (query) {
spec.setQuery(query);
}
if (body) {
spec.setBody(body);
}
for (const [key, value] of Object.entries(headers || {})) {
spec.setHeader(key, Array.isArray(value) ? value.join(", ") : value);
}
const result = await sdk.requests.send(spec);
return result.response ?? null;
} catch {
sdk.console.error(
`Error during custom fetch to ${url}: ${String(error)}`
);
return null;
}
}
} }

View file

@ -1,5 +1,6 @@
// app.js // app.js
const express = require("express"); const express = require("express");
const crypto = require("crypto");
const app = express(); const app = express();
const port = 8000; const port = 8000;
@ -43,8 +44,6 @@ app.get("/authorize/mismatch-state", (req, res) => {
); );
const code = "authcode-67890"; const code = "authcode-67890";
console.log(`[VULN] original state from client:`, originalState);
// 클라이언트 state와 다르게 'wrong-state'를 삽입 // 클라이언트 state와 다르게 'wrong-state'를 삽입
const wrongState = "wrong-state"; const wrongState = "wrong-state";
const location = `${redirectUri}?code=${code}&state=${wrongState}&client_id=${clientId}`; const location = `${redirectUri}?code=${code}&state=${wrongState}&client_id=${clientId}`;
@ -52,6 +51,24 @@ app.get("/authorize/mismatch-state", (req, res) => {
res.status(302).send(`Redirecting to ${location}`); res.status(302).send(`Redirecting to ${location}`);
}); });
/**
* 3) 랜덤 state를 생성하여 리다이렉트를 발생시키는 테스트용 엔드포인트
* - /authorize/reuse-state-test 16 state
* - 최초 요청에 OAuth 파라미터가 없으므로 isOauthUri(request) == false
* - 응답에 Location 헤더로 '...?state=<랜덤값>' 포함
* -> Caido 플러그인의 checkNonceReuse 로직에서 새로운 state가 발급되었는지,
* 재사용되었는지를 검증할 있음
* - 더하여 callback uri에서 해당 nonce의 유효성을 판단하지 않고 응답 시에 vuln
*/
app.get("/authorize/reuse-state-test", (req, res) => {
const state = crypto.randomBytes(16).toString("hex");
// 고정된 콜백 URI로 리다이렉트 (OAuth 파라미터는 여기서만 주입)
const location = `http://localhost:${port}/callback?state=${state}&client_id=123`;
res.set("Location", location);
res.status(302).send(`Redirecting to ${location}`);
});
app.listen(port, () => { app.listen(port, () => {
console.log( console.log(
`Vulnerable OAuth test server listening at http://localhost:${port}` `Vulnerable OAuth test server listening at http://localhost:${port}`
@ -62,4 +79,7 @@ app.listen(port, () => {
console.log( console.log(
`2) Mismatch-State: http://localhost:${port}/authorize/mismatch-state?client_id=abc&state=xyz&redirect_uri=http://localhost:${port}/callback` `2) Mismatch-State: http://localhost:${port}/authorize/mismatch-state?client_id=abc&state=xyz&redirect_uri=http://localhost:${port}/callback`
); );
console.log(
`3) Reuse-State-Test: http://localhost:${port}/authorize/reuse-state-test`
);
}); });