Detecting and Preventing Injection Attacks: A Deep Dive into SQL, NoSQL, and Scanners

Detecting and Preventing Injection Attacks: A Deep Dive into SQL, NoSQL, and Scanners

Code injection represents a critical class of security vulnerability where unvalidated data is added (injected) into a vulnerable program and executed. This flaw is widespread and can occur in various environments, including SQL, NoSQL, LDAP, XPath, XML parsers, and even through SMTP headers.


Understanding Code Injection and its Types

The insidious nature of code injection lies in its ability to bypass an application’s intended logic. Even Cross-Site Scripting (XSS) vulnerabilities are examples of code injection. When an unsanitized HTML tag containing malicious code within its attribute is submitted to a web application’s database (perhaps via a comment thread or discussion board), that code is injected into the application. This malicious script is then executed when other users view that same content, leading to a compromise.

For the purpose of this detailed analysis, the focus is squarely on detecting and preventing code injection attacks related to databases—specifically SQL Injection (SQLi) and NoSQL Injection (NoSQLi). This article explores how to use powerful Command Line Interface (CLI) tools to test form inputs for these vulnerabilities, scan for various injection attacks, and outlines best practices for avoiding damage to your target’s database during testing.

Key Topics Covered:


Technical Requirements for Vulnerability Testing

To perform effective testing for injection vulnerabilities, several tools are required. In addition to using existing Burp and Burp Proxy integration with a browser like Chrome (version 66.0.3359.139 is noted), the following tools are indispensable:

Installation Note for Arachni: It is recommended to install Arachni from the site’s Download page, for example: http://www.arachni-scanner.com/download/#Mac-OS X (Please note: Always check the official website for the current installation method).

After downloading the appropriate package, it is necessary to create a symlink (symbolic link) so that all the arachni CLI packages are available within your system’s path.

Example Symlink Command:

sudo ln -s /Path/to/arachni-1.5.1-0.5.12/bin/arachni* /usr/local/bin

If you encounter an error like:

/usr/local/bin/arachni: line 3: /usr/local/bin/readlink_f.sh: No such file or directory
/usr/local/bin/arachni: line 4: readlink_f: command not found
/usr/local/bin/arachni: line 4: ./../system/setenv: No such file or directory

Simply symlink, copy, or move the readlink_f.sh script from your Arachni installation’s bin directory to your path.

Symlinking readlink_f.sh:

sudo ln -s /Path/to/arachni-1.5.1-0.5.12/bin/readlink_f.sh /usr/local/bin/readline_f.sh

With this setup, you can invoke arachni directly without typing the full path every time.


SQLi and Other Code Injection Attacks – Accepting Unvalidated Data

SQL Injection (SQLi) is a rather old vulnerability, with public disclosures appearing as far back as 1998 in publications like Phrack. Despite its age, it persists, often leading to critically damaging consequences.

SQLi flaws can allow an attacker to read sensitive data, update database information, and sometimes even issue OS commands. As OWASP (Open Web Application Security Project) succinctly states, the “flaw depends on the fact that SQL makes no real distinction between the control and data planes.” This means that SQL commands can modify both the data they contain and parts of the underlying system running the software. When certain access prerequisites are met, an SQLi flaw can even be used to issue system commands, demonstrated by features like sqlmap‘s --os-shell flag.

While many tools and design patterns exist for prevention, the pressure of rapidly deploying new applications and iterating quickly on features often means that SQLi-vulnerable inputs are not properly audited, and the necessary prevention procedures are neglected.

As a vulnerability endemic (commonly found) to one of the most common languages for database development, and one that is easily detected, easily exploited, and richly rewarded by attackers, SQLi is an extremely worthy subject for study.

A Simple SQLi Example

To understand how SQLi works, consider the following database query, where the value of $id would be user-supplied input:

SELECT title, author FROM posts WHERE id=$id

One common SQLi technique involves inputting data that can change the context or logic of the SQL statement’s execution. Since the $id value is being inserted directly—with no data sanitization (removal of dangerous code) or data type transformation—the SQL statement becomes dynamic and subject to tampering.

Consider a user-supplied input that changes the execution logic:

SELECT title, author FROM posts WHERE id=10 OR 1=1

In this case, 10 OR 1=1 is the user-supplied data. By modifying the WHERE clause, the user can successfully alter the logic of the developer-supplied part of the executed example. The original developer intended to retrieve only the post with ID 10, but the injected clause OR 1=1 (which is always true) effectively makes the WHERE clause true for every row, potentially returning all posts.

While the example above is relatively innocuous (harmless) for a blog post, if the statement were querying for sensitive account information from a user table, or a part of the database associated with privileges, that vulnerability could represent a way to seriously damage the application.


Testing for SQLi With Sqlmap – Where to Find It and How to Verify It

sqlmap is a popular CLI tool for detecting and exploiting SQLi vulnerabilities. When testing, the primary goal is discovery, though understanding the weaponization (the attacker’s use) is helpful for brainstorming possible attack scenarios for security report submissions.

The simplest use of sqlmap involves the -u flag to target the parameters being passed in a specific URL. Using webscantest.com as an example target, you can test parameters in a form submission that is specifically vulnerable to GET requests:

sqlmap -u "http://webscantest.com/datastore/search_get_by_id.php?id=3"

As sqlmap begins probing the parameters passed in the target URL, it will prompt you with questions to refine the scope of the attack:

it looks like the back-end DBMS is 'MySQL'. Do you want to skip test payloads specific for other DBMSes? [Y/n]

If the backend database management system (DBMS) can be successfully identified through separate investigations, it’s a good idea to answer Y (Yes) here to reduce potential noise in the final report.

You will also be asked about the risk level of input values you are willing to tolerate:

for the remaining tests, do you want to include all tests for 'MySQL' extending provided level (1) and risk (1) values?

Since sqlmap is designed to both detect and exploit SQLi vulnerabilities, it must be handled with care. Unless the testing is against a sandboxed instance (an isolated testing environment) completely independent from all production systems, it is crucial to select the lower risk-level settings. Using the lowest risk level ensures that sqlmap will test the form with malicious SQL inputs designed to cause the database to sleep or enumerate hidden information—and not corrupt data or compromise authentication systems. Due to the sensitivity of the information and processes in the targeted SQL database, it is paramount to tread carefully with vulnerabilities associated with backend systems.

After sqlmap runs through its range of test inputs and you have addressed all parameters passed in the targeted URL, it will print out a report of all discovered vulnerabilities.

Successful Discovery Example: A successful scan often reveals multiple vulnerabilities related to a parameter, such as a pair of blind SQLi vulnerabilities (where the results of the injection are not directly visible in the GUI), and error- and UNION-based inputs—all confirmed by the documentation on a dedicated testing site like webscantest.com.


Trawling for Bugs – Using Google Dorks and Python for SQLi Discovery

While sqlmap requires a URL with testable parameters, this next technique—Google Dorks—can be used to find potentially vulnerable targets first. This method can specifically target applications and form inputs, or simply return a list of sites theoretically susceptible to SQLi vulnerabilities.

Google Dorks for SQLi

Google Dorks—sometimes referred to as Google hacking—involves employing specially-crafted search queries to compel search engines to return sites that may be susceptible to SQLi and other vulnerabilities. The name “Google dork” is derived from the idea of a hapless (unfortunate) employee misconfiguring their site and exposing sensitive corporate information online.

Here are a few examples of common Google Dorks used for discovering instances of SQLi:

These queries are designed to return results where the discovered sites are at least theoretically susceptible to SQLi because of their specific URL structure (i.e., passing parameters like id, category, or file in the URL).

The basic form of a dork is search_method:domain/dork, where the search_method and dork are calibrated to look for a specific type of vulnerability, and domain is used when targeting a specific application.

Example of a different dork (not for SQLi):

intitle:”EvoCam” inurl:”webcam.html”

This dork doesn’t target a particular URL; it’s simply looking for any site where the page’s title contains EvoCam and the page’s URL contains webcam.html, potentially returning insecure CCTV feeds.

Validating a Dork

Imagine discovering a dork such as this on a security site (the company title is fictionalized):

inurl:index.jsp? intext:"some company title"

This dork focuses on a particular company via the intext search filter. The jsp in the inurl value is the file extension for JSP (JavaServer Pages), a web application framework for Java servlets. JSP is older technology (Sun Microsystems’ 1999 response to Microsoft’s Active Server Pages), but like much older tech, it is still employed in legacy industries, small businesses, and small development shops.

When this dork is used in a Google search, the first result might return a URL containing index.jsp?:

http://www.examplesite.com/index.jsp?idPagina=12

This shows the site is making a GET request, passing a parameter identifying the page visited (idPagina). This URL can then be checked for vulnerability by passing it to sqlmap:

sqlmap -u "http://www.examplesite.com/index.jsp?idPagina=12"

This is a valid sqlmap command. The tool also supports an option for Dorks, -g, making it possible to pass the dork string directly to sqlmap:

sqlmap -g 'inurl:index.jsp? intext:"some company title"'

In this instance, sqlmap will use the dork to search Google, take the results from the first page, and analyze them one-by-one, prompting the user each time to ask if they want to analyze the URL, skip it, or quit.

Targeting a single result from the dork (the one passed to sqlmap via -u) might reveal both time-based and error-based SQLi vulnerabilities.


Scanning for SQLi With Arachni

As previously mentioned, Arachni is chosen as the scanner for its advantages: open source, extensible, multi-threaded, and a CLI that integrates well with automation.

After installing Arachni and symlinking its executable, you can access the arachni CLI in your $PATH. Exploring the help message reveals numerous options, though only a truncated version can be presented here. Certain CLI options are essential for extending functionality and creating more sophisticated testing workflows.

Going Beyond Defaults

Like many scanners, Arachni can be simple to use, but no extra arguments are required to start spidering a URL from the command line. However, several critical options should be used to ensure better functionality:

Writing a Wrapper Script

Just as a convenient wrapper script was used to initialize Burp’s JAR file, a similar script can be written for Arachni to avoid typing the full path and all options for every scan. This script, named ascan.sh, incorporates the options covered:

#!/bin/sh
arachni $1 \
--checks=*,-emails* \
--scope-include-subdomains \
--timeout 1:00:00 \
--http-request-concurrency 10

Like any shell script, it can be made executable with chmod u+x ascan.sh and added to the path using a symlink: sudo ln -s /Path/to/ascan.sh /usr/local/bin/ascan.

The timeout is purposefully long (1 hour) to accommodate longer hangups that occur with a smaller request pool and the extended waiting necessary because of time-based SQLi calls.


NoSQL Injection – Injecting Malformed MongoDB Queries

According to OWASP, there are over 150 varieties of NoSQL database available for use in web applications. To illustrate how injection works across different toolsets, we focus on MongoDB, the most widely-used, open source, unstructured NoSQL database.

The MongoDB API typically expects BSON data (binary JSON) constructed using a secure BSON query construction tool. However, in certain cases, MongoDB can also accept unserialized JSON and JavaScript expressions—notably in the case of the $where operator.

This operator is usually used as a filter, similar to the SQL WHERE operator:

db.myCollection.find( { $where: "this.foo == this.baz" } );

The expression can become more complicated. Ultimately, if the data is not properly sanitized, the MongoDB $where clause is capable of inserting and executing entire scripts written in JavaScript. Unlike SQL, which is a declarative and somewhat limited language, MongoDB’s NoSQL support for sophisticated JavaScript conditionals exposes it to exploits leveraging the language’s full range of features.

Attack patterns for this type of vulnerability are visible. Lists enumerating different malicious MongoDB $where inputs can be found on code-sharing sites.

Another vector for code injection within MongoDB is available in PHP implementations. Since $where is not only a MongoDB reserved word but also valid PHP syntax, an attacker can potentially submit code into a query by creating a $where variable.

Regardless of the specific implementation, all these attacks rely on the same core principle as general injection attacks: unsanitized data being mistaken for and executed as an application command.

As the MongoDB example demonstrates, the principle of malformed input changing the logic of a developer’s code is a pervasive problem that extends well beyond SQL or any other specific language, framework, or tool.


SQLi – An End-to-End Example

Returning to Arachni, a scan is initiated against a test URL, for instance: https://webscantest.com/datastore.

arachni https://webscantest.com/datastore

After the scan completes (which will take time), Arachni prints the results to the console and generates an AFR file. The AFR extension stands for Arachni Framework Report and is the format Arachni uses to store scan results. This AFR file can then be converted to formats like HTML, JSON, or XML.

A scan might immediately show a vulnerability that needs detailed exploration. This is the ideal time to use the HTML version of the report for visualization of the entire scan results.

To generate a zipped HTML file from the AFR, use the arachni_reporter executable:

arachni_reporter some_report.afr --reporter=html:outfile=my_report.html.zip

Crucially, it is important to specify the outfile as zipped HTML. If the .zip suffix is omitted, the resulting HTML file will likely show a long stream of unformatted, unintelligible special characters when opened in a browser.

Once unzipped and viewed in a browser, the report provides a clear overview of the discovered issues. Drilling down, one might find instances of SQLi, such as a timing issue. The report will scroll past explanatory text and remediation guidance to show the payload and affected URLs.

Gathering Report Information

The next step is to gather all the information needed to write a professional and actionable security report.

Final Report Submission Format

Using the gathered information, the submission can be formatted as follows:

CATEGORY: Blind SQLi (time-based)
TIME: 2018-06-18 3:23 AM (3:23) UTC
URL: http://webscantest.com/datastore/search_by_id.php
PAYLOAD: sleep(16000/1000);
METHODOLOGY: Vulnerability detected with Arachni scanner, v. 1.5.1-0.5.12

INSTRUCTIONS TO REPRODUCE:
1. Navigate to "/search_by_id.php".
2. Enter the SQLi payload into the search form.
3. Submit the query.
4. The time-based SQLi code will cause a delay in the SQL thread execution, confirming the vulnerability.

ATTACK SCENARIO:
With a time-based SQL injection vulnerability to exploit, a malicious actor could use the time-delay combined with SQL expressions to enumerate sensitive information—authentication credentials, payment data, DB information, and more—by inferring the truth of conditions based on the resulting page load time.

💡 Summary and Next Steps

This article covered the fundamentals of SQL and NoSQL injection, demonstrated how to use sqlmap to test a target host URL, highlighted the value of Google Dorks for both application-targeted and general vulnerability analysis, and detailed the process of scanning with Arachni and reporting a SQLi bug properly, from detection to submission.

Review Questions

1. What are blind SQLi, error-based SQLi, and time-based SQLi?

These are all sub-categories of SQL Injection (SQLi), distinguished by how you extract data from the database.

2. What are some of the dangers of trying to detect SQLi vulnerabilities using aggressive string inputs (high risk payloads)?

Using aggressive payloads (e.g., ' OR 1=1; DROP TABLE users--) is extremely risky and unprofessional because it can:

Best Practice: Always start with passive detection (e.g., ' to cause a syntax error) and gradually escalate to more complex, but non-destructive, payloads (e.g., using OR 1=1 to log in, or using UNION SELECT to retrieve system information like @@version).

3. What’s a Google dork? How did the technique get its name?

4. What command-line options are particularly useful for the arachni CLI?

While Arachni has a GUI, its CLI is powerful for automation. Key options include:

5. How does one generate a report from an Arachni Framework Report (AFR) file?

You use the arachni_reporter tool. The process is simple:

  1. After a scan, you have an scan.afr file.
  2. Run the command: arachni_reporter scan.afr --reporter=html:outfile=report.html
    • scan.afr is your saved scan file.
    • --reporter= specifies the format and output location.
    • You can generate multiple formats (JSON, XML, PDF, etc.) from the same AFR file.

6. What are some injection vectors in MongoDB?

MongoDB uses a JSON-like query syntax (BSON), so traditional SQLi doesn’t work. The main risk is NoSQL Injection, where attackers inject JSON objects instead of SQL strings.

7. What’s the value of being able to make a SQL thread sleep during an attack?

The primary value is for confirming and exploiting Time-Based Blind SQL Injection, as mentioned in question #1.

Data Exfiltration: It’s the mechanism for exfiltrating data. By using conditional sleeps (e.g., IF(condition, SLEEP(5), 0)), you can ask yes/no questions of the database. A delayed response means “yes,” and a normal response means “no.” This allows you to extract data one bit or one character at a time, which can be automated with tools like SQLmap.

Confirmation: It’s the definitive way to confirm a SQLi vulnerability when there are no visible errors or boolean-based differences in the page output. If you can make the database sleep and the response is delayed, you have 100% proof of injection.

Further Reading

You can find out more about some of the topics discussed in this article at:

Exit mobile version