| name | scan-api-security |
| description | Scan API for security vulnerabilities |
| shortcut | apis |
Scan API Security
Perform comprehensive automated security scanning to identify OWASP API Security Top 10 vulnerabilities, misconfigurations, and potential attack vectors with detailed remediation guidance.
When to Use This Command
Use /scan-api-security when you need to:
- Audit API security before production deployment
- Perform regular security assessments
- Validate security fixes and patches
- Comply with security standards (OWASP, PCI DSS)
- Identify authentication and authorization flaws
- Detect data exposure and injection vulnerabilities
DON'T use this when:
- Scanning third-party APIs without permission (illegal)
- As a replacement for manual security review (use both)
- Performance testing is the primary goal (use load testing instead)
Design Decisions
This command implements OWASP ZAP + Custom Scanners as the primary approach because:
- Industry-standard security testing framework
- Comprehensive vulnerability coverage
- Active and passive scanning modes
- API-specific security checks
- Detailed reporting and remediation guidance
- Integration with CI/CD pipelines
Alternative considered: Burp Suite
- More features for manual testing
- Better for complex authentication flows
- Commercial license required
- Recommended for enterprise environments
Alternative considered: Manual testing only
- More thorough for business logic flaws
- Time-consuming and expensive
- Inconsistent coverage
- Recommended as complement to automated scanning
Prerequisites
Before running this command:
- API documentation (OpenAPI/Swagger preferred)
- Test environment with realistic data
- Authentication credentials for all roles
- Permission to perform security testing
- Baseline security requirements defined
Implementation Process
Step 1: Configure Security Scanner
Set up OWASP ZAP or similar tools with API-specific rules and authentication.
Step 2: Perform Automated Scanning
Run comprehensive automated scans for known vulnerability patterns.
Step 3: Execute Manual Verification
Verify critical findings and test business logic vulnerabilities.
Step 4: Analyze Results
Review findings, eliminate false positives, and prioritize by severity.
Step 5: Generate Security Report
Create detailed report with findings, evidence, and remediation steps.
Output Format
The command generates:
security-report.html - Executive summary with charts
vulnerabilities.json - Machine-readable findings
evidence/ - Screenshots and request/response logs
remediation-guide.md - Fix recommendations by priority
security-tests.py - Regression tests for found issues
compliance-checklist.md - Standards compliance status
Code Examples
Example 1: Comprehensive API Security Scanner
const ZAPClient = require('zaproxy');
const axios = require('axios');
const jwt = require('jsonwebtoken');
const { createHash } = require('crypto');
class APISecurityScanner {
constructor(apiUrl, options = {}) {
this.apiUrl = apiUrl;
this.zapOptions = {
proxy: options.zapProxy || 'http://localhost:8080',
apiKey: options.zapApiKey || 'your-zap-api-key'
};
this.zap = new ZAPClient(this.zapOptions);
this.findings = [];
this.credentials = options.credentials || {};
}
async runComprehensiveScan() {
console.log('Starting comprehensive API security scan...');
try {
await this.();
.();
.();
.();
.();
.();
.();
.();
} (error) {
.(, error);
error;
}
}
() {
.();
tests = [
{
: ,
: () => {
token = jwt.({ : }, , { : });
modifiedToken = token.(, );
{
response = axios.(, {
: { : }
});
(response. === ) {
.({
: ,
: ,
: ,
: ,
: { : modifiedToken, : response. },
:
});
}
} (error) {
}
}
},
{
: ,
: () => {
weakPasswords = [, , ];
( password weakPasswords) {
{
response = axios.(, {
: ,
: password
});
(response. === ) {
.({
: ,
: ,
: ,
: ,
: { password, : response. },
:
});
}
} (error) {
}
}
}
},
{
: ,
: () => {
fixedSession = ;
{
response = axios.(,
{ : , : },
{ : { : } }
);
setCookie = response.[];
(setCookie && setCookie.(fixedSession)) {
.({
: ,
: ,
: ,
: ,
: { : fixedSession, setCookie },
:
});
}
} (error) {
}
}
}
];
( test tests) {
{
test.();
} (error) {
.(, error.);
}
}
}
() {
.();
userTokens = {
: .(, ),
: .(, )
};
{
response = axios.(, {
: { : }
});
(response. === ) {
.({
: ,
: ,
: ,
: ,
: {
: ,
: ,
: response.
},
:
});
}
} (error) {
}
{
response = axios.(,
{ : },
{ : { : } }
);
(response. === ) {
.({
: ,
: ,
: ,
: ,
: { : , : response. },
:
});
}
} (error) {
}
}
() {
.();
injectionPayloads = {
: [, , ],
: [, , ],
: [, , ],
: [],
: [, , ]
};
( [type, payloads] .(injectionPayloads)) {
( payload payloads) {
{
response = axios.(, {
: payload
});
(response. && .(response.).(payload)) {
.({
: ,
: ,
: ,
: ,
: { payload, : response. },
:
});
}
} (error) {
}
}
}
}
() {
.();
{
response = axios.();
(response. && .(response.)) {
sensitiveFields = [, , , , ];
exposedFields = [];
response..( {
sensitiveFields.( {
(user[field] !== ) {
exposedFields.(field);
}
});
});
(exposedFields. > ) {
.({
: ,
: ,
: ,
: ,
: { : [... (exposedFields)] },
:
});
}
}
} (error) {
.(, error.);
}
}
() {
.();
endpoint = ;
requests = [];
requestCount = ;
( i = ; i < requestCount; i++) {
requests.(
axios.(endpoint, {
: ,
:
}).( ({ : err.?. }))
);
}
responses = .(requests);
successfulRequests = responses.( r. !== ).;
(successfulRequests === requestCount) {
.({
: ,
: ,
: ,
: ,
: {
endpoint,
: requestCount,
successfulRequests
},
:
});
}
}
() {
.();
{
response = axios.(.);
headers = response.;
requiredHeaders = {
: ,
: ,
: ,
: ,
:
};
missingHeaders = [];
( [header, expectedValue] .(requiredHeaders)) {
(!headers[header]) {
missingHeaders.(header);
} (expectedValue && headers[header] !== expectedValue) {
missingHeaders.();
}
}
(missingHeaders. > ) {
.({
: ,
: ,
: ,
: ,
: { missingHeaders },
:
});
}
} (error) {
.(, error.);
}
}
() {
.();
...(, );
...();
contextId = ...();
...(contextId, );
scanId = ...(., , );
progress = ;
(progress < ) {
progress = ...(scanId);
.();
.();
}
alerts = ...(.);
alerts.( {
.({
: .(alert.),
: ,
: alert.,
: alert.,
: {
: alert.,
: alert.,
: alert.,
: alert.
},
: alert.
});
});
}
() {
..({
...finding,
: ().(),
: ().(.(finding)).()
});
}
() {
mapping = {
: ,
: ,
: ,
:
};
mapping[risk] || ;
}
() {
{
response = axios.(, {
username,
password
});
response..;
} (error) {
.();
;
}
}
() {
( (resolve, ms));
}
() {
report = {
: ().(),
: .,
: {
: ..,
: ..( f. === ).,
: ..( f. === ).,
: ..( f. === ).,
: ..( f. === ).
},
: .,
: .()
};
().(
,
.(report, , )
);
.();
.();
.();
.();
report;
}
() {
recommendations = [];
(..( f. === )) {
recommendations.({
: ,
: ,
: [
,
,
]
});
}
(..( f. === )) {
recommendations.({
: ,
: ,
: [
,
,
]
});
}
recommendations;
}
}
scanner = (, {
: {
: { : , : },
: { : , : }
},
: ,
:
});
scanner.()
.( {
.();
})
.( {
.(, error);
process.();
});
Example 2: Python Security Testing Framework
import requests
import json
import hashlib
import time
from typing import Dict, List, Any
from dataclasses import dataclass, asdict
from enum import Enum
import jwt
import base64
from urllib.parse import urlparse
class Severity(Enum):
CRITICAL = "CRITICAL"
HIGH = "HIGH"
MEDIUM = "MEDIUM"
LOW = "LOW"
INFO = "INFO"
@dataclass
class SecurityFinding:
severity: Severity
category: str
title: str
description: str
evidence: Dict[str, Any]
remediation: str
cwe_id: str = None
owasp_category: str = None
class APISecurityTester:
def __init__(self, base_url: str, auth_token: str = None):
self.base_url = base_url
self.session = requests.Session()
auth_token:
.session.headers[] =
.findings: [SecurityFinding] = []
():
()
test_suites = [
.test_broken_authentication,
.test_broken_authorization,
.test_excessive_data_exposure,
.test_lack_of_resources_rate_limiting,
.test_security_misconfiguration,
.test_injection_vulnerabilities,
.test_improper_assets_management,
.test_insufficient_logging
]
test_suite test_suites:
:
test_suite()
Exception e:
()
.generate_report()
():
()
sql_payloads = [
,
,
,
]
endpoints = [, , ]
endpoint endpoints:
payload sql_payloads:
:
response = .session.get(
,
params={: payload}
)
error_indicators = [
,
,
,
,
]
response_text = response.text.lower()
indicator error_indicators:
indicator.lower() response_text:
.add_finding(
severity=Severity.CRITICAL,
category=,
title=,
description=,
evidence={
: endpoint,
: payload,
: indicator
},
remediation=,
cwe_id=
)
Exception e:
():
()
test_token =
header = base64.urlsafe_b64encode(
json.dumps({: , : }).encode()
).decode().rstrip()
payload = test_token.split()[]
none_token =
response = .session.get(
,
headers={: }
)
response.status_code == :
.add_finding(
severity=Severity.CRITICAL,
category=,
title=,
description=,
evidence={: none_token[:] + },
remediation=,
cwe_id=
)
():
finding = SecurityFinding(**kwargs)
.findings.append(finding)
()
() -> [, ]:
report = {
: time.strftime(),
: .base_url,
: (.findings),
: {
: ([f f .findings f.severity == Severity.CRITICAL]),
: ([f f .findings f.severity == Severity.HIGH]),
: ([f f .findings f.severity == Severity.MEDIUM]),
: ([f f .findings f.severity == Severity.LOW])
},
: [asdict(f) f .findings]
}
(, ) f:
json.dump(report, f, indent=)
()
report
__name__ == :
scanner = APISecurityTester()
report = scanner.run_security_tests()
()
Error Handling
| Error | Cause | Solution |
|---|
| "Connection refused to ZAP" | ZAP proxy not running | Start ZAP daemon on configured port |
| "Permission denied" | No authorization for security testing | Obtain written permission before scanning |
| "Rate limited during scan" | Too many requests | Reduce scan speed, add delays |
| "False positive findings" | Overly aggressive rules | Manually verify and tune scanner rules |
| "Incomplete scan results" | Scan timeout | Increase timeout, scan in phases |
Configuration Options
Scan Modes
passive: Non-intrusive scanning only
active: Full vulnerability testing
targeted: Focus on specific vulnerabilities
compliance: Check against standards
Authentication Types
bearer: JWT/OAuth tokens
basic: Username/password
apikey: API key authentication
certificate: Client certificates
Best Practices
DO:
- Always get written permission before scanning
- Test in non-production environments first
- Verify findings manually to eliminate false positives
- Document all security tests performed
- Prioritize fixes based on severity and exploitability
- Retest after implementing fixes
DON'T:
- Scan production APIs during peak hours
- Ignore low-severity findings (defense in depth)
- Share vulnerability details publicly
- Rely solely on automated scanning
- Skip retesting after remediation
Security Standards Compliance
OWASP API Security Top 10 (2023)
- Broken Object Level Authorization
- Broken Authentication
- Broken Object Property Level Authorization
- Unrestricted Resource Consumption
- Broken Function Level Authorization
- Unrestricted Access to Sensitive Business Flows
- Server Side Request Forgery
- Security Misconfiguration
- Improper Inventory Management
- Unsafe Consumption of APIs
Related Commands
/api-authentication-builder - Implement secure authentication
/api-rate-limiter - Add rate limiting protection
/api-monitoring-dashboard - Monitor security events
/api-response-validator - Validate API responses
Version History
- v1.0.0 (2024-10): Initial implementation with OWASP API Top 10 coverage
- Planned v1.1.0: Add GraphQL and gRPC security testing