PenTest Playbook
  • Welcome!
  • Web App Pentesting
    • SQL Injection
    • NoSQL Injection
    • XSS
    • CSRF
    • SSRF
    • XXE
    • IDOR
    • SSTI
    • Broken Access Control/Privilege Escalation
    • Open Redirect
    • File Inclusion
    • File Upload
    • Insecure Deserialization
      • XMLDecoder
    • LDAP Injection
    • XPath Injection
    • JWT
    • Parameter Pollution
    • Prototype Pollution
    • Race Conditions
    • CRLF Injection
    • LaTeX Injection
    • CORS Misconfiguration
    • Handy Commands & Payloads
  • Active Directory Pentest
    • Domain Enumeration
      • User Enumeration
      • Group Enumeration
      • GPO & OU Enumeration
      • ACLs
      • Trusts
      • User Hunting
    • Domain Privilege Escalation
      • Kerberoast
        • AS-REP Roast (Kerberoasting)
        • CRTP Lab 14
      • Targeted Kerberoasting
        • AS-REP Roast
        • Set SPN
      • Kerberos Delegation
        • Unconstrained Delegation
          • CRTP Lab 15
        • Constrained Delegation
          • CRTP Lab 16
        • Resource Based Constrained Delegation (RBCD)
          • CRTP Lab 17
      • Across Trusts
        • Child to Parent (Cross Domain)
          • Using Trust Tickets
            • CRTP Lab 18
          • Using KRBTGT Hash
            • CRTP Lab 19
        • Cross Forest
          • Lab 20
        • AD CS (Across Domain Trusts)
          • ESC1
            • CRTP Lab 21
        • Trust Abuse - MSSQL Servers
          • CRTP Lab 22
    • Lateral Movement
      • PowerShell Remoting
      • Extracting Creds, Hashes, Tickets
      • Over-PassTheHash
      • DCSync
    • Evasion
      • Evasion Cheetsheet
    • Persistence
      • Golden Ticket
        • CRTP Lab 8
      • Silver Ticket
        • CRTP Lab 9
      • Diamond Ticket
        • CRTP Lab 10
      • Skeleton Key
      • DSRM
        • CRTP Lab 11
      • Custom SSP
      • Using ACLs
        • AdminSDHolder
        • Rights Abuse
          • CRTP Lab 12
        • Security Descriptors
          • CRTP Lab 13
    • Tools
    • PowerShell
  • AI Security
    • LLM Security Checklist
    • GenAI Vision Security Checklist
    • Questionnaire for AI/ML/GenAI Engineering Teams
  • Network Pentesting
    • Information Gathering
    • Scanning
    • Port/Service Enumeration
      • 21 FTP
      • 22 SSH
      • 25, 465, 587 SMTP
      • 53 DNS
      • 80, 443 HTTP/s
      • 88 Kerberos
      • 135, 593 MSRPC
      • 137, 138, 139 NetBios
      • 139, 445 SMB
      • 161, 162, 10161, 10162/udp SNMP
      • 389, 636, 3268, 3269 LDAP
      • Untitled
      • Page 14
      • Page 15
      • Page 16
      • Page 17
      • Page 18
      • Page 19
      • Page 20
    • Nessus
    • Checklist
  • Mobile Pentesting
    • Android
      • Android PenTest Setup
      • Tools
    • iOS
  • DevSecOps
    • Building CI Pipeline
    • Threat Modeling
    • Secure Coding
      • Code Review Examples
        • Broken Access Control
        • Broken Authentication
        • Command Injection
        • SQLi
        • XSS
        • XXE
        • SSRF
        • SSTI
        • CSRF
        • Insecure Deserialization
        • XPath Injection
        • LDAP Injection
        • Insecure File Uploads
        • Path Traversal
        • LFI
        • RFI
        • Prototype Pollution
        • Connection String Injection
        • Sensitive Data Exposure
        • Security Misconfigurations
        • Buffer Overflow
        • Integer Overflow
        • Symlink Attack
        • Use After Free
        • Out of Bounds
      • C/C++ Secure Coding
      • Java/JS Secure Coding
      • Python Secure Coding
  • Malware Dev
    • Basics - Get detected!
    • Not so easy to stage!
    • Base64 Encode Shellcode
    • Caesar Cipher (ROT 13) Encrypt Shellcode
    • XOR Encrypt Shellcode
    • AES Encrypt Shellcode
  • Handy
    • Reverse Shells
    • Pivoting
    • File Transfers
    • Tmux
  • Wifi Pentesting
    • Monitoring
    • Cracking
  • Buffer Overflows
  • Cloud Security
    • AWS
    • GCP
    • Azure
  • Container Security
  • Todo
Powered by GitBook
On this page
  1. DevSecOps
  2. Secure Coding
  3. Code Review Examples

CSRF

CSRF in JavaScript

Vulnerability: Cross-Site Request Forgery (CSRF)

Vulnerable Code:

javascriptCopy code// No CSRF token validation
fetch('/update-profile', {
    method: 'POST',
    body: JSON.stringify({ email: 'newemail@example.com' })
});

Reason for vulnerability: The code performs a sensitive action without validating a CSRF token, making it susceptible to CSRF attacks.

Fixed Code:

javascriptCopy code// Fetch CSRF token from meta tag
const token = document.querySelector('meta[name="csrf-token"]').getAttribute('content');

fetch('/update-profile', {
    method: 'POST',
    headers: {
        'CSRF-Token': token,
        'Content-Type': 'application/json'
    },
    body: JSON.stringify({ email: 'newemail@example.com' })
});

Reason for fix: Including a CSRF token in the request header ensures that the request is legitimate and not forged by an attacker.


Vulnerable Code

@Controller
public class TransferController {
    @PostMapping("/transfer")
    public String transferMoney(@RequestParam String to, @RequestParam BigDecimal amount) {
        // Perform money transfer
        return "redirect:/success";
    }
}

Reason for Vulnerability:

This endpoint doesn't implement any CSRF protection, allowing attackers to trick users into making unintended transfers.

Fixed Code:

javaCopy@Controller
public class TransferController {
    @PostMapping("/transfer")
    public String transferMoney(@RequestParam String to, @RequestParam BigDecimal amount, 
                                @RequestParam String _csrf, HttpSession session) {
        if (!_csrf.equals(session.getAttribute("csrfToken"))) {
            return "redirect:/error";
        }
        // Perform money transfer
        return "redirect:/success";
    }

    @ModelAttribute
    public void addCsrfToken(HttpSession session, Model model) {
        String csrfToken = UUID.randomUUID().toString();
        session.setAttribute("csrfToken", csrfToken);
        model.addAttribute("csrfToken", csrfToken);
    }
}

Reason for Fix:

The fixed code implements a custom CSRF token validation. A more robust solution would be to use Spring Security's built-in CSRF protection.


Vulnerable Code:

from flask import Flask, request, session

app = Flask(__name__)

@app.route('/change_email', methods=['POST'])
def change_email():
    new_email = request.form['email']
    user_id = session['user_id']
    update_email(user_id, new_email)
    return "Email updated successfully"

Reason for Vulnerability:

This Flask route doesn't implement any CSRF protection, allowing attackers to trick users into changing their email without their knowledge.

Fixed Code:

pythonCopyfrom flask import Flask, request, session
from flask_wtf.csrf import CSRFProtect

app = Flask(__name__)
csrf = CSRFProtect(app)

@app.route('/change_email', methods=['POST'])
@csrf.exempt
def change_email():
    if request.form['csrf_token'] != session['csrf_token']:
        return "CSRF token mismatch", 403
    new_email = request.form['email']
    user_id = session['user_id']
    update_email(user_id, new_email)
    return "Email updated successfully"

@app.before_request
def csrf_protect():
    if request.method == "POST":
        token = session.pop('csrf_token', None)
        if not token or token != request.form.get('csrf_token'):
            abort(403)

Reason for Fix:

The fixed code implements CSRF protection using Flask-WTF's CSRFProtect and custom token validation.

JavaScript Example

Vulnerable Code:

javascriptCopy// Client-side code
fetch('/api/update-profile', {
    method: 'POST',
    body: JSON.stringify({ name: 'New Name' }),
    headers: {
        'Content-Type': 'application/json'
    }
});

// Server-side code (Express.js)
app.post('/api/update-profile', (req, res) => {
    // Update user profile
    res.send('Profile updated');
});

Reason for Vulnerability:

The API endpoint doesn't implement any CSRF protection, making it vulnerable to cross-site requests.

Fixed Code:

javascriptCopy// Client-side code
fetch('/api/update-profile', {
    method: 'POST',
    body: JSON.stringify({ name: 'New Name' }),
    headers: {
        'Content-Type': 'application/json',
        'X-CSRF-Token': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
    },
    credentials: 'include'
});

// Server-side code (Express.js)
const csrf = require('csurf');
const csrfProtection = csrf({ cookie: true });

app.use(csrfProtection);

app.get('/form', (req, res) => {
    res.render('form', { csrfToken: req.csrfToken() });
});

app.post('/api/update-profile', csrfProtection, (req, res) => {
    // Update user profile
    res.send('Profile updated');
});

Reason for Fix:

The fixed code implements CSRF protection using the csurf middleware for Express.js and includes the CSRF token in API requests.

PreviousSSTINextInsecure Deserialization

Last updated 9 months ago