Regex and grep for finding CTF flags in dumps part 1

Depov

Moderator
Staff member
MODERATOR
ULTIMATE
SUPREME
PREMIUM
MEMBER
Joined
Feb 18, 2025
Messages
790
Reaction score
1,510
How CTF flags work and why grep "flag" doesn't work

Before we launch anything, let's figure out the format of what we're looking for. The vast majority of CTF competitions use a template. PREFIX{содержимое}, where PREFIX is the platform name or standard marker: For more details, see our article on creating CTF tasks .



The first mistake of a beginner is the command grep "flag" dump.txtIn a two-gigabyte log, the word “flag” will appear thousands of times: in command line arguments ( --flag), in variable names, and in comments. Get pages of garbage. Searching for a flag in a CTF dump requires a regex pattern that precisely describes the flag's format—with curly braces and specific content.

Basic logic: We need a regular expression for flag{}, which matches the word flag, followed by an opening curly brace, then any content, and a closing brace. In regex, this is flag\{[^}]+\}— literal symbols flag, shielded \{ (because {— a metacharacter in regex), one or more characters except } ( [^}]+) and closing \}Escaping is required: without backslashes, grep interprets the curly braces as a repetition quantifier, not as part of the search text.
grep -E -o: Usage examples for extracting flags

Two grep utility flags that solve 70% of CTF tasks - -E And -oIt is possible to work without them, but it is noticeably more painful.

Flag -Eswitches grep to Extended Regular Expressions (ERE) mode. In ERE, metacharacters +, ?, |and grouping brackets ()work directly, without backslash escaping. Without -EI would have to write grep 'flag\{[^}]\+\}'- pay attention to \+instead of +. With -Ethe pattern is cleaner: grep -E 'flag\{[^}]+\}'.

Flag -ooutputs only the matched part of the string, not the entire string. Without -ogrep will show a log line that is a thousand characters long, with a flag hidden somewhere inside it. -oyou get exactly flag{ваш_ответ}— and nothing extra. This saves nerves during CTFs.

Team grep -Eo 'flag\{[^}]+\}' dump.txt— the basic workhorse. It should be run first on any CTF task that requires a text file.

If the flag format is not known in advance, the pattern is expanded: grep -Eoi '[a-zA-Z0-9_]+\{[^}]+\}' dump.txt. Here [a-zA-Z0-9_]+matches any "word" before the curly braces, and the flag -iadds case insensitivity. This command will catch FLAG{}, CTF{}, Key{}and any other format with curly braces.
Regex Patterns for CTFs: From Flag{} to Custom Formats

In practice, regex patterns have to be adapted to the specific competition. Here's a set that covers most scenarios:

grep -Eo 'flag\{[^}]+\}' dump.txt
grep -Eo 'picoCTF\{[^}]+\}' dump.txt
grep -Eoi '(flag|ctf|key|secret|hack)\{[^}]+\}' dump.txt
grep -Eo '[A-Fa-f0-9]{32}' dump.txt
grep -Eo '[A-Fa-f0-9]{64}' dump.txt
grep -Po 'flag\{.+?\}' dump.txt

The first three lines are searches for a specific or general format. PREFIX{...}The fourth and fifth are searches for MD5 and SHA-256 hashes when the flag is a bare hash without brackets (32 or 64 hexadecimal characters). The sixth uses -P(PCRE) with non-greedy quantifier .+?— more on that below.

Alternating through |allows you to search for multiple formats in one pass through the file. The command grep -Eoi '(flag|ctf|key|secret)\{[^}]+\}' dump.txtwill find flag{...}, CTF{...}, key{...} And secret{...}simultaneously. Instead of four passes, grep makes one—on a gigabyte-sized file, this is noticeable.

A separate trap is greedy quantifiers. If a log line contains flag{abc} мусор flag{real_answer}, pattern with greedy .+will capture everything from the first opening parenthesis to the last closing parenthesis: flag{abc} мусор flag{real_answer}. Not greedy .+?(available only with flag -P) will return two separate results: flag{abc} And flag{real_answer}It's a small thing, but on a CTF it can cost 15 minutes.
Parsing Linux Logs with Regular Expressions via PCRE

Flag -PIn GNU grep, Perl-Compatible Regular Expressions are available. For CTF, there are two key tools:

Non-greedy quantifiers. Already mentioned .+?instead of .+. In ERE (mode -E) there are no non-greedy quantifiers - this is the main reason to switch to -Pfor complex tasks.

Lookahead/lookbehind. If you need to extract only the contents of the flag without the parentheses, the following construct will come in handy: grep -Po '(?<=flag\{)[^}]+(?=\})' dump.txtRetrospective verification (?<=flag\{)means "the match must be preceded by flag{», leading (?=\})- "After the match there should be }" The result is only the text between the brackets. It's convenient when the platform accepts the response without the framing. flag{...}.

A limitation that is often forgotten: -P— GNU grep extension. On macOS, BSD grep is installed, where -Pnot supported. Options: install GNU grep via brew install grep(the team will become ggrep -P) or use pcregrep, which can run PCRE natively.

Parsing Linux logs with regular expressions in a CTF context goes beyond the simple flag{}The organizers hide flags in HTTP headers, cookies, and base64 strings within JSON. For such cases, a pipelined approach works better than a monolithic regex: first, grepisolates suspicious lines, then cut or awkextracts the required field, then base64 -dDecodes. More on this in the section on encodings.
How to find a flag in a large text file

CTF dumps can be large. 500 MB is common in forensics, while 2 GB or more is common in advanced competitions. Processing large logs with the command line requires a few tricks, and here are some that actually work:

LC_ALL=C— switches grep to a single-byte locale instead of UTF-8. On files without Cyrillic characters (most CTF dumps are in English), this provides a 5-10x speedup. The reason is simple: in UTF-8, grep checks the validity of multibyte sequences on each character. In the C locale, each byte is a separate character, so checking is not necessary. It's used like this: LC_ALL=C grep -Eo 'flag\{[^}]+\}' huge_dump.txtI always start with this.

-m 1— stop after the first match. If you know there's only one flag in the file (and most CTF tasks do), grep -Eom1 'flag\{[^}]+\}' dump.txtwill stop reading the file immediately after the first match. On a 2GB file, the difference is minutes, because grep doesn't finish reading the remaining tail.

-a(aka --binary-files=text) — forces grep to treat binary files as text files. Without this, grep will output Binary file matchesand stop without showing a match. CTF dumps often contain binary inclusions—forgotten headers, fragments of images.

stringsbefore grep - utility stringsExtracts only printable sequences from a file (default: 4 characters). Pipeline strings dump.bin | grep -Eo 'flag\{[^}]+\}'works faster and cleaner than grep -aby binary file, because grep receives only text fragments as input.
ripgrep and strings to speed up searching in dumps

ripgrep (team rg) is written in Rust, and for CTF it has three trump cards: automatic skipping of binary files, recursive search by default, and speed - on files over 1 GB, ripgrep consistently outperforms GNU grep by 2-5 times due to parallel reading.

Syntax almost identical: rg -o 'flag\{[^}]+\}' dump.txtFor PCRE patterns: rg -Po '(?<=flag\{)[^}]+(?=\})' dump.txt(requires ripgrep to be built with PCRE2 support, which is enabled by default in most package managers).

Installation: apt install ripgrep on Debian/Ubuntu, brew install ripgrepOn macOS. Ripgrep is often not recommended on CTF machines, so knowing GNU grep is essential, and keeping ripgrep as an accelerator on your workstation.

Combination strings And rgespecially good for binary dumps: strings -n 8 firmware.bin | rg -o 'flag\{[^}]+\}'. Parameter -n 8in stringsRaises the minimum length of extracted lines to 8 characters, cutting off garbage short fragments.
 
Top Bottom