3 Quick Tips for Input Validation
Tags: programming, security, webdev, javascript
Published: 2023-01-22 15:04:45

**Input validation** is a technique used to ensure that input data is properly formatted and within an expected range before it is processed by the application. By implementing input validation, developers can mitigate several common security threats, such as SQL injection, cross-site scripting (XSS), and path traversal. 

- **SQL injection** occurs when an attacker injects malicious code into an application's input fields in order to gain unauthorized access to a database.

- **XSS attacks** involve injecting malicious code into an application's input fields in order to execute scripts on the client side. 

- **Path traversal**, also known as directory traversal, occurs when an attacker manipulates input fields to access files or directories outside of the intended directory.

These types of attacks can be mitigated by properly validating and normalizing input to ensure that it is within the expected range and format, and by sanitizing input to remove any potentially malicious code.

In this post, I will show three ways to effectively implement input validation in your application.

## 1. Use Allowlists, not Blocklists
An allowlist is a list of allowed characters or values, while a blocklist is a list of disallowed characters or values. When using a blocklist, it can be difficult to anticipate all possible attack vectors and ensure that your application is protected against them. On the other hand, using an allowlist lets you specify exactly what input is accepted by your application, making it more secure.

For example, if you are validating an email address, you can use a regular expression to ensure that the input is in the correct format. The regular expression used in this code example is a standard pattern for email validation. The function returns `true` if the input matches the pattern and `false` if it doesn't.

```javascript
const emailRegex = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;

function validateEmail(email) {
    return emailRegex.test(email);
}
```

##2. Use a Sanitization Library
It's also important to sanitize user input to prevent the injection of malicious code. Several libraries can help you with this such as [xss-clean](https://www.npmjs.com/package/xss-clean), [dompurify](https://www.npmjs.com/package/dompurify) or [santize-html](https://www.npmjs.com/package/sanitize-html).

Here is an example of how to use dompurify to sanitize user input:

```javascript
const DOMPurify = require('dompurify');

function sanitizeInput(input) {
    return DOMPurify.sanitize(input);
}
```

This function uses the DOMPurify library to sanitize the input. The `DOMPurify.sanitize()` method takes the input as an argument and removes any potentially malicious code or scripts that may have been injected. This helps prevent SQL injection and cross-site scripting (XSS) attacks and ensures that the input is safe to use in the application.

##3. Normalize and Validate Paths
One way to protect against path traversal attacks is to use the `path.normalize()` method provided by the Node.js `path` module. Here is an example of how to use this method to protect against path traversal attacks:

```javascript
const path = require('path');

function protectPath(filePath) {
    const safeFilePath = path.normalize(filePath);

    if (safeFilePath.startsWith('/path/to/intended/directory')) {
        // Perform file operations on the safe file path
    } else {
        throw new Error('Invalid file path');
    }
}
```

This function takes a file path as an argument and normalizes it, replacing any instances of `../` or `./` with the absolute path. If the normalized path is within the intended directory, the function performs the file operations, otherwise it throws an error.

## Summary

Input validation is a crucial aspect of application security. By limiting input to expected values and using libraries to normalize and sanitize data, you can ensure that input data is properly formatted, within an expected range, and free of potentially malicious code before it is processed by the application.

Do you have any tips for input validation? Let me know in the comments below 👇