NashTech Insights

How To Test Web Applications Against SQL Injection

Deepansh Gupta
Deepansh Gupta
Table of Contents

Every application nowadays has some form of sensitive data that needs to be protected. Such data in the wrong hands can lead to catastrophic failures. Avoiding such failures is extremely important with the advancement in technology. Security testing can be performed on your web application to find security gaps so that your data is safe in production from attackers.

One of the common security vulnerabilities that you might find in your web application is SQL Injection. They usually occur when an attacker injects malicious code (SQL, OS commands, etc.) into an application, often through input fields. Let us look at this type of security vulnerability in further detail.

What is SQL Injection?

SQL Injection is a type of cyber attack that targets databases through input fields in web applications. It occurs when an attacker manipulates the input of a website’s form or query parameter in such a way that it tricks the application into executing unintended SQL (Structured Query Language) commands on the underlying database.

Here’s how it usually works:

  • Input Fields: Web applications often take user input, such as search queries or login credentials, and use that input to construct SQL queries to interact with a database.
  • Malicious Input: An attacker enters specially crafted input that includes SQL code as part of the user input. This can be done by adding SQL statements or fragments to input fields.
  • Improper Handling: If the application doesn’t properly validate, sanitize, or escape user input before using it to build SQL queries, the injected SQL code can become part of the executed query.
  • Unintended Execution: When the injected SQL code is executed, it can perform various actions, such as retrieving, modifying, or deleting data from the database. This can lead to unauthorized access, data leakage, or even complete loss of control over the database.

SQL Injection attacks can have severe consequences, including unauthorized access to sensitive data, data manipulation, unauthorized administrative actions, and in some cases, even the ability to take control of the entire system hosting the database.

Example of SQL Injection

Following is an example of such an attack :

Your application takes some user input, say username and puts it into an SQL query to retrieve the information for the specified username from the database. The query would look like this:-

user_input = request.get("username")
query = "SELECT * FROM users WHERE username = '" + user_input + "';"
result = execute_sql_query(query)

Suppose a user adds the following in the place of a valid username : ‘ OR ‘1’=’1. The query would look then like :-

SELECT * FROM users WHERE username = '' OR '1'='1';

Since ‘1’=’1′ is always true, this modified query would retrieve all the rows from the user table, effectively bypassing any legitimate authentication or filtering mechanisms.

How To Prevent It?

To prevent SQL Injection attacks, a team should follow secure coding practices:

  • Input Validation: Sanitize all user input before using it in SQL queries. Use parameterized queries or prepared statements to separate user input from the query structure.
  • Parameterized Queries: Use libraries or frameworks that support parameterized queries, as they automatically handle the proper escaping and separation of user input from the SQL query.
  • Escaping User Input: If parameterized queries are not possible, escape user input to ensure that any malicious code within the input is treated as data rather than executable SQL code.
  • Least Privilege: Ensure that the database user account used by the application has the least privilege necessary to perform its intended operations. This limits the potential damage if an SQL Injection attack is successful.
  • Regular Updates and Patching: Keep your web application, database software, and any associated libraries up to date to benefit from the latest security patches.

By following these practices, developers can significantly reduce the risk of SQL Injection vulnerabilities and help protect their applications and databases from these types of attacks.

Detect SQL Injection With Selenium And OWASP ZAP Integration

OWASP Zap (Zed Attack Proxy) is a widely used open-source web application security testing tool. Security professionals use OWASP Zap to identify and fix vulnerabilities in web applications during the development and testing stages.

Prerequisites

1. You have installed JAVA 11 or higher on your machine.
2. You have installed IDE (IntelliJ) on your machine.
3. You have installed OWASP Zap on your machine. You can use the following URL to install it based on your requirements – OWASP Zap installation.
4. You have installed Selenium in your system and have the latest version of your browser driver.
5. You have created a Maven project and added the following dependencies to your pom.xml file:

<dependency>
            <groupId>org.zaproxy</groupId>
            <artifactId>zap-clientapi</artifactId>
            <version>1.11.0</version>
</dependency>
<dependency>
            <groupId>org.zaproxy</groupId>
            <artifactId>zap</artifactId>
            <version>2.12.0</version>
</dependency>

Steps to Detect SQL Injection

Step 1: Launch OWASP ZAP and get the API key

Open the OWASP Zap so that it is running on your local machine. The default port for the application to run is port 8080. To check if Zap is running on your machine, you can hit localhost:8080 in your browser. At this point, you should see the following page on that local address.

To get the API key for your application, go to Tools > Options > API. You should be able to see your specific API key. You will need this in later steps. There is also a random key generator option if you want to avail it.

Step 2: Add @BeforeMethod to start a proxy Zap server
static final String proxy_address_zap = "localhost";
static final int proxy_port_zap = 8080;
WebDriver driver;
static String appUrl = "your_app_url"; 

public void startUp(){
        ChromeOptions options = new ChromeOptions();
        options.addArguments("--ignore-certificate-errors");
        String proxyUrl = proxy_address_zap + ":" + proxy_port_zap;
        Proxy proxyServer = new Proxy();     //An instance of the Proxy class is created. This class represents the proxy configuration for Selenium WebDriver.
        proxyServer.setHttpProxy(proxyUrl) 
                .setSslProxy(proxyUrl);  //This method sets the HTTP and SSL proxy for the proxyServer instance. 
        options.setCapability(CapabilityType.PROXY, proxyServer);
        driver = new ChromeDriver();
        driver.manage().window().maximize();
    }

Therefore by configuring the Proxy object and setting the CapabilityType.PROXY capability, Selenium WebDriver will route all the HTTP and HTTPS requests through the specified proxy server. This allows you to intercept and inspect the network traffic using OWASP ZAP.

Step 3: Create a method to start a spider scan for your web application

Spider scan is a feature that allows for the automated exploration and discovery of a web application’s structure and content. It mimics the behaviour of a user browsing the application by navigating through its pages and following links to identify additional resources, endpoints, and parameters. The spider scan is designed to crawl a web application, systematically visit different URLs, and capture information about each request and response.

You can also configure other types of scanning like active scanning. There is also an option to configure scanning with specific security policies like SQL injection, and cross-site scripting amongst many more.

static final String proxy_apiKey_zap = "your_api_key";
private static ClientApi api;

 public static void spiderScan(String webAppUrl, String zapAddress, int zapPort) throws ClientApiException {
        api = new ClientApi(zapAddress, zapPort, proxy_apiKey_zap); //Instance of ClientApi class, which represents the client for interacting with the ZAP API
        ApiResponse apiResponse = api.spider.scan(webAppUrl, null, null, null, null);  //The api object (OWASP ZAP client) calls the spider.scan() method to initiate a spider scan on a web application
        logger.info("apiResponse : " + apiResponse.getName());
    }

By calling the spider.scan() method, the ZAP API sends a request to the ZAP instance to start the spider scan process on the specified web application. The response from the API call is stored in the ApiResponse object for further analysis or processing.

Step 4: Generate a report for your scan to see vulnerabilities
 public static void getReports(String webAppUrl) throws ClientApiException, IOException {
        byte[] bytes = api.core.htmlreport();

        // getting the alert messages and just printing those.
        ApiResponse messages =  api.core.messages(webAppUrl,"0","99999999");
        logger.info("messages : " + messages);

        // storing the bytes in to html report.
        String str = new String(bytes, StandardCharsets.UTF_8);
        File newTextFile = new File("security_report.html");
        FileWriter fw = new FileWriter(newTextFile);
        fw.write(str);
        fw.close();
    }

Step 5: Call your methods in the @Test method
@Test
    public void testLoginSpiderSecurity() throws ClientApiException {
        loginToWebApp(); //A method to login to our web application. This contains your selenium code to automate login to the application.
        Utility.spiderScan(appUrl, proxy_address_zap, proxy_port_zap);
    }

Also read: OWASP TOP 10 – What you need to know

Featured image source https://www.geeksforgeeks.org/sql-injection/

Deepansh Gupta

Deepansh Gupta

Deepansh is a Quality Analyst with 3+ years of experience in both manual and automation testing. He has worked on various tech stacks which include technologies such as Selenium, RestAssured, Gatling among others.

Leave a Comment

Your email address will not be published. Required fields are marked *

Suggested Article

%d bloggers like this: