Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
87 changes: 87 additions & 0 deletions src/features/ctf/detectors.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
import { DEFAULT_FLAG_PATTERNS, buildFlagPatternRegex } from "./flagPatterns";
import type { CtfDetection, CtfDetector } from "./types";

const BASE64_CANDIDATE_PATTERN = /(?:[A-Za-z0-9+/]{4}){3,}(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?/g;
const HEX_CANDIDATE_PATTERN = /(?:0x)?(?:[0-9a-fA-F]{2}[\s:-]?){4,}/g;
const URL_ENCODED_PATTERN = /(?:%[0-9a-fA-F]{2})+/g;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Include mixed URL-encoded runs

For URL-encoded strings that contain ordinary safe characters between escapes (for example %66%6c%61%67%7Bsample%7D), this regex still stops at sample, returning two detections instead of the full token. Fresh evidence beyond the earlier byte-grouping comment is that the new test expects this exact mixed string to be one range through input.length; with the current pattern, any consumer applying url-decode to the detected range cannot recover the complete flag.

Useful? React with 👍 / 👎.


const createDetection = (
type: string,
confidence: number,
start: number,
end: number,
recommendedActions: readonly string[],
): CtfDetection => ({
type,
confidence,
range: { start, end },
recommendedActions,
});

const detectionLength = (detection: CtfDetection): number =>
detection.range.end - detection.range.start;

const removeOverlappingDetections = (detections: readonly CtfDetection[]): readonly CtfDetection[] => {
const selectedDetections = [...detections]
.sort((left, right) =>
right.confidence - left.confidence || detectionLength(right) - detectionLength(left),
)
.reduce<CtfDetection[]>((selected, detection) => {
const overlaps = selected.some(
(selectedDetection) =>
detection.range.start < selectedDetection.range.end &&
detection.range.end > selectedDetection.range.start,
);

return overlaps ? selected : [...selected, detection];
}, []);

return selectedDetections.sort((left, right) => left.range.start - right.range.start);
};

export const CTF_DETECTORS = [
{
id: "flag-pattern",
label: "Flag Pattern",
detect: (input, options) => {
const patterns = options?.flagPatterns ?? DEFAULT_FLAG_PATTERNS;
const detections = patterns.flatMap((pattern) =>
Array.from(input.matchAll(buildFlagPatternRegex(pattern)), (match) =>
createDetection(
pattern.id,
0.95,
match.index,
match.index + match[0].length,
["検出した flag 候補を提出前に問題文の形式と照合してください。"],
),
),
);

return removeOverlappingDetections(detections);
},
},
{
id: "base64-candidate",
label: "Base64 Candidate",
detect: (input) =>
Array.from(input.matchAll(BASE64_CANDIDATE_PATTERN), (match) =>
createDetection("base64", 0.7, match.index, match.index + match[0].length, ["base64-decode"]),
),
},
{
id: "hex-candidate",
label: "Hex Candidate",
detect: (input) =>
Array.from(input.matchAll(HEX_CANDIDATE_PATTERN), (match) =>
createDetection("hex", 0.65, match.index, match.index + match[0].length, ["hex-decode"]),
),
},
{
id: "url-encoded-candidate",
label: "URL Encoded Candidate",
detect: (input) =>
Array.from(input.matchAll(URL_ENCODED_PATTERN), (match) =>
createDetection("url-encoded", 0.6, match.index, match.index + match[0].length, ["url-decode"]),
),
},
] as const satisfies readonly CtfDetector[];
37 changes: 37 additions & 0 deletions src/features/ctf/flagPatterns.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import type { FlagPattern } from "./types";

export const DEFAULT_FLAG_PATTERNS = [
{
id: "flag-braces",
label: "flag{...}",
source: "flag\\{[^}]+\\}",
flags: "gi",
description: "一般的な flag{...} 形式を検出します。",
},
{
id: "ctf-braces",
label: "ctf{...}",
source: "ctf\\{[^}]+\\}",
flags: "gi",
description: "イベント名を省略した ctf{...} 形式を検出します。",
},
{
id: "htb-braces",
label: "HTB{...}",
source: "HTB\\{[^}]+\\}",
flags: "g",
description: "Hack The Box でよく使われる HTB{...} 形式を検出します。",
},
{
id: "picoctf-braces",
label: "picoCTF{...}",
source: "picoCTF\\{[^}]+\\}",
flags: "g",
description: "picoCTF でよく使われる picoCTF{...} 形式を検出します。",
},
] as const satisfies readonly FlagPattern[];

export const buildFlagPatternRegex = (pattern: FlagPattern): RegExp => {
const flags = pattern.flags?.includes("g") ? pattern.flags : `${pattern.flags ?? ""}g`;
return new RegExp(pattern.source, flags);
};
41 changes: 41 additions & 0 deletions src/features/ctf/hints.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import type { CtfHintSection } from "./types";

export const CTF_HINT_SECTIONS = [
{
title: "Forensics",
items: [
"Log analysis: grep, grep -v (exclude), uniq (deduplicate), sort",
],
},
{
title: "Web",
items: ["Burpsuite"],
},
{
title: "Network",
items: ["Wireshark", "Scapy", "socket", "Port scan: nmap"],
},
{
title: "Binary",
items: [
"Binary editor: Hex Fiend",
"file: identify binary file type",
"less: view file contents",
"strings: extract readable strings",
],
},
{
title: "Encoding",
items: [
"Base64: A-Z, a-z, 0-9, +, / (64 chars), ends with =",
'Decode: echo "encoded_string" | base64 -d -o output',
],
},
{
title: "File Location",
items: [
"locate: find file location",
"VS Code SSH: browse files via GUI",
],
},
] as const satisfies readonly CtfHintSection[];
91 changes: 91 additions & 0 deletions src/features/ctf/transforms.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
import type { CtfTransform } from "./types";

const textDecoder = new TextDecoder();
const textEncoder = new TextEncoder();

const fromBase64 = (input: string): string => {
const binary = atob(input.replace(/\s/g, ""));
const bytes = Uint8Array.from(binary, (character) => character.charCodeAt(0));
return textDecoder.decode(bytes);
};

const toBase64 = (input: string): string => {
const bytes = textEncoder.encode(input);
const binary = Array.from(bytes, (byte) => String.fromCharCode(byte)).join("");
return btoa(binary);
};

const fromHex = (input: string): string => {
const normalizedInput = input.replace(/(?:0x|\s|:|-)/gi, "");
if (normalizedInput.length % 2 !== 0 || /[^0-9a-f]/i.test(normalizedInput)) {
return "";
}

const bytes = normalizedInput.match(/.{2}/g)?.map((hex) => parseInt(hex, 16)) ?? [];
return textDecoder.decode(Uint8Array.from(bytes));
};

const rotateAsciiLetter = (character: string, shift: number): string => {
const code = character.charCodeAt(0);
const upperA = 65;
const upperZ = 90;
const lowerA = 97;
const lowerZ = 122;

if (code >= upperA && code <= upperZ) {
return String.fromCharCode(((code - upperA + shift) % 26) + upperA);
}

if (code >= lowerA && code <= lowerZ) {
return String.fromCharCode(((code - lowerA + shift) % 26) + lowerA);
}

return character;
};

export const CTF_TRANSFORMS = [
{
id: "base64-decode",
label: "Base64 Decode",
category: "encoding",
description: "Base64 文字列を UTF-8 テキストとして復号します。",
run: (input) => ({ output: fromBase64(input) }),
},
{
id: "base64-encode",
label: "Base64 Encode",
category: "encoding",
description: "UTF-8 テキストを Base64 文字列に変換します。",
run: (input) => ({ output: toBase64(input) }),
},
{
id: "url-decode",
label: "URL Decode",
category: "web",
description: "URL エンコードされた文字列を復号します。",
run: (input) => ({ output: decodeURIComponent(input.replace(/\+/g, " ")) }),
},
{
id: "url-encode",
label: "URL Encode",
category: "web",
description: "文字列を URL コンポーネントとしてエンコードします。",
run: (input) => ({ output: encodeURIComponent(input) }),
},
{
id: "hex-decode",
label: "Hex Decode",
category: "encoding",
description: "16 進表現を UTF-8 テキストとして復号します。",
run: (input) => ({ output: fromHex(input) }),
},
{
id: "rot13",
label: "ROT13",
category: "crypto",
description: "英字に ROT13 を適用します。",
run: (input) => ({
output: Array.from(input, (character) => rotateAsciiLetter(character, 13)).join(""),
}),
},
] as const satisfies readonly CtfTransform[];
56 changes: 56 additions & 0 deletions src/features/ctf/types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
export type CtfTransformCategory =
| "encoding"
| "crypto"
| "forensics"
| "network"
| "web"
| "binary";

export interface CtfTransformOptions {
readonly flagPatterns?: readonly FlagPattern[];
readonly [key: string]: unknown;
}

export interface CtfTransformResult {
readonly output: string;
readonly notes?: readonly string[];
}

export interface CtfTransform {
readonly id: string;
readonly label: string;
readonly category: CtfTransformCategory;
readonly description: string;
run(input: string, options?: CtfTransformOptions): CtfTransformResult;
}

export interface DetectionRange {
readonly start: number;
readonly end: number;
}

export interface CtfDetection {
readonly type: string;
readonly confidence: number;
readonly range: DetectionRange;
readonly recommendedActions: readonly string[];
}

export interface CtfDetector {
readonly id: string;
readonly label: string;
detect(input: string, options?: CtfTransformOptions): readonly CtfDetection[];
}

export interface FlagPattern {
readonly id: string;
readonly label: string;
readonly source: string;
readonly flags?: string;
readonly description: string;
}

export interface CtfHintSection {
readonly title: string;
readonly items: readonly string[];
}
Loading
Loading