Appearance
OWASP ZAP Cheat Sheet
Overview
OWASP ZAP (Zed Attack Proxy) is one of the world's most popular free security tools and is actively maintained by hundreds of international volunteers. ZAP is a comprehensive web application security scanner that helps developers and security professionals automatically find security vulnerabilities in web applications during development and testing phases. Developed by the Open Web Application Security Project (OWASP), ZAP provides both automated scanning capabilities and manual testing tools, making it suitable for both security novices and experienced penetration testers.
The core strength of OWASP ZAP lies in its intercepting proxy functionality, which allows security professionals to intercept, inspect, and modify HTTP/HTTPS traffic between web browsers and applications in real-time. This man-in-the-middle capability enables comprehensive security testing by providing visibility into all client-server communications, including AJAX requests, WebSocket connections, and API calls. ZAP's automated scanner can detect a wide range of security vulnerabilities including SQL injection, cross-site scripting (XSS), cross-site request forgery (CSRF), directory traversal, and many other OWASP Top 10 vulnerabilities, while its passive scanning capabilities continuously monitor traffic for security issues without actively attacking the application.
ZAP's extensive feature set includes advanced spidering capabilities for comprehensive application discovery, fuzzing tools for input validation testing, and a powerful scripting engine that supports multiple programming languages for custom security tests. The platform offers both desktop GUI and command-line interfaces, making it suitable for interactive testing and automated CI/CD integration. With its comprehensive API, extensive plugin ecosystem, and active community support, OWASP ZAP provides enterprise-grade web application security testing capabilities while remaining completely free and open-source, making it an essential tool for organizations implementing DevSecOps practices and security-first development methodologies.
Installation
Ubuntu/Debian Installation
Installing OWASP ZAP on Ubuntu/Debian systems:
bash
# Update system packages
sudo apt update && sudo apt upgrade -y
# Install Java (required for ZAP)
sudo apt install -y openjdk-11-jdk
# Verify Java installation
java -version
# Download and install ZAP
wget https://github.com/zaproxy/zaproxy/releases/download/v2.14.0/ZAP_2_14_0_unix.sh
chmod +x ZAP_2_14_0_unix.sh
sudo ./ZAP_2_14_0_unix.sh
# Alternative: Install via Snap
sudo snap install zaproxy --classic
# Alternative: Install via APT (may be older version)
sudo apt install -y zaproxy
# Install ZAP daemon for headless operation
sudo apt install -y zaproxy-daemon
# Verify installation
zap.sh -version
# Install additional dependencies
sudo apt install -y firefox-esr xvfb
# Create desktop shortcut
cat > ~/Desktop/OWASP-ZAP.desktop << 'EOF'
[Desktop Entry]
Version=1.0
Type=Application
Name=OWASP ZAP
Comment=Web Application Security Scanner
Exec=/opt/zaproxy/zap.sh
Icon=/opt/zaproxy/zap.ico
Terminal=false
Categories=Development;Security;
EOF
chmod +x ~/Desktop/OWASP-ZAP.desktop
CentOS/RHEL Installation
bash
# Install Java
sudo yum install -y java-11-openjdk java-11-openjdk-devel
# Verify Java installation
java -version
# Download ZAP
wget https://github.com/zaproxy/zaproxy/releases/download/v2.14.0/ZAP_2_14_0_unix.sh
chmod +x ZAP_2_14_0_unix.sh
sudo ./ZAP_2_14_0_unix.sh
# Alternative: Install via RPM
wget https://github.com/zaproxy/zaproxy/releases/download/v2.14.0/ZAP_2_14_0_Linux.tar.gz
tar -xzf ZAP_2_14_0_Linux.tar.gz
sudo mv ZAP_2.14.0 /opt/zaproxy
sudo ln -sf /opt/zaproxy/zap.sh /usr/local/bin/zap
# Install Firefox for browser integration
sudo yum install -y firefox
# Verify installation
zap --version
macOS Installation
bash
# Install using Homebrew
brew install --cask owasp-zap
# Alternative: Download installer
# https://github.com/zaproxy/zaproxy/releases
# Install Java if needed
brew install openjdk@11
# Verify installation
/Applications/OWASP\ ZAP.app/Contents/MacOS/OWASP\ ZAP.sh -version
# Create command line alias
echo 'alias zap="/Applications/OWASP\ ZAP.app/Contents/MacOS/OWASP\ ZAP.sh"' >> ~/.zshrc
source ~/.zshrc
Windows Installation
bash
# Download Windows installer
# https://github.com/zaproxy/zaproxy/releases/download/v2.14.0/ZAP_2_14_0_windows.exe
# Install using Chocolatey
choco install zap
# Install using Scoop
scoop bucket add extras
scoop install owasp-zap
# Verify installation
"C:\Program Files\OWASP\Zed Attack Proxy\ZAP.exe" -version
# Add to PATH
setx PATH "%PATH%;C:\Program Files\OWASP\Zed Attack Proxy"
Docker Installation
Running OWASP ZAP in Docker:
bash
# Pull official ZAP image
docker pull owasp/zap2docker-stable
# Run ZAP daemon
docker run -u zap -p 8080:8080 -i owasp/zap2docker-stable zap.sh -daemon -host 0.0.0.0 -port 8080
# Run ZAP with GUI (requires X11 forwarding)
docker run -u zap -p 8080:8080 -e DISPLAY=$DISPLAY -v /tmp/.X11-unix:/tmp/.X11-unix owasp/zap2docker-stable zap.sh
# Run baseline scan
docker run -v $(pwd):/zap/wrk/:rw -t owasp/zap2docker-stable zap-baseline.py -t https://example.com
# Run full scan
docker run -v $(pwd):/zap/wrk/:rw -t owasp/zap2docker-stable zap-full-scan.py -t https://example.com
# Run API scan
docker run -v $(pwd):/zap/wrk/:rw -t owasp/zap2docker-stable zap-api-scan.py -t https://example.com/api/openapi.json
# Create custom Dockerfile
cat > Dockerfile.zap << 'EOF'
FROM owasp/zap2docker-stable
# Install additional tools
USER root
RUN apt-get update && apt-get install -y \
curl \
jq \
python3-pip
# Install Python dependencies
RUN pip3 install requests beautifulsoup4
# Switch back to zap user
USER zap
# Set working directory
WORKDIR /zap
# Default command
CMD ["zap.sh", "-daemon", "-host", "0.0.0.0", "-port", "8080"]
EOF
# Build custom image
docker build -f Dockerfile.zap -t zap-custom .
# Run custom image
docker run -p 8080:8080 zap-custom
Basic Usage
GUI Interface
Using ZAP's graphical interface:
bash
# Start ZAP GUI
zap.sh
# Start with specific configuration
zap.sh -config api.key=your-api-key
# Start with custom memory allocation
zap.sh -Xmx2g
# Start with specific session file
zap.sh -session /path/to/session.session
# Start with addon directory
zap.sh -addoninstalldir /path/to/addons
# Configure proxy settings
# Tools > Options > Local Proxies
# Default: localhost:8080
# Configure browser proxy
# Firefox: Preferences > Network Settings
# Set HTTP Proxy: localhost:8080
# Check "Use this proxy server for all protocols"
# Import CA certificate
# Tools > Options > Dynamic SSL Certificates
# Save certificate and import to browser
# Manual explore mode
# Navigate through application manually
# ZAP will passively scan all traffic
# Automated scan
# Right-click on target in Sites tree
# Select "Attack" > "Active Scan"
Command Line Interface
Using ZAP from command line:
bash
# Start ZAP daemon
zap.sh -daemon -host localhost -port 8080
# Start with API key
zap.sh -daemon -config api.key=your-api-key
# Start headless (no GUI)
zap.sh -daemon -host 0.0.0.0 -port 8080
# Quick baseline scan
zap-baseline.py -t https://example.com
# Full scan with report
zap-full-scan.py -t https://example.com -r zap-report.html
# API scan
zap-api-scan.py -t https://example.com/api/swagger.json
# Custom scan with configuration
zap.sh -daemon -quickurl https://example.com -quickout zap-report.html
# Scan with authentication
zap.sh -daemon -quickurl https://example.com -quickauth username:password
# Scan with custom rules
zap.sh -daemon -quickurl https://example.com -quickrules /path/to/rules.conf
Proxy Configuration
Setting up ZAP as intercepting proxy:
bash
# Configure ZAP proxy
# Default settings:
# Address: localhost
# Port: 8080
# Configure browser proxy (Firefox)
# about:preferences#general
# Network Settings > Settings
# Manual proxy configuration:
# HTTP Proxy: localhost Port: 8080
# HTTPS Proxy: localhost Port: 8080
# Configure browser proxy (Chrome)
# Settings > Advanced > System > Open proxy settings
# Or use command line:
google-chrome --proxy-server="localhost:8080"
# Configure system proxy (Linux)
export http_proxy=http://localhost:8080
export https_proxy=http://localhost:8080
# Configure curl to use ZAP proxy
curl --proxy localhost:8080 https://example.com
# Configure wget to use ZAP proxy
wget --proxy=on --http-proxy=localhost:8080 https://example.com
# Import ZAP CA certificate
# Tools > Options > Dynamic SSL Certificates
# Click "Save" to export certificate
# Import certificate to browser/system trust store
# Certificate import (Firefox)
# about:preferences#privacy
# Certificates > View Certificates > Authorities > Import
# Certificate import (Chrome)
# Settings > Privacy and security > Security > Manage certificates
# Authorities > Import
# Certificate import (Linux system)
sudo cp owasp_zap_root_ca.cer /usr/local/share/ca-certificates/
sudo update-ca-certificates
Advanced Features
Automated Scanning
Configuring and running automated scans:
bash
# Spider configuration
# Tools > Options > Spider
# Max Depth: 5
# Max Children: 0 (unlimited)
# Max Duration: 0 (unlimited)
# Request Delay: 0ms
# Active scan configuration
# Tools > Options > Active Scan
# Threads per host: 2
# Max rule duration: 0 (unlimited)
# Max scan duration: 0 (unlimited)
# Delay when scanning: 0ms
# Passive scan configuration
# Tools > Options > Passive Scanner
# Enable all rules
# Max alerts per rule: 0 (unlimited)
# Start spider scan
# Right-click target in Sites tree
# Attack > Spider
# Start active scan
# Right-click target in Sites tree
# Attack > Active Scan
# Configure scan policy
# Analyse > Scan Policy Manager
# Create new policy or modify existing
# Enable/disable specific rules
# Set attack strength levels
# Custom scan script
#!/bin/bash
ZAP_API_KEY="your-api-key"
TARGET_URL="https://example.com"
# Start ZAP daemon
zap.sh -daemon -config api.key=$ZAP_API_KEY &
sleep 30
# Spider the target
curl "http://localhost:8080/JSON/spider/action/scan/?url=$TARGET_URL&apikey=$ZAP_API_KEY"
# Wait for spider to complete
while [ $(curl -s "http://localhost:8080/JSON/spider/view/status/?apikey=$ZAP_API_KEY" | jq -r '.status') != "100" ]; do
echo "Spider progress: $(curl -s "http://localhost:8080/JSON/spider/view/status/?apikey=$ZAP_API_KEY" | jq -r '.status')%"
sleep 10
done
# Start active scan
curl "http://localhost:8080/JSON/ascan/action/scan/?url=$TARGET_URL&apikey=$ZAP_API_KEY"
# Wait for active scan to complete
while [ $(curl -s "http://localhost:8080/JSON/ascan/view/status/?apikey=$ZAP_API_KEY" | jq -r '.status') != "100" ]; do
echo "Active scan progress: $(curl -s "http://localhost:8080/JSON/ascan/view/status/?apikey=$ZAP_API_KEY" | jq -r '.status')%"
sleep 30
done
# Generate report
curl "http://localhost:8080/OTHER/core/other/htmlreport/?apikey=$ZAP_API_KEY" > zap-report.html
echo "Scan completed. Report saved to zap-report.html"
Authentication
Configuring authentication for protected applications:
bash
# Form-based authentication
# Tools > Options > Authentication
# Select "Form-based Authentication"
# Login URL: https://example.com/login
# Username parameter: username
# Password parameter: password
# Username: testuser
# Password: testpass
# Logged in indicator: "Welcome"
# Logged out indicator: "Login"
# Script-based authentication
# Create authentication script
cat > auth_script.js << 'EOF'
function authenticate(helper, paramsValues, credentials) {
var msg = helper.prepareMessage();
msg.setRequestHeader("Content-Type", "application/json");
msg.setRequestBody('{"username":"' + credentials.getParam("username") + '","password":"' + credentials.getParam("password") + '"}');
helper.sendAndReceive(msg, false);
return msg;
}
function getRequiredParamsNames() {
return ["username", "password"];
}
function getOptionalParamsNames() {
return [];
}
function getCredentialsParamsNames() {
return ["username", "password"];
}
EOF
# HTTP/NTLM authentication
# Tools > Options > Authentication
# Select "HTTP/NTLM Authentication"
# Hostname: example.com
# Realm: DOMAIN
# Username: user
# Password: pass
# API key authentication
# Tools > Options > Authentication
# Select "Script-based Authentication"
# Add API key to headers or parameters
# Session management
# Tools > Options > Session Management
# Cookie-based session management (default)
# HTTP authentication session management
# Script-based session management
# User management
# Tools > Options > Users
# Add users for authenticated scanning
# Configure credentials for each user
Fuzzing
Using ZAP's fuzzing capabilities:
bash
# Manual fuzzing
# Right-click on request in History
# Attack > Fuzz
# Configure fuzz locations
# Select text to fuzz
# Add fuzz location
# Choose payload type:
# - File
# - Strings
# - Numberzz
# - Regex
# Common fuzz payloads
# SQL injection payloads
' OR '1'='1
'; DROP TABLE users; --
' UNION SELECT null,null,null--
# XSS payloads
<script>alert('XSS')</script>
<img src=x onerror=alert('XSS')>
javascript:alert('XSS')
# Directory traversal payloads
../../../etc/passwd
..\..\..\..\windows\system32\drivers\etc\hosts
%2e%2e%2f%2e%2e%2f%2e%2e%2fetc%2fpasswd
# Command injection payloads
; ls -la
| whoami
& dir
`id`
# Custom fuzzing script
#!/bin/bash
# Automated fuzzing with ZAP API
ZAP_API_KEY="your-api-key"
TARGET_URL="https://example.com/search?q=test"
# Create fuzz payload file
cat > fuzz_payloads.txt << 'EOF'
<script>alert('XSS')</script>
' OR '1'='1
../../../etc/passwd
; ls -la
${7*7}
{{7*7}}
EOF
# Start fuzzing via API
curl -X POST "http://localhost:8080/JSON/fuzzer/action/addPayload/" \
-d "type=file&file=fuzz_payloads.txt&apikey=$ZAP_API_KEY"
# Monitor fuzzing progress
curl "http://localhost:8080/JSON/fuzzer/view/scans/?apikey=$ZAP_API_KEY"
Scripting and Automation
Advanced scripting capabilities:
bash
# JavaScript scripting
# Tools > Options > Scripts
# Create new script
# Passive scan script example
cat > passive_scan_script.js << 'EOF'
function scan(ps, msg, src) {
var body = msg.getResponseBody().toString();
var url = msg.getRequestHeader().getURI().toString();
// Check for sensitive information disclosure
if (body.indexOf("password") != -1 || body.indexOf("secret") != -1) {
ps.raiseAlert(
1, // Risk: High
1, // Confidence: High
"Sensitive Information Disclosure",
"The response contains sensitive information",
url,
"",
"",
"Remove sensitive information from responses",
body,
0, // CWE ID
13, // WASC ID
msg
);
}
}
EOF
# Active scan script example
cat > active_scan_script.js << 'EOF'
function scan(as, msg, param, value) {
var newMsg = msg.cloneRequest();
// Test for SQL injection
var sqlPayload = "' OR '1'='1";
as.setParam(newMsg, param, sqlPayload);
as.sendAndReceive(newMsg, false, false);
var response = newMsg.getResponseBody().toString();
if (response.indexOf("SQL syntax") != -1 || response.indexOf("mysql_fetch") != -1) {
as.raiseAlert(
3, // Risk: High
2, // Confidence: Medium
"SQL Injection",
"Possible SQL injection vulnerability",
newMsg.getRequestHeader().getURI().toString(),
param,
sqlPayload,
"Use parameterized queries",
response,
89, // CWE ID
19, // WASC ID
newMsg
);
}
}
EOF
# Python scripting
cat > zap_automation.py << 'EOF'
#!/usr/bin/env python3
import time
import requests
import json
class ZAPAutomation:
def __init__(self, zap_url="http://localhost:8080", api_key=None):
self.zap_url = zap_url
self.api_key = api_key
def spider_scan(self, target_url):
"""Start spider scan"""
params = {
'url': target_url,
'apikey': self.api_key
}
response = requests.get(f"{self.zap_url}/JSON/spider/action/scan/", params=params)
return response.json()
def active_scan(self, target_url):
"""Start active scan"""
params = {
'url': target_url,
'apikey': self.api_key
}
response = requests.get(f"{self.zap_url}/JSON/ascan/action/scan/", params=params)
return response.json()
def get_alerts(self):
"""Get all alerts"""
params = {
'apikey': self.api_key
}
response = requests.get(f"{self.zap_url}/JSON/core/view/alerts/", params=params)
return response.json()
def generate_report(self, format='html'):
"""Generate scan report"""
params = {
'apikey': self.api_key
}
if format == 'html':
response = requests.get(f"{self.zap_url}/OTHER/core/other/htmlreport/", params=params)
elif format == 'xml':
response = requests.get(f"{self.zap_url}/OTHER/core/other/xmlreport/", params=params)
elif format == 'json':
response = requests.get(f"{self.zap_url}/JSON/core/view/alerts/", params=params)
return response.json()
return response.text
# Usage example
if __name__ == "__main__":
zap = ZAPAutomation(api_key="your-api-key")
# Start spider scan
target = "https://example.com"
spider_result = zap.spider_scan(target)
print(f"Spider scan started: {spider_result}")
# Wait for spider to complete
time.sleep(60)
# Start active scan
active_result = zap.active_scan(target)
print(f"Active scan started: {active_result}")
# Wait for active scan to complete
time.sleep(300)
# Get alerts
alerts = zap.get_alerts()
print(f"Found {len(alerts['alerts'])} alerts")
# Generate report
report = zap.generate_report('html')
with open('zap_report.html', 'w') as f:
f.write(report)
print("Report saved to zap_report.html")
EOF
Integration Examples
CI/CD Integration
yaml
# GitLab CI/CD Pipeline
stages:
- security-test
zap-security-scan:
stage: security-test
image: owasp/zap2docker-stable
script:
# Baseline scan
- zap-baseline.py -t $TARGET_URL -r baseline-report.html
# Full scan for staging environment
- |
if [ "$CI_COMMIT_REF_NAME" = "staging" ]; then
zap-full-scan.py -t $TARGET_URL -r full-report.html
fi
# API scan if OpenAPI spec exists
- |
if [ -f "openapi.json" ]; then
zap-api-scan.py -t $TARGET_URL -f openapi -r api-report.html
fi
artifacts:
when: always
paths:
- "*.html"
reports:
junit: zap-report.xml
allow_failure: true
# GitHub Actions Workflow
name: Security Scan with OWASP ZAP
on:
push:
branches: [ main, develop ]
pull_request:
branches: [ main ]
jobs:
zap-scan:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: ZAP Baseline Scan
uses: zaproxy/action-baseline@v0.7.0
with:
target: 'https://example.com'
rules_file_name: '.zap/rules.tsv'
cmd_options: '-a'
- name: ZAP Full Scan
uses: zaproxy/action-full-scan@v0.4.0
with:
target: 'https://example.com'
rules_file_name: '.zap/rules.tsv'
cmd_options: '-a'
- name: Upload ZAP Reports
uses: actions/upload-artifact@v2
with:
name: zap-reports
path: |
report_html.html
report_json.json
# Jenkins Pipeline
pipeline {
agent {
docker {
image 'owasp/zap2docker-stable'
args '-u root --entrypoint='
}
}
environment {
TARGET_URL = 'https://example.com'
ZAP_API_KEY = credentials('zap-api-key')
}
stages {
stage('ZAP Security Scan') {
parallel {
stage('Baseline Scan') {
steps {
script {
sh '''
zap-baseline.py -t $TARGET_URL \
-r baseline-report.html \
-x baseline-report.xml
'''
}
}
}
stage('API Scan') {
when {
expression { fileExists('swagger.json') }
}
steps {
script {
sh '''
zap-api-scan.py -t $TARGET_URL \
-f openapi \
-r api-report.html \
-x api-report.xml
'''
}
}
}
}
}
stage('Process Results') {
steps {
// Archive reports
archiveArtifacts artifacts: '*.html,*.xml', fingerprint: true
// Publish test results
publishTestResults testResultsPattern: '*.xml'
// Publish HTML reports
publishHTML([
allowMissing: false,
alwaysLinkToLastBuild: true,
keepAll: true,
reportDir: '.',
reportFiles: '*.html',
reportName: 'ZAP Security Report'
])
}
}
}
post {
always {
// Clean up
sh 'rm -f *.html *.xml'
}
failure {
// Send notification
emailext (
subject: "Security Scan Failed: ${env.JOB_NAME} - ${env.BUILD_NUMBER}",
body: "ZAP security scan failed. Check console output for details.",
to: "${env.SECURITY_TEAM_EMAIL}"
)
}
}
}
Troubleshooting
Common Issues
Proxy Configuration Issues:
bash
# Check ZAP proxy status
curl -x localhost:8080 http://httpbin.org/ip
# Test HTTPS through proxy
curl -x localhost:8080 -k https://httpbin.org/ip
# Check certificate installation
openssl s_client -connect localhost:8080 -servername example.com
# Reset proxy settings
# Tools > Options > Local Proxies > Reset to defaults
# Clear browser proxy cache
# Firefox: about:networking#dns > Clear DNS Cache
# Chrome: chrome://net-internals/#dns > Clear host cache
Memory Issues:
bash
# Increase memory allocation
zap.sh -Xmx4g
# Monitor memory usage
# Help > Support Info > Memory
# Optimize for large applications
# Tools > Options > Spider > Max Depth: 3
# Tools > Options > Active Scan > Threads per host: 1
# Clear session data
# File > New Session
Performance Issues:
bash
# Reduce scan intensity
# Tools > Options > Active Scan > Attack mode: Safe
# Limit scan scope
# Tools > Options > Active Scan > Input vectors: Reduce selection
# Increase delays
# Tools > Options > Active Scan > Delay when scanning: 1000ms
# Use scan policies
# Analyse > Scan Policy Manager > Create lightweight policy
Authentication Issues:
bash
# Verify authentication configuration
# Tools > Options > Authentication > Test authentication
# Check session management
# Tools > Options > Session Management > Verify session handling
# Monitor authentication in History tab
# Look for login/logout requests
# Use manual authentication
# Manually log in through ZAP proxy
# Right-click authenticated request > Flag as Context > Authentication
# Debug authentication script
# Add logging to authentication script
# Check ZAP logs for errors
API Troubleshooting
Debugging ZAP API issues:
bash
# Test API connectivity
curl "http://localhost:8080/JSON/core/view/version/"
# Check API key
curl "http://localhost:8080/JSON/core/view/version/?apikey=your-api-key"
# Enable API debugging
# Tools > Options > API > Enable debug logging
# Check API logs
tail -f ~/.ZAP/zap.log | grep API
# Test specific API endpoints
curl "http://localhost:8080/JSON/spider/view/status/?apikey=your-api-key"
curl "http://localhost:8080/JSON/ascan/view/status/?apikey=your-api-key"
# Validate API responses
curl -s "http://localhost:8080/JSON/core/view/alerts/?apikey=your-api-key" | jq .
Security Considerations
Operational Security
Safe Testing Practices:
- Only test applications you own or have explicit permission to test
- Use isolated testing environments to prevent data exposure
- Implement proper network segmentation for security testing
- Configure appropriate scan policies to avoid service disruption
- Monitor application performance during testing
Data Protection:
- Encrypt ZAP session files and reports containing sensitive data
- Implement secure data retention policies for scan results
- Control access to ZAP installations and configuration files
- Secure transmission of scan reports and findings
- Regular cleanup of temporary files and session data
Defensive Considerations
Detection and Prevention:
- Monitor for ZAP user agents and scanning patterns
- Implement Web Application Firewalls (WAF) with security testing detection
- Deploy application security monitoring and anomaly detection
- Regular security code reviews and static analysis
- Implement proper input validation and output encoding