Foundations

Security Review with AI

Lesson 4 of 4 Estimated Time 45 min

Security Review with AI

Security is hard. You need to think like both a developer and an attacker. AI assistants have learned from vast amounts of security resources, best practices, and vulnerability databases. They can help spot security issues you might miss.

However, AI has limitations in security review. It can find obvious issues, but sophisticated attacks might slip through. Treat AI as a helpful tool, not a replacement for professional security audits.

How AI Helps With Security

Strength 1: Common Vulnerabilities

AI knows the most common web vulnerabilities (OWASP Top 10):

// Vulnerable to SQL injection
const user = db.query(`SELECT * FROM users WHERE id = ${userId}`);

You: "Is this code vulnerable?
     [paste code above]"

AI: "YES. This is vulnerable to SQL injection.
    Use parameterized queries:
    const user = db.query('SELECT * FROM users WHERE id = ?', [userId]);"

AI consistently catches the most common issues.

Strength 2: Common Mistakes

# Storing password in plain text
user.password = request.form['password']
db.save(user)

You: "Security review for user registration:
     [paste code]"

AI: "Don't store plain text passwords.
    Use bcrypt or similar:
    from werkzeug.security import generate_password_hash
    user.password = generate_password_hash(request.form['password'])"

AI knows security best practices and catches their absence.

Strength 3: Pattern Recognition

You: "Review this authentication code for issues:
     [paste token handling code]"

AI: "I see several concerns:
    1. Tokens don't expire
    2. Tokens aren't invalidated on logout
    3. Token is sent in URL (logged in server logs)

    Recommendations:
    [fixes for each issue]"

AI sees patterns you might miss.

Common Security Issues AI Can Find

Issue Type 1: SQL Injection

Vulnerable:

query = "SELECT * FROM users WHERE email = '" + email + "'"

AI finds this immediately and suggests parameterized queries.

Issue Type 2: Cross-Site Scripting (XSS)

Vulnerable:

const html = `<div>${userInput}</div>`;
document.innerHTML = html;  // User input directly in HTML

AI suggests: Escape HTML or use safe DOM APIs.

Issue Type 3: Authentication Issues

Vulnerable:

if password == stored_password:  # String comparison (timing attack)
    login_user()

AI suggests: Use constant-time comparison to prevent timing attacks.

Issue Type 4: Authorization Issues

Vulnerable:

app.get('/users/:id', (req, res) => {
  // No check that current user can access this user
  return res.json(User.find(req.params.id));
});

AI suggests: Check authorization before returning data.

Issue Type 5: Sensitive Data Exposure

Vulnerable:

user = User.find(id)
return jsonify(user)  # Returns all fields including password_hash

AI suggests: Return only needed fields, hide sensitive data.

Issue Type 6: CSRF (Cross-Site Request Forgery)

Vulnerable:

app.post('/transfer-money', (req, res) => {
  // No CSRF token validation
  transfer(req.body.amount);
});

AI suggests: Validate CSRF tokens on state-changing operations.

Using AI for Security Review

Security Review Template

Technology Stack:
- Language: Python
- Framework: Django
- Database: PostgreSQL
- Authentication: JWT
- Hosting: AWS

Features to Review:
1. User registration
2. Login
3. Password reset
4. File upload

Code: [paste the code]

Potential Concerns:
- How is sensitive data handled?
- What about authorization?
- Input validation?

With this structure, AI can give targeted security feedback.

Interactive Security Analysis

You: "Is this authentication code secure?
     [paste code]"

AI: "I see three issues:
    1. [Issue]
    2. [Issue]
    3. [Issue]"

You: "How would I fix issue 1?"

AI: "[Explanation and code fix]"

You: "What about issue 2?"

AI: "[Explanation and code fix]"

Iterate through issues one by one.

OWASP Top 10 Security Review

AI can check for OWASP vulnerabilities:

You: "OWASP security check for my web app.
     Here's my code:
     [paste relevant code sections]

     Check for:
     1. Injection
     2. Broken Authentication
     3. Sensitive Data Exposure
     4. XML External Entities (XXE)
     5. Broken Access Control
     6. Security Misconfiguration
     7. XSS
     8. Insecure Deserialization
     9. Vulnerable Dependencies
     10. Insufficient Logging"

AI: [Checks each category]
"Looks good for injection, authentication...
But I see XSS vulnerability here: [issue]
And access control issue here: [issue]"

Structure your security review around OWASP.

Dependency and Vulnerability Scanning

Ask About Dependencies

You: "Are these dependencies safe?
     [paste package.json or requirements.txt]"

AI: "Most look good. But [old-library] version 1.0 has
    known vulnerabilities. Update to 2.5+.
    Also consider [alternative] instead of [deprecated]."

AI knows about many known vulnerabilities.

Check for Outdated Packages

You: "Dependencies:
     - express 3.2 (from 2015)
     - lodash 2.1 (from 2014)
     - passport 0.2 (from 2012)"

AI: "These are very outdated. Update them immediately:
    - express 4.18 (current standard)
    - lodash 4.17
    - passport 0.6

    Be prepared for breaking changes."

Time to proactively check dependency age.

Limitations of AI Security Review

AI has significant limitations:

Limitation 1: Context-Specific Logic

You: "Is this authorization check correct?
     Can a user access other users' data?
     [paste code]"

AI: [Analyzes the code]
"The code checks user role, but I need to understand
your business logic. Do admins access all data? Should users
see anonymized others' data?"

You: [Clarifies business rules]

AI: [Reviews with full context]

AI can’t understand business logic without you explaining it.

Limitation 2: Sophisticated Attacks

Simple attacks (SQL injection) → AI finds them. Complex attacks (subtle timing attacks, sophisticated CSRF) → Might miss them.

Use AI for basic security, hire experts for sophisticated review.

Limitation 3: Integration Issues

You: "I use OAuth with Google. Is this secure?
     [paste code]"

AI: [Reviews your code]
"Your code looks good, but only you can verify:
- Are you using correct callback URLs?
- Are you validating tokens from Google correctly?
- Are you handling edge cases?"

AI reviews code, not your entire system integration.

Limitation 4: No Real-Time Threat Intelligence

AI training data has a cutoff. New vulnerabilities discovered after training might not be known:

You: "Any issues with using [new_library]?"

AI: "I'm not familiar with it (released after my training).
    Search for known vulnerabilities and security advisories."

Always check current security advisories independently.

Building Security Into Your Workflow

Proactive Security

Instead of reviewing code after it’s written:

Before implementing:
You: "I'm building a file upload feature.
     What security considerations should I have?"

AI: [Lists file upload security considerations]
- File type validation
- Size limits
- Virus scanning
- Sanitized filenames
- Restricted upload directory
- Rate limiting

Then implement with security in mind.

Prevention is easier than fixing security later.

Security Checklist

Create a security checklist for your project:

# Security Checklist

## Authentication
- [ ] Passwords hashed with bcrypt
- [ ] MFA available
- [ ] Sessions invalidate on logout
- [ ] Token expiration implemented

## Authorization
- [ ] Role-based access control
- [ ] User can't access others' data
- [ ] Admin functions protected

## Input Validation
- [ ] All user input validated
- [ ] SQL injection prevention
- [ ] XSS prevention

## Data Protection
- [ ] Sensitive data encrypted
- [ ] HTTPS only
- [ ] Secrets in environment variables

## Dependencies
- [ ] No known vulnerabilities
- [ ] Dependencies updated regularly
- [ ] Lock files committed

Ask AI to help verify each item.

Real-World Security Review Example

Scenario: Review a REST API

Code sections:
- Authentication endpoint
- User CRUD endpoints
- Authorization middleware
- Password reset feature

Step 1: Ask for overall review
"Security review for my REST API:
[paste key code]"

Step 2: Get feedback
AI identifies:
1. Password not hashed properly
2. Authorization not checked
3. Passwords sent in email (insecure)
4. SQL injection in search

Step 3: Fix each issue
You fix #1, ask: "Is this better?
[updated code]"

Step 4: Iterate
Continue until AI gives approval

Step 5: Final check
"Any remaining issues I should address?"

Step 6: Documentation
"Document the security practices I've implemented"
AI generates security documentation

When to Hire Security Experts

Don’t rely on AI alone for:

  • Critical systems (payment processing, healthcare, government)
  • High-value targets (valuable user data, IP-protected code)
  • Sophisticated threats (targeted attacks, advanced exploits)
  • Compliance (HIPAA, PCI-DSS, SOC 2)
  • Penetration testing (find actual vulnerabilities)

Use AI for:

  • First-pass security review (catch obvious issues)
  • Learning security (understand vulnerabilities)
  • Ongoing checks (catch regressions)
  • Security practices (secure coding patterns)

Exercises

  1. OWASP Review: Pick a web application you’ve built. Ask AI to review it for OWASP Top 10 vulnerabilities. Document findings.

  2. Vulnerable Code Correction: Find vulnerable code online (OWASP WebGoat, HackTheBox). Ask AI to:

    • Identify vulnerabilities
    • Explain the attack
    • Provide secure version
  3. Dependency Audit: Check your project’s dependencies:

    npm audit  # or equivalent for your language

    Ask AI to explain findings and prioritize fixes.

  4. Security Patterns: For each OWASP category, ask AI:

    • What’s the vulnerability?
    • How do you prevent it?
    • Show me a secure code example Build a security pattern library.
  5. Security Improvement Plan: For a project you maintain:

    • Ask AI to review security
    • Document issues found
    • Create improvement plan
    • Implement fixes
    • Re-review to verify