惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

IT之家
IT之家
博客园 - 聂微东
雷峰网
雷峰网
Microsoft Azure Blog
Microsoft Azure Blog
WordPress大学
WordPress大学
Hugging Face - Blog
Hugging Face - Blog
S
SegmentFault 最新的问题
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
T
Tailwind CSS Blog
博客园 - 三生石上(FineUI控件)
V
Visual Studio Blog
博客园 - 司徒正美
爱范儿
爱范儿
月光博客
月光博客
阮一峰的网络日志
阮一峰的网络日志
博客园_首页
博客园 - 【当耐特】
Jina AI
Jina AI
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
酷 壳 – CoolShell
酷 壳 – CoolShell
大猫的无限游戏
大猫的无限游戏
小众软件
小众软件
人人都是产品经理
人人都是产品经理
V
V2EX

NodeJS Security & NodeJS Secure Coding's Blog

Hardening Your npm and pnpm Configs in the Age of Shai-Hulud Argument Injection vulnerability in git-blame@1.4.0 Argument Injection vulnerability in `gits@0.1.8` Command Injection vulnerability in `@fab1o/git@1.4.0` Command Injection vulnerability in `git-contributors` via unsanitized CLI arguments Command Injection vulnerability in `git-q@0.0.3` Command injection vulnerability via unsanitized CLI arguments in touxing/fast-git-clone Command Injection vulnerability in `willitmerge@0.2.1` A Directory Traversal Vulnerability I found in Mastra AI Frameworks MCP Server Mastering NPX: A Cheatsheet for npm and Node.js Power Users Mitigate Supply Chain Security with DevContainers and 1Password for Node.js Local Development The Tale of the Vulnerable MCP Database Server Bad Security Defaults in Mastra AI Frameworks Templates SQL Injection and Bypassing "Read-Only" Mode in Xata's MCP Server Security Advisory for qix npm supply-chain compromise affecting debug and billions of weekly download users How to Mitigate SQL Bypass in MCP Servers Enhancing MCP Server Security: A Guide to Using execFile Argument Injection Vulnerability in ggit How to Bypass Access Control in PostgreSQL in Simple PSQL MCP Server for SQL Injection Command Injection Flaws in ggit: Unveiling a Vulnerability Command Injection Vulnerability in Create MCP Server STDIO Tool Exposes System Monitoring Functions GitHub Kanban MCP Server Command Injection Vulnerability Threatens Developer Workflows Critical Command Injection Flaw in iOS Simulator MCP Server Exposes Development Environments Command Injection Vulnerability Discovered in Codehooks MCP Server: A Critical Security Analysis SSRF Shenanigans in safe-axios: Redirects Open the Backdoor SSRF Vulnerability in safe-axios: Unintended Public Address Classification Bypassing SSRF Safeguards in ssrfcheck: A Case of Incomplete Denylists Don't Be Fooled by Multicast, SSRF Bypass in private-ip Node.js Authentication from Lucia to Better Auth Bypassing SSRF Protection in nossrf: When Your Safeguards Become Loopholes
Input Validation Security Best Practices for Node.js
2024-02-27 · via NodeJS Security & NodeJS Secure Coding's Blog

For backend Node.js developers, prioritizing security ranks high on the list of crucial considerations. One key aspect of securing your backend applications lies in meticulously validating all incoming user input. This practice effectively minimizes the risk of falling prey to prevalent attack vectors such as OS command injections, SQL injections, and prototype pollution vulnerabilities.

This guide goes into the best practices for input validation in Node.js, equipping you with the knowledge and tools to build robust and secure applications. We’ll explore key strategies, code examples, and recommendations to fortify your development approach.

Guarding Against Malicious Input: Validation and Sanitization

The fundamental principle behind input validation and sanitization revolves around filtering out potentially harmful characters and establishing a allowlist of authorized values. This approach effectively prevents the execution of malicious payloads that may be embedded within user input. Let’s delve into some essential validation strategies:

1. Leverage validation libraries

Libraries like joi and validator.js streamline the validation process by providing tools to verify input data types, formats, and values. These libraries offer comprehensive pre-built validation rules that can be easily integrated into your code.

const Joi = require('joi');

const validateUser = (data) => {

const schema = Joi.object({

username: Joi.string().alphanum().min(3).max(20).required(),

email: Joi.string().email().required(),

password: Joi.string().min(8).required()

});

const validationResult = schema.validate(data);

if (validationResult.error) {

throw new Error(validationResult.error.message);

}

return data;

};

2. Prevent XSS with character encoding

Libraries like he come in handy for encoding special characters in user input, effectively thwarting XSS (Cross-Site Scripting) attacks. By encoding these characters, you render them harmless within your application’s context.

const he = require('he');

const encodedMessage = he.encode(userMessage);

// example 1

he.encode('foo © and & ampersand', {

'allowUnsafeSymbols': true

});

// results in 'foo © and & ampersand'

// example 2:

he.escape('<img src=\'x\' onerror="prompt(1)">');

// result in '&lt;img src=&#x27;x&#x27; onerror=&quot;prompt(1)&quot;&gt;'

3. Sanitize HTML input

Libraries like sanitize-html provide a shield against malicious code injection by filtering out unwanted HTML tags and attributes from user input intended for display. This ensures that only safe and sanitized content is rendered in your application.

const sanitizeHtml = require('sanitize-html');

const sanitizedContent = sanitizeHtml(userContent, { allowedTags: ['p', 'b', 'i'] });

Or consider using a library like dompurify to sanitize HTML content:

import DOMPurify from 'dompurify';

const clean = DOMPurify.sanitize(dirty);

4. Embrace allow-lists

Instead of spending valuable effort attempting to denylist every conceivable malicious character, it’s recommended to establish allowlists that solely permit authorized characters within user input. This approach simplifies the validation process and reduces the risk of overlooking potential vulnerabilities.

These strategies, when combined, form a robust defense against malicious input attempts.

Parameterized Queries: Shielding Against SQL Injection

Parameterized queries are an effective safeguard against SQL injection vulnerabilities. They achieve this by separating the structure of your SQL statement from the user-provided values. This separation prevents malicious code from being directly injected into your queries. Here are valuable tips for implementing this technique:

1. Utilize ORM libraries

Utilizing Object-Relational Mapping (ORM) libraries like Sequelize or Mongoose significantly streamlines the process of automatically parameterizing your queries. These libraries handle the details of building and executing secure queries, allowing you to focus on your application logic.

// Using Sequelize

const user = await User.findByPk(userId, { attributes: ['username', 'email'] });

// Using Mongoose

// Here, you should be careful of passing `userId` as an object to avoid NoSQL injection

const user = await User.findById(userId).select('username email');

2. Utilize prepared statements with raw SQL

When working directly with raw SQL statements, leverage prepared statements with placeholder values for user input. This approach clearly separates values from the query structure, ensuring security.

const connection = await pool.connect();

const query = "SELECT * FROM users WHERE username = $1";

const result = await connection.query(query, [username]);

await connection.release();

3. Never concatenate user input

It’s critical to avoid dynamically building SQL query strings by concatenating user input directly into the query. This practice poses a significant security risk and should be strictly avoided.

By adhering to these practices, you can effectively mitigate the threat of SQL injection vulnerabilities in your Node.js applications.

Summary

By implementing these input validation best practices, you can significantly enhance the security posture of your Node.js applications. These strategies provide a robust defense against common security vulnerabilities, ensuring that your applications remain resilient to malicious input attempts.