## Security Audit Framework
### Phase 1: Attack Surface Mapping
```
I need to audit the security of:
**Application:** [Name and description]
**Tech Stack:** [Languages, frameworks, databases]
**Architecture:** [Monolith, microservices, serverless]
**Deployment:** [Cloud provider, on-prem, hybrid]
Map the attack surface:
1. **Entry Points**
- Public endpoints (APIs, web pages)
- Authentication endpoints
- File upload handlers
- Webhook receivers
- WebSocket connections
2. **Data Flows**
- User input sources
- Data storage locations
- External service integrations
- Data export/download paths
3. **Trust Boundaries**
- Authenticated vs. unauthenticated zones
- Admin vs. user privileges
- Internal vs. external services
- Third-party dependencies
4. **Sensitive Assets**
- User credentials and PII
- API keys and secrets
- Financial data
- Business-critical information
5. **Existing Security Controls**
- Authentication mechanisms
- Authorization framework
- Input validation
- Encryption (at rest, in transit)
Generate attack surface diagram and risk matrix.
```
### Phase 2: Vulnerability Assessment
#### OWASP Top 10 Audit
```
Audit for OWASP Top 10 vulnerabilities:
**Codebase:** [Repository or code sample]
For each category, check:
**A01: Broken Access Control**
- IDOR (Insecure Direct Object References)
- Privilege escalation paths
- Missing function-level access control
- CORS misconfigurations
- JWT token manipulation
**A02: Cryptographic Failures**
- Weak encryption algorithms (MD5, SHA1, DES)
- Hardcoded secrets in code
- Insufficient key management
- Missing HTTPS enforcement
- Insecure random number generation
**A03: Injection**
- SQL injection (parameterized queries?)
- NoSQL injection
- Command injection
- LDAP injection
- XPath injection
**A04: Insecure Design**
- Missing rate limiting
- Lack of defense in depth
- Insufficient logging
- Missing security requirements
**A05: Security Misconfiguration**
- Default credentials
- Verbose error messages
- Unnecessary features enabled
- Missing security headers
- Outdated software versions
**A06: Vulnerable Components**
- Known CVEs in dependencies
- Outdated packages
- Abandoned libraries
- License compliance issues
**A07: Authentication Failures**
- Weak password policies
- Missing brute force protection
- Session fixation
- Insecure session storage
- Missing MFA options
**A08: Data Integrity Failures**
- Unsigned updates
- Deserialization vulnerabilities
- CI/CD pipeline security
- Dependency integrity (lockfiles)
**A09: Logging & Monitoring Failures**
- Missing security event logging
- Insufficient log detail
- No alerting on attacks
- Log injection vulnerabilities
**A10: SSRF**
- Server-Side Request Forgery
- URL validation bypasses
- Cloud metadata access
Generate findings report with severity ratings.
```
#### Code-Level Security Review
```
Review code for security issues:
**File/Module:** [Path or code snippet]
**Language:** [JavaScript, Python, etc.]
Security checklist:
1. **Input Validation**
- All user inputs validated?
- Type checking and sanitization?
- Length limits enforced?
- Whitelist vs. blacklist approach?
2. **Output Encoding**
- HTML encoding for web output?
- SQL parameterization?
- JSON encoding for API responses?
- Context-appropriate encoding?
3. **Authentication**
- Secure password storage (bcrypt, argon2)?
- Session management security?
- Token generation entropy?
- Secure cookie attributes?
4. **Authorization**
- Access control on every request?
- Principle of least privilege?
- Resource ownership verification?
- Role hierarchy properly enforced?
5. **Error Handling**
- Generic error messages to users?
- Stack traces hidden in production?
- Errors logged securely?
- Fail-secure behavior?
6. **Sensitive Data**
- Secrets in environment variables?
- No hardcoded credentials?
- PII handling compliant?
- Secure data deletion?
Provide annotated code review with fixes.
```
### Phase 3: Dependency & Infrastructure Security
```
Audit dependencies and infrastructure:
**Package Manager:** [npm, pip, cargo, etc.]
**Lock File:** [package-lock.json, requirements.txt, etc.]
**Infrastructure:** [Docker, Kubernetes, cloud services]
1. **Dependency Vulnerability Scan**
- Run npm audit / safety check / cargo audit
- Check for known CVEs
- Identify transitive vulnerabilities
- Prioritize by exploitability
2. **Supply Chain Security**
- Verify package sources
- Check maintainer reputation
- Review dependency permissions
- Ensure reproducible builds
3. **Container Security**
- Base image vulnerabilities
- Running as non-root?
- Secrets in image layers?
- Read-only filesystem?
4. **Cloud Configuration**
- IAM policies (least privilege)
- S3 bucket permissions
- Database public access
- Security group rules
- Encryption at rest
5. **Network Security**
- TLS configuration (cipher suites)
- Certificate management
- Internal service authentication
- Network segmentation
Generate vulnerability report with remediation priority.
```
### Phase 4: Remediation & Hardening
```
Create remediation plan for findings:
**Findings:**
1. [Vulnerability 1: severity, location]
2. [Vulnerability 2: severity, location]
...
For each finding:
1. **Immediate Mitigation**
- Quick fix to reduce risk
- WAF rules or configuration changes
- Feature flags to disable vulnerable code
2. **Permanent Fix**
- Code changes required
- Dependencies to update
- Architecture changes needed
- Testing requirements
3. **Verification**
- How to test the fix
- Regression testing needs
- Penetration test validation
4. **Prevention**
- Security controls to add
- CI/CD security checks
- Developer training needs
5. **Prioritization**
- CVSS score or custom severity
- Exploitability assessment
- Business impact analysis
- Remediation effort estimate
Generate prioritized remediation backlog with code examples.
```
## Security Headers Checklist
```
Verify security headers are configured:
Required Headers:
- Content-Security-Policy: [define allowed sources]
- X-Content-Type-Options: nosniff
- X-Frame-Options: DENY or SAMEORIGIN
- Strict-Transport-Security: max-age=31536000; includeSubDomains
- Referrer-Policy: strict-origin-when-cross-origin
- Permissions-Policy: [restrict browser features]
Cookie Security:
- Secure flag for HTTPS-only
- HttpOnly flag to prevent XSS access
- SameSite=Strict or Lax
- Reasonable expiration times
CORS Configuration:
- Explicit allowed origins (not *)
- Allowed methods restricted
- Credentials handling reviewed
```
## Best Practices
1. **Shift Left**: Integrate security checks into CI/CD pipeline
2. **Defense in Depth**: Multiple layers of security controls
3. **Least Privilege**: Minimum permissions for every component
4. **Fail Secure**: Default to denying access on errors
5. **Security Logging**: Log security events for detection
6. **Regular Updates**: Keep dependencies and systems patched
7. **Threat Modeling**: Consider adversary capabilities and motivations
8. **Penetration Testing**: Regular third-party security assessments
## Example Session
**User**: "Review this authentication endpoint for security issues."
**Response**:
> I've identified several security vulnerabilities in the authentication code:
>
> **Critical Issues:**
>
> 1. **SQL Injection (Line 42)** - User input directly concatenated into query
>
> ```javascript
> // VULNERABLE
> const query = `SELECT * FROM users WHERE email = '${email}'`;
>
> // FIXED
> const query = 'SELECT * FROM users WHERE email = $1';
> const result = await db.query(query, [email]);
> ```
>
> 2. **Weak Password Hashing (Line 58)** - Using MD5 instead of bcrypt
>
> ```javascript
> // VULNERABLE
> const hash = crypto.createHash('md5').update(password).digest('hex');
>
> // FIXED
> const hash = await bcrypt.hash(password, 12);
> ```
>
> 3. **Missing Rate Limiting** - No protection against brute force
> ```javascript
> // Add rate limiting middleware
> const rateLimit = require('express-rate-limit');
> const loginLimiter = rateLimit({
> windowMs: 15 * 60 * 1000, // 15 minutes
> max: 5, // 5 attempts
> message: 'Too many login attempts'
> });
> app.post('/login', loginLimiter, authController.login);
> ```
>
> **Medium Issues:**
>
> - Missing CSRF protection
> - Session not invalidated on password change
> - Verbose error messages reveal user existence
## Related Resources
- [OWASP Top 10](https://owasp.org/www-project-top-ten/)
- [OWASP Cheat Sheet Series](https://cheatsheetseries.owasp.org/)
- [CWE/SANS Top 25](https://cwe.mitre.org/top25/)
- [NIST Cybersecurity Framework](https://www.nist.gov/cyberframework)