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

推荐订阅源

F
Full Disclosure
WordPress大学
WordPress大学
小众软件
小众软件
Cloudbric
Cloudbric
AWS News Blog
AWS News Blog
腾讯CDC
量子位
人人都是产品经理
人人都是产品经理
大猫的无限游戏
大猫的无限游戏
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
V
Vulnerabilities – Threatpost
Scott Helme
Scott Helme
Hugging Face - Blog
Hugging Face - Blog
博客园_首页
C
CXSECURITY Database RSS Feed - CXSecurity.com
The Hacker News
The Hacker News
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
IT之家
IT之家
Jina AI
Jina AI
Attack and Defense Labs
Attack and Defense Labs
S
SegmentFault 最新的问题
Simon Willison's Weblog
Simon Willison's Weblog
The Cloudflare Blog
阮一峰的网络日志
阮一峰的网络日志
T
Tailwind CSS Blog
Last Week in AI
Last Week in AI
博客园 - 【当耐特】
Google Online Security Blog
Google Online Security Blog
美团技术团队
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
V
Visual Studio Blog
罗磊的独立博客
L
LINUX DO - 最新话题
博客园 - Franky
博客园 - 叶小钗
Apple Machine Learning Research
Apple Machine Learning Research
The Last Watchdog
The Last Watchdog
J
Java Code Geeks
AI
AI
C
Cisco Blogs
酷 壳 – CoolShell
酷 壳 – CoolShell
C
Cyber Attacks, Cyber Crime and Cyber Security
Cisco Talos Blog
Cisco Talos Blog
博客园 - 三生石上(FineUI控件)
雷峰网
雷峰网
Help Net Security
Help Net Security
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
云风的 BLOG
云风的 BLOG
I
Intezer
S
Securelist

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 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 Input Validation Security Best Practices for Node.js 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
Can a Node.js Secure Code Review Find Future Vulnerabilities?
2024-12-06 · via NodeJS Security & NodeJS Secure Coding's Blog

Imagine a typical day at work where you help a colleague review a Node.js codebase. You hopefully apply some secure code review skills to identify potential security vulnerabilities. But can you find all the vulnerabilities in a given pull request? What about the security issues that might arise later in the future from the same code change if a refactor takes place?

Let’s put this secure code review to the test. Following is a Node.js code snippet from your favorite framework, whether Express, Fastify, or otherwise.

Take a look at this server-side JavaScript code and before you dive into the next section of a collaborative secure code review, try your best to spot any potential security vulnerabilities:

// save user's avatar to images/ directory

const IMAGE_DIR = '/src/tmp/images'

app.post('/upload', async (req, res) => {

const uploadedFile = req.files.avatar

const fileName = uploadedFile.name

const fileContent = await uploadedFile.data()

const contentHash = Util.hashContent(uploadedFile.name)

const filePath = Path.createAbsolutePath(`${IMAGE_DIR}/${contentHash}`)

if (!await filePath.exists()) {

await FS.writeFile(filePath, fileContent);

return res.send('File uploaded!')

}

return res.status(400).send()

})

Node.js Secure Code Review

I shared a similar Node.js pseudo code snippet on social (X, Bluesky, and LinkedIn) and asked friends to provide feedback on what they thought about the code.

Let’s dive head on and break apart the above Node.js code snippet for the code review comments I received:

Large File Uploads in Node.js

One friend commented wouldn't the thread hang for very large files?. Valid point indeed. In the code snippet specifically, the Promise syntax won’t hang JavaScript’s main event loop thread, but processing large files through a Promise can still cause issues around memory handling. A better approach would be to utilize Node.js streams API and stream the file content to disk directly.

Upload Storage Capacity

In continuation to the above, one could also raise the question about free storage capacity on the server and whether the server has enough disk space to begin with, to store the uploaded files, particularly in the designated /src/tmp/images directory.

Rate Limits in Node.js

Both of the above comments around large file handling and upload storage capacity lead to a higher-level concept of rate limiting.

What is Rate Limiting? Rate limiting is a security measure to prevent abuse of a service (such as an exposed Node.js API) by limiting the number of requests a client or API consumer can make in a given time frame.

In Node.js, you can implement rate limiting within the Node.js web application server or in the reverse proxy server (such as Nginx or Apache) that often in production workloads sits in front of the Node.js server. If you’re looking for a quick rate limiting solution to an Express-powered Node.js server you can use the express-rate-limit npm package.

Time of Check to Time of Use (TOCTOU) Vulnerability

This is a bit of an advanced topic but worth digging into.

Not surprising to receive this feedback from a security-minded friend. Vladimir from Microsoft’s research team commented that perhaps time of check / time of use issue may arise between the time that passed while checking if a file exists and writing it. This could possibly leave a gap for race conditions if this can be executed in parallel.

File Upload Validation in Node.js

Another friend, Tomer, head of security research at F5 also pointed out the mandatory need for file upload validation. In the code snippet, the uploaded file is not validated for its file type, size, or content. This could lead to a potential security vulnerability such as a file upload vulnerability.

For example, a file type can be determined by either a file extension check (which is more often than not mistaken to be based on a string matching of the extension string) or by checking the file’s magic bytes. Magic bytes are the first few bytes of a file that can be used to determine the file type. For example, a PNG file’s magic bytes are 89 50 4E 47 0D 0A 1A 0A.

File Upload Privacy and File Upload Sanitization

An interesting aspect of handling user uploads could be around keeping user’s privacy a top concern and mixing that with sanitization of metadata in the uploaded files from being a potential source-to-sink attack vector.

Let’s say you’re building a social media platform and users can upload their profile pictures. You’d want to make sure that the uploaded image doesn’t contain any metadata that could potentially leak sensitive information about the user. Pictures taken with a camera or a phone could contain metadata such as GPS coordinates, camera model and other tidbits that could be reverse engineered using OSINT techniques to identify information about the user who took the picture.

Hash Collision in File Uploads

Let’s look at the relevant part of the code snippet:

const fileContent = await uploadedFile.data()

const contentHash = Util.hashContent(uploadedFile.name)

The file name being written to disk is based on a hash of the file name. What happens if another user uploads a file with the same name? What happens if two different file names end up having the same hash?

These could potentially lead to a hash collision. Is it a better approach to hash the file content itself rather than the file name to ensure uniqueness? Imagine the following:

const fileContent = await uploadedFile.data()

const contentHash = Util.hashContent(fileContent)

What’s the issue now?

File Permissions

Ok so you’re writing files to disk in the /src/tmp/images directory. What are the file permissions set on the directory? Do those belong to the Node.js server user? Is that a good idea?

Soumen who runs Security Governance at Barco raised this concern too, which many developers don’t often think about because they’re not aware of file systems.

File Upload Size Edge Cases

What happens if there’s an edge case where the file contents is empty and effectively the file size is 0. First off, remember we raised a prior concern during code review about a using a unique file name based on hashing the file’s content? Well, that’s not going to work well here.

Think about edge cases, people!

Cross-site Scripting (XSS) in File Uploads

Ugh, yes. The one that’s so commonly overlooked. What does a client-side vulnerability such as Cross-site Scripting (XSS) have to do with server-side file uploads? Isn’t that the client’s problem? Well, kind of but also, “depends”.

Let’s say the attacker manipulated the file name so that the file name has special HTML characters in it. What if the file name is set by the attacker to be hello-<script>alert('XSS')</script>.pdf?

Now, imagine that the client-side takes the file metadata, such as the file name, as part of the Node.js API server response and displays it on the client-side. The frontend developer might commonly mistake to think that if this is coming from the server, especially something as seemingly harmless as a file name, it would be safe to render on the client-side.

If the file name is not properly escaped in the client-side, this effortlessly turns into an attack vector that manifests as an XSS vulnerability.

File Upload Persistence

How about we take a step back and think about the persistence of the uploaded files?

In the provided code snippet, the uploaded files are placed in the /src/tmp/images directory. What happens if the server crashes? What if you need to spin it up or down? are you managing mounted file paths properly?

A better cloud-native development approach would be to store the uploaded files directly in the cloud via services like Amazon S3, Google Cloud Storage, or Azure Blob Storage. This way, you can ensure that the uploaded files are persisted and available even if the server crashes. This also has other benefits like scalability, durability, performance, and even security!

So yes, consider uploading the file directly to cloud storage.

The Security Bug You Totally Missed: Path Traversal in Node.js

Not one person at all, through-out all of the different platforms I shared this Node.js code snippet on, mentioned the potential security vulnerability that exists in the code snippet - Path Traversal.

“Wait, what? There’s no path traversal vulnerability here!” you might say.

Let’s see if you’re right. Look again at the code snippet:

const fileName = uploadedFile.name

const fileContent = await uploadedFile.data()

const contentHash = Util.hashContent(uploadedFile.name)

const filePath = Path.createAbsolutePath(`${IMAGE_DIR}/${contentHash}`)

If the file name is ../ or %2e%2e%2f (URL encoded ../), none of these would result in a path traversal vulnerability because the file name is hashed into an alpha numeric string (depends on the hash function, but you get the point). So if the file name input is ../../../../../etc/passwd then the effective contentHash would be ab15sb176bs61bs7b9sbs71gs71b and the file path would be /src/tmp/images/ab15sb176bs61bs7b9sbs71gs71b.

So where is the file path traversal vulnerability, you ask?

Right now there is no path traversal. The root problem with path traversal happens due to how paths are constructed and used in the application. RIGHT NOW the file path is constructed by concatenating the IMAGE_DIR and the contentHash. This is the last thing you want to do. You never concatenate paths together to form a file path. That’s the root cause of path traversal vulnerabilities.

What happens if in a future code refactor, the product manager decides it is more user-friendly to store the uploaded files in a directory structure that mirrors the user’s email address? or keeps the original file name to allow for a nice friendly download experience to users? Now, the file name will be derived from a user-controlled input and leaving the rest of the code as is, which means concatenating a directory with a file name is a recipe for disaster.

Learn about Secure Coding and Path Traversal Vulnerabilities

If you are serious about polishing your secure coding skills, go grab a copy of my Node.js Secure Coding book that teaches you how to defend against path traversal vulnerabilities from the inside out and how to build secure Node.js applications.