logo

Database

Javascript Manual Csrf Token Handling Xhr

Description

This detector identifies JavaScript code that manually handles CSRF tokens in XMLHttpRequest (XHR) calls without proper security measures. Manual CSRF token handling can lead to vulnerabilities if tokens are not properly validated, transmitted securely, or if the implementation has logical flaws that bypass CSRF protection mechanisms.

Weakness:

014 - Insecure functionality

Category: Functionality Abuse

Detection Strategy

    Scans JavaScript source code for XMLHttpRequest (XHR) implementations

    Identifies code patterns where CSRF tokens are manually handled rather than using secure framework-provided mechanisms

    Triggers when XHR requests contain custom CSRF token handling logic that may be improperly implemented

    Reports findings when manual token management is detected in AJAX calls, as this increases the risk of CSRF vulnerabilities due to implementation errors

Vulnerable code example

// VULNERABLE: CSRF token extracted from URL and used in XHR header
const token = new URLSearchParams(window.location.search).get('csrfToken');
const xhr = new XMLHttpRequest();
xhr.open('POST', '/api/update');
xhr.setRequestHeader('X-CSRF-Token', token); // Attacker can control token via URL
xhr.send();

✅ Secure code example

// SECURE: CSRF token from meta tag instead of URL parameter
const token = document.querySelector('meta[name="csrf-token"]').getAttribute('content');
const xhr = new XMLHttpRequest();
xhr.open('POST', '/api/update');
xhr.setRequestHeader('X-CSRF-Token', token); // Token from DOM, not controllable via URL
xhr.send();