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

推荐订阅源

小众软件
小众软件
Y
Y Combinator Blog
Cisco Talos Blog
Cisco Talos Blog
T
Threatpost
T
Tor Project blog
I
Intezer
T
Threat Research - Cisco Blogs
L
LINUX DO - 热门话题
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
L
Lohrmann on Cybersecurity
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
The Last Watchdog
The Last Watchdog
Application and Cybersecurity Blog
Application and Cybersecurity Blog
P
Privacy & Cybersecurity Law Blog
N
News | PayPal Newsroom
N
News and Events Feed by Topic
C
CERT Recently Published Vulnerability Notes
T
Tenable Blog
K
Kaspersky official blog
V
Visual Studio Blog
T
Troy Hunt's Blog
Project Zero
Project Zero
博客园_首页
The Register - Security
The Register - Security
O
OpenAI News
G
Google Developers Blog
Simon Willison's Weblog
Simon Willison's Weblog
J
Java Code Geeks
D
DataBreaches.Net
F
Full Disclosure
Latest news
Latest news
C
CXSECURITY Database RSS Feed - CXSecurity.com
S
Security Affairs
Recent Commits to openclaw:main
Recent Commits to openclaw:main
腾讯CDC
有赞技术团队
有赞技术团队
Hacker News - Newest:
Hacker News - Newest: "LLM"
阮一峰的网络日志
阮一峰的网络日志
C
Cisco Blogs
Vercel News
Vercel News
V
Vulnerabilities – Threatpost
月光博客
月光博客
Hacker News: Ask HN
Hacker News: Ask HN
B
Blog RSS Feed
P
Palo Alto Networks Blog
Stack Overflow Blog
Stack Overflow Blog
The Cloudflare Blog
C
Cyber Attacks, Cyber Crime and Cyber Security
D
Darknet – Hacking Tools, Hacker News & Cyber Security
G
GRAHAM CLULEY

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 Vue CLI Security Fix to Mitigate NPM Binary Planting Node.js API Security Vulnerabilities with Path Traversal in files-bucket-server Will You Accept These GPT 4o Secure Coding Recommendations? Command Injection Vulnerability in interactive-git-checkout npm package An Introduction to SSRF Bypasses and Denylist Failures Disclosing a Command Injection Vulnerability in `git-checkout-tool` Prisma Raw Query Leads to SQL Injection? Yes and No Flawed Git Promises Library on npm Leads to Command Injection Vulnerability Regex Gone Wrong: How parse-duration npm Package Can Crash Your Node.js App How I found an XSS in the Nuxt MDC Library for Markdown Content Holes in the Safety Net: Bypassing SSRF Protection in safe-axios How to Parse URLs from Markdown to HTML Securely? NPM Ignore Scripts Best Practices as Security Mitigation for Malicious Packages Where to find npm vulnerabilities? How to Hunt for IDOR Vulnerabilities To Exploit Security Misconfiguration? How to Avoid JWT Security Mistakes in Node.js Can a Node.js Secure Code Review Find Future Vulnerabilities? The Okta bcrypt Security Incident and The Bun vs Node.js Angle in Secure By Design NodeJS Path Traversal Vulnerability Scanner Do not use secrets in environment variables and here's how to do it better How to use npm audit How to use yarn audit Raw SQL Queries are Actually Better for Security Than ORMs? Node API Security Is Node.js Secure? URL Regex Validation: what can go wrong? Uncovering a Prototype Pollution Regression in the core Node.js project Deno CLI Vulnerability Repeats npm mistakes: CVE-2024-37150 Security skills for JavaScript developers Understanding and Preventing Prototype Pollution in Node.js How to protect against a security breach in React Server Components IDOR Vulnerability: What is it and how to prevent it? The security vulnerability of serving images via a route as opposed to static middleware in Node.js Why is it considered a bad practice to write raw SQL commands? JS Security Concepts for JavaScript Developers Secure Coding Practices in Node.js Against Path Traversal Vulnerabilities Secure JavaScript Coding Practices Against Command Injection Vulnerabilities To IDOR or Not to IDOR: Insecure Direct Object Reference in JavaScript Applications Explained npm vulnerabilities: reviewing the security of your dependencies Disclosing code injection vulnerabilities in safe-eval-2 npm package Introducing Node.js Security Permissions Model, Threat Model, and Security Releases Common Node.js Security Issues and How to Mitigate Them How JavaScript developers should embrace npm security The XZ backdoor CVE-2024-3094: a JavaScript perspective Node.js Security Best Practices The Case for Node.js Secure Configuration Protecting Against Common Node.js Vulnerabilities A Node.js Vulnerability Scanner to Avoid Security Risks of EOL Runtime Versions JavaScript Security Issues in Node.js Applications OWASP Node.js Authentication, Authorization and Cryptography Practices OWASP Node.js Best Practices Guide Secure JavaScript Coding to Avoid Insecure Direct Object References (IDOR) North Korea malware on npm and Ledger connect-kit crypto heist 10 Best Practices for Secure Code Review of Node.js code Node.js and OWASP Top Ten Command Injection: Don't Let Your App Go 'BOOM' Secure Code Review Tips to Defend Against Vulnerable Node.js Code Destroyed by Dashes: How Two Hyphens Cause Argument Injection Vulnerability in blamer npm Package Securing Your Node.js Apps by Analyzing Real-World Command Injection Examples An Introduction to Command Injection Vulnerabilities in Node.js and JavaScript
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.