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