NashTech Insights

Integrating OWASP Zap With Selenium For Effective Testing

Deepansh Gupta
Deepansh Gupta
Table of Contents

In today’s rapidly evolving technological landscape, the significance of security testing has escalated. It is imperative for every web application to possess a secure framework that effectively thwarts any potential malicious intrusions. The most effective approach to guaranteeing the security of your application against such vulnerabilities is through conducting thorough security testing.

Security testing can be performed effectively on any web application via numerous ways. While manually executing test cases can be effective, it can become laborious and time-consuming over time. Therefore, automating security tests emerges as a superior choice. In this article, our main emphasis will be on leveraging OWASP ZAP’s integration with Selenium tests to ensure that our web application undergoes security testing with each test execution.

The seamless combination of Selenium and OWASP Zap guarantees the continuous safety and readiness of your application for deployment. Let us see what it is why we need it.

What is OWASP Zap?

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 development and testing stages. OWASP Zap is developed by the Open Web Application Security Project (OWASP), a non-profit organization.

OWASP Zap provides a range of features and functionalities to assist with various aspects of web application security testing. Some of its key features include:

  1. Proxy Mode: OWASP Zap acts as an intermediary between the user’s browser and the web application. Therefore, allows interception and inspection of requests and responses. This enables users to examine and modify web traffic, such as injecting payloads or modifying parameters, to identify security vulnerabilities.
  2. Active Scanning: OWASP Zap can actively scan web applications for common security vulnerabilities. This includes cross-site scripting (XSS), SQL injection, insecure direct object references, and more. It automates the process of sending malicious payloads and analyzes the responses to identify potential vulnerabilities.
  3. Spidering: The tool includes a spidering feature that automatically navigates through a web application, discovering and mapping its structure. This helps in identifying hidden or unlinked pages and resources.
  4. Fuzzing: OWASP Zap supports fuzzing techniques. It generates and sends a large number of malformed or unexpected inputs to the target application to trigger potential vulnerabilities. It helps in finding issues like buffer overflows, input validation problems, and more.
  5. Reporting: The tool provides comprehensive reports on discovered vulnerabilities. This includes details on the affected URLs, the nature of the vulnerabilities, and suggestions for remediation.
  6. Extensibility: OWASP Zap can be extended through various plugins and extensions. It allows users to customize and enhance its functionality based on their specific requirements.

Why do we need OWASP Zap?

Within the official OWASP Zap documentation, the top ten most critical issues encountered during web application security testing is presented. Utilizing the OWASP Zap tool for conducting security tests on your website can help you to find these issues. Let us now examine these ten critical issues that may manifest within your application:

  1. Broken access control : Broken access control is a security vulnerability that occurs when the application fails to properly enforce restrictions on user access to certain resources. When access control is broken, it can lead to serious security breaches and unauthorized activities within the application.
  2. Cryptographic failure : Cryptographic failure refers to the occurrence of vulnerabilities in the usage of cryptographic algorithms and protocols. It is essential to follow best practices for cryptographic implementation. This includes the use of strong algorithms and regular updates to address any known vulnerabilities in cryptographic libraries.
  3. SQL injection : SQL injection is a vulnerability that occurs when an attacker manipulates SQL queries executed by the application’s database. It occurs when the application fails to properly validate user-supplied input before incorporating it into SQL statements. This allows an attacker to inject malicious SQL code.
  4. Insecure design : Insecure design, also known as security design flaws or security architecture flaws, refers to vulnerabilities that arise from fundamental flaws or weaknesses in the overall design or architecture of a software system. It pertains to the inadequate consideration or implementation of security controls and mechanisms during the initial design phase of a system or application.
  5. Security misconfiguration : Security misconfiguration refers to the improper configuration or implementation of security controls, settings, or components within a software system or application. It occurs when system administrators or developers unintentionally leave vulnerabilities or weaknesses in the system’s configuration, making it susceptible to potential exploitation by attackers.
  6. Vulnerable components : Vulnerable components, in the context of security testing, refer to software or hardware components within a system or application that have known security vulnerabilities or weaknesses. These vulnerabilities can be the result of programming errors in addition to design flaws, or the presence of outdated or unpatched software libraries, frameworks, or third-party dependencies.
  7. Identification and authentication failures : Identification and authentication failures cover vulnerabilities or weaknesses in the processes and mechanisms used to identify and authenticate users or entities within a system. These failures can lead to unauthorized access, identity spoofing, or the compromise of sensitive information.
  8. Data integrity failures : Data integrity failures includes vulnerabilities or weaknesses that result in the compromise or unauthorized modification of data, leading to a loss of data integrity. Data integrity ensures that data remains accurate, complete, and unchanged throughout its lifecycle.
  9. Security logging and monitoring : Security logging involves capturing and recording relevant events and activities within a system, while monitoring involves actively analyzing and reviewing the logged data to identify potential security incidents or anomalies.
  10. Server side request forgery : Server-Side Request Forgery (SSRF) is a security vulnerability that allows an attacker to manipulate the server-side components of a web application to make unauthorized requests to other internal or external resources. In an SSRF attack, the attacker can exploit the functionality provided by the application to send crafted requests, tricking the server into making unintended requests on behalf of the attacker.

How to integrate Selenium with Zap?

Prerequisites for Integration

Before working on writing the actual code, let us look at the prerequisites you need to complete in order to make the integration successful :

  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 integrate Selenium and OWASP Zap

Step 1: Launch OWASP Zap and find 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 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 designs to crawl a web application, systematically visits different URLs, and captures information about each request and response.

You can also configure other types of scanning like active scanning. There is also option to configure scanning with specific security policies like sql injection, 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 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 @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);
    }

You can check generated reports and see what vulnerabilities your application has.

Image source : https://www.enmilocalfunciona.io/automatizacion-de-una-prueba-de-seguridad-con-selenium-y-owasp-zap/

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: