OWASP ZAP Custom Rules
Creating and implementing custom scan rules and policies in OWASP ZAP
Custom Rules in OWASP ZAP
OWASP ZAP provides powerful capabilities for creating custom scan rules to detect application-specific vulnerabilities. This guide covers how to develop, implement, and manage custom rules to enhance your security testing.
Understanding ZAP Rules
Passive Scan Rules
Passive scan rules analyze requests and responses without sending additional requests:
- They examine traffic that passes through ZAP
- They don't modify requests or generate new ones
- They're ideal for detecting information disclosure, missing headers, etc.
- They run automatically on all traffic
Examples include:
- Information disclosure detection
- Security header analysis
- Content security policy validation
- Cookie attribute checking
Creating Custom Rules with Scripts
Set Up the Scripting Environment
- Install the Script Console add-on if not already installed
- Go to Tools > Scripts
- Select the appropriate script type:
- Passive Rules for passive scanning
- Active Rules for active scanning
- Click New Script
- Select the scripting language (JavaScript, Grails, Python, etc.)
- Name your script and click OK
Understand the Script Template
For passive rules, implement these functions:
// The scan function will be called for request/response pairs
function scan(ps, msg, src) {
// ps - PassiveScan parent object
// msg - HTTP Message being scanned
// src - Source of the message (proxy, spider, etc.)
// Your scanning logic here
// If an issue is found, raise an alert
ps.newAlert()
.setRisk(1) // 0: info, 1: low, 2: medium, 3: high
.setConfidence(2) // 0: false positive, 1: low, 2: medium, 3: high
.setName("Example Vulnerability")
.setDescription("Description of the vulnerability")
.setParam("parameter")
.setEvidence("evidence")
.setMessage(msg)
.raise();
}
// The setParameter function will be called when the user changes the script parameters
function setParameter(param) {
// Handle any script parameters
}
For active rules, implement these functions:
// The scan function will be called for each URL
function scan(as, msg, param, value) {
// as - ActiveScan parent object
// msg - HTTP Message being scanned
// param - Parameter being tested
// value - Value of the parameter
// Your scanning logic here
// If an issue is found, raise an alert
as.newAlert()
.setRisk(1)
.setConfidence(2)
.setName("Example Vulnerability")
.setDescription("Description of the vulnerability")
.setParam(param)
.setEvidence("evidence")
.setMessage(msg)
.raise();
}
Implement Your Rule Logic
For a passive rule example (detecting sensitive information):
function scan(ps, msg, src) {
// Only check responses
if (!msg.isResponseFromTargetHost()) {
return;
}
// Get the response body
var responseBody = msg.getResponseBody().toString();
// Check for sensitive patterns
var patterns = {
"credit_card": /\b(?:\d{4}[- ]?){3}\d{4}\b/,
"ssn": /\b\d{3}[- ]?\d{2}[- ]?\d{4}\b/,
"api_key": /['"]?api[_-]?key['"]?\s*[:=]\s*['"]?([a-zA-Z0-9]{20,})/i
};
// Check each pattern
for (var key in patterns) {
var matches = responseBody.match(patterns[key]);
if (matches) {
// Create an alert
ps.newAlert()
.setRisk(2) // Medium
.setConfidence(2) // Medium
.setName("Sensitive Information Disclosure")
.setDescription("The response contains potentially sensitive information: " + key)
.setEvidence(matches[0])
.setMessage(msg)
.raise();
// Only raise one alert per pattern
break;
}
}
}
For an active rule example (testing for open redirects):
function scan(as, msg, param, value) {
// Create a test URL
var attackUrl = "https://evil-site.com";
// Make a copy of the message
var testMsg = msg.cloneRequest();
// Update the parameter value
as.setParam(testMsg, param, attackUrl);
// Send the request
as.sendAndReceive(testMsg);
// Check if the response is a redirect to our attack URL
var responseHeader = testMsg.getResponseHeader().toString();
if (responseHeader.indexOf("Location: " + attackUrl) > 0) {
// Create an alert
as.newAlert()
.setRisk(2) // Medium
.setConfidence(2) // Medium
.setName("Open Redirect")
.setDescription("The application redirects to arbitrary URLs")
.setParam(param)
.setEvidence("Location: " + attackUrl)
.setMessage(testMsg)
.raise();
}
}
Advanced Rule Development
Java-Based Rules
For more complex rules, you can develop Java-based scan rules:
-
Setup Development Environment:
- Clone the ZAP repository
- Set up Java development environment
- Understand ZAP's plugin architecture
-
Implement Scan Rule Classes:
- For passive rules, extend
PluginPassiveScanner
- For active rules, extend
AbstractAppParamPlugin
- Implement required methods
- For passive rules, extend
Example passive scanner class structure:
public class CustomPassiveScanner extends PluginPassiveScanner {
@Override
public void scanHttpRequestSend(HttpMessage msg, int id) {
// Scan the request if needed
}
@Override
public void scanHttpResponseReceive(HttpMessage msg, int id, Source source) {
// Scan the response
// If issue found, createAlert()
}
@Override
public int getPluginId() {
return 60101; // Custom ID
}
@Override
public String getName() {
return "Custom Passive Scanner";
}
}
Custom Scan Policies
Create a Custom Scan Policy
- Go to Analyze > Scan Policy Manager
- Click Add
- Enter a name for your policy
- Select a template to start from (e.g., Default Policy)
- Click OK
- Modify the policy settings:
- Enable/disable specific rules
- Adjust rule strength and threshold
- Configure category settings
- Click Save
Configure Policy Settings
Customize policy settings for different scenarios:
-
API Testing Policy:
- Disable browser-based rules
- Enable API-specific rules
- Focus on injection vulnerabilities
- Configure appropriate thresholds
-
Performance-Focused Policy:
- Disable resource-intensive rules
- Lower scan strength for faster execution
- Focus on critical vulnerabilities only
- Limit scan depth and breadth
-
Compliance Policy:
- Enable rules relevant to specific standards
- Configure appropriate risk thresholds
- Include all required compliance checks
- Generate appropriate reporting
Export and Share Policies
Share your custom policies with your team:
- In the Scan Policy Manager, select your policy
- Click Export
- Save the policy file (.policy)
- Share the file with your team
- Others can import it via Import in the Scan Policy Manager
This allows standardized testing across your organization.
Application-Specific Rules
Web Application Rules
Custom rules for common web application vulnerabilities:
-
Business Logic Vulnerabilities:
- Create rules to detect application-specific logic flaws
- Test for insecure direct object references
- Check for missing access controls
- Verify transaction integrity
-
Custom Authentication Checks:
- Test for weak password policies
- Check for authentication bypasses
- Verify multi-factor authentication
- Test session management
Example passive rule for detecting weak password reset functionality:
function scan(ps, msg, src) {
var url = msg.getRequestHeader().getURI().toString();
// Check if this is a password reset page
if (url.indexOf("reset-password") > 0 ||
url.indexOf("forgot-password") > 0) {
var responseBody = msg.getResponseBody().toString();
// Check for indicators of insecure practices
if (responseBody.indexOf("security question") > 0 ||
responseBody.indexOf("mother's maiden name") > 0) {
ps.newAlert()
.setRisk(2) // Medium
.setConfidence(2) // Medium
.setName("Weak Password Reset Mechanism")
.setDescription("The application uses potentially weak methods for password reset")
.setEvidence("security question")
.setMessage(msg)
.raise();
}
}
}
Rule Management Best Practices
Organize Your Rules
Implement a structured approach to rule management:
-
Categorize rules by:
- Vulnerability type
- Application area
- Risk level
- Testing phase
-
Use consistent naming conventions:
- Include vulnerability type in name
- Use prefixes for categorization
- Include version numbers
- Document rule purpose
Version Control
Maintain rules in version control:
-
Store rules in a repository:
- Use Git for version control
- Document changes and updates
- Track rule effectiveness
- Implement peer review process
-
Implement change management:
- Test rules before deployment
- Document rule changes
- Communicate updates to team
- Track rule versions
Continuous Improvement
Regularly review and improve your rules:
-
Monitor rule effectiveness:
- Track true/false positives
- Gather user feedback
- Analyze detection rates
- Compare with manual testing
-
Update rules based on:
- New vulnerability types
- Application changes
- False positive reduction
- Performance optimization
- User feedback
Integration with Development Workflow
CI/CD Integration
Integrate custom rules into CI/CD pipelines:
-
Automated Testing:
- Run ZAP with custom rules in CI/CD
- Configure appropriate scan policies
- Set quality gates based on findings
- Generate reports for review
-
Implementation Example:
Jenkins pipeline example:
pipeline { agent any stages { stage('ZAP Security Test') { steps { sh ''' docker run -v $(pwd):/zap/wrk/:rw -t owasp/zap2docker-stable \ zap-baseline.py -t https://example.com \ -c custom-rules.conf -r testreport.html ''' } post { always { publishHTML([ allowMissing: false, alwaysLinkToLastBuild: true, keepAll: true, reportDir: '.', reportFiles: 'testreport.html', reportName: 'ZAP Security Report' ]) } } } } }
Case Studies
E-commerce Application
Custom rules for an e-commerce platform:
-
Business Logic Rules:
- Price manipulation detection
- Order process validation
- Discount code abuse detection
- Inventory manipulation checks
-
Implementation Approach:
- Created passive rules for monitoring transactions
- Developed active rules for testing checkout process
- Implemented custom scan policy for e-commerce
- Integrated with CI/CD pipeline
-
Results:
- Detected price manipulation vulnerability
- Found order process bypass
- Identified insecure discount code implementation
- Improved overall security posture
Banking Application
Custom rules for a banking application:
-
Security-Critical Rules:
- Transaction integrity validation
- Authentication flow testing
- Session management verification
- Authorization bypass detection
-
Implementation Approach:
- Developed Java-based custom rules
- Created application-specific scan policy
- Implemented continuous security testing
- Integrated with compliance reporting
-
Results:
- Identified session fixation vulnerability
- Detected insecure transaction processing
- Found authorization bypass in account management
- Achieved compliance with financial regulations
Healthcare System
Custom rules for a healthcare system:
-
Privacy-Focused Rules:
- PHI exposure detection
- Access control verification
- Audit logging validation
- Encryption implementation checks
-
Implementation Approach:
- Created passive rules for PHI detection
- Developed active rules for access control testing
- Implemented HIPAA-focused scan policy
- Integrated with compliance reporting
-
Results:
- Detected PHI exposure in error messages
- Found insufficient access controls
- Identified missing audit logs
- Improved HIPAA compliance
Next Steps
Now that you understand custom rules in OWASP ZAP, explore these related topics:
- Advanced Techniques - Explore other advanced ZAP features
- Scripting - Learn more about ZAP scripting capabilities
- Automation - Automate security testing with ZAP
- Best Practices - Best practices for effective and ethical use of ZAP