Front End Security Using OWASP and Python

Front End Security Using OWASP and Python

The Frontend of a website serves as the interface for users to interact with a webpage. It holds important information about the application’s components and is one vulnerable part of a web application which has continued to be exploited by malicious attackers.

In this article, we'll explore front end security threats and how Python can be used to enhance the security of a web application. We’ll cover the importance of securing frontend applications, third-party tools to monitor frontend security, how to integrate Python with these tools to receive alerts, and all other measures which can be taken to enhance the security of the frontend.

What is Frontend Security?

Front end Security are the various measures aimed at protecting a web application and its users against malicious attacks. These measures cover both the server’s side and the client’s side of the application.

Why Frontend Security?

The benefits of securing a website's front end include:

  • User Privacy: Front end security helps safeguard user data and protects against data breaches.

  • Protection of Assets: It helps detect and protect against malicious threats that can harm client and server assets.

  • Trustworthiness: A secure website is more trusted by users, which increases users' confidence when using your application.

  • Loss Prevention: Front end Security reduces the risk of losses associated with malicious attacks, such as fraud and system breakdown.

  • Compliance with Security Regulations: Front end security ensures a website's protocols follow established industry standards.

  • Timely Detection of Threats: It ensures threats are detected on time and allows for quick response.

Common Front End Security Threats

The Open Web Application Security Project (OWASP) is an open-source initiative that aims to improve the security of Web Applications. The OWASP Top Ten is an awareness document of the ten most common threats to web security. This list is updated every three to four years, with the latest release being the OWASP Top Ten 2021. The following threats were outlined as being the top threats to web security:

  1. Broken Access Control:

    Access Control is a security protocol that defines the privileges and restrictions of each user in accessing a website's data. Broken access control occurs when there is no proper restriction on what a user can do. It can be done by manipulation of URLs, vulnerable APIs or metadata.

  2. Cryptographic Failures:

    Cryptography is a mathematical technique used to encrypt and secure data from unauthorized access. Cryptographic failure occurs when sensitive data on a web application becomes compromised. This can occur due to weak encryption techniques or the use of outdated cryptographic algorithms, amongst others. A Password is an example of sensitive data which are susceptible to this attack.

  3. Injection Attacks:

    In this type of attack, an attacker injects harmful code into the source code of a web application. This injected code is programmed to trigger some action when accessed by a user. Examples of injection attacks include SQL injection, buffer overflow, and cross-site scripting (XSS).

  4. Insecure Design:

    Insecure design are errors in the way a web application is designed. These errors occur when the application is still under development and may go unnoticed until the application is released. This security flaw is harder to detect and provides easy compromise of a web application.

  5. Security Misconfiguration:

    This happen when a website or web application has not uniquely configured its security settings. Security misconfigurations can lead to vulnerabilities such as open cloud storage and error messages that expose much information.

  6. Vulnerable and Outdated Components:

    This happens when a web application uses a third-party tool, operating system, API, or open-source library that is outdated or exposed to security breaches.

  7. Identification and authentication failures:

    This occurs when a web application lacks the mechanisms to authenticate a user's identity properly. This could be caused by the absence of two-factor authentication, improper credential handling, and when strong password policies are not enforced on users.

  8. Data Integrity Failures:

    This occurs when there is a failure to protect an application's data from being modified by an unauthorized user. Data Integrity failures can arise due to vulnerabilities in the application itself or weaknesses in the structures that protect the data.

  9. Security Logging and Monitoring Failures:

    A security log is a detailed record of security events such as user actions, data modification, and system changes. Security logging and monitoring failures occur when a web application's security log is not effectively monitored and analyzed.

  10. Server-Side Request Forgery (SSRF):

    SSRF occurs when an attacker can make a server send unauthorized requests by tricking the server that it originates from an authorised source.

Existing Tools for Front End Security Monitoring

  • Zed Attack Policy (ZAP)

    ZAP is an open-source project by OWASP that can be used to carry out security tests and scans of web applications. It is easy to use and allows users to automate the test process. It is a cross-platform software, meaning that it can run on any operating system. It can also be integrated with other tools like Jenkins. ZAP protects against attacks like injections, Cross-Site Scripting (XSS), and Cross-Site Request Forgery (CSRF).

  • BurpSuite

    Burpsuite is an automated security scanner that searches for common web application vulnerabilities and allows users to capture and modify traffic between their browser and the target web application.

  • Arachni

    Arachni is an automated security scanner that studies the behavior of a web application in order to scan packets and detect changes that may have occurred to a packet while traveling through the application's network. It can also audit elements such as links and cookies. Arachni is user-friendly, fast, and easy to scale.

  • Cloudflare

    Cloudflare is a Content Delivery Network (CDN) and cloud service provider that provides security features for web applications. It includes a firewall that prevents injections, protects the Secure Surface Layer (SSL), secures APIs, and monitors the browser. Many top websites, such as Udemy, use Cloudflare.

  • CodeQL

    CodeQL is a free open-source feature provided by GitHub that automatically scans for vulnerabilities in an application's codebase. With CodeQL, you can write queries to perform scans and pre-defined queries that can be shared with others.

  • SonarQube

    SonarQube is an open-source code quality inspector that scans for compliance with securing standards during the development phase. It can analyze codebases written in over 20 programming languages; including JavaScript and Python. It has an interactive interface and also provides notification of when security issues are detected.

  • W3af

    Web Application Attack and Audit Framework (W3af) is a security scanner for python-based web applications. It provides audit features for applications to be checked against vulnerabilities. It can detect over 200 web threats including injections, click-jacking, and phishing scams. This process can be automated, and it also supports the use of plugins.

How Python Can Enhance Front End Security

Python is a favorite among security professionals because it is versatile, easy to learn and supports many libraries.

One of Python's strengths is its ability to automate security processes. Python allows for automating tasks such as malware analysis, packet sniffing, and port scanning.

Another strength is in the sanitization of input. Libraries like Cerberus, Pydantic, and Marshmallow, are effective for validating schema. They ensure only properly formatted data is processed and sent to the front end.

Python web development libraries like Django and Flask have built-in security features such as input validation, password hashing, user authentication, and session management. They also provide mechanisms for HTML encodings and packet analysis to ensure that data communicated to a website remains secure. Other security libraries includes Scapy for network packet manipulation and Paramiko for Secure Shell (SSH) connections.

Integrating Python with Third-Party Frontend Security Tools

To illustrate how Python can be integrated with frontend security tools, we'll use OWASP's Zed Attack Proxy (ZAP). ZAP provides a REST API for accessing its features. A secure key is required to use this API. ZAP's API provides access to its Spider web crawler and security scanner. If you need additional features that are not available in the core ZAP installation, you'll need to install extra add-ons.

The API key will look like this:

"http://zap/<format>/<component>/<operation>/<operation name>[/?<parameters>]"

Where;

  • format: The format in which the API should be accessed (JSON, XML, or HTML) depending on the desired readability.

  • component: The component to interact with, such as generating a report or starting a scan. Accepted inputs are view and action.

pip install zaproxy

Ensure you have ZAP Desktop installed on your computer, then run the app using shell or in daemon mode:

<ZAP_HOME>/zap.sh -daemon -config api.key=your-api-key
#or
<ZAP_HOME>/zap.sh

Next, crawling the web application before scanning for vulnerabilities is recommended to generate more accurate results. To do this you'll need to use a spider. The spider runs in a recursive process and keeps a record of all URLs visited. For this article, we'll use a traditional HTML Spider.

import time
from pprint import pprint
from zapv2 import ZAPv2

# Define the target URL and API key
web_url = "https://the-public-website-address-to-scan"
api_key = "yourAPIkey"

# Initialize the ZAP API client
zap = ZAPv2(apikey=api_key, proxies={'http': 'http://127.0.0.1:8080', 'https': 'http://127.0.0.1:8080'})

# Start the spider scan
scan_id = zap.spider.scan(web_url)

# Wait for the spider scan to complete
while int(zap.spider.status(scan_id)) < 100:
    print(f"Spider is {zap.spider.status(scan_id)}% in progress")
    time.sleep(1)
print("Spider is now complete")

# Display the spider scan results
print("\n".join(map(str, zap.spider.results(scan_id))))

The above code creates a ZAP API client instance, which connects to port 8080 by default. If ZAP is on a different port, you can use the proxies parameter to specify a port. The code initiates the spider by calling zap.spider.scan on the target website and prints the completion progress every second. The code then retrieves and prints the URLs found by the spider using zap.spider.results(scanID). Next, after exploring the application with a spider, we can carry out an active scan for vulnerabilities. Note that this time, we use zap.ascan.scan and not zap.spider.scan.

# Start the active scan
print(f'Actively Scanning {web_url}')
active_scan_id = zap.ascan.scan(web_url)

# Wait for the active scan to complete
while int(zap.ascan.status(active_scan_id)) < 100:
    print(f'Scan progress %: {zap.ascan.status(active_scan_id)}')
    time.sleep(5)
print('Active Scan completed')

# Display the hosts and alerts
print(f"Hosts: {', '.join(zap.core.hosts)}")
print('Alerts:')
pprint(zap.core.alerts(baseurl=web_url))

After the scan is complete, we output the results/alerts in batches of 5000.

# Retrieve all alerts with pagination
start = 0
page = 5000
alert_count = 0
alerts = zap.alert.alerts(baseurl=web_url, start=start, count=page)
blacklist = [1, 2]

while len(alerts) > 0:
    print(f'Reading {page} alerts from {start}')
    alert_count += len(alerts)
    for alert in alerts:
        plugin_id = alert.get('pluginId')
        if plugin_id in blacklist:
            continue
        if alert.get('risk') in ['High', 'Informational']:
            continue
    start += page
    alerts = zap.alert.alerts(baseurl=web_url, start=start, count=page)

print(f'Total number of alerts: {alert_count}')

Full Code:

import time
from pprint import pprint
from zapv2 import ZAPv2

# Define the target URL and API key
web_url = "https://the-public-website-address-to-scan"
api_key = "yourAPIkey"

# Initialize the ZAP API client
zap = ZAPv2(apikey=api_key, proxies={'http': 'http://127.0.0.1:8080', 'https': 'http://127.0.0.1:8080'})

# Start the spider scan
scan_id = zap.spider.scan(web_url)

# Wait for the spider scan to complete
while int(zap.spider.status(scan_id)) < 100:
    print(f"Spider is {zap.spider.status(scan_id)}% in progress")
    time.sleep(1)
print("Spider is now complete")

# Display the spider scan results
print("\n".join(map(str, zap.spider.results(scan_id))))

# Start the active scan
print(f'Actively Scanning {web_url}')
active_scan_id = zap.ascan.scan(web_url)

# Wait for the active scan to complete
while int(zap.ascan.status(active_scan_id)) < 100:
    print(f'Scan progress %: {zap.ascan.status(active_scan_id)}')
    time.sleep(5)
print('Active Scan completed')

# Display the hosts and alerts
print(f"Hosts: {', '.join(zap.core.hosts)}")
print('Alerts:')
pprint(zap.core.alerts(baseurl=web_url))

# Retrieve all alerts with pagination
start = 0
page = 5000
alert_count = 0
alerts = zap.alert.alerts(baseurl=web_url, start=start, count=page)
blacklist = [1, 2]

while len(alerts) > 0:
    print(f'Reading {page} alerts from {start}')
    alert_count += len(alerts)
    for alert in alerts:
        plugin_id = alert.get('pluginId')
        if plugin_id in blacklist:
            continue
        if alert.get('risk') in ['High', 'Informational']:
            continue
    start += page
    alerts = zap.alert.alerts(baseurl=web_url, start=start, count=page)

print(f'Total number of alerts: {alert_count}')

More Front-End Security Measures

You can protect your front end using the following measures in Python:

  • CSP Headers: A Content Security Policy (CSP) header helps prevent XSS attacks by restricting the sources from which content can be loaded. You can automatically include CSP headers when using Python frameworks like Flask or Django.

  • HTTPS Encryption: HTTPS encrypts data transmitted between the user's browser and your web server. Ensure you serve your web application over HTTPS and use libraries like certbot to manage SSL/TLS certificates.

  • Anti-CSRF Token Generation Techniques: Anti-CSRF tokens are unique values included in requests to ensure that the request originates from a legitimate source. Frameworks like Flask or Django provide built-in mechanisms for CSRF protection which can be used to implement token generation.

  • Cross-Origin Resource Sharing (CORS): CORS policies control how resources are shared between different origins, which helps in preventing unauthorized requests. Configure CORS settings in your server or API endpoints using tools like flask-cors or django-cors-headers.

  • Captcha Tests: Integrate CAPTCHA services into your login and registration forms using Python libraries like Captcha.

  • Login Attempts: Implement account lockout mechanisms and track failed login attempts using tools like Django-axes or Flask-Limiter.

  • Two-Factor Authentication (2FA): Use libraries like pyotp to integrate 2FA into your authentication process.

  • Rate Limits: Rate limitations control the number of requests a user can make in a given period. This can be implemented using tools such as Flask-Limiter or django-ratelimit to control API request rates.

  • Environment Variables: Environment variables securely manage sensitive information like API keys and credentials. Use python-decouple or dotenv libraries to manage environment variables. Also, avoid hardcoding secrets in your codebase.

  • Session Timeouts: Session timeouts reduce the risk of unauthorized access by automatically logging out inactive users. Configure session timeouts in your web framework using Flask-Session or django-session-timeout.

  • Use Automated Security Tools and Scanners.

Conclusion

Securing the front end of your web application is not just another box to tick but a continuous commitment to protect your users and application from malicious attacks. We've explored common threats to front end security and practical strategies to prevent these threats. We've also discussed how to use tools like OWASP's ZAP and Python to enhance the security of your web application. Remember, the key to effective front end security is to stay informed, vigilant, and proactive!

Reference

Introduction - API Reference (zaproxy.org)