# OWASP ZAP (Zed Attack Proxy)

> **Free and Open Source Web Application Security Scanner**

## 📋 Overview

OWASP ZAP (Zed Attack Proxy) adalah open-source security testing tool yang dikembangkan oleh OWASP community. ZAP dirancang untuk membantu developer dan security professionals dalam menemukan vulnerabilities secara otomatis dan manual pada web applications.

## 🎯 Key Features

### 🔍 **Automated Scanning**

* **Spider/Crawler** - Automated application discovery
* **Active Scan** - Automated vulnerability detection
* **Passive Scan** - Non-intrusive analysis
* **AJAX Spider** - JavaScript-heavy application crawling

### 🔧 **Manual Testing Tools**

* **Intercepting Proxy** - Request/response manipulation
* **Fuzzer** - Custom payload testing
* **Brute Forcer** - Authentication testing
* **Requester** - Manual request crafting

### 🛡️ **Security Testing**

* **OWASP Top 10** - Built-in rules for common vulnerabilities
* **Custom Scripts** - Python, JavaScript, Ruby scripting
* **API Testing** - REST and GraphQL API security
* **Authentication Support** - Multiple authentication methods

### 📊 **Reporting & Integration**

* **HTML Reports** - Detailed vulnerability reports
* **JSON/XML Export** - Machine-readable formats
* **CI/CD Integration** - GitHub Actions, Jenkins, GitLab CI
* **SARIF Format** - GitHub Security tab integration

## 🚀 Installation

### Download Options

```bash
# Download from https://www.zaproxy.org/download/
# Available formats:
# - Windows Installer (.exe)
# - macOS Disk Image (.dmg)
# - Linux Package (.deb/.rpm)
# - Docker Image
# - Cross-platform Package (.zip)
```

### Docker Installation (Recommended)

```bash
# Pull latest image
docker pull owasp/zap2docker-stable

# Run with persistent data
docker run -t -i \
  -p 8080:8080 \
  -v $(pwd)/zap-data:/zap/wrk \
  owasp/zap2docker-stable zap.sh -daemon -host 0.0.0.0 -port 8080

# Run with desktop GUI
docker run -t -i \
  -p 5900:5900 \
  -v $(pwd)/zap-data:/zap/wrk \
  owasp/zap2docker-stable x11vnc -forever -usepw -create
```

### Linux Installation

```bash
# Ubuntu/Debian
sudo apt-get update
sudo apt-get install zaproxy

# CentOS/RHEL/Fedora
sudo dnf install zaproxy

# Or download directly
wget https://github.com/zaproxy/zaproxy/releases/download/v2.12.0/ZAP_2.12.0_Linux.tar.gz
tar -xzf ZAP_2.12.0_Linux.tar.gz
cd ZAP_2.12.0
./zap.sh
```

### macOS Installation

```bash
# Using Homebrew
brew install --cask zap

# Or download .dmg and install
# Mount DMG and drag to Applications
```

## 🔧 Basic Configuration

### First-Time Setup

1. **Launch ZAP** - Start the application
2. **Set Proxy** - Default: 127.0.0.1:8080
3. **Configure Browser** - Set browser proxy to ZAP
4. **Context Setup** - Define target application context

### Browser Proxy Configuration

```
Firefox:
- Settings → Network Settings → Manual proxy configuration
- HTTP Proxy: 127.0.0.1:8080
- Check "Use this proxy for all protocols"

Chrome:
- Settings → Advanced → System → Open proxy settings
- Configure HTTP Proxy: 127.0.0.1:8080
```

## 🔍 Basic Usage

### Manual Testing Workflow

1. **Configure Browser Proxy** - Point browser to ZAP
2. **Browse Application** - Let ZAP discover endpoints
3. **Analyze Sites Tab** - Review discovered applications
4. **Start Active Scan** - Begin automated testing
5. **Review Alerts** - Analyze found vulnerabilities

### Command Line Interface

```bash
# Quick scan
./zap.sh -cmd -quickurl https://example.com

# Full scan with authentication
./zap.sh -cmd \
  -quickurl https://example.com \
  -quickauthurl https://example.com/login \
  -quickauthusername admin \
  -quickauthpassword password

# API scan
./zap.sh -cmd \
  -quickurl https://api.example.com \
  -openapifile ./api-spec.json
```

### Python API Integration

```python
from zapv2 import ZAPv2

# Connect to ZAP API
zap = ZAPv2(proxies={'http': 'http://127.0.0.1:8080', 'https': 'http://127.0.0.1:8080'})

# Spider the application
scan_id = zap.spider.scan('https://example.com')
while int(zap.spider.status(scan_id)) < 100:
    print(f"Spider progress: {zap.spider.status(scan_id)}%")

# Active scan
scan_id = zap.ascan.scan('https://example.com')
while int(zap.ascan.status(scan_id)) < 100:
    print(f"Scan progress: {zap.ascan.status(scan_id)}%")

# Get alerts
alerts = zap.core.alerts()
for alert in alerts:
    print(f"Alert: {alert['alert']}, Risk: {alert['risk']}")
```

## 🎯 Common Use Cases

### 1. **Basic Web Application Scan**

```
1. Start ZAP and configure browser proxy
2. Browse through the application manually
3. Right-click on site → "Active Scan"
4. Review results in Alerts tab
5. Generate HTML report
```

### 2. **API Security Testing**

```
1. Import API specification (OpenAPI/Swagger)
2. Configure API authentication
3. Run automated API scan
4. Test custom endpoints manually
5. Export findings
```

### 3. **Authentication Testing**

```
1. Configure authentication context
2. Set up form-based authentication
3. Test for weak passwords
4. Check session management
5. Verify authorization bypass
```

### 4. **Fuzzing Custom Parameters**

```
1. Identify target parameter
2. Create fuzzing payload list
3. Configure fuzzer settings
4. Run fuzzing attack
5. Analyze responses for vulnerabilities
```

## 🔧 Advanced Features

### Context Management

```bash
# Create context for target application
# Sites Tab → Right-click → Create Context
# Define:
# - Target URLs
# - Authentication method
# - Excluded URLs
# - Technology stack
```

### Authentication Methods

```bash
# Form-based Authentication
# Context → Authentication → Form-based
# Login URL: https://example.com/login
# Username Parameter: username
# Password Parameter: password
# Logged Out Regex: (Login|Sign in)

# JSON Token Authentication
# Context → Authentication → JSON Token
# Header Name: Authorization
# Token Format: Bearer {token}

# OAuth 2.0
# Context → Authentication → OAuth 2.0
# Configure OAuth flow parameters
```

### Scripting

```javascript
// Example: Custom HTTP Sender Script
function sendingRequest(msg, initiator, helper) {
    // Modify request before sending
    if (msg.getRequestHeader().getURI().toString().includes('/api/')) {
        msg.getRequestHeader().setHeader('X-Custom-Header', 'value');
    }
}

function responseReceived(msg, initiator, helper) {
    // Analyze response
    var body = msg.getResponseBody().toString();
    if (body.includes('error')) {
        print('Error detected in response: ' + msg.getRequestHeader().getURI());
    }
}
```

## 📊 Scanning Profiles

### Built-in Profiles

* **Safety First** - Low impact, safe for production
* **Standard** - Balanced testing approach
* **Full Scan** - Comprehensive vulnerability detection
* **Development** - Optimized for development environments

### Custom Profiles

```bash
# Create custom scan policy
# Analysis → Scan Policy → Add
# Configure:
# - Plugin strength (High, Medium, Low, Off)
# - Alert threshold (High, Medium, Low, Off)
# - Custom plugin settings
```

## 🔗 CI/CD Integration

### GitHub Actions

```yaml
# .github/workflows/zap-scan.yml
name: ZAP Security Scan
on: [push, pull_request]

jobs:
  zap-scan:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      - name: ZAP Baseline Scan
        uses: zaproxy/action-baseline@v0.7.0
        with:
          target: 'http://localhost:3000'
          rules_file_name: '.zap/rules.tsv'
          cmd_options: '-a'
```

### GitLab CI

```yaml
# .gitlab-ci.yml
zap-scan:
  stage: test
  image: owasp/zap2docker-stable
  script:
    - mkdir -p /zap/wrk/
    - /zap/zap-baseline.py -t $TARGET_URL -J gl-sast-report.json
  artifacts:
    reports:
      sast: gl-sast-report.json
```

### Jenkins Pipeline

```groovy
pipeline {
    agent any
    stages {
        stage('ZAP Scan') {
            steps {
                script {
                    sh 'docker run -t owasp/zap2docker-stable zap-baseline.py -t http://target-app'
                }
            }
        }
    }
}
```

## 📈 Reports and Analysis

### Report Types

* **HTML Report** - Comprehensive findings report
* **Markdown Report** - Documentation-friendly format
* **JSON/XML** - Machine-readable formats
* **PDF Report** - Professional documentation

### Alert Levels

* **High** - Critical vulnerabilities requiring immediate attention
* **Medium** - Security issues that should be addressed
* **Low** - Minor security improvements
* **Informational** - Security observations and recommendations

### Export Examples

```bash
# Generate HTML report
./zap.sh -cmd -quickurl https://example.com -quickout /path/to/report.html

# Export JSON for automation
./zap.sh -cmd -quickurl https://example.com -quickprogress -quickout /path/to/report.json
```

## 🔧 Customization and Extensions

### Marketplace Add-ons

```
Tools → Marketplace → Available Add-ons
Popular add-ons:
- SOAP Support - SOAP web service testing
- Selenium Scripts - Browser automation
- LDAP Injection - LDAP vulnerability testing
- Replacer - Automated request modification
- Forced Browse - Directory and file discovery
```

### Custom Scripts

```python
# Python script example
def zap_init():
    # Initialize script
    pass

def zap_pre_auth(msg):
    # Process request before authentication
    return msg

def zap_post_auth(msg):
    # Process request after authentication
    return msg
```

## 📊 Best Practices

### Scanning Guidelines

1. **Scope Definition** - Clearly define testing scope
2. **Authorization** - Always get permission before testing
3. **Production Safety** - Use "Safety First" profile for production
4. **Regular Scanning** - Integrate into CI/CD pipeline
5. **False Positives** - Manually verify critical findings

### Performance Optimization

```bash
# Limit concurrent connections
./zap.sh -cmd -config connection.maxConn=5

# Adjust thread pools
./zap.sh -cmd -config spider.maxDepth=10

# Optimize for large applications
./zap.sh -cmd -config scanner.strength=HIGH -config scanner.alertThreshold=LOW
```

### Team Collaboration

* **Session Persistence** - Save and share ZAP sessions
* **Policy Standardization** - Use consistent scan policies
* **Alert Triage** - Establish triage process
* **Documentation** - Document findings and remediation steps

## 🎓 Learning Resources

### Official Documentation

* [OWASP ZAP User Guide](https://www.zaproxy.org/docs/)
* [ZAP Blog](https://www.zaproxy.org/blog/)
* [ZAP YouTube Channel](https://www.youtube.com/c/ZAPROXY)
* [ZAP Community](https://community.zaproxy.org/)

### Training Resources

* [OWASP Security Shepherd](https://github.com/OWASP/SecurityShepherd)
* [WebGoat](https://github.com/WebGoat/WebGoat)
* [Damn Vulnerable Web Application (DVWA)](https://github.com/digininja/DVWA)

## 📈 Comparison with Other Tools

| Feature                | OWASP ZAP | Burp Suite     | Netsparker    | Acunetix      |
| ---------------------- | --------- | -------------- | ------------- | ------------- |
| **Cost**               | 🆓 Free   | 💰 Paid        | 💰 Enterprise | 💰 Enterprise |
| **Open Source**        | ✅         | 🆓 Community   | ❌             | ❌             |
| **Learning Curve**     | 📚 Easy   | 📚 Medium      | 📚 Easy       | 📚 Easy       |
| **Automated Scanning** | ✅         | ✅ Professional | ✅             | ✅             |
| **Manual Testing**     | ✅         | ✅              | Limited       | Limited       |
| **API Testing**        | ✅         | ✅ Professional | ✅             | ✅             |
| **CI/CD**              | ✅         | ✅ Professional | ✅             | ✅             |

## 🔧 Troubleshooting

### Common Issues

```bash
# Proxy not working
# Check browser proxy settings
# Verify ZAP is listening on correct port
# Check firewall settings

# SSL/TLS issues
# Import ZAP certificate into browser/system
# Disable SSL certificate validation for testing

# Performance issues
# Increase JVM memory: -Xmx2g
# Limit scan scope
# Use appropriate scan policy

# Authentication problems
# Verify authentication configuration
# Check session handling
# Test manually first
```

### Debug Mode

```bash
# Enable debug logging
./zap.sh -cmd -config connection.timeoutInSecs=60 -debug

# Monitor API calls
# Tools → Options → API → Enable API logging
```

## 🛡️ Enterprise Features

### ZAP API

```bash
# Start ZAP daemon mode
./zap.sh -daemon -host 0.0.0.0 -port 8080

# API endpoints
# http://localhost:8080/JSON/core/view/urls/
# http://localhost:8080/JSON/ascan/action/scan/
```

### Team Features

* **Session Sharing** - Collaborative testing
* **Policy Management** - Consistent testing standards
* **Reporting Templates** - Standardized documentation
* **Integration Hub** - Extended ecosystem support

***

**🔒 Remember**: Only use ZAP on systems you own or have explicit permission to test. Unauthorized security testing is illegal.

**⚡ Pro Tip**: Start with the "Safety First" scan policy for production systems and gradually increase scanning intensity based on your environment's tolerance.

*📅 Last Updated: 2024*
