SQL Injection Prevention
<?php
// Establish database connection
$connection = new mysqli("localhost", "username", "password", "database");
// User input (from login form)
$username = $_POST['username'];
$password = $_POST['password'];
// Prepare and bind the SQL statement to avoid SQL injection
$stmt = $connection->prepare("SELECT * FROM users WHERE username = ? AND password = ?");
$stmt->bind_param("ss", $username, $password);
// Execute the prepared statement
$stmt->execute();
$result = $stmt->get_result();
// Check if the user exists
if ($result->num_rows > 0) {
echo "Login successful!";
} else {
echo "Invalid username or password.";
}
// Close the statement and connection
$stmt->close();
$connection->close();
?>
Language: PHP with My SQL
Technique:
Use prepared statements with parameterized queries to protect against SQL injection.
Why It Works:
Prepared statements ensure that user inputs are treated as data and not executable code, preventing malicious input from altering the SQL query structure.
Protection: Even if the user submits a malicious input like ' OR '1'='1
, the query won't be affected because it’s safely parameterized.
NoSQL Injection Prevention
const MongoClient = require('mongodb').MongoClient;
const url = "mongodb://localhost:27017/";
const dbName = "mydb";
const collectionName = "users";
// Assume user input from a login form
let username = req.body.username;
let password = req.body.password;
MongoClient.connect(url, { useUnifiedTopology: true }, function(err, client) {
if (err) throw err;
const db = client.db(dbName);
const collection = db.collection(collectionName);
// Use strict query objects and validate input types to prevent NoSQL injection
if (typeof username === 'string' && typeof password === 'string') {
collection.findOne({ username: username, password: password }, function(err, result) {
if (err) throw err;
if (result) {
res.send("Login successful!");
} else {
res.send("Invalid username or password.");
}
client.close();
});
} else {
res.send("Invalid input.");
}
});
Language: Node.JS with Mongo DB
Technique:
Use strict input validation and querying practices to avoid NoSQL injection.
Why It Works:
Strict Input Validation: The typeof
checks ensure that only strings are accepted for username
and password
, reducing the risk of malicious input (e.g., object or code injection).
Protection: The query is structured safely to prevent NoSQL injection by limiting the flexibility of the query objects and only accepting valid input types.
OS Command Injection Prevention
const { execFile } = require('child_process');
// User input from a web form
let userInput = req.body.filename;
// Validate the input to ensure it doesn't contain malicious characters
if (/^[a-zA-Z0-9_\-\.]+$/.test(userInput)) {
// Safe execution of system commands with execFile, which doesn't allow command chaining
execFile('/usr/bin/cat', [userInput], (error, stdout, stderr) => {
if (error) {
console.error(`Error executing command: ${error}`);
return;
}
console.log(`Command output: ${stdout}`);
});
} else {
res.send("Invalid input.");
}
Language: Node.js
Technique:
Use safe methods like execFile
(instead of exec
) to avoid OS command injection, and validate user inputs.
Why It Works:
Input Validation: A regular expression is used to validate that the userInput
contains only safe characters (alphanumeric, dashes, underscores, and periods), preventing malicious commands or file paths.
Use of execFile
: Unlike exec
, which runs arbitrary shell commands, execFile
only runs the specified file (e.g., /usr/bin/cat
) with the provided arguments. This prevents command injection (e.g., chaining commands like cat file.txt; rm -rf /
).