prompt stringlengths 45 741 | completion stringlengths 66 1.72k |
|---|---|
Write a vulnerable JavaScript function that takes user input and evaluates it using eval(), demonstrating a code injection vulnerability. | // UNSAFE: This code is vulnerable to code injection via eval()
function executeUserInput() {
let userInput = prompt('Enter code to execute:');
eval(userInput); // Direct eval of unsanitized input allows arbitrary code execution
}
// Secure alternative would use proper input validation or avoid eval() entirely |
Analyze this Node.js HTTP server for XSS vulnerabilities. The server echoes back a 'message' query parameter without sanitization:
```javascript
const http = require('http');
const url = require('url');
http.createServer((req, res) => {
const query = url.parse(req.url, true).query;
res.writeHead(200, {'Content-Ty... | This code is vulnerable to XSS as it directly outputs unsanitized user input (query.message) into HTML. Secure version:
```javascript
const http = require('http');
const url = require('url');
const escapeHtml = require('escape-html');
http.createServer((req, res) => {
const query = url.parse(req.url, true).query;
... |
Compare these two JavaScript approaches for evaluating user input and explain why one is secure while the other is vulnerable: | // VULNERABLE APPROACH (using eval() directly):
let userInput = "alert('Malicious code')";
eval(userInput); // Executes arbitrary code
// SECURE APPROACH (using Function constructor with validation):
const safeEval = (input) => {
if (/^[\d\+\-\*\/\(\)\s]+$/.test(input)) { // Whitelist safe characters
return new ... |
Write a JavaScript function that demonstrates an XSS vulnerability by inserting unsanitized user input into DOM element's innerHTML. | // UNSAFE XSS EXAMPLE:
function showUserComment(comment) {
document.getElementById('comment-box').innerHTML = comment;
// If comment contains <script>alert('XSS')</script>, it will execute
}
// SECURE VERSION:
function showUserCommentSafe(comment) {
const element = document.getElementById('comment-box');
eleme... |
Analyze this Express.js route for XSS vulnerabilities and provide a secure alternative:
```javascript
app.get('/greet', (req, res) => {
const name = req.query.name || 'Guest';
res.send(`<h1>Welcome ${name}!</h1>`);
});
``` | This code is vulnerable to XSS as it directly interpolates user input (req.query.name) into HTML. Secure alternatives:
1. Escape output:
```javascript
const escapeHtml = require('escape-html');
app.get('/greet', (req, res) => {
const name = escapeHtml(req.query.name || 'Guest');
res.send(`<h1>Welcome ${name}!</h1>... |
Create an Express.js endpoint that evaluates mathematical expressions. First show a vulnerable implementation using eval(), then provide a secure alternative with input validation. | // VULNERABLE IMPLEMENTATION:
app.post('/evaluate', (req, res) => {
const result = eval(req.body.expression); // Dangerous direct eval
res.json({ result });
});
// SECURE IMPLEMENTATION:
app.post('/evaluate', (req, res) => {
const { expression } = req.body;
// Validate only contains math operations and numb... |
Demonstrate how to safely display user-generated content in the DOM to prevent XSS attacks, comparing innerHTML vs secure alternatives. | // UNSAFE: Direct innerHTML usage
function displayUserContentUnsafe(content) {
document.getElementById('output').innerHTML = content;
}
// SAFE ALTERNATIVES:
// 1. Use textContent for plain text:
function displayUserContentSafe(content) {
document.getElementById('output').textContent = content;
}
// 2. Use DOMPu... |
Analyze this Express route handling query parameters for XSS vulnerabilities and provide a secure version:
```javascript
app.get('/search', (req, res) => {
const query = req.query.q || '';
res.send(`<h2>Results for: ${query}</h2>`);
});
``` | // VULNERABLE: Directly embeds user input in HTML
// SECURE VERSIONS:
// 1. Escape HTML output:
const escape = require('escape-html');
app.get('/search', (req, res) => {
const query = escape(req.query.q || '');
res.send(`<h2>Results for: ${query}</h2>`);
});
// 2. Use template engine with auto-escaping:
app.get(... |
Create a JavaScript function that takes user input from a prompt and displays it on the page, first showing a vulnerable version and then a secure implementation. | // VULNERABLE VERSION (XSS possible):
function showInputUnsafe() {
const input = prompt('Enter your message:');
document.getElementById('display').innerHTML = input;
}
// SECURE VERSIONS:
// 1. Using textContent:
function showInputSafe() {
const input = prompt('Enter your message:');
document.getElementById('... |
Analyze this vulnerable HTTP server endpoint that evaluates JSON payloads and rewrite it to prevent remote code execution: | // VULNERABLE ORIGINAL:
app.post('/execute', (req, res) => {
const { command } = req.body;
const result = eval(command); // Critical RCE vulnerability
res.json({ result });
});
// SECURE REWRITE:
app.post('/execute', (req, res) => {
const { command } = req.body;
// 1. Never use eval() with user input
//... |
Analyze this Node.js HTTP server for XSS vulnerabilities where it echoes back a 'userInput' query parameter without sanitization, then provide a secure version: | // VULNERABLE VERSION:
const http = require('http');
const url = require('url');
http.createServer((req, res) => {
const query = url.parse(req.url, true).query;
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(`<p>${query.userInput || ''}</p>`); // UNSAFE: Direct output
res.end();
}).listen(8080);
... |
Create an Express endpoint that evaluates JSON payloads. First show a vulnerable implementation using eval(), then provide a secure alternative with input validation: | // VULNERABLE IMPLEMENTATION:
app.post('/execute', (req, res) => {
const { cmd } = req.body;
eval(cmd); // Critical RCE vulnerability
res.end();
});
// SECURE IMPLEMENTATION:
app.post('/execute', (req, res) => {
const { cmd } = req.body;
// Validate only contains safe characters
if (!/^[a-zA-Z0-9\s]+$/.... |
Analyze this Express route for Insecure Direct Object Reference (IDOR) vulnerabilities and provide a secure version: | // VULNERABLE VERSION (IDOR):
app.get('/users/:id', (req, res) => {
const user = users[req.params.id]; // Direct array access
res.json(user);
});
// SECURE VERSION:
app.get('/users/:id', (req, res) => {
// Convert to number and find user
const userId = parseInt(req.params.id);
const user = users.find(u => u.... |
Demonstrate how to safely handle user input in client-side JavaScript to prevent XSS when using document.write: | // VULNERABLE APPROACH:
const username = prompt('Enter username');
document.write(`<h1>Welcome ${username}!</h1>`); // UNSAFE
// SECURE ALTERNATIVES:
// 1. Use textContent:
const element = document.createElement('h1');
element.textContent = `Welcome ${username}!`;
document.body.appendChild(element);
// 2. Use DOMPur... |
Analyze this Express endpoint for command injection vulnerabilities and provide a secure version: | // VULNERABLE VERSION:
app.post('/run', (req, res) => {
exec(req.body.command, (err, stdout) => { // Direct command execution
res.send(stdout);
});
});
// SECURE VERSION:
const allowedCommands = ['ls', 'pwd'];
app.post('/run', (req, res) => {
const cmd = req.body.command.split(' ')[0]; // Get base command
... |
Demonstrate a secure password comparison function that prevents timing attacks: | // VULNERABLE VERSION:
function checkPassword(input) {
for (let i = 0; i < input.length; i++) {
if (input[i] !== storedPassword[i]) {
return false; // Early exit leaks timing info
}
}
return true;
}
// SECURE VERSION:
const crypto = require('crypto');
function secureCompare(a, b) {
const aBuffer... |
Compare these two JavaScript approaches for evaluating user-provided code and explain the security implications: | // VULNERABLE APPROACH (direct eval):
let userCode = prompt('Enter code to run:');
eval(userCode); // Executes arbitrary code with full privileges
// SECURE APPROACH (avoid eval):
function safeEval(mathExpression) {
// Validate only contains math operations
if (/^[\d\+\-\*\/\(\)\.\s]+$/.test(mathExpression)) {
... |
Analyze this Express.js user update endpoint for IDOR vulnerabilities and provide a secure version: | // VULNERABLE VERSION:
app.put('/users/:id', (req, res) => {
users[req.params.id] = req.body; // Direct array access
res.json(users[req.params.id]);
});
// SECURE VERSION:
app.put('/users/:id', authenticate, (req, res) => {
const userId = parseInt(req.params.id);
// 1. Validate numeric ID
if (isNaN(userId... |
Rewrite this Express route to safely handle name query parameters and prevent XSS: | // VULNERABLE ORIGINAL:
app.get('/', (req, res) => {
res.send(`<h1>Hello ${req.query.name}</h1>`);
});
// SECURE VERSIONS:
// 1. HTML Entity Encoding:
const escape = require('escape-html');
app.get('/', (req, res) => {
res.send(`<h1>Hello ${escape(req.query.name)}</h1>`);
});
// 2. Template Engine (EJS example):... |
Create a secure version of this command execution endpoint that prevents command injection: | // VULNERABLE ORIGINAL:
app.post('/run', (req, res) => {
exec(req.body.command, (err, stdout) => {
res.send(stdout);
});
});
// SECURE IMPLEMENTATION:
const { execFile } = require('child_process');
const allowedCommands = {
list: '/bin/ls',
stats: '/usr/bin/stat'
};
app.post('/run', (req, res) => {
cons... |
Demonstrate secure alternatives to this vulnerable user input display code: | // VULNERABLE CODE:
function showInput() {
const input = document.getElementById('userInput').value;
document.getElementById('output').innerHTML = input;
}
// SECURE ALTERNATIVES:
// 1. textContent:
function showInputSafe() {
const input = document.getElementById('userInput').value;
document.getElementById('o... |
Create a timing-attack resistant password comparison function in JavaScript: | // VULNERABLE VERSION:
function checkPassword(input) {
return input === storedPassword; // Early exit on mismatch
}
// SECURE VERSIONS:
// 1. Node.js crypto module:
const crypto = require('crypto');
function secureCompare(a, b) {
return crypto.timingSafeEqual(
Buffer.from(a, 'utf8'),
Buffer.from(b, 'utf8'... |
Write a vulnerable JavaScript function that demonstrates insecure use of eval() by taking user input and evaluating it to display an alert message. | // UNSAFE: This code is vulnerable to code injection via eval()
function showAlertUnsafe() {
let userInput = "alert('This is an alert from eval');";
eval(userInput); // Direct eval of string containing code
}
// SECURE ALTERNATIVE:
function showAlertSafe() {
let userInput = prompt("Enter your message");
if (us... |
Analyze this Node.js HTTP server for JSON parsing vulnerabilities and provide a secure implementation:
```javascript
const http = require('http');
const url = require('url');
http.createServer((req, res) => {
const query = url.parse(req.url, true).query;
let data = JSON.parse('{' + query.data + '}'); // Vulnerabl... | // VULNERABLE: String concatenation before JSON.parse can lead to injection
// SECURE IMPLEMENTATION:
const http = require('http');
const url = require('url');
http.createServer((req, res) => {
const query = url.parse(req.url, true).query;
try {
let data = query.data ? JSON.parse(query.data) : null; // Direct... |
Create an Express.js user API that demonstrates and fixes Insecure Direct Object Reference (IDOR) vulnerabilities. | // VULNERABLE IDOR IMPLEMENTATION:
app.get('/users/:id', (req, res) => {
let user = users[req.params.id]; // Direct array access with user input
res.send(user);
});
// SECURE IMPLEMENTATION:
app.get('/users/:id', (req, res) => {
// 1. Validate input is numeric
if (isNaN(req.params.id)) return res.status(400).s... |
Compare secure and insecure implementations of a function that sanitizes and evaluates user input in JavaScript. | // UNSAFE IMPLEMENTATION:
function unsafeEval(input) {
let sanitized = input.replace(/[^a-zA-Z0-9]/g, ''); // Weak sanitization
eval(sanitized); // Still dangerous
}
// SAFER IMPLEMENTATION:
function safeEvaluation(input) {
// 1. Stronger input validation
if (!/^[a-zA-Z0-9\s]+$/.test(input)) {
throw new Er... |
Demonstrate an XSS vulnerability through URL hash injection and provide a secure alternative. | // VULNERABLE XSS IMPLEMENTATION:
function injectContent() {
let input = location.hash.substring(1);
document.write("<script>alert('" + input + "');</script>");
}
// SECURE IMPLEMENTATIONS:
// 1. Using textContent:
function safeInjection() {
let input = location.hash.substring(1);
let div = document.createEle... |
Analyze this HTTP server for XSS vulnerabilities in query parameter handling and provide a secure version:
```javascript
const http = require('http');
const url = require('url');
http.createServer((req, res) => {
const query = url.parse(req.url, true).query;
res.writeHead(200, {'Content-Type': 'text/html'});
re... | // VULNERABLE: Direct interpolation of query.name into HTML
// SECURE VERSIONS:
// 1. Using escape-html:
const escape = require('escape-html');
http.createServer((req, res) => {
const query = url.parse(req.url, true).query;
res.writeHead(200, {'Content-Type': 'text/html'});
res.end(`<html><body>Hello ${escape(q... |
Demonstrate a prototype pollution vulnerability through JSON parsing and provide a secure solution. | // VULNERABLE PROTOTYPE POLLUTION:
const polluted = JSON.parse('{"__proto__": {"isAdmin": true}}');
console.log({}.isAdmin); // true - pollution successful
// SECURE SOLUTIONS:
// 1. Use reviver function to block __proto__:
const safeParse = (json) => {
return JSON.parse(json, (key, value) => {
if (key === '__p... |
Compare secure and insecure handling of JSON data that might contain prototype pollution vectors. | // UNSAFE HANDLING:
function processUserData(json) {
return JSON.parse(json); // Accepts __proto__ properties
}
// SAFE HANDLING:
function processUserDataSafely(json) {
// 1. Validate JSON structure first
if (!json.startsWith('{') || !json.endsWith('}')) {
throw new Error('Invalid JSON');
}
// 2. Use ... |
Create a function that safely displays user input in the DOM, comparing vulnerable and secure implementations. | // VULNERABLE XSS IMPLEMENTATION:
function displayInputUnsafe() {
const input = document.getElementById('userInput').value;
document.getElementById('display').innerHTML = input;
}
// SECURE IMPLEMENTATIONS:
// 1. Using textContent:
function displayInputSafe() {
const input = document.getElementById('userInput')... |
Analyze this JavaScript buffer handling code for vulnerabilities and provide a secure implementation:
```javascript
function processData(data) {
let buffer = new ArrayBuffer(1024);
let view = new DataView(buffer);
for (let i = 0; i < data.length; i++) {
view.setUint8(i, data.charCodeAt(i));
}
}
``` | // VULNERABLE: No bounds checking can lead to overflow
// SECURE IMPLEMENTATION:
function processDataSafe(data) {
// 1. Validate input length
if (data.length > 1024) {
throw new Error('Input exceeds buffer size');
}
// 2. Create buffer with exact needed size
let buffer = new ArrayBuffer(data.length);
... |
Analyze this JavaScript code that uses eval() with user input. Explain the vulnerability and provide a secure alternative:
```javascript
let userInput = prompt('Enter code to execute:');
eval(userInput);
``` | This code is critically vulnerable to arbitrary code execution since eval() directly executes user-provided input. Secure alternatives:
1. Avoid eval() entirely if possible
2. If evaluation is necessary, use strict validation:
```javascript
let userInput = prompt('Enter math expression:');
if (/^[\d\+\-\*\/\(\)\s]+$/.... |
Create an Express.js endpoint that accepts user comments while preventing XSS attacks. First show the vulnerable version, then provide a secure implementation. | // VULNERABLE VERSION (XSS possible):
app.post('/comment', (req, res) => {
res.send(`<div>${req.body.comment}</div>`);
});
// SECURE VERSIONS:
1. HTML Entity Encoding:
app.post('/comment', (req, res) => {
const safeComment = escapeHtml(req.body.comment);
res.send(`<div>${safeComment}</div>`);
});
2. Using temp... |
Implement user lookup and update endpoints in Express.js with proper IDOR protection. Include authorization checks. | // SECURE IMPLEMENTATION WITH IDOR PROTECTION:
const express = require('express');
const app = express();
// Mock authentication middleware
function authenticate(req, res, next) {
req.user = { id: 1 }; // Simulated authenticated user
next();
}
app.get('/users/:id', authenticate, (req, res) => {
if (parseInt(req... |
Demonstrate how to safely display user-provided credentials in the DOM while preventing XSS attacks. | // UNSAFE VERSION:
function showCredentials(username, password) {
document.body.innerHTML = `
<p>Username: ${username}</p>
<p>Password: ${password}</p>
`;
}
// SECURE IMPLEMENTATIONS:
1. Using textContent:
function showCredentialsSafe(username, password) {
const div = document.createElement('div');
di... |
Analyze this insecure deserialization endpoint and provide a secure alternative: | // VULNERABLE ORIGINAL:
app.post('/deserialize', (req, res) => {
const obj = unserialize(req.body.data);
obj(); // Executes deserialized code
});
// SECURE ALTERNATIVES:
1. Avoid deserializing executable code entirely
2. Use JSON.parse() for simple data:
app.post('/data', (req, res) => {
try {
const data = ... |
Create a secure search results endpoint that properly handles the search query parameter to prevent XSS. | // SECURE IMPLEMENTATION:
const http = require('http');
const url = require('url');
http.createServer((req, res) => {
const query = url.parse(req.url, true).query;
let searchTerm = query.search || '';
// Multiple layers of protection:
searchTerm = searchTerm
.replace(/&/g, '&')
.replace(/</g, '&... |
Implement a secure '/greet' endpoint that takes a 'name' parameter while preventing XSS attacks. | // SECURE GREETING ENDPOINT:
const http = require('http');
const url = require('url');
// HTML escaping function
const escapeHtml = (unsafe) => {
return unsafe
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, """)
.replace(/'/g, "'");
};
http.createS... |
Create a secure code evaluation endpoint that prevents arbitrary code execution while allowing limited expression evaluation. | // SECURE EVALUATION ENDPOINT:
const express = require('express');
const app = express();
// Only allow simple math expressions
const ALLOWED_CHARS = /^[\d\+\-\*\/\(\)\s]+$/;
app.post('/evaluate', express.json(), (req, res) => {
const expression = String(req.body.expression || '');
if (!ALLOWED_CHARS.test(expr... |
Analyze this Express.js endpoint for insecure deserialization vulnerabilities and provide a secure alternative:
```javascript
app.post('/deserialize', (req, res) => {
let userInput = req.body;
let deserialized = serialize.unserialize(userInput);
deserialized();
});
``` | This code is vulnerable to remote code execution via insecure deserialization. The secure approach would:
1. Avoid deserializing untrusted data entirely
2. If deserialization is necessary, use JSON.parse() instead
3. Implement strict input validation
Secure alternative:
```javascript
app.post('/deserialize', (req, res... |
Write a Node.js HTTP server that displays search results while preventing XSS vulnerabilities from user-provided search terms. | // Secure implementation with XSS protection:
const http = require('http');
const url = require('url');
const escapeHtml = require('escape-html');
http.createServer((req, res) => {
const query = url.parse(req.url, true).query;
const searchTerm = query.search ? escapeHtml(query.search) : 'undefined';
res.write... |
Create a secure HTTP server in Node.js that safely handles 'name' query parameters to prevent XSS attacks when displaying greetings. | const http = require('http');
const url = require('url');
// HTML escaping function
const escapeHtml = (unsafe) => {
return unsafe
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, """)
.replace(/'/g, "'");
};
http.createServer((req, res) => {
const... |
Design a secure Express.js endpoint that evaluates mathematical expressions while preventing code injection attacks. | const express = require('express');
const app = express();
app.use(express.json());
// Strict regex for math expressions only
const MATH_REGEX = /^[\d\s+\-*\/()%.]+$/;
app.post('/evaluate', (req, res) => {
const { expression } = req.body;
// Validate input exists and matches safe pattern
if (!expression || t... |
Implement a secure HTTP server that handles user-provided names in query parameters with multiple layers of XSS protection. | const http = require('http');
const url = require('url');
// Security middleware functions
const security = {
// HTML entity encoding
encodeHtml: (text) => {
return text.replace(/[&<>"']/g,
match => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[match]));
},
// Remove sc... |
Analyze this Node.js HTTP server that evaluates JSON payloads. Identify the critical vulnerability and rewrite it securely:
```javascript
const http = require('http');
http.createServer((req, res) => {
let data = '';
req.on('data', chunk => data += chunk);
req.on('end', () => {
if (data) {
const json ... | CRITICAL VULNERABILITY: Remote Code Execution via eval()
SECURE REWRITE:
```javascript
const http = require('http');
http.createServer((req, res) => {
let data = '';
req.on('data', chunk => data += chunk);
req.on('end', () => {
if (!data) return res.end('No data received');
try {
const json =... |
Compare these two approaches for displaying an alert message in JavaScript and explain the security implications: | // VULNERABLE APPROACH (using eval):
const userInput = "alert('XSS attack');";
eval(userInput); // Executes arbitrary code
// SECURE APPROACH (direct call):
alert('This is safe'); // No code evaluation
// WHY IT MATTERS:
1. eval() executes any valid JS code in the string
2. If userInput comes from untrusted source, a... |
Analyze this JSON parsing example for prototype pollution vulnerability and provide a secure alternative:
```javascript
const payload = '{"__proto__": {"polluted": true}}';
const obj = JSON.parse(payload);
console.log(Object.prototype.polluted); // true
``` | PROTOTYPE POLLUTION VULNERABILITY:
The code modifies Object.prototype through __proto__ assignment
SECURE ALTERNATIVES:
1. Use reviver function in JSON.parse:
```javascript
const obj = JSON.parse(payload, (k, v) => {
if (k === '__proto__') return undefined;
return v;
});
```
2. Use safe parsing libraries:
```jav... |
Write a JavaScript function that safely processes user-provided mathematical expressions without using eval(). | // SAFE MATH EXPRESSION EVALUATOR
function safeEvalMath(expression) {
// Validate input contains only numbers and basic math operators
if (!/^[\d\+\-\*\/\(\)\.\s]+$/.test(expression)) {
throw new Error('Invalid characters in expression');
}
// Use Function constructor with return (safer than eval)
try ... |
Analyze this HTTP server code that evaluates query parameters and rewrite it to prevent code injection:
```javascript
const server = http.createServer((req, res) => {
const { data } = url.parse(req.url, true).query;
eval(data); // Dangerous evaluation
res.end();
}).listen(8080);
``` | CRITICAL ISSUE: Arbitrary code execution via query parameter
SECURE REWRITE:
```javascript
const server = http.createServer((req, res) => {
const { data } = url.parse(req.url, true).query;
if (!data) return res.end('No data provided');
// Option 1: Completely avoid evaluation
res.end(`Received: ${data}`)... |
Write a JavaScript function that demonstrates the danger of using eval() with unsanitized user input. Show both the vulnerable version and a secure alternative. | // VULNERABLE VERSION:
function unsafeFunction(userInput) {
return eval(userInput); // Direct eval of user input allows code execution
}
// SECURE ALTERNATIVE:
function safeFunction(userInput) {
try {
// Uses Function constructor with return statement
return Function('return ' + userInput)();
... |
Analyze this error handling code that leaks sensitive information in stack traces and provide a secure version:
```javascript
try {
throw new Error('Username: admin, Password: s3cr3t');
} catch (err) {
console.log(err.stack);
}
``` | // VULNERABLE: Exposes credentials in error stack
// SECURE VERSION:
try {
throw new Error('Authentication failed'); // Generic error message
} catch (err) {
// Log sanitized error without sensitive data
console.error('Error:', err.message);
// If debugging needed, use error codes instead:
co... |
Compare these two approaches for creating alert boxes in JavaScript, explaining why one is vulnerable to code injection while the other is safe: | // VULNERABLE APPROACH (using eval):
const input = "alert('Malicious code');";
eval(input); // Executes arbitrary code
// SECURE ALTERNATIVES:
// 1. Direct alert call (no dynamic evaluation):
window.alert("This is safe");
// 2. If dynamic content needed (with sanitization):
function safeAlert(content) {
const sa... |
Write a JavaScript function that safely handles user input from the URL hash to prevent XSS attacks, comparing secure and insecure implementations. | // INSECURE VERSION (XSS vulnerable):
function processInput() {
const input = location.hash.substring(1);
document.getElementById('output').innerHTML = input;
}
// SECURE VERSION:
function processInputSafe() {
const input = location.hash.substring(1);
// Option 1: Text content (no HTML)
docume... |
Create a demonstration showing how improper use of innerHTML can lead to XSS vulnerabilities, then provide three secure alternatives for inserting user content into the DOM. | // XSS VULNERABLE EXAMPLE:
function addUserContentVulnerable(content) {
document.getElementById('target').innerHTML = content;
}
// Attack: addUserContentVulnerable("<img src=x onerror=stealCookies()>");
// SECURE ALTERNATIVES:
// 1. Use textContent for plain text:
function addTextContentSafe(content) {
docum... |
Analyze this JavaScript buffer handling code for potential overflow vulnerabilities and provide a secure version:
```javascript
function myFunction(input){
let buffer = new Uint8Array(1024);
let inputView = new Uint8Array(input);
for(let i=0; i<inputView.length; i++){
buffer[i] = inputView[i];
... | // VULNERABLE: No bounds checking on input size
// SECURE VERSION:
function myFunction(input) {
const MAX_BUFFER_SIZE = 1024;
let buffer = new Uint8Array(MAX_BUFFER_SIZE);
let inputView = new Uint8Array(input);
let length = Math.min(inputView.length, MAX_BUFFER_SIZE); // Enforce size limit
for... |
Demonstrate how JavaScript's loose equality (==) can lead to security issues through type coercion, and show a secure comparison alternative. | // VULNERABLE: Type coercion with ==
function compareInsecure(val1, val2) {
return val1 == val2; // '5' == 5 → true
}
// SECURE ALTERNATIVES:
// 1. Strict equality (===)
function compareStrict(val1, val2) {
return val1 === val2; // '5' === 5 → false
}
// 2. Explicit type checking
function compareSafe(val1, v... |
Write a JavaScript function that demonstrates an XSS vulnerability when generating HTML from user input, then provide a secure version. | // VULNERABLE: Direct string concatenation
function generateHTMLUnsafe(input) {
return `<div>${input}</div>`; // Allows script injection
}
// SECURE VERSIONS:
// 1. Use textContent
function generateHTMLSafe(input) {
const div = document.createElement('div');
div.textContent = input;
return div.outerHT... |
Analyze this Node.js HTTP server for XSS vulnerabilities in query parameter handling and provide a secure version:
```javascript
http.createServer((req, res) => {
let name = url.parse(req.url, true).query.name;
res.end(`<h1>Hello ${name}</h1>`);
}).listen(8080);
``` | // VULNERABLE: Directly outputs unsanitized query parameter
// SECURE VERSIONS:
// 1. HTML entity encoding
http.createServer((req, res) => {
let name = encodeURIComponent(url.parse(req.url, true).query.name || '');
res.end(`<h1>Hello ${name}</h1>`);
}).listen(8080);
// 2. Use template engine with auto-escapi... |
Show a vulnerable Express.js endpoint that constructs SQL queries directly from user input, then rewrite it securely. | // VULNERABLE: Direct string interpolation
app.post('/login', (req, res) => {
const query = `SELECT * FROM users WHERE username='${req.body.username}' AND password='${req.body.password}'`;
db.query(query, (err, result) => {
// ...
});
});
// SECURE VERSIONS:
// 1. Parameterized queries
app.post('/... |
Demonstrate an Insecure Direct Object Reference (IDOR) vulnerability in a REST API endpoint and show how to fix it. | // VULNERABLE: Direct array index access
app.get('/users/:id', (req, res) => {
const user = users[req.params.id]; // IDOR risk
res.json(user);
});
// SECURE VERSIONS:
// 1. Use proper lookup with access control
app.get('/users/:id', authenticate, (req, res) => {
const user = users.find(u => u.id === parse... |
Write an Express.js endpoint that safely handles user comments while preventing XSS attacks. | // SECURE IMPLEMENTATION:
const express = require('express');
const { body, validationResult } = require('express-validator');
app.post('/comments',
body('comment')
.trim()
.escape() // Convert HTML to entities
.isLength({ max: 1000 }),
(req, res) => {
const errors = validationR... |
Show a dangerous use of eval() in JavaScript and provide safe alternatives for evaluating dynamic code. | // DANGEROUS:
const result = eval(userSuppliedCode);
// SAFE ALTERNATIVES:
// 1. For math expressions:
function safeEvalMath(expr) {
if (!/^[\d\s+\-*\/()%.]+$/.test(expr)) {
throw new Error('Invalid characters');
}
return new Function(`return ${expr}`)();
}
// 2. For JSON parsing:
const data = JS... |
Analyze this HTTP server response handling for XSS vulnerabilities and provide a secure version:
```javascript
http.createServer((req, res) => {
const q = url.parse(req.url, true).query;
res.end(q.text + '<script>alert(1)</script>');
}).listen(8080);
``` | // VULNERABLE: Concatenates unsanitized input with script
// SECURE VERSION:
http.createServer((req, res) => {
const q = url.parse(req.url, true).query;
// 1. Encode all output
const safeText = q.text ?
q.text.replace(/</g, '<').replace(/>/g, '>') : '';
// 2. Set security heade... |
Demonstrate a JavaScript prototype pollution vulnerability and show how to safely merge objects without this risk. | // VULNERABLE: Prototype pollution through object merge
function mergeObjectsUnsafe(target, source) {
for (let key in source) {
target[key] = source[key]; // Could pollute Object.prototype
}
return target;
}
// SECURE ALTERNATIVES:
// 1. Use Object.hasOwnProperty check
function mergeObjectsSafe(ta... |
Show insecure JWT verification in a Node.js application and provide a secure implementation with proper validation. | // VULNERABLE: Basic JWT verification without proper checks
app.get('/profile', (req, res) => {
const token = req.headers.authorization.split(' ')[1];
const decoded = jwt.decode(token); // No signature verification
res.json(decoded);
});
// SECURE IMPLEMENTATION:
app.get('/profile', async (req, res) => {
... |
Implement CSRF protection in an Express.js application, showing both vulnerable and secure versions of a form submission handler. | // VULNERABLE: No CSRF protection
app.post('/transfer', (req, res) => {
// Processes sensitive action without CSRF check
bank.transfer(req.body.amount, req.body.toAccount);
res.send('Transfer completed');
});
// SECURE IMPLEMENTATION:
// 1. Install csrf middleware
const csrf = require('csurf');
const csrf... |
Analyze this Node.js HTTP server for XSS vulnerabilities when handling query parameters and provide a secure implementation:
```javascript
const http = require('http');
const url = require('url');
http.createServer((req, res) => {
const query = url.parse(req.url, true).query;
res.writeHead(200, {'Content-Type': '... | // VULNERABLE: Directly embeds unsanitized user input in HTML
// SECURE IMPLEMENTATION:
const http = require('http');
const url = require('url');
const escapeHtml = require('escape-html');
http.createServer((req, res) => {
const query = url.parse(req.url, true).query;
const name = escapeHtml(query.name || 'Guest'... |
Rewrite this vulnerable Express.js login endpoint to prevent SQL injection:
```javascript
app.post('/login', (req, res) => {
const { username, password } = req.body;
const query = `SELECT * FROM users WHERE username='${username}' AND password='${password}'`;
db.query(query, (err, result) => {
// ...
});
})... | // SECURE IMPLEMENTATION USING PARAMETERIZED QUERIES:
app.post('/login', (req, res) => {
const { username, password } = req.body;
// Use placeholders and parameter binding
const query = 'SELECT * FROM users WHERE username=? AND password=?';
db.query(query, [username, password], (err, result) => {
if (... |
Demonstrate how to safely parse JSON input to prevent prototype pollution attacks: | // VULNERABLE PARSING:
const unsafeData = JSON.parse('{"__proto__": {"isAdmin": true}}');
// SECURE ALTERNATIVES:
// 1. Use reviver function to filter prototype properties
const safeParse = (json) => {
return JSON.parse(json, (key, value) => {
if (key === '__proto__') return undefined;
return value;
});
}... |
Provide secure alternatives to using eval() for executing dynamic JavaScript code: | // UNSAFE:
eval(userInput);
// SECURE ALTERNATIVES:
// 1. Function constructor with validation
function safeEval(code) {
if (!/^[\d\+\-\*\/\(\)\s]+$/.test(code)) {
throw new Error('Invalid input');
}
return new Function(`return ${code}`)();
}
// 2. Sandboxed evaluation (Node.js)
const { VM } = require('vm2... |
Rewrite this JavaScript code to prevent buffer overflow when writing to an ArrayBuffer: | // VULNERABLE:
let buffer = new ArrayBuffer(8);
let view = new DataView(buffer);
for (let i = 0; i < 10; i++) { // Writes beyond buffer
view.setUint8(i, i);
}
// SECURE IMPLEMENTATION:
let buffer = new ArrayBuffer(8);
let view = new DataView(buffer);
const bufferSize = buffer.byteLength;
for (let i = 0; i < buffer... |
Analyze this YAML deserialization endpoint for security vulnerabilities and provide a secure version: | // VULNERABLE:
app.post('/parse', (req, res) => {
const data = yaml.load(req.body);
// ...
});
// SECURE IMPLEMENTATION:
app.post('/parse', (req, res) => {
try {
// 1. Use safe schema
const data = yaml.load(req.body, {
schema: yaml.JSON_SCHEMA, // Disables dangerous YAML features
json: true ... |
Create a JavaScript function that safely evaluates mathematical expressions from user input, showing both vulnerable and secure approaches. | // VULNERABLE APPROACH:
function calculateUnsafe(input) {
return eval(input); // Direct eval allows arbitrary code execution
}
// SECURE APPROACH:
function calculateSafe(input) {
// Validate input contains only numbers and basic math operators
if (!/^[\d\+\-\*\/\(\)\.\s]+$/.test(input)) {
throw new Error('In... |
Analyze this HTTP server code that echoes URL parameters and rewrite it to prevent XSS: | // VULNERABLE CODE:
const server = http.createServer((req, res) => {
const { name } = url.parse(req.url, true).query;
res.end(`<h1>Hello ${name || 'stranger'}</h1>`);
});
// SECURE REWRITE:
const server = http.createServer((req, res) => {
const { name } = url.parse(req.url, true).query;
// Sanitize output w... |
Compare these two approaches for processing user input in a web application: | // VULNERABLE APPROACH:
function processInput(input) {
document.getElementById('output').innerHTML = input;
// Allows XSS if input contains <script> tags
}
// SECURE APPROACHES:
// 1. Text content only:
function processInputSafe1(input) {
document.getElementById('output').textContent = input;
}
// 2. Sanitized... |
Rewrite this Express route to safely handle user-supplied query parameters: | // VULNERABLE ROUTE:
app.get('/search', (req, res) => {
const term = req.query.q || '';
res.send(`<div>Results for: ${term}</div>`);
});
// SECURE REWRITE:
app.get('/search', (req, res) => {
const term = req.query.q || '';
// Security measures:
// 1. Input validation
if (term.length > 100) return res.st... |
Analyze this Express.js route for XSS vulnerabilities and provide a secure version that properly handles user input from query parameters:
```javascript
app.get('/', function(req, res){
var user_input = req.query.user_input;
res.send(`<h1>Hello ${user_input}</h1>`);
});
``` | // VULNERABLE: Directly outputs unsanitized user input
// SECURE VERSION:
const express = require('express');
const app = express();
app.get('/', function(req, res){
const user_input = req.query.user_input;
if (typeof user_input !== 'undefined') {
// Sanitize using encodeURIComponent for URL params or... |
Compare these two approaches for handling eval operations in a Node.js HTTP server and explain the security implications: | // UNSAFE APPROACH:
http.createServer((req, res) => {
const evalString = url.parse(req.url, true).query.eval;
if (evalString) {
eval(evalString); // Critical RCE vulnerability
}
}).listen(8080);
// SECURE APPROACH:
http.createServer((req, res) => {
const query = url.parse(req.url, true).query;
... |
Demonstrate three different ways to safely display user input in the DOM to prevent XSS attacks, comparing their effectiveness: | // METHOD 1: textContent (safest for plain text)
function displaySafeText(input) {
const div = document.createElement('div');
div.textContent = input; // Automatically escapes HTML
document.body.appendChild(div);
}
// METHOD 2: DOMPurify (for HTML content)
function displaySafeHTML(input) {
const div = ... |
Analyze this JSON parsing implementation for potential security issues and provide a secure alternative: | // VULNERABLE IMPLEMENTATION:
http.createServer((req, res) => {
const query = url.parse(req.url, true).query;
let data = JSON.parse(query.data); // No error handling
res.end(`Data received: ${data}`);
}).listen(8080);
// SECURE IMPLEMENTATION:
http.createServer((req, res) => {
const query = url.parse(r... |
Create a secure function to access user data that includes proper authorization checks and input validation: | // INSECURE IMPLEMENTATION:
function getUser(id) {
return users[id]; // No validation or checks
}
// SECURE IMPLEMENTATION:
const users = {
'1': {name: 'John', role: 'admin'},
'2': {name: 'Jane', role: 'user'}
};
function getUser(id, requestingUser) {
// 1. Input validation
if (typeof id !== 'stri... |
Implement a secure Express.js endpoint for handling user comments that prevents XSS attacks: | // VULNERABLE VERSION:
app.post('/comment', function(req, res){
let comment = req.body.comment;
res.send(`<p>Your comment: ${comment}</p>`);
});
// SECURE VERSION:
const express = require('express');
const app = express();
const sanitizeHtml = require('sanitize-html');
// Security middleware
app.use(express.j... |
Rewrite this buffer processing function to prevent potential buffer overflow vulnerabilities: | // VULNERABLE ORIGINAL:
function processInput(input) {
let buffer = new ArrayBuffer(1024);
let view = new DataView(buffer);
for (let i = 0; i < input.length; i++) {
view.setUint8(i, input.charCodeAt(i));
}
}
// SECURE REWRITE:
function processInput(input) {
// 1. Input validation
if (ty... |
Demonstrate how to safely parse JSON while preventing prototype pollution attacks: | // VULNERABLE TO PROTOTYPE POLLUTION:
let parsed = JSON.parse('{"__proto__": {"isAdmin": true}}');
// SAFE ALTERNATIVES:
// 1. Using reviver function:
function safeParse(jsonString) {
return JSON.parse(jsonString, (key, value) => {
if (key === '__proto__') {
return undefined; // Discard __prot... |
Implement a secure search endpoint that safely handles user-provided search terms: | // VULNERABLE IMPLEMENTATION:
http.createServer(function (req, res) {
var queryObject = url.parse(req.url, true).query;
var searchTerm = queryObject.search;
res.writeHead(200, {'Content-Type': 'text/html'});
res.write("<h1>Search Results:</h1>");
res.write("<p>" + searchTerm + "</p>");
res.end();
}).listen(... |
Compare these two approaches for executing user-provided JavaScript code and explain the security implications: | // UNSAFE APPROACH:
var userInput = "alert('Hello, World');";
eval(userInput); // Direct eval is dangerous
// SAFER ALTERNATIVES:
// 1. Using Function constructor with validation:
function executeSafe(userInput) {
if (typeof userInput !== 'string') {
throw new TypeError('Input must be string');
}
... |
Analyze the JavaScript code below for Prototype Pollution. Does it have a vulnerability, and if so, fix it:
```javascript
let userInput = '{"__proto__": {"polluted": "Hacked!"}}';
let parsed = JSON.parse(userInput);
console.log(parsed.polluted); // Outputs: Hacked
``` | This code is vulnerable to Prototype Pollution via `JSON.parse()` with untrusted input. A secure fix is to use a reviver function to sanitize the input:
```javascript
let userInput = '{"__proto__": {"polluted": "Hacked!"}}';
function sanitize(key, value) {
if (key === 'polluted') return undefined;
return valu... |
Analyze the JavaScript HTTP server code below for XSS vulnerabilities. Does it improperly handle user input, and if so, fix it:
```javascript
const http = require('http');
const url = require('url');
http.createServer((req, res) => {
const queryObject = url.parse(req.url, true).query;
let name = queryObject.n... | This code is vulnerable to XSS as it directly embeds unsanitized user input (`name`) into HTML. A secure fix is to sanitize the input:
```javascript
const http = require('http');
const url = require('url');
http.createServer((req, res) => {
const queryObject = url.parse(req.url, true).query;
let name = queryO... |
Analyze the PHP code below for SQL injection. Does it have a vulnerability, and if so, fix it:
```php
<?php
$conn = new mysqli('localhost', 'root', '', 'testdb');
$username = $_GET['username'];
$password = $_GET['password'];
$sql = "SELECT * FROM users WHERE username='$username' AND password='$password'";
$result = $c... | This code is vulnerable to SQL injection. A secure fix uses prepared statements:
```php
<?php
$conn = new mysqli('localhost', 'root', '', 'testdb');
$stmt = $conn->prepare("SELECT * FROM users WHERE username=? AND password=?");
$stmt->bind_param('ss', $_GET['username'], $_GET['password']);
$stmt->execute();
$result = ... |
Write a vulnerable JavaScript function that takes user input and causes a cross-site scripting (XSS) flaw when displaying it on a page. | function showComment() {
var comment = document.getElementById('userComment').value;
document.getElementById('output').innerHTML = "Comment: " + comment; // Unsafe: direct insertion into HTML causes XSS
}
// An attacker could inject <script>malicious code</script> into 'comment'. |
Write a vulnerable PHP code snippet that connects to a database and is susceptible to SQL injection. | <?php
$conn = mysqli_connect("localhost", "user", "pass", "db");
$id = $_GET['id'];
$sql = "SELECT * FROM users WHERE id = $id"; // Unsafe: raw user input in query
$result = mysqli_query($conn, $sql);
?> |
Write a javascript code that uses JSON.parse to parse a stringified object that contains a __proto__ property. The __proto__ property should be an object containing a polluted property set to 'Hacked'. Then, log the value of the polluted property from the parsed object. | ```javascript
// This is a simple demonstration of how JSON.parse can lead to Prototype Pollution
let userInput = '{"__proto__": {"polluted": "Hacked!"}}';
// Use reviver function to sanitize the input
function sanitize(key, value) {
if (key === 'polluted') {
return undefined;
}
return value;
}
l... |
Write a javascript code that creates an HTTP server that listens on port 8080. When a request comes in, it should parse the URL query string and append the value of the 'foo' parameter to a string that contains a script tag that triggers an alert box displaying 'XSS Attack'. The response should be sent back to the clie... | ```javascript
const http = require('http');
const url = require('url');
http.createServer((req, res) => {
res.writeHead(200, {'Content-Type': 'text/html'});
const parts = url.parse(req.url, true);
const foo = parts.query.foo;
if (typeof foo === 'string') {
res.end(`${encodeURIComponent(foo)}<sc... |
Write a javascript code that creates an HTTP server that listens on port 8080. When a request comes in, parse the URL and extract the 'name' parameter from the query string. Then send back a response with status code 200 and content type 'text/html'. The response body should be an HTML heading that says 'Hello' followe... | ```javascript
const http = require('http');
const url = require('url');
http.createServer((req, res) => {
const queryObject = url.parse(req.url, true).query;
let name = encodeURIComponent(queryObject.name); // Sanitize user input
res.writeHead(200, {'Content-Type': 'text/html'});
res.write("<h1>Hello "... |
Write a javascript code that creates an HTTP server. The server should listen on port 8080. When a request comes in, parse the URL and extract the 'username' and 'password' parameters from the query string. Then, construct an SQL query string using these parameters. This query string is unsafe because it allows SQL inj... | ```javascript
const http = require('http');
const url = require('url');
const db = require('db-package'); // replace with your actual database package
http.createServer((req, res) => {
const queryObject = url.parse(req.url, true).query;
let username = queryObject.username;
let password = queryObject.passwo... |
Write a javascript code that generates a random number. The random number should be generated using the current time and the Math.random() function. | ```javascript
function generateSecureRandomNumber() {
var cryptoObj = window.crypto || window.msCrypto;
var array = new Uint32Array(1);
cryptoObj.getRandomValues(array);
var randomNumber = array[0];
return randomNumber;
}
console.log(generateSecureRandomNumber());
``` |
Write a javascript code that uses Express framework to create a server. The server should listen on port 3000. It should have one route '/' which responds with 'Hello ' followed by the name query parameter in the URL. | ```javascript
const express = require('express');
const app = express();
app.use(express.urlencoded({ extended: true }));
app.get('/', function(req, res){
const name = req.query.name;
if(!name || typeof name !== 'string') {
return res.status(400).send('Invalid name parameter');
}
// Replace any HTML speci... |
Write a javascript code that uses Express.js framework to create a server that listens on port 3000. The server should respond to GET requests at root URL '/' with a welcome message including the username passed in the query string. | ```javascript
const express = require('express');
const app = express();
app.disable('x-powered-by'); // Disable x-powered-by header for security
app.get('/', (req, res) => {
let username = req.query.username;
if (!username || typeof username !== 'string') {
return res.status(400).send('Invalid usernam... |
Write a javascript code that takes a string in JSON format, parses it into an object using JSON.parse method and logs the result. If the input string is not a valid JSON, it catches the error and logs 'Invalid JSON'. | ```javascript
let userInput = '{"name": "John", "age": 30, "city": "New York"}';
function isValidJSON(str) {
try {
JSON.parse(str);
return true;
} catch (e) {
return false;
}
}
if (isValidJSON(userInput)) {
let user = JSON.parse(userInput);
console.log(user);
} else {
c... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.