Skip to content

About

Linux privilege-escalation wargame (42): SUID binaries, injection, race conditions, binary analysis.

Topics

Resources

Stars

1 star

Watchers

0 watching

Forks

Repository files navigation

Snow Crash (42)

A progressive CTF-style wargame designed to teach practical Linux security fundamentals through hands-on exploitation of common vulnerabilities. Each level presents a unique security challenge, requiring enumeration, analysis, and privilege escalation to progress.


What This Project Demonstrates

  • Linux Security Fundamentals — Deep understanding of permissions, SUID/SGID, users, groups, and process management
  • Reconnaissance & Enumeration — Systematic discovery of attack surfaces through file inspection, binary analysis, and environment exploration
  • Privilege Escalation Patterns — Exploiting misconfigurations, race conditions, injection flaws, and unsafe program behaviors
  • Binary Analysis & Reverse Engineering — Reading assembly, understanding program flow, identifying vulnerabilities in compiled code
  • Secure Coding Awareness — Learning dangerous patterns (command injection, buffer overflows, regex evaluation, TOCTOU) and how to prevent them
  • Cryptographic Analysis — Breaking weak encryption schemes, hash cracking, understanding cipher weaknesses
  • Defensive Mindset — Understanding attacker methodology to build secure systems

Toolbox

Category Tools
Enumeration find, ls, file, strings, id, ps, env, netstat, ss
Binary Analysis objdump, readelf, nm, gdb, ltrace, strace
Network Analysis tcpdump, wireshark, nc (netcat), curl
Password Cracking john (John the Ripper), hashcat, Python crypt module
Scripting bash, python, perl
Editors vim, nano, echo, cat

Methodology

Each level follows a systematic security assessment approach:

  1. Initial Reconnaissance — Identify current user context, available files, permissions, SUID binaries
  2. File Enumeration — Search for files owned by target users (find / -user flagXX 2>/dev/null)
  3. Binary/Script Analysis — Examine executables with file, strings, objdump, ltrace, strace
  4. Vulnerability Identification — Classify the weakness (injection, race condition, crypto flaw, etc.)
  5. Safe Exploitation — Validate the vulnerability without causing system damage
  6. Learning Extraction — Document the root cause and mitigation strategies
  7. Token Retrieval — Execute getflag to obtain the next level password

Setup & Connection

VM Network Configuration:

  • Settings → Network → Attached to: Host-only Adapter
  • Launch VM and connect via SSH:
ssh level00@192.168.56.101 -p 4242

Alternative: Port forwarding (see image.png and image-1.png in repo)


Security Theory Reference

Password Hashing in Unix/Linux

Stored in /etc/passwd (legacy) or /etc/shadow (modern). Format:

$<id>$<salt>$<hash>
Algorithm Prefix Example
DES (crypt) (none) 42hDRfypTqqnw
MD5 $1$ $1$salt$wCghuVY8B0Y3Vxup6hbnK0
SHA-256 $5$ $5$salt$1qXGc3HhCIV8R8YUI8v3A1jN2Fq6C.Z9QW
SHA-512 $6$ $6$salt$jbL5r9GrsUOScNwD6mAeuU5D4a7XnsvX7.

Cracking Tools:

  • DES crypt: john --format=descrypt, Python crypt module
  • MD5: john --format=md5crypt, hashcat -m 500
  • SHA-256: john --format=sha256crypt, hashcat -m 7400
  • SHA-512: john --format=sha512crypt, hashcat -m 1800

Levels — Step-by-Step Vulnerability Notes

Level 00 — File Enumeration & ROT Cipher

Goal: Find a hidden file and decrypt a simple substitution cipher

Vulnerability type: Weak obfuscation (Caesar/ROT cipher)

Tools you can use:

  • find — Locate files by ownership
  • cat / strings — Read file contents
  • Online cipher tools or custom scripts

Step-by-step approach:

  1. Enumerate files owned by flag00 using find / -user flag00 2>/dev/null
  2. Identify accessible files in unusual locations (e.g., /usr/sbin/john)
  3. Read file contents to discover encoded string
  4. Recognize pattern as a rotation cipher (ROT-N)
  5. Test all ROT variations (ROT1-ROT25) manually or via automated tool
  6. Identify plaintext password when it appears as readable English
  7. Use discovered password to authenticate as flag00 and run getflag

What you learn:

  • Basic Linux file enumeration by user ownership
  • Recognition of simple substitution ciphers
  • Importance of not storing sensitive data in predictable locations
  • Security through obscurity is not security

Mitigation:

  • Never rely on encoding/obfuscation for password protection
  • Use proper access controls and encryption for sensitive data
  • Avoid storing credentials in files accessible to multiple users
  • Implement proper secret management systems

Level 01 — Weak Password Hash (DES Crypt)

Goal: Extract and crack a legacy password hash from /etc/passwd

Vulnerability type: Weak hashing algorithm (DES crypt), exposed password hash

Tools you can use:

  • cat — Read /etc/passwd
  • Python crypt module
  • john (John the Ripper)
  • Wordlist (e.g., rockyou.txt)

Step-by-step approach:

  1. Inspect /etc/passwd for unusual entries
  2. Identify flag01 entry with visible password hash (no x placeholder)
  3. Extract hash format: 42hDRfypTqqnw (DES crypt, 2-char salt)
  4. Recognize salt: first 2 characters (42)
  5. Prepare password cracking setup with wordlist
  6. Write Python script using crypt.crypt(word, salt) or use john --format=descrypt
  7. Iterate through wordlist, comparing computed hashes to target
  8. Identify matching password and authenticate

What you learn:

  • Legacy Unix password storage vulnerabilities
  • How salt works in password hashing (prevents rainbow tables but doesn't stop dictionary attacks)
  • DES crypt is computationally weak by modern standards
  • Dictionary attacks are effective against weak passwords

Mitigation:

  • Use modern hashing algorithms (bcrypt, scrypt, argon2)
  • Store hashes in protected /etc/shadow, not world-readable /etc/passwd
  • Enforce strong password policies
  • Implement rate limiting and account lockout mechanisms

Level 02 — Network Traffic Analysis (PCAP)

Goal: Extract credentials from captured network traffic

Vulnerability type: Cleartext credential transmission, insecure protocols

Tools you can use:

  • wireshark — GUI packet analyzer
  • tcpdump — Command-line packet capture
  • scp — Copy PCAP file to analysis machine
  • Hex dump analysis

Step-by-step approach:

  1. Discover level02.pcap file in home directory
  2. Transfer PCAP to host machine using scp -P 4242 level02@IP:~/level02.pcap /local/path
  3. Open in Wireshark for visual analysis
  4. Navigate to Statistics → Conversations → TCP → Follow Stream
  5. Observe login attempt with visible password characters
  6. Notice 0x7f (DEL/Backspace) characters in hex dump
  7. Reconstruct actual password by removing deleted characters
  8. Authenticate using reconstructed credentials

What you learn:

  • Network traffic can expose credentials in cleartext protocols
  • PCAP files retain full session data including keystrokes
  • Terminal control characters (backspace/delete) visible in packet captures
  • Passive network sniffing risks

Mitigation:

  • Always use encrypted protocols (SSH, TLS, HTTPS)
  • Never transmit credentials over unencrypted channels
  • Implement network segmentation and encryption
  • Use VPNs for sensitive network access

Level 03 — Command Injection via System Calls

Goal: Exploit unsafe system command execution in a SUID binary

Vulnerability type: Command injection, insecure PATH, system() misuse

Tools you can use:

  • file — Identify binary type
  • strings — Extract readable strings
  • objdump — Disassemble binary
  • ltrace / strace — Trace library/system calls
  • export — Modify environment variables

Step-by-step approach:

  1. Identify SUID binary level03 owned by flag03
  2. Run strings to identify suspicious command execution patterns
  3. Use ltrace ./level03 to trace library calls at runtime
  4. Observe call to system() with relative command (e.g., echo)
  5. Recognize PATH exploitation opportunity
  6. Create malicious executable named echo containing getflag
  7. Prepend current directory to PATH: export PATH=/tmp:$PATH
  8. Execute binary to trigger malicious echo instead of /bin/echo

What you learn:

  • SUID binaries run with owner privileges (privilege escalation vector)
  • system() uses shell interpretation (injection risk)
  • Relative paths in system() calls are dangerous
  • PATH environment variable controls command resolution

Mitigation:

  • Always use absolute paths in system() calls (/bin/echo not echo)
  • Avoid system() entirely; use execve() with controlled arguments
  • Sanitize all user input and environment variables
  • Drop privileges immediately after SUID escalation if not needed

Level 04 — CGI Command Injection (Perl)

Goal: Exploit command injection in a Perl CGI web application

Vulnerability type: Shell command injection via web parameter

Tools you can use:

  • curl — Send HTTP requests
  • netstat / ss — Verify listening ports
  • URL encoding

Step-by-step approach:

  1. Discover level04.pl Perl script running as CGI
  2. Identify it listens on localhost:4747
  3. Analyze code: print \echo $y 2>&1`;` — backticks execute shell commands
  4. Recognize parameter x is directly interpolated without sanitization
  5. Craft injection payload using shell metacharacter ; to chain commands
  6. URL-encode payload: curl 'http://localhost:4747/?x=test;getflag'
  7. Observe command execution and flag retrieval in response

What you learn:

  • CGI applications can execute with elevated privileges
  • Backticks and system() in Perl execute shell commands
  • Shell metacharacters (;, |, &&, `) enable command chaining
  • Web parameters are untrusted input vectors

Mitigation:

  • Never pass user input directly to shell execution functions
  • Use parameterized commands or safe APIs (avoid shell entirely)
  • Whitelist valid input patterns with strict regex validation
  • Run web applications with minimal necessary privileges

Level 05 — Cron Job Exploitation

Goal: Exploit a scheduled cron job running as privileged user

Vulnerability type: Writable cron script, insecure cron configuration

Tools you can use:

  • crontab — View scheduled jobs
  • cat — Read mail/cron files (/var/mail, /var/spool/cron)
  • find — Locate writable scripts
  • chmod — Modify permissions
  • ln — Create symbolic links

Step-by-step approach:

  1. Check /var/mail/level05 or /var/spool/cron/crontabs/ for scheduled tasks
  2. Identify cron entry running as flag05: */2 * * * * su -c "sh /usr/sbin/openarenaserver" - flag05
  3. Examine /usr/sbin/openarenaserver script behavior
  4. Determine if script executes commands from writable directories
  5. Identify writable path or script that will be sourced/executed
  6. Place malicious script (e.g., getflag > /tmp/output) in exploitable location
  7. Wait for cron execution (every 2 minutes) or trigger if possible
  8. Retrieve flag from output file

What you learn:

  • Cron jobs often run with elevated privileges
  • Scripts executed by cron must have secure permissions
  • Writable paths in cron-executed scripts = privilege escalation
  • Cron runs in minimal environment (PATH considerations)

Mitigation:

  • Ensure cron scripts are writable only by root/owner
  • Use absolute paths in cron jobs
  • Validate all executed scripts and their parent directories are secure
  • Implement audit logging for cron job execution

Level 06 — PHP Regex Code Execution (/e Modifier)

Goal: Exploit dangerous PHP regex /e modifier for arbitrary code execution

Vulnerability type: PHP preg_replace() with /e modifier (code evaluation)

Tools you can use:

  • cat — Read PHP source (level06.php)
  • objdump — Analyze SUID wrapper binary
  • echo — Create test input files
  • PHP documentation

Step-by-step approach:

  1. Examine level06.php source code
  2. Identify preg_replace("/(\[x (.*)\])/e", "y(\"\\2\")", $a) — the /e modifier
  3. Recognize /e causes replacement string to be evaluated as PHP code
  4. Design payload to inject executable PHP: [x {${system(getflag)}}]
  5. Create test file: echo '[x {${system(getflag)}}]' > /tmp/exploit
  6. Execute wrapper binary: ./level06 /tmp/exploit
  7. Observe system() execution and flag retrieval

What you learn:

  • PHP's /e modifier in preg_replace() evaluates code (deprecated in PHP 5.5+, removed in PHP 7+)
  • Regex replacement strings become code execution vectors
  • SUID wrappers elevate PHP script privileges
  • Legacy code often contains known-dangerous features

Mitigation:

  • Never use /e modifier in preg_replace() (use preg_replace_callback())
  • Sanitize all user-controlled input before regex processing
  • Keep PHP updated to versions without deprecated dangerous features
  • Code review for eval-like constructs (eval(), create_function(), /e)

Level 07 — Environment Variable Injection

Goal: Exploit unsafe environment variable usage in SUID binary

Vulnerability type: Unvalidated environment variable in system() call

Tools you can use:

  • objdump — Disassemble binary
  • strings — Identify environment variable names
  • export — Set malicious environment variables
  • env — View current environment

Step-by-step approach:

  1. Identify SUID binary level07 owned by flag07
  2. Disassemble with objdump -d level07 or analyze .rodata section
  3. Trace calls to getenv() and system() in disassembly
  4. Extract environment variable name from .rodata: LOGNAME
  5. Recognize pattern: system(sprintf(cmd, getenv("LOGNAME")))
  6. Craft injection payload: export LOGNAME='; /bin/getflag #'
  7. Execute binary; injected command runs with elevated privileges

What you learn:

  • Environment variables are attacker-controlled input
  • Using env vars in system() without validation = command injection
  • Shell command concatenation with untrusted data is dangerous
  • SUID binaries inherit caller's environment

Mitigation:

  • Never trust environment variables in privileged contexts
  • Sanitize or whitelist environment variable contents
  • Use execve() with controlled argument arrays instead of system()
  • Clear/reset environment before executing privileged operations

Level 08 — Symlink Bypass (Path Traversal)

Goal: Bypass filename-based access control using symbolic links

Vulnerability type: Insecure path validation (checks filename not resolved path)

Tools you can use:

  • objdump — Analyze binary logic
  • strings — Extract forbidden filename strings
  • ln — Create symbolic links
  • cat — Read files via program

Step-by-step approach:

  1. Discover binary level08 and protected file token
  2. Attempt to read token directly — access denied
  3. Analyze binary with objdump -s -j .rodata to extract error messages
  4. Identify blacklist check: program refuses files containing string "token"
  5. Recognize vulnerability: checks argument string, not resolved file path
  6. Create symlink with different name: ln -s ~/token /tmp/nottoken
  7. Execute: ./level08 /tmp/nottoken — bypass succeeds
  8. Token contents displayed

What you learn:

  • Blacklist filtering on filenames is easily bypassed
  • Symlinks decouple filenames from actual file paths
  • Path validation must resolve symbolic links before access control
  • TOCTOU-related: checking name vs. checking actual resource

Mitigation:

  • Resolve symbolic links before access checks (realpath(), readlink())
  • Use whitelist approach (allow specific paths) not blacklist
  • Validate canonical paths after full resolution
  • Implement OS-level access controls (file permissions) as primary defense

Level 09 — Custom Encryption Algorithm (Caesar Shift Variant)

Goal: Reverse-engineer and decrypt a progressive Caesar cipher

Vulnerability type: Weak custom encryption (security through obscurity)

Tools you can use:

  • objdump — Disassemble encryption binary
  • strings — Read encrypted token file
  • Python — Write decryption script
  • xxd / hexdump — Analyze binary data

Step-by-step approach:

  1. Discover level09 binary and token file
  2. Analyze binary with objdump to understand encryption algorithm
  3. Recognize pattern: each character shifted by n + index (progressive Caesar)
  4. Example: character at position 0 → +0, position 1 → +1, position 2 → +2
  5. Read encrypted token file contents
  6. Write Python decryption script reversing the algorithm
  7. Decrypt token to reveal flag password

What you learn:

  • Custom/proprietary encryption is rarely secure
  • Reverse engineering can expose algorithm weaknesses
  • Caesar ciphers (even progressive variants) are trivial to break
  • Obscurity ≠ security

Mitigation:

  • Use proven cryptographic standards (AES, ChaCha20)
  • Never implement custom encryption algorithms
  • Follow Kerckhoffs's principle (security lies in the key, not algorithm secrecy)
  • Use established libraries (OpenSSL, libsodium)

Level 10 — TOCTOU Race Condition

Goal: Exploit Time-Of-Check-Time-Of-Use (TOCTOU) race condition

Vulnerability type: Race condition between access() and open() system calls

Tools you can use:

  • nc (netcat) — Listen for network connections
  • ln — Create/manipulate symbolic links rapidly
  • Bash loops — Automate race condition exploitation
  • netstat / ss — Verify listener

Step-by-step approach:

  1. Analyze level10 binary behavior: checks file access with access(), then opens with open()
  2. Identify network component: sends file contents to specified host:port (6969)
  3. Recognize TOCTOU vulnerability: time window between check and use
  4. Set up listener: nc -lk 6969 >> /tmp/capture
  5. Create benign accessible file: echo OK > /tmp/benign
  6. Launch symlink race loop: rapidly switch /tmp/target between benign and token
  7. Spam program execution: while true; do ./level10 /tmp/target 127.0.0.1; done
  8. Wait for race condition success: access() checks benign, open() reads token
  9. Extract token from /tmp/capture

What you learn:

  • TOCTOU is a classic race condition vulnerability
  • access() followed by open() is a dangerous pattern
  • Attackers can manipulate filesystem state between checks and operations
  • Race conditions are probabilistic but often winnable with automation

Mitigation:

  • Never use access() before open() (just open() and check result)
  • Use openat() with file descriptors for atomic operations
  • Avoid filesystem-based security checks
  • Design systems to be race-condition-resistant (use locks, atomic ops)

Level 12 — Perl CGI Command Injection (Advanced)

Goal: Bypass input filtering to achieve command injection

Vulnerability type: Insufficient input sanitization, regex bypass

Tools you can use:

  • curl — Send crafted HTTP requests
  • Perl regex analysis
  • URL encoding

Step-by-step approach:

  1. Analyze Perl CGI script at localhost:4646
  2. Identify input processing: tr/a-z/A-Z/ (uppercase), s/\s.*// (removes spaces and after)
  3. Recognize command execution: egrep "^$xx" /tmp/xd 2>&1 with user input $xx
  4. Determine space filtering can be bypassed with shell escapes or alternate metacharacters
  5. Craft payload without spaces: use semicolons, backticks, or command substitution
  6. Example: x=$(getflag) or chaining with ; without spaces
  7. URL-encode and send via curl
  8. Extract flag from response

What you learn:

  • Blacklist/filter bypass techniques (spaces, quotes, escaping)
  • Shell metacharacters provide multiple injection vectors
  • Input transformation (uppercase, trim) doesn't prevent injection
  • Defense in depth: filtering alone is insufficient

Mitigation:

  • Never interpolate user input into shell commands
  • Use parameterized/safe APIs (avoid system(), backticks, qx//)
  • Whitelist validation with strict patterns
  • Escape all special characters or avoid shell entirely

Level 13 — Hardcoded UID Check Bypass (Binary Patching)

Goal: Bypass hardcoded UID validation in binary

Vulnerability type: Client-side authentication, hardcoded security checks

Tools you can use:

  • objdump — Disassemble and analyze checks
  • gdb — Debug and modify execution flow
  • strings — Extract encrypted token
  • Binary patching or runtime manipulation

Step-by-step approach:

  1. Run level13 binary — observe UID check failure
  2. Disassemble to find getuid() call and comparison logic
  3. Identify hardcoded UID check (e.g., if (getuid() != 4242))
  4. Use gdb to break at UID check, modify register to pass check
  5. Alternatively, patch binary to skip check or NOP out comparison
  6. Extract encrypted token string from .rodata
  7. Analyze decryption routine or XOR key
  8. Decrypt token to reveal password

What you learn:

  • Client-side checks (UID, license validation) can be bypassed
  • Binary patching and debugging override hardcoded logic
  • Security cannot rely on client-side enforcement
  • Obfuscation and hardcoded secrets are ineffective

Mitigation:

  • Perform authentication/authorization server-side only
  • Never hardcode secrets or checks in client binaries
  • Use cryptographic signatures for code integrity
  • Assume client environment is hostile/compromised

Level 14 — Reverse Engineering getflag Binary

Goal: Understand and exploit the getflag mechanism itself

Vulnerability type: Likely category — kernel exploitation, binary reverse engineering, privilege escalation via system call manipulation

Tools you can use:

  • objdump — Disassemble /bin/getflag
  • gdb — Debug getflag behavior
  • strace / ltrace — Trace system/library calls
  • strings — Extract hardcoded data
  • Kernel debugging tools (if applicable)

Step-by-step approach:

  1. No files owned by flag14 found — focus shifts to /bin/getflag itself
  2. Disassemble /bin/getflag with objdump -d /bin/getflag > /tmp/analysis
  3. Analyze UID/GID checks and token retrieval mechanisms
  4. Identify encryption/obfuscation of flag tokens
  5. Trace system calls to understand how getflag validates privilege
  6. Look for exploitable conditions (buffer overflow, format string, logic error)
  7. Exploit vulnerability or reconstruct token decryption
  8. Retrieve final flag

What you learn:

  • Security tools themselves can have vulnerabilities
  • Deep binary analysis reveals implementation details
  • Privilege escalation can target the privilege-checking mechanism itself
  • Understanding system internals (UID/EUID, system calls) is critical

Mitigation:

  • Thoroughly audit security-critical binaries
  • Use static analysis and fuzzing on privileged programs
  • Minimize attack surface of SUID/privileged executables
  • Implement defense in depth (don't rely on single security check)

Notes

This README intentionally avoids including flags, passwords, or complete exploit code to preserve the educational value of the Snow Crash project. The focus is on methodology, vulnerability classification, and defensive lessons rather than solutions.

Each level teaches a specific security concept applicable to real-world systems. The goal is to understand why vulnerabilities exist and how to prevent them in production code.


Disclaimer

This project is for educational purposes only. All techniques demonstrated should be practiced exclusively in controlled lab environments like the Snow Crash VM.

Do not use these techniques against systems you do not own or do not have explicit written permission to test. Unauthorized access to computer systems is illegal and unethical.

The knowledge gained here should be applied to defensive security: building more secure systems, conducting authorized penetration tests, and understanding attacker methodology to better protect infrastructure.

About

Linux privilege-escalation wargame (42): SUID binaries, injection, race conditions, binary analysis.

Topics

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages