Table of Contents
- Setting Up the Project
- Creating Middleware for Input Sanitization
- Setting Up the Express Application
- Sanitizing URL Parameters
- Sanitizing Form Data
- Example: Complete Application
- Conclusion
Setting Up the Project
First, let’s set up a new Node.js project and install the necessary dependencies.
1. Create a new directory for your project:
mkdir secure-nodejs-app
cd secure-nodejs-app
2. Initialize a new Node.js project:
npm init -y
3. Install the required dependencies:
npm install express body-parser mysql2
- Express: A web framework for Node.js.
- Body-parser: Middleware to handle incoming request bodies.
- MySQL2: A MySQL client for Node.js.
Creating Middleware for Input Sanitization
We will create a middleware function that sanitizes user inputs to prevent malicious data from being processed. This function will escape special characters in URL parameters and sanitizeinput
data from forms. You can also create a middleware function called sanitizeMaliciousInput
to handle various types of potentially harmful input.
Create a file named sanitize.js
and maliciousInputMiddleware.js
in the root of your project:
// sanitize.js
const mysql = require('mysql2');
function sanitizeInput(req, res, next) {
// Sanitize URL parameters
for (const param in req.params) {
req.params[param] = req.params[param].replace(/[^a-zA-Z0-9-_]/g, ''); // Allow only alphanumeric, hyphen, and underscore
}
// Sanitize form data (body)
for (const field in req.body) {
req.body[field] = mysql.escape(req.body[field]); // Escape input for SQL
}
next();
}
module.exports = sanitizeInput;
// maliciousInputMiddleware.js
function sanitizeMaliciousInput(req, res, next) {
// Sanitize URL parameters
for (const param in req.params) {
req.params[param] = req.params[param].replace(/[<>"'();&]/g, ''); // Remove dangerous characters
}
// Sanitize query parameters
for (const query in req.query) {
req.query[query] = req.query[query].replace(/[<>"'();&]/g, ''); // Remove dangerous characters
}
// Sanitize body data
if (req.body) {
for (const field in req.body) {
if (typeof req.body[field] === 'string') {
req.body[field] = req.body[field].replace(/[<>"'();&]/g, ''); // Remove dangerous characters
}
}
}
// Continue to the next middleware
next();
}
module.exports = sanitizeMaliciousInput;
Setting Up the Express Application
Now, let’s set up a basic Express application that uses our sanitization middleware.
Create a file named app.js
:
// app.js
const express = require('express');
const bodyParser = require('body-parser');
const sanitizeInput = require('./sanitize');
const sanitizeMaliciousInput = require('./maliciousInputMiddleware');
const bcrypt = require('bcrypt'); const mysql = require('mysql2');
const app = express();
const PORT = process.env.PORT || 3000;
// MySQL connection const db = mysql.createConnection({ host: 'localhost', user: 'your_username', password: 'your_password', database: 'your_database', });
db.connect(err => { if (err) throw err; console.log('Connected to MySQL database.'); });
// Middleware
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(sanitizeInput);
app.use(sanitizeMaliciousInput); // Use the malicious input sanitizer middleware
// Sample route to demonstrate sanitization
app.get('/user/:username', (req, res) => {
const username = req.params.username;
const sql = 'SELECT * FROM users WHERE username = ?';
db.query(sql, [username], async (err, results) => {
if (err || results.length === 0) return res.status(401).send('Invalid username ');
res.send(`Hello, ${username}!`);
});
});
// Sample route to demonstrate sanitization with form data
app.post('/submit', (req, res) => {
const userData = req.body;
res.send(`Received sanitized data: ${JSON.stringify(userData)}`);
});
// Start the server
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});
Sanitizing URL Parameters
In our sanitizeInput
middleware, we replace any characters in the URL parameters that are not alphanumeric, hyphen, or underscore. This helps ensure that special characters do not pose a risk when included in the application logic.
For example, if a user tries to access http://localhost:3000/user/<script>alert('XSS')</script>
, the sanitized output will only include the alphanumeric characters and allowed symbols.
Sanitizing Form Data
When handling form submissions, the middleware uses MySQL's escape
method to escape special characters. This is particularly important to prevent SQL injection attacks. The escaped input can then be safely used in SQL queries without fear of malicious data execution.
Example: Complete Application
1. Run the Application
Make sure your MySQL server is running and the connection settings are correctly configured in your application. You can add a database connection in your application as needed.
Start your application:
node app.js
2. Test the Application
Testing URL Parameter Sanitization
http://localhost:3000/user/test_user123
Response: Hello, test_user123!
If you try:
http://localhost:3000/user/<script>alert('XSS')</script>
The application will sanitize the input, and you’ll receive a safe response.
Testing Form Data Sanitization
Use a tool like Postman or CURL
to send a POST
request to test form data sanitization:
curl -X POST http://localhost:3000/submit -H "Content-Type: application/json" -d '{"name":"John Doe","email":"[email protected]; DROP TABLE users;"}'
You should receive a response like:
Received sanitized data:
{"name":"John Doe","email":"[email protected]"}
Conclusion
Input sanitization is a crucial aspect of secure coding in Node.js applications. By implementing a middleware for sanitizing user inputs, you can significantly reduce the risk of attacks such as SQL injection and XSS. In this article, we created a simple Node.js application that demonstrates how to sanitize URL parameters and form data effectively.
Always remember that security is an ongoing process; regular code reviews, security audits, and staying updated with best practices are essential in maintaining a secure application. Happy coding!
Hope you find this helpful !!!
Secure Coding in Node.js: Input Sanitization Using Middleware