Security Audit
Overview
This skill provides comprehensive security auditing capabilities to identify vulnerabilities, misconfigurations, and security best practice violations across:
- Application code (OWASP Top 10, injection flaws, authentication issues)
- APIs (REST, GraphQL, gRPC security patterns)
- Infrastructure (cloud configs, IaC, container security)
- Data pipelines (data flow security, PII handling, encryption)
- ML models (adversarial attacks, model poisoning, data leakage)
- Compliance frameworks (SOC2, PCI-DSS, HIPAA, GDPR)
Use this skill for security reviews, vulnerability assessments, penetration testing preparation, risk assessments, and compliance audits.
Instructions
1. Scope Assessment
- Identify assets to audit
- Determine compliance requirements
- Review security policies
- Plan audit methodology
2. Application Security Review
- Search for hardcoded secrets (API keys, credentials, tokens)
- Identify injection vulnerabilities (SQL, command, LDAP, XPath, NoSQL)
- Check authentication/authorization (session management, RBAC/ABAC)
- Review cryptographic implementations (algorithms, key management)
- Verify input validation and output encoding
- Check for OWASP Top 10 vulnerabilities
- Review error handling (information disclosure)
- Audit dependency vulnerabilities (CVEs, supply chain)
3. API Security Review
- Authentication mechanisms (OAuth2, JWT, API keys)
- Authorization checks on all endpoints
- Rate limiting and throttling
- Input validation (request body, headers, params)
- API versioning and deprecation handling
- CORS policies and origin validation
- GraphQL query complexity limits and depth restrictions
- gRPC authentication and authorization
- API documentation security (no sensitive data exposure)
4. Infrastructure Security Review
- Cloud configuration audits (AWS, GCP, Azure, Kubernetes)
- IaC security scanning (Terraform, CloudFormation, Pulumi)
- Container security (image scanning, runtime policies)
- Network segmentation and firewall rules
- Secrets management (vaults, rotation policies)
- Service mesh security (mTLS, service-to-service auth)
- CI/CD pipeline security (supply chain, artifact signing)
- Logging and monitoring configuration
5. Data Pipeline Security Review
- Data classification and tagging
- PII/PHI handling and encryption
- Data access controls and audit logs
- Data retention and deletion policies
- Data flow mapping and lineage
- Encryption at rest and in transit
- Backup security and recovery procedures
- Cross-border data transfer compliance
6. ML Model Security Review
- Training data poisoning risks
- Model inversion attacks
- Adversarial input handling
- Model extraction protection
- Inference API security
- Data leakage in model outputs
- Privacy-preserving techniques (differential privacy, federated learning)
- Model versioning and deployment security
7. Compliance Assessment
- SOC2 controls mapping
- PCI-DSS requirements (if processing payments)
- HIPAA compliance (if handling health data)
- GDPR requirements (if EU data subjects)
- Data residency requirements
- Audit trail completeness
- Incident response procedures
- Security awareness training
8. Report Findings
- Categorize by severity (Critical, High, Medium, Low, Info)
- Map to compliance frameworks (CWE, CVE, OWASP)
- Provide remediation steps with code examples
- Prioritize fixes by risk and effort
- Document evidence (file paths, line numbers, screenshots)
- Calculate risk scores (CVSS where applicable)
- Create executive summary and technical details
Best Practices
- Defense in Depth: Multiple security layers (network, application, data)
- Least Privilege: Minimum necessary permissions for users, services, and processes
- Secure Defaults: Safe out-of-the-box settings, fail securely
- Input Validation: Never trust user input, validate server-side
- Encryption: Protect data at rest and in transit (TLS 1.2+, AES-256)
- Logging: Comprehensive audit trails without sensitive data
- Updates: Keep dependencies current, patch CVEs promptly
- Zero Trust: Verify explicitly, assume breach, least privileged access
- Secure SDLC: Security requirements, threat modeling, code review
- Incident Response: Documented procedures, tested playbooks
Examples
Example 1: Common Vulnerability Patterns
# CRITICAL: SQL Injection
# Vulnerable
query = f"SELECT * FROM users WHERE id = {user_id}"
cursor.execute(query)
# Secure
query = "SELECT * FROM users WHERE id = %s"
cursor.execute(query, (user_id,))
# CRITICAL: Command Injection
# Vulnerable
os.system(f"ping {hostname}")
# Secure
import shlex
subprocess.run(["ping", shlex.quote(hostname)])
# HIGH: Cross-Site Scripting (XSS)
# Vulnerable
return f"<h1>Welcome {username}</h1>"
# Secure
from markupsafe import escape
return f"<h1>Welcome {escape(username)}</h1>"
# HIGH: Path Traversal
# Vulnerable
file_path = f"/uploads/{filename}"
with open(file_path) as f:
return f.read()
# Secure
import os
base_dir = "/uploads"
safe_path = os.path.normpath(os.path.join(base_dir, filename))
if not safe_path.startswith(base_dir):
raise SecurityError("Path traversal detected")
# MEDIUM: Insecure Deserialization
# Vulnerable
import pickle
data = pickle.loads(user_input)
# Secure
import json
data = json.loads(user_input)
# MEDIUM: Hardcoded Secrets
# Vulnerable
API_KEY = "sk-1234567890abcdef"
# Secure
API_KEY = os.environ.get("API_KEY")
Example 2: Security Checklist
## Authentication & Authorization
- [ ] Passwords hashed with bcrypt/argon2 (cost factor >= 10)
- [ ] MFA available for sensitive operations
- [ ] Session tokens are cryptographically random
- [ ] Session invalidation on logout
- [ ] Rate limiting on login attempts
- [ ] Account lockout after failed attempts
## Input Validation
- [ ] All inputs validated server-side
- [ ] Parameterized queries for all database operations
- [ ] Output encoding for HTML contexts
- [ ] File upload validation (type, size, content)
- [ ] URL validation and sanitization
## Cryptography
- [ ] TLS 1.2+ enforced for all connections
- [ ] Strong cipher suites only
- [ ] Certificates from trusted CAs
- [ ] Secrets stored in secure vault
- [ ] No deprecated algorithms (MD5, SHA1, DES)
## Access Control
- [ ] Principle of least privilege applied
- [ ] RBAC/ABAC properly implemented
- [ ] Resource authorization checked on every request
- [ ] Admin interfaces protected and audited
## Data Protection
- [ ] Sensitive data encrypted at rest
- [ ] PII handling compliant with regulations
- [ ] Data retention policies implemented
- [ ] Secure data deletion procedures
## Logging & Monitoring
- [ ] Security events logged
- [ ] Logs protected from tampering
- [ ] Alerting on suspicious activities
- [ ] Log retention meets compliance
Example 3: Security Scanning Commands
# Secret scanning with trufflehog
trufflehog filesystem --directory=. --only-verified
# Dependency vulnerability scanning
npm audit --production
pip-audit
cargo audit
# Static analysis
semgrep --config=auto .
bandit -r src/
# Container scanning
trivy image myapp:latest
grype myapp:latest
# Infrastructure scanning
checkov -d terraform/
tfsec terraform/
# OWASP ZAP API scan
zap-api-scan.py -t https://api.example.com/openapi.json -f openapi
# SSL/TLS testing
testssl.sh https://example.com
# Kubernetes security
kubesec scan deployment.yaml
kube-bench run --targets=node
Example 4: Security Headers Configuration
# Nginx security headers
add_header X-Frame-Options "DENY" always;
add_header X-Content-Type-Options "nosniff" always;
add_header X-XSS-Protection "1; mode=block" always;
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
add_header Content-Security-Policy "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: https:; font-src 'self'; object-src 'none'; frame-ancestors 'none'; base-uri 'self'; form-action 'self';" always;
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains; preload" always;
add_header Permissions-Policy "geolocation=(), microphone=(), camera=()" always;
# Hide server version
server_tokens off;
Example 5: API Security Audit Checklist
## REST API Security
Authentication & Authorization:
- [ ] JWT tokens validated on every request
- [ ] Token expiration enforced (access: 15min, refresh: 7days)
- [ ] Token revocation mechanism implemented
- [ ] API keys scoped with least privilege
- [ ] OAuth2 flows correctly implemented
- [ ] Authorization checked at resource level (not just endpoint)
Input Validation:
- [ ] Request body validated against schema (JSON Schema, Pydantic)
- [ ] Path parameters validated (type, format, range)
- [ ] Query parameters validated and sanitized
- [ ] Headers validated (Content-Type, Accept)
- [ ] File uploads validated (type, size, content scanning)
- [ ] URL parameters encoded to prevent injection
Rate Limiting & DoS Protection:
- [ ] Rate limiting per API key/user/IP
- [ ] Burst protection implemented
- [ ] Request size limits enforced
- [ ] Timeout policies configured
- [ ] Circuit breakers for downstream services
CORS & Origin Validation:
- [ ] CORS policies restrictive (not wildcard \*)
- [ ] Allowed origins whitelisted
- [ ] Credentials flag used correctly
- [ ] Preflight requests handled securely
Error Handling:
- [ ] Generic error messages to clients
- [ ] Stack traces never exposed
- [ ] Error codes documented without leaking internals
- [ ] Sensitive data redacted from logs
GraphQL Specific:
- [ ] Query depth limiting (max 7-10 levels)
- [ ] Query complexity scoring implemented
- [ ] Introspection disabled in production
- [ ] Batch query limits enforced
- [ ] Field-level authorization implemented
gRPC Specific:
- [ ] mTLS for service-to-service communication
- [ ] Interceptors for authentication/authorization
- [ ] Message size limits configured
- [ ] Streaming RPCs have timeout/cancellation
- [ ] Reflection service disabled in production
Example 6: Infrastructure Security Audit
# AWS security audit
aws iam get-account-password-policy
aws s3api get-bucket-encryption --bucket mybucket
aws ec2 describe-security-groups --query 'SecurityGroups[?IpPermissions[?FromPort==`22` && ToPort==`22` && IpRanges[?CidrIp==`0.0.0.0/0`]]]'
aws cloudtrail describe-trails
aws kms list-keys
# Kubernetes security audit
kubectl get pods --all-namespaces -o jsonpath='{range .items[*]}{.metadata.name}{"\t"}{.spec.containers[*].securityContext}{"\n"}{end}'
kubectl get networkpolicies --all-namespaces
kubectl get psp # Pod Security Policies
kubectl get serviceaccounts --all-namespaces -o json | jq '.items[] | select(.automountServiceAccountToken != false)'
# Terraform security scanning
tfsec . --format=json --out=tfsec-results.json
checkov -d . --framework terraform --output-file-path . --output json
# Container image scanning
trivy image --severity HIGH,CRITICAL myapp:latest
grype myapp:latest -o json
docker scan myapp:latest
# SAST scanning
semgrep --config=p/owasp-top-ten --config=p/security-audit .
bandit -r . -f json -o bandit-results.json
Example 7: Data Pipeline Security Review
## Data Flow Security
Data Classification:
- [ ] Data classified (Public, Internal, Confidential, Restricted)
- [ ] PII/PHI identified and tagged
- [ ] Sensitive data inventory maintained
- [ ] Data retention policies defined per classification
Encryption:
- [ ] Data encrypted at rest (AES-256 or equivalent)
- [ ] Data encrypted in transit (TLS 1.2+)
- [ ] Key management via KMS/vault (not hardcoded)
- [ ] Key rotation policies implemented
- [ ] Encryption verified at each pipeline stage
Access Controls:
- [ ] Role-based access to data sources
- [ ] Service accounts with least privilege
- [ ] Data access logged and monitored
- [ ] Column-level security for sensitive fields
- [ ] Row-level security where applicable
Data Validation:
- [ ] Schema validation at ingestion
- [ ] Data quality checks prevent malicious inputs
- [ ] Anomaly detection for unusual patterns
- [ ] PII detection and masking automated
Compliance:
- [ ] GDPR: Right to erasure implemented
- [ ] GDPR: Data minimization applied
- [ ] GDPR: Consent tracking for EU subjects
- [ ] HIPAA: BAA with third-party processors
- [ ] CCPA: Do Not Sell mechanism implemented
- [ ] Data residency requirements met
Audit Trail:
- [ ] Data lineage tracked end-to-end
- [ ] Access logs immutable and retained
- [ ] Change tracking for schema/permissions
- [ ] Anomaly detection and alerting
Example 8: ML Model Security Audit
## ML Security Threats
Training Phase:
- [ ] Training data provenance verified
- [ ] Data poisoning detection (outlier detection, statistical tests)
- [ ] Training environment isolated and hardened
- [ ] Model checkpoints encrypted and access-controlled
- [ ] Training logs sanitized (no PII/secrets)
Model Artifacts:
- [ ] Models versioned and signed
- [ ] Model registry access-controlled
- [ ] Model artifacts scanned for embedded secrets
- [ ] Model provenance tracked (data, hyperparameters, code)
Inference Phase:
- [ ] Input validation and sanitization
- [ ] Adversarial input detection
- [ ] Rate limiting on inference API
- [ ] Output filtering (prevent data leakage)
- [ ] Inference logs sanitized
Attack Vectors:
- [ ] Model inversion attacks: Cannot reconstruct training data from model
- [ ] Membership inference: Cannot determine if data was in training set
- [ ] Model extraction: API rate limits prevent model stealing
- [ ] Evasion attacks: Adversarial robustness tested
- [ ] Backdoor attacks: Model audited for hidden triggers
Privacy Preservation:
- [ ] Differential privacy applied (if required)
- [ ] Federated learning for sensitive data (if applicable)
- [ ] Synthetic data used for testing
- [ ] PII removed from training data or anonymized
Monitoring:
- [ ] Model drift detection
- [ ] Inference anomaly detection
- [ ] Performance degradation alerting
- [ ] Security event logging
Example 9: Compliance Mapping
## SOC2 Type II Controls
CC6.1 Logical and Physical Access Controls:
- [ ] MFA enforced for all users
- [ ] Password complexity requirements
- [ ] Account lockout after failed attempts
- [ ] Access reviews quarterly
- [ ] Privileged access monitored
CC6.6 Logical Access - Encryption:
- [ ] Data encrypted at rest (AES-256)
- [ ] Data encrypted in transit (TLS 1.2+)
- [ ] Key management documented
- [ ] Encryption verified in audits
CC7.2 System Monitoring - Detection:
- [ ] SIEM deployed and configured
- [ ] Intrusion detection system active
- [ ] Log aggregation and retention
- [ ] Alerting on security events
- [ ] Incident response playbooks
## PCI-DSS Requirements
Requirement 3: Protect Stored Cardholder Data
- [ ] Cardholder data encrypted (AES-256)
- [ ] Encryption keys managed securely
- [ ] Card data retention minimized
- [ ] PAN masked in logs/UI (show last 4 only)
Requirement 6: Develop Secure Systems
- [ ] Secure coding guidelines followed
- [ ] Code review for security
- [ ] Web application firewall deployed
- [ ] Vulnerability scanning quarterly
- [ ] Penetration testing annually
Requirement 10: Track and Monitor Access
- [ ] Audit trails for all access to cardholder data
- [ ] Logs protected from modification
- [ ] Log retention 90 days immediate, 1 year archive
- [ ] Daily log review process
## GDPR Compliance
Data Subject Rights:
- [ ] Right to access: Export user data API
- [ ] Right to rectification: Update mechanisms
- [ ] Right to erasure: Delete all user data
- [ ] Right to portability: Machine-readable export
- [ ] Right to object: Opt-out mechanisms
Privacy by Design:
- [ ] Data minimization applied
- [ ] Purpose limitation enforced
- [ ] Storage limitation policies
- [ ] Privacy impact assessments completed
- [ ] DPO designated (if required)
Security Measures:
- [ ] Pseudonymization where possible
- [ ] Encryption for sensitive data
- [ ] Regular security testing
- [ ] Breach notification procedures (<72 hours)
Example 10: Vulnerability Severity Matrix
## Severity Classification
CRITICAL (CVSS 9.0-10.0):
- Remote code execution (RCE)
- SQL injection with data exfiltration
- Authentication bypass
- Hardcoded master credentials
- Unrestricted file upload with execution
Action: Patch immediately, emergency change process
HIGH (CVSS 7.0-8.9):
- Privilege escalation
- Cross-site scripting (XSS) in admin panel
- Insecure deserialization
- Missing authentication on sensitive endpoints
- Exposed admin interfaces
Action: Patch within 7 days
MEDIUM (CVSS 4.0-6.9):
- Information disclosure (stack traces, versions)
- CSRF on non-critical operations
- Missing rate limiting
- Weak password policies
- Outdated dependencies with CVEs
Action: Patch within 30 days
LOW (CVSS 0.1-3.9):
- Missing security headers
- Verbose error messages
- Directory listing enabled
- HTTP methods not restricted
- Cookie security flags missing
Action: Patch in next release
INFO (CVSS 0.0):
- Security best practice recommendations
- Hardening opportunities
- Defense in depth suggestions
1---2name: loom-security-audit3description: Comprehensive security audits identifying vulnerabilities, misconfigurations, and best-practice violations across applications, APIs, infrastructure, and data pipelines. Use for OWASP Top 10 reviews, compliance assessments (SOC2, PCI-DSS, HIPAA, GDPR), threat modeling, risk assessment, and hardening.4---5
6# Security Audit
7
8## Overview
9
10This skill provides comprehensive security auditing capabilities to identify vulnerabilities, misconfigurations, and security best practice violations across:
11
12- Application code (OWASP Top 10, injection flaws, authentication issues)
13- APIs (REST, GraphQL, gRPC security patterns)
14- Infrastructure (cloud configs, IaC, container security)
15- Data pipelines (data flow security, PII handling, encryption)
16- ML models (adversarial attacks, model poisoning, data leakage)
17- Compliance frameworks (SOC2, PCI-DSS, HIPAA, GDPR)
18
19Use this skill for security reviews, vulnerability assessments, penetration testing preparation, risk assessments, and compliance audits.
20
21## Instructions
22
23### 1. Scope Assessment
24
25- Identify assets to audit
26- Determine compliance requirements
27- Review security policies
28- Plan audit methodology
29
30### 2. Application Security Review
31
32- Search for hardcoded secrets (API keys, credentials, tokens)
33- Identify injection vulnerabilities (SQL, command, LDAP, XPath, NoSQL)
34- Check authentication/authorization (session management, RBAC/ABAC)
35- Review cryptographic implementations (algorithms, key management)
36- Verify input validation and output encoding
37- Check for OWASP Top 10 vulnerabilities
38- Review error handling (information disclosure)
39- Audit dependency vulnerabilities (CVEs, supply chain)
40
41### 3. API Security Review
42
43- Authentication mechanisms (OAuth2, JWT, API keys)
44- Authorization checks on all endpoints
45- Rate limiting and throttling
46- Input validation (request body, headers, params)
47- API versioning and deprecation handling
48- CORS policies and origin validation
49- GraphQL query complexity limits and depth restrictions
50- gRPC authentication and authorization
51- API documentation security (no sensitive data exposure)
52
53### 4. Infrastructure Security Review
54
55- Cloud configuration audits (AWS, GCP, Azure, Kubernetes)
56- IaC security scanning (Terraform, CloudFormation, Pulumi)
57- Container security (image scanning, runtime policies)
58- Network segmentation and firewall rules
59- Secrets management (vaults, rotation policies)
60- Service mesh security (mTLS, service-to-service auth)
61- CI/CD pipeline security (supply chain, artifact signing)
62- Logging and monitoring configuration
63
64### 5. Data Pipeline Security Review
65
66- Data classification and tagging
67- PII/PHI handling and encryption
68- Data access controls and audit logs
69- Data retention and deletion policies
70- Data flow mapping and lineage
71- Encryption at rest and in transit
72- Backup security and recovery procedures
73- Cross-border data transfer compliance
74
75### 6. ML Model Security Review
76
77- Training data poisoning risks
78- Model inversion attacks
79- Adversarial input handling
80- Model extraction protection
81- Inference API security
82- Data leakage in model outputs
83- Privacy-preserving techniques (differential privacy, federated learning)
84- Model versioning and deployment security
85
86### 7. Compliance Assessment
87
88- SOC2 controls mapping
89- PCI-DSS requirements (if processing payments)
90- HIPAA compliance (if handling health data)
91- GDPR requirements (if EU data subjects)
92- Data residency requirements
93- Audit trail completeness
94- Incident response procedures
95- Security awareness training
96
97### 8. Report Findings
98
99- Categorize by severity (Critical, High, Medium, Low, Info)
100- Map to compliance frameworks (CWE, CVE, OWASP)
101- Provide remediation steps with code examples
102- Prioritize fixes by risk and effort
103- Document evidence (file paths, line numbers, screenshots)
104- Calculate risk scores (CVSS where applicable)
105- Create executive summary and technical details
106
107## Best Practices
108
1091. **Defense in Depth**: Multiple security layers (network, application, data)
1102. **Least Privilege**: Minimum necessary permissions for users, services, and processes
1113. **Secure Defaults**: Safe out-of-the-box settings, fail securely
1124. **Input Validation**: Never trust user input, validate server-side
1135. **Encryption**: Protect data at rest and in transit (TLS 1.2+, AES-256)
1146. **Logging**: Comprehensive audit trails without sensitive data
1157. **Updates**: Keep dependencies current, patch CVEs promptly
1168. **Zero Trust**: Verify explicitly, assume breach, least privileged access
1179. **Secure SDLC**: Security requirements, threat modeling, code review
11810. **Incident Response**: Documented procedures, tested playbooks
119
120## Examples
121
122### Example 1: Common Vulnerability Patterns
123
124```python
125# CRITICAL: SQL Injection
126# Vulnerable
127query = f"SELECT * FROM users WHERE id = {user_id}"
128cursor.execute(query)
129
130# Secure
131query = "SELECT * FROM users WHERE id = %s"
132cursor.execute(query, (user_id,))
133
134# CRITICAL: Command Injection
135# Vulnerable
136os.system(f"ping {hostname}")
137
138# Secure
139import shlex
140subprocess.run(["ping", shlex.quote(hostname)])
141
142# HIGH: Cross-Site Scripting (XSS)
143# Vulnerable
144return f"<h1>Welcome {username}</h1>"
145
146# Secure
147from markupsafe import escape
148return f"<h1>Welcome {escape(username)}</h1>"
149
150# HIGH: Path Traversal
151# Vulnerable
152file_path = f"/uploads/{filename}"
153with open(file_path) as f:
154 return f.read()
155
156# Secure
157import os
158base_dir = "/uploads"
159safe_path = os.path.normpath(os.path.join(base_dir, filename))
160if not safe_path.startswith(base_dir):
161 raise SecurityError("Path traversal detected")
162
163# MEDIUM: Insecure Deserialization
164# Vulnerable
165import pickle
166data = pickle.loads(user_input)
167
168# Secure
169import json
170data = json.loads(user_input)
171
172# MEDIUM: Hardcoded Secrets
173# Vulnerable
174API_KEY = "sk-1234567890abcdef"
175
176# Secure
177API_KEY = os.environ.get("API_KEY")
178```
179
180### Example 2: Security Checklist
181
182```markdown
183## Authentication & Authorization
184
185- [ ] Passwords hashed with bcrypt/argon2 (cost factor >= 10)
186- [ ] MFA available for sensitive operations
187- [ ] Session tokens are cryptographically random
188- [ ] Session invalidation on logout
189- [ ] Rate limiting on login attempts
190- [ ] Account lockout after failed attempts
191
192## Input Validation
193
194- [ ] All inputs validated server-side
195- [ ] Parameterized queries for all database operations
196- [ ] Output encoding for HTML contexts
197- [ ] File upload validation (type, size, content)
198- [ ] URL validation and sanitization
199
200## Cryptography
201
202- [ ] TLS 1.2+ enforced for all connections
203- [ ] Strong cipher suites only
204- [ ] Certificates from trusted CAs
205- [ ] Secrets stored in secure vault
206- [ ] No deprecated algorithms (MD5, SHA1, DES)
207
208## Access Control
209
210- [ ] Principle of least privilege applied
211- [ ] RBAC/ABAC properly implemented
212- [ ] Resource authorization checked on every request
213- [ ] Admin interfaces protected and audited
214
215## Data Protection
216
217- [ ] Sensitive data encrypted at rest
218- [ ] PII handling compliant with regulations
219- [ ] Data retention policies implemented
220- [ ] Secure data deletion procedures
221
222## Logging & Monitoring
223
224- [ ] Security events logged
225- [ ] Logs protected from tampering
226- [ ] Alerting on suspicious activities
227- [ ] Log retention meets compliance
228```
229
230### Example 3: Security Scanning Commands
231
232```bash
233# Secret scanning with trufflehog
234trufflehog filesystem --directory=. --only-verified
235
236# Dependency vulnerability scanning
237npm audit --production
238pip-audit
239cargo audit
240
241# Static analysis
242semgrep --config=auto .
243bandit -r src/
244
245# Container scanning
246trivy image myapp:latest
247grype myapp:latest
248
249# Infrastructure scanning
250checkov -d terraform/
251tfsec terraform/
252
253# OWASP ZAP API scan
254zap-api-scan.py -t https://api.example.com/openapi.json -f openapi
255
256# SSL/TLS testing
257testssl.sh https://example.com
258
259# Kubernetes security
260kubesec scan deployment.yaml
261kube-bench run --targets=node
262```
263
264### Example 4: Security Headers Configuration
265
266```nginx
267# Nginx security headers
268add_header X-Frame-Options "DENY" always;
269add_header X-Content-Type-Options "nosniff" always;
270add_header X-XSS-Protection "1; mode=block" always;
271add_header Referrer-Policy "strict-origin-when-cross-origin" always;
272add_header Content-Security-Policy "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: https:; font-src 'self'; object-src 'none'; frame-ancestors 'none'; base-uri 'self'; form-action 'self';" always;
273add_header Strict-Transport-Security "max-age=31536000; includeSubDomains; preload" always;
274add_header Permissions-Policy "geolocation=(), microphone=(), camera=()" always;
275
276# Hide server version
277server_tokens off;
278```
279
280### Example 5: API Security Audit Checklist
281
282```markdown
283## REST API Security
284
285Authentication & Authorization:
286
287- [ ] JWT tokens validated on every request
288- [ ] Token expiration enforced (access: 15min, refresh: 7days)
289- [ ] Token revocation mechanism implemented
290- [ ] API keys scoped with least privilege
291- [ ] OAuth2 flows correctly implemented
292- [ ] Authorization checked at resource level (not just endpoint)
293
294Input Validation:
295
296- [ ] Request body validated against schema (JSON Schema, Pydantic)
297- [ ] Path parameters validated (type, format, range)
298- [ ] Query parameters validated and sanitized
299- [ ] Headers validated (Content-Type, Accept)
300- [ ] File uploads validated (type, size, content scanning)
301- [ ] URL parameters encoded to prevent injection
302
303Rate Limiting & DoS Protection:
304
305- [ ] Rate limiting per API key/user/IP
306- [ ] Burst protection implemented
307- [ ] Request size limits enforced
308- [ ] Timeout policies configured
309- [ ] Circuit breakers for downstream services
310
311CORS & Origin Validation:
312
313- [ ] CORS policies restrictive (not wildcard \*)
314- [ ] Allowed origins whitelisted
315- [ ] Credentials flag used correctly
316- [ ] Preflight requests handled securely
317
318Error Handling:
319
320- [ ] Generic error messages to clients
321- [ ] Stack traces never exposed
322- [ ] Error codes documented without leaking internals
323- [ ] Sensitive data redacted from logs
324
325GraphQL Specific:
326
327- [ ] Query depth limiting (max 7-10 levels)
328- [ ] Query complexity scoring implemented
329- [ ] Introspection disabled in production
330- [ ] Batch query limits enforced
331- [ ] Field-level authorization implemented
332
333gRPC Specific:
334
335- [ ] mTLS for service-to-service communication
336- [ ] Interceptors for authentication/authorization
337- [ ] Message size limits configured
338- [ ] Streaming RPCs have timeout/cancellation
339- [ ] Reflection service disabled in production
340```
341
342### Example 6: Infrastructure Security Audit
343
344```bash
345# AWS security audit
346aws iam get-account-password-policy
347aws s3api get-bucket-encryption --bucket mybucket
348aws ec2 describe-security-groups --query 'SecurityGroups[?IpPermissions[?FromPort==`22` && ToPort==`22` && IpRanges[?CidrIp==`0.0.0.0/0`]]]'
349aws cloudtrail describe-trails
350aws kms list-keys
351
352# Kubernetes security audit
353kubectl get pods --all-namespaces -o jsonpath='{range .items[*]}{.metadata.name}{"\t"}{.spec.containers[*].securityContext}{"\n"}{end}'
354kubectl get networkpolicies --all-namespaces
355kubectl get psp # Pod Security Policies
356kubectl get serviceaccounts --all-namespaces -o json | jq '.items[] | select(.automountServiceAccountToken != false)'
357
358# Terraform security scanning
359tfsec . --format=json --out=tfsec-results.json
360checkov -d . --framework terraform --output-file-path . --output json
361
362# Container image scanning
363trivy image --severity HIGH,CRITICAL myapp:latest
364grype myapp:latest -o json
365docker scan myapp:latest
366
367# SAST scanning
368semgrep --config=p/owasp-top-ten --config=p/security-audit .
369bandit -r . -f json -o bandit-results.json
370```
371
372### Example 7: Data Pipeline Security Review
373
374```markdown
375## Data Flow Security
376
377Data Classification:
378
379- [ ] Data classified (Public, Internal, Confidential, Restricted)
380- [ ] PII/PHI identified and tagged
381- [ ] Sensitive data inventory maintained
382- [ ] Data retention policies defined per classification
383
384Encryption:
385
386- [ ] Data encrypted at rest (AES-256 or equivalent)
387- [ ] Data encrypted in transit (TLS 1.2+)
388- [ ] Key management via KMS/vault (not hardcoded)
389- [ ] Key rotation policies implemented
390- [ ] Encryption verified at each pipeline stage
391
392Access Controls:
393
394- [ ] Role-based access to data sources
395- [ ] Service accounts with least privilege
396- [ ] Data access logged and monitored
397- [ ] Column-level security for sensitive fields
398- [ ] Row-level security where applicable
399
400Data Validation:
401
402- [ ] Schema validation at ingestion
403- [ ] Data quality checks prevent malicious inputs
404- [ ] Anomaly detection for unusual patterns
405- [ ] PII detection and masking automated
406
407Compliance:
408
409- [ ] GDPR: Right to erasure implemented
410- [ ] GDPR: Data minimization applied
411- [ ] GDPR: Consent tracking for EU subjects
412- [ ] HIPAA: BAA with third-party processors
413- [ ] CCPA: Do Not Sell mechanism implemented
414- [ ] Data residency requirements met
415
416Audit Trail:
417
418- [ ] Data lineage tracked end-to-end
419- [ ] Access logs immutable and retained
420- [ ] Change tracking for schema/permissions
421- [ ] Anomaly detection and alerting
422```
423
424### Example 8: ML Model Security Audit
425
426```markdown
427## ML Security Threats
428
429Training Phase:
430
431- [ ] Training data provenance verified
432- [ ] Data poisoning detection (outlier detection, statistical tests)
433- [ ] Training environment isolated and hardened
434- [ ] Model checkpoints encrypted and access-controlled
435- [ ] Training logs sanitized (no PII/secrets)
436
437Model Artifacts:
438
439- [ ] Models versioned and signed
440- [ ] Model registry access-controlled
441- [ ] Model artifacts scanned for embedded secrets
442- [ ] Model provenance tracked (data, hyperparameters, code)
443
444Inference Phase:
445
446- [ ] Input validation and sanitization
447- [ ] Adversarial input detection
448- [ ] Rate limiting on inference API
449- [ ] Output filtering (prevent data leakage)
450- [ ] Inference logs sanitized
451
452Attack Vectors:
453
454- [ ] Model inversion attacks: Cannot reconstruct training data from model
455- [ ] Membership inference: Cannot determine if data was in training set
456- [ ] Model extraction: API rate limits prevent model stealing
457- [ ] Evasion attacks: Adversarial robustness tested
458- [ ] Backdoor attacks: Model audited for hidden triggers
459
460Privacy Preservation:
461
462- [ ] Differential privacy applied (if required)
463- [ ] Federated learning for sensitive data (if applicable)
464- [ ] Synthetic data used for testing
465- [ ] PII removed from training data or anonymized
466
467Monitoring:
468
469- [ ] Model drift detection
470- [ ] Inference anomaly detection
471- [ ] Performance degradation alerting
472- [ ] Security event logging
473```
474
475### Example 9: Compliance Mapping
476
477```markdown
478## SOC2 Type II Controls
479
480CC6.1 Logical and Physical Access Controls:
481
482- [ ] MFA enforced for all users
483- [ ] Password complexity requirements
484- [ ] Account lockout after failed attempts
485- [ ] Access reviews quarterly
486- [ ] Privileged access monitored
487
488CC6.6 Logical Access - Encryption:
489
490- [ ] Data encrypted at rest (AES-256)
491- [ ] Data encrypted in transit (TLS 1.2+)
492- [ ] Key management documented
493- [ ] Encryption verified in audits
494
495CC7.2 System Monitoring - Detection:
496
497- [ ] SIEM deployed and configured
498- [ ] Intrusion detection system active
499- [ ] Log aggregation and retention
500- [ ] Alerting on security events
501- [ ] Incident response playbooks
502
503## PCI-DSS Requirements
504
505Requirement 3: Protect Stored Cardholder Data
506
507- [ ] Cardholder data encrypted (AES-256)
508- [ ] Encryption keys managed securely
509- [ ] Card data retention minimized
510- [ ] PAN masked in logs/UI (show last 4 only)
511
512Requirement 6: Develop Secure Systems
513
514- [ ] Secure coding guidelines followed
515- [ ] Code review for security
516- [ ] Web application firewall deployed
517- [ ] Vulnerability scanning quarterly
518- [ ] Penetration testing annually
519
520Requirement 10: Track and Monitor Access
521
522- [ ] Audit trails for all access to cardholder data
523- [ ] Logs protected from modification
524- [ ] Log retention 90 days immediate, 1 year archive
525- [ ] Daily log review process
526
527## GDPR Compliance
528
529Data Subject Rights:
530
531- [ ] Right to access: Export user data API
532- [ ] Right to rectification: Update mechanisms
533- [ ] Right to erasure: Delete all user data
534- [ ] Right to portability: Machine-readable export
535- [ ] Right to object: Opt-out mechanisms
536
537Privacy by Design:
538
539- [ ] Data minimization applied
540- [ ] Purpose limitation enforced
541- [ ] Storage limitation policies
542- [ ] Privacy impact assessments completed
543- [ ] DPO designated (if required)
544
545Security Measures:
546
547- [ ] Pseudonymization where possible
548- [ ] Encryption for sensitive data
549- [ ] Regular security testing
550- [ ] Breach notification procedures (<72 hours)
551```
552
553### Example 10: Vulnerability Severity Matrix
554
555```markdown
556## Severity Classification
557
558CRITICAL (CVSS 9.0-10.0):
559
560- Remote code execution (RCE)
561- SQL injection with data exfiltration
562- Authentication bypass
563- Hardcoded master credentials
564- Unrestricted file upload with execution
565
566Action: Patch immediately, emergency change process
567
568HIGH (CVSS 7.0-8.9):
569
570- Privilege escalation
571- Cross-site scripting (XSS) in admin panel
572- Insecure deserialization
573- Missing authentication on sensitive endpoints
574- Exposed admin interfaces
575
576Action: Patch within 7 days
577
578MEDIUM (CVSS 4.0-6.9):
579
580- Information disclosure (stack traces, versions)
581- CSRF on non-critical operations
582- Missing rate limiting
583- Weak password policies
584- Outdated dependencies with CVEs
585
586Action: Patch within 30 days
587
588LOW (CVSS 0.1-3.9):
589
590- Missing security headers
591- Verbose error messages
592- Directory listing enabled
593- HTTP methods not restricted
594- Cookie security flags missing
595
596Action: Patch in next release
597
598INFO (CVSS 0.0):
599
600- Security best practice recommendations
601- Hardening opportunities
602- Defense in depth suggestions
603```