1
+---
2
+name: "security_audit"
3
+description: "Security audit and vulnerability assessment skill. Use when reviewing code for security issues, hardening systems, or implementing security best practices."
4
+version: "1.0.0"
5
+author: "Agent Zero Team"
6
+tags: ["security", "audit", "vulnerability", "owasp", "hardening"]
7
+trigger_patterns:
8
+ - "security"
9
+ - "vulnerability"
10
+ - "secure"
11
+ - "audit"
12
+ - "owasp"
13
+ - "penetration"
14
+---
15
+
16
+# Security Audit Skill
17
+
18
+Comprehensive security review and vulnerability assessment guidance.
19
+
20
+## OWASP Top 10 Checklist
21
+
22
+### 1. Broken Access Control
23
+
24
+```markdown
25
+## Check for:
26
+- [ ] Direct object references (IDOR)
27
+- [ ] Missing function-level access control
28
+- [ ] Privilege escalation paths
29
+- [ ] Bypassing access control via URL manipulation
30
+
31
+## Example vulnerability:
32
+```python
33
+# Bad: No authorization check
34
+@app.get("/api/users/{user_id}")
35
+def get_user(user_id: int):
36
+ return db.get_user(user_id) # Any user can access any other user!
37
+
38
+# Good: Verify authorization
39
+@app.get("/api/users/{user_id}")
40
+def get_user(user_id: int, current_user: User = Depends(get_current_user)):
41
+ if current_user.id != user_id and not current_user.is_admin:
42
+ raise HTTPException(403, "Not authorized")
43
+ return db.get_user(user_id)
44
+```
45
+```
46
+
47
+### 2. Cryptographic Failures
48
+
49
+```markdown
50
+## Check for:
51
+- [ ] Sensitive data transmitted in plaintext
52
+- [ ] Weak encryption algorithms (MD5, SHA1 for passwords)
53
+- [ ] Hardcoded secrets
54
+- [ ] Insecure random number generation
55
+
56
+## Secure practices:
57
+```python
58
+# Password hashing
59
+from argon2 import PasswordHasher
60
+ph = PasswordHasher()
61
+hash = ph.hash("password")
62
+ph.verify(hash, "password") # Raises exception if invalid
63
+
64
+# Secure token generation
65
+import secrets
66
+token = secrets.token_urlsafe(32)
67
+
68
+# Never do this:
69
+import hashlib
70
+hash = hashlib.md5(password.encode()).hexdigest() # WEAK!
71
+```
72
+```
73
+
74
+### 3. Injection
75
+
76
+```markdown
77
+## Check for:
78
+- [ ] SQL injection
79
+- [ ] NoSQL injection
80
+- [ ] Command injection
81
+- [ ] LDAP injection
82
+- [ ] XPath injection
83
+
84
+## SQL Injection Prevention:
85
+```python
86
+# Bad: String concatenation
87
+cursor.execute(f"SELECT * FROM users WHERE id = {user_id}")
88
+
89
+# Good: Parameterized queries
90
+cursor.execute("SELECT * FROM users WHERE id = %s", (user_id,))
91
+
92
+# Good: ORM with proper escaping
93
+User.query.filter_by(id=user_id).first()
94
+```
95
+
96
+## Command Injection Prevention:
97
+```python
98
+# Bad
99
+os.system(f"echo {user_input}")
100
+
101
+# Good: Use subprocess with list arguments
102
+subprocess.run(["echo", user_input], shell=False)
103
+
104
+# Better: Avoid shell commands with user input entirely
105
+```
106
+```
107
+
108
+### 4. Insecure Design
109
+
110
+```markdown
111
+## Check for:
112
+- [ ] Missing threat modeling
113
+- [ ] No rate limiting on sensitive operations
114
+- [ ] Lack of defense in depth
115
+- [ ] Missing business logic validation
116
+
117
+## Example:
118
+```python
119
+# Bad: No rate limiting on login
120
+@app.post("/login")
121
+def login(credentials: Credentials):
122
+ return authenticate(credentials)
123
+
124
+# Good: Rate limited
125
+from slowapi import Limiter
126
+limiter = Limiter(key_func=get_remote_address)
127
+
128
+@app.post("/login")
129
+@limiter.limit("5/minute")
130
+def login(credentials: Credentials):
131
+ return authenticate(credentials)
132
+```
133
+```
134
+
135
+### 5. Security Misconfiguration
136
+
137
+```markdown
138
+## Check for:
139
+- [ ] Default credentials in use
140
+- [ ] Unnecessary features enabled
141
+- [ ] Missing security headers
142
+- [ ] Verbose error messages in production
143
+- [ ] Outdated software
144
+
145
+## Security Headers:
146
+```python
147
+# Flask example
148
+@app.after_request
149
+def add_security_headers(response):
150
+ response.headers['X-Content-Type-Options'] = 'nosniff'
151
+ response.headers['X-Frame-Options'] = 'DENY'
152
+ response.headers['X-XSS-Protection'] = '1; mode=block'
153
+ response.headers['Strict-Transport-Security'] = 'max-age=31536000; includeSubDomains'
154
+ response.headers['Content-Security-Policy'] = "default-src 'self'"
155
+ return response
156
+```
157
+```
158
+
159
+### 6. Vulnerable Components
160
+
161
+```markdown
162
+## Check for:
163
+- [ ] Outdated dependencies
164
+- [ ] Known vulnerable packages
165
+- [ ] Unmaintained libraries
166
+
167
+## Tools:
168
+```bash
169
+# Python
170
+pip-audit
171
+safety check -r requirements.txt
172
+
173
+# JavaScript
174
+npm audit
175
+yarn audit
176
+
177
+# General
178
+snyk test
179
+```
180
+```
181
+
182
+### 7. Authentication Failures
183
+
184
+```markdown
185
+## Check for:
186
+- [ ] Weak password policies
187
+- [ ] Missing MFA option
188
+- [ ] Session fixation
189
+- [ ] Insecure session management
190
+
191
+## Secure Session Management:
192
+```python
193
+# Secure session configuration
194
+app.config.update(
195
+ SESSION_COOKIE_SECURE=True, # HTTPS only
196
+ SESSION_COOKIE_HTTPONLY=True, # No JavaScript access
197
+ SESSION_COOKIE_SAMESITE='Lax', # CSRF protection
198
+ PERMANENT_SESSION_LIFETIME=3600 # 1 hour timeout
199
+)
200
+
201
+# Regenerate session on login
202
+@app.route('/login', methods=['POST'])
203
+def login():
204
+ if authenticate(request.form):
205
+ session.regenerate() # Prevent session fixation
206
+ session['user_id'] = user.id
207
+```
208
+```
209
+
210
+### 8. Data Integrity Failures
211
+
212
+```markdown
213
+## Check for:
214
+- [ ] Missing integrity checks on critical data
215
+- [ ] Insecure deserialization
216
+- [ ] Missing code signing
217
+
218
+## Secure Deserialization:
219
+```python
220
+# Bad: Pickle with untrusted data
221
+import pickle
222
+data = pickle.loads(untrusted_data) # DANGEROUS!
223
+
224
+# Good: Use safe serialization
225
+import json
226
+data = json.loads(untrusted_data)
227
+
228
+# If you must use pickle, sign and verify
229
+import hmac
230
+def safe_pickle_loads(data, key):
231
+ signature = data[:32]
232
+ pickled = data[32:]
233
+ expected = hmac.new(key, pickled, 'sha256').digest()
234
+ if not hmac.compare_digest(signature, expected):
235
+ raise ValueError("Invalid signature")
236
+ return pickle.loads(pickled)
237
+```
238
+```
239
+
240
+### 9. Logging & Monitoring Failures
241
+
242
+```markdown
243
+## Check for:
244
+- [ ] Sensitive data in logs
245
+- [ ] Missing audit logs
246
+- [ ] No alerting for security events
247
+- [ ] Logs not protected
248
+
249
+## Secure Logging:
250
+```python
251
+import logging
252
+
253
+# Configure secure logging
254
+logging.basicConfig(
255
+ level=logging.INFO,
256
+ format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
257
+)
258
+
259
+# Sanitize sensitive data
260
+def sanitize_log(data):
261
+ sensitive_keys = ['password', 'token', 'api_key', 'ssn']
262
+ return {k: '***' if k in sensitive_keys else v for k, v in data.items()}
263
+
264
+# Log security events
265
+def log_security_event(event_type, details):
266
+ logger.warning(f"SECURITY: {event_type} - {sanitize_log(details)}")
267
+```
268
+```
269
+
270
+### 10. Server-Side Request Forgery (SSRF)
271
+
272
+```markdown
273
+## Check for:
274
+- [ ] URL parameters used for server requests
275
+- [ ] Unvalidated redirects
276
+- [ ] Internal service exposure
277
+
278
+## Prevention:
279
+```python
280
+from urllib.parse import urlparse
281
+import ipaddress
282
+
283
+ALLOWED_HOSTS = ['api.example.com', 'cdn.example.com']
284
+BLOCKED_NETWORKS = [
285
+ ipaddress.ip_network('10.0.0.0/8'),
286
+ ipaddress.ip_network('172.16.0.0/12'),
287
+ ipaddress.ip_network('192.168.0.0/16'),
288
+ ipaddress.ip_network('127.0.0.0/8'),
289
+]
290
+
291
+def is_safe_url(url):
292
+ try:
293
+ parsed = urlparse(url)
294
+
295
+ # Check allowed hosts
296
+ if parsed.hostname not in ALLOWED_HOSTS:
297
+ return False
298
+
299
+ # Check not internal IP
300
+ ip = ipaddress.ip_address(parsed.hostname)
301
+ for network in BLOCKED_NETWORKS:
302
+ if ip in network:
303
+ return False
304
+
305
+ return True
306
+ except:
307
+ return False
308
+```
309
+```
310
+
311
+## Security Audit Process
312
+
313
+### 1. Information Gathering
314
+
315
+```markdown
316
+- [ ] Identify all entry points (APIs, forms, file uploads)
317
+- [ ] Map authentication and authorization flows
318
+- [ ] Document data flows
319
+- [ ] List third-party integrations
320
+- [ ] Review infrastructure configuration
321
+```
322
+
323
+### 2. Automated Scanning
324
+
325
+```bash
326
+# Web application scanning
327
+nikto -h https://target.com
328
+nuclei -u https://target.com -t cves/
329
+
330
+# Dependency scanning
331
+npm audit
332
+pip-audit
333
+
334
+# Static analysis
335
+bandit -r ./src # Python
336
+semgrep --config auto ./src # Multi-language
337
+```
338
+
339
+### 3. Manual Testing
340
+
341
+```markdown
342
+## Input Validation
343
+- [ ] Test with SQL injection payloads
344
+- [ ] Test with XSS payloads
345
+- [ ] Test with path traversal (../)
346
+- [ ] Test file upload restrictions
347
+
348
+## Authentication
349
+- [ ] Test password reset flow
350
+- [ ] Test session timeout
351
+- [ ] Test concurrent session handling
352
+- [ ] Test remember me functionality
353
+
354
+## Authorization
355
+- [ ] Test horizontal privilege escalation
356
+- [ ] Test vertical privilege escalation
357
+- [ ] Test API endpoint permissions
358
+```
359
+
360
+### 4. Report Template
361
+
362
+```markdown
363
+# Security Audit Report
364
+
365
+## Executive Summary
366
+[Brief overview of findings]
367
+
368
+## Scope
369
+- Systems tested:
370
+- Testing period:
371
+- Methodology:
372
+
373
+## Findings
374
+
375
+### Critical
376
+| ID | Title | Impact | CVSS |
377
+|----|-------|--------|------|
378
+| C1 | SQL Injection in login | Data breach | 9.8 |
379
+
380
+### High
381
+[Similar table]
382
+
383
+### Medium
384
+[Similar table]
385
+
386
+### Low
387
+[Similar table]
388
+
389
+## Detailed Findings
390
+
391
+### C1: SQL Injection in Login Form
392
+
393
+**Description**: The login form is vulnerable to SQL injection...
394
+
395
+**Impact**: An attacker could bypass authentication and access any account...
396
+
397
+**Proof of Concept**:
398
+```
399
+Username: ' OR '1'='1
400
+Password: anything
401
+```
402
+
403
+**Recommendation**: Use parameterized queries...
404
+
405
+**References**:
406
+- CWE-89
407
+- OWASP SQL Injection
408
+```
409
+
410
+## Quick Reference
411
+
412
+### Input Validation
413
+
414
+```python
415
+import re
416
+from html import escape
417
+
418
+def sanitize_input(user_input: str) -> str:
419
+ # Remove/escape HTML
420
+ sanitized = escape(user_input)
421
+
422
+ # Limit length
423
+ sanitized = sanitized[:1000]
424
+
425
+ # Remove null bytes
426
+ sanitized = sanitized.replace('\x00', '')
427
+
428
+ return sanitized
429
+
430
+def validate_email(email: str) -> bool:
431
+ pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
432
+ return bool(re.match(pattern, email))
433
+```
434
+
435
+### Environment Configuration
436
+
437
+```python
438
+# Never commit secrets!
439
+import os
440
+from dotenv import load_dotenv
441
+
442
+load_dotenv()
443
+
444
+DATABASE_URL = os.getenv('DATABASE_URL')
445
+SECRET_KEY = os.getenv('SECRET_KEY')
446
+API_KEY = os.getenv('API_KEY')
447
+
448
+# Verify all required env vars are set
449
+required = ['DATABASE_URL', 'SECRET_KEY', 'API_KEY']
450
+missing = [v for v in required if not os.getenv(v)]
451
+if missing:
452
+ raise RuntimeError(f"Missing environment variables: {missing}")
453
+```