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

推荐订阅源

D
Docker
IT之家
IT之家
Microsoft Security Blog
Microsoft Security Blog
博客园 - 司徒正美
云风的 BLOG
云风的 BLOG
P
Proofpoint News Feed
D
DataBreaches.Net
B
Blog RSS Feed
博客园_首页
The GitHub Blog
The GitHub Blog
I
InfoQ
L
LangChain Blog
G
Google Developers Blog
M
MIT News - Artificial intelligence
美团技术团队
腾讯CDC
V
Visual Studio Blog
aimingoo的专栏
aimingoo的专栏
博客园 - 聂微东
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
Apple Machine Learning Research
Apple Machine Learning Research
A
About on SuperTechFans
博客园 - 三生石上(FineUI控件)
博客园 - 叶小钗

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
JavaScript Security Issues in Node.js Applications
2024-02-05 · via NodeJS Security & NodeJS Secure Coding's Blog

As server-side rendering technology gains popularity for building fast and scalable frontend applications, security needs to be top of mind for developers.

JavaScript is a flexible language, but that flexibility can lead to vulnerabilities if coders aren’t careful. In this article I’ll briefly cover common JavaScript security issues in Node.js that are likely to impact the Node.js runtime and how to address them.

Cross-Site Scripting (XSS) Hazards

A prominent risk with JavaScript applications is XSS or cross-site scripting. This is where attackers inject malicious client-side code. It often happens when dynamically generating HTML from the server-side without properly escaping user input.

For example, consider the following Express middleware code:

app.get('/comment', (req, res) => {

const comment = req.query.comment;

// ❌ Danger: allows HTML/script injection

res.send(`<div>${comment}</div>`);

// ✅ Safer with input sanitization, for example using the DOMPurify library

const clean = sanitizeHtml(comment);

res.send(`<div>${clean}</div>`);

});

The first handler directly inserts a comment parameter into HTML output without validation. By passing user input that contains encoded JavaScript in the URL, attackers can execute scripts in the browser. Instead, sanitize all dynamic output before rendering to prevent XSS.

This code snippet makes a reference to the DOMPurify library that can be used to sanitize untrusted input. Make sure you apply it to the correct context (such as HTML DOM elements vs an element’s own attributes and their values).

Using Content Security Policy

Content Security Policy (CSP) is an HTTP header that further helps mitigate XSS and other attacks. It restricts resources like JavaScript and CSS to trusted domains. This limits the impact of any malicious scripts that bypass other defenses.

Here is an example CSP:

Content-Security-Policy: script-src 'self'; object-src 'none';

This allows JavaScript only from the app’s own origin, blocking inline scripts. It is considered a best practice to set a strict CSP. The above is just one pattern.

Another tip here, regularly test applications for XSS using automated scanners and manual testing. Always assume some user input contains attacks. Limiting damage via techniques like CSP demonstrates an applied defense in depth practice.

In 2017, I spoke at the wonderful JSHeroes conference in Cluj, Romania, about JavaScript security topics that revolve around the browser and JavaScript security issues for frontend developers. The talk covers many of the topics mentioned above including HTTP security headers, keeping dependencies secure and more, and you can watch it below:

Command Injection and Path Traversal Risks

Two major server-side rendering JavaScript risks are command injection and path traversal attacks. These security vulnerabilities of course, also extend to Node.js backends. If left unmitigated, they allow attackers to execute system commands, read or write sensitive files, and escalate privileges.

In some use-cases, Node.js apps might need to spawn child processes or access the file system. For example, think of server-side actions such as manipulating images to resize them, or modify PDF files, and result in increasing the attack exposure.

// ❌ Risky and insecure way to run a a command

const { exec } = require('child_process');

const ls = exec('/usr/bin/convert ' + req.query.file + ' /tmp/out.png');

// ✅ Safer way to run a command ??

const { execFile } = require('child_process');

const ls = execFile('/usr/bin/convert', [req.query.file, '/tmp/out.png']);

The first example runs the ImageMagick convert command without scoping, prepared statements, or validating input, which could allow an attacker to run arbitrary commands. The second example uses execFile to run the same command with a safer approach.

However, the second example is still vulnerable to many aspects, including:

  • The attacker can still run arbitrary commands by if they can trigger argument injection
  • The attacker can specify arbitrary file paths and exploit path traversal vulnerabilities to read or write sensitive files on the server (e.g. /etc/passwd) or even overwrite the application code itself.

Other JavaScript Security Best Practices

Other good practices include:

  • Validating and sanitizing all user input data.
  • Using parameterized queries to prevent SQL injection
  • Implementing CSRF protections
  • Enabling HTTP security headers like CSP
  • Keeping dependencies updated to avoid known exploits
  • Regular code reviews focused on security also help catch issues early. Consider tools like ESLint to catch common bugs. Monitoring for suspicious activity is also advised to detect attacks.

Stay Secure with Node.js Secure Coding Resources

For developer-friendly secure coding guidance in Node.js, check out my latest books Node.js Secure Coding. Learn JavaScript security fundamentals for building applications on-top of Node.js, command injection and path traversal vulnerabilities, and review practical code examples for building more resilient apps.

The key is making security a priority early in development to protect users and business-critical assets. Following best practices and threat modeling can help identify and address risks in a cost-effective manner.