Node.js Secure Coding:

Prevention and Exploitation of Path Traversal Vulnerabilities

$ npm install url-parse serve @node-red/runtime
added 176 packages, and audited 177 packages in 16s
12 high severity vulnerabilities

Don't take security vulnerabilities for granted. Learn how to write secure code.

Node.js Secure Coding: Defending Against Command Injection Vulnerabilities
Node.js Secure Coding: Defending Against Command Injection Vulnerabilities, dark mode edition

Digital book

PDF & EPUB

The book features:

  • 117 Pages
  • 7 Vulnerable npm Packages
  • 40 Self-assessment Questions
  • 11 Chapters
  • Light Mode
  • Dark Mode SPECIAL EDITION
  • September 2023 release
  • Sale 15% OFF
$57.60 $48.96

Tip: get 2 secure coding books bundle for $120.96 and save 30% Buy Bundle

ThomasManuelYoniTallyMateoSergioManuHungKriakosSophiaDanielDavidMiguelJoachimJesúsDiMilanAshifIvanHeruNgoran +400

Join 424+ developers learning Node.js security skills

Liran is a tireless advocate for security in the JS ecosystem. He works hard to build bridges, educate developers about security issues, and support Open Source projects working to improve their security posture. Liran has served on the Node security team and is always available to support developers!

by the OpenJS Foundation

Quick peak into secure best practices and vulnerable code analysis

Handful of pages from the Node.js security book showing Path Traversal vulnerabilities and Secure Coding flaws

Path Traversal book cover Path Traversal book table of contents Path Traversal book vulnerability in practice code example Path Traversal book vulnerability in serve npm package Path Traversal book offensive security Path Traversal book offensive security docker setup Preventing Path Traversal vulnerability in Node.js The hidden impact of path traversal vulnerability in Node.js Test your knowledge of Path Traversal vulnerability in Node.js Path Traversal vulnerability book back cover
Be The Hacker

1 Chapter dedicated to offensive path traversal security tools and techniques in which you launch an automated attack

11

Chapters

2 introductory chapters to learn about Path Traversal vulnerabilities, followed by 7 laser-focused CVE chapters reviewing real-world vulnerable npm packages, 1 chapter on offensive security tools, 1 path traversal secure coding best practices chapter and 1 concluding chapter with 40 self-assessment path traversal security questions.

2014-2021

CVE Security Reports

Learn from past mistakes of other developers and open-source maintainers who published JavaScript packages to npm and were affected by security vulnerabilities.

40

QUIZ Questions

Are you learning effectively? This book includes 40 self-assessment questions in the form of Yes-no, Fill-the-blanks, and multiple answers questions to help evaluate your understanding of secure coding in Node.js and assess your application security skills.

117

Pages

117 pages of Node.js secure coding lessons, best practices, and real-world vulnerabilities analysis and insights.

7

vulnerable npm packages

7 Chapters covering security vulnerability reports (CVEs) in real-world vulnerable npm packages, and in-depth code review analysis of the path traversal vulnerabilities, the security fix strategy and lessons learned with key takeaways for secure coding.

Node.js Security Modules in the Book

Chapter 1

Mastering Security Foundations for Node.js Development

In this introduction chapter, Node.js developers delve into the core security concepts that lay the foundation for robust application development. Beyond the realms of coding, we explore the indispensable terminology embraced by security practitioners. You'll gain a profound understanding of pivotal standards such as CVE and CWE, unraveling the intricate relationship between them. We demystify the significance of OWASP Top 10, decode the role of NVD, and navigate the intricacies of source-to-sink, empowering you with the knowledge to architect applications resilient to a spectrum of attack vectors.

Chapter 2

Navigating Path Traversal Hazards in Node.js Applications

Embark on a journey through the intricacies of path traversal vulnerabilities in this chapter, where we unravel the reasons behind their prevalence in software. Going beyond the surface, we explore the nuanced impact of these vulnerabilities on Node.js applications and the software libraries residing in the expansive npm registry. As we dissect the anatomy of insecure code patterns, we equip Node.js developers with the tools to not only recognize but mitigate path traversal risks. By understanding the diverse classification employed by application security engineers, you'll emerge adept at fortifying your Node.js applications against the subtle yet potent threats of path traversal vulnerabilities. This chapter stands as a beacon, guiding developers toward secure coding practices in the dynamic landscape of Node.js development.

Chapter 3

Decoding Path Join: Navigating Security Pitfalls in Node.js

In this chapter, we unravel the intricacies of path traversal vulnerabilities, even for seasoned engineers crafting scalable systems and popular open-source libraries. We spotlight a seemingly innocuous coding convention, exposing the peril of concatenating user input for file names or paths into predefined directories. Through a critical examination of a popular npm library's insecure practices, particularly in the utilization of path.join(), we unveil the pathway to arbitrary file access and the emergence of path traversal vulnerabilities. Our exploration transcends the naive assumption that a requested file path, labeled as 'relativePath,' is always as innocent as it seems. By going into the behavior of path.join() through a matrix table of inputs and returned values, we empower Node.js developers to fortify their code against the subtle yet potent risks posed by path traversal vulnerabilities. This chapter serves as a practical guide, steering developers away from insecure coding practices and towards robust, secure coding patterns

Chapter 4

Unveiling Nuances: Beyond the ../ String in Node.js Path Traversal

Dive deep into the subtleties of path and directory traversal as we uncover its manifestations beyond the apparent ../ string in URLs. Our journey reveals a critical layer—URL strings encoded with percent-encoding. This chapter elucidates that the devil is in the details: insecure handling of file path resolution, characters decoding, becomes a breeding ground for path traversal attacks. Moreover, we scrutinize the deceptive assurances offered by functions like path.normalize() and other path and URL parsers, emphasizing their reluctance to evaluate and resolve percent-encoded URL strings. This nuanced exploration equips Node.js developers with the precision needed to fortify their applications against the intricacies of path traversal vulnerabilities, ensuring robust and secure coding practices.

Chapter 5

Mastering Security: Navigating Nuances Beyond Classic Path Traversal in Node.js

This chapter unfolds the invaluable lessons gained from the secure coding journey, highlighting the 'send' npm package's resilient track record since 2015. The focus extends to intricate aspects like adjacent file paths and the perils of insecure logic checks that fail to firmly bind a requested path to its root. This exploration is a beacon for Node.js developers, steering them through complexities that often elude standard security measures.

Chapter 6

Unveiling Vulnerabilities: The Anatomy of Simple Code's Impact on Security

In this chapter, we dissect the seemingly innocuous rush to quick implementations under tight deadlines, unraveling the security lesson that even the simplest code can harbor security vulnerabilities.

Chapter 7

Navigating the Maze: Path Traversal Vulnerabilities in HTTP server npm devtools

What do we find when dissecting multiple versions and commits that attempted to fix a directory traversal security bug? The GitHub issue, titled "Incorrect commits for CVE-2018-3713," serves as a comprehensive repository of these vulnerabilities, annotated with versions and commit links. A pivotal lesson surfaces from the analysis: even with a focus on sanitization logic and an acute awareness of handling traversal steps, developers can stumble on seemingly simple oversights. The chapter highlights a specific case where a code logic error, compounded by the CLI starting with no root directory configuration, enabled attackers to exploit arbitrary file access on the host.

Chapter 8

A Deep Dive into Security Oversights in a File Server npm devtool

In this chapter, we turn our attention to the less-traveled paths of security vulnerabilities within an npm package that, while not widely adopted, offers crucial insights into the intricacies of secure coding. The library's case study unfolds a narrative of developers being conscientious about security aspects and potential vulnerabilities, yet succumbing to programming errors tied to the very security controls implemented.

Chapter 9

Path Traversal Beyond Deny-lists and Operating System Support

The first takeaway, a clear wake up call to developers, underscores the inadequacy and peril of relying on deny-lists as security controls. Their ineffectiveness not only undermines the security posture but also engenders a false sense of protection. The chapter advocates for a strategic placement of deny-lists as the final layer in a comprehensive security architecture. The second revelation dives into the often-overlooked realm of cross-platform operating system compatibility. The vulnerability dissected in this library lays bare the genuine security implications tied to a seemingly innocuous concept—an operating system support matrix.

Chapter 10

Offensive Security: Automation, Exploitation, and Node.js Vigilance

Embark on a journey through the tactical landscape of offensive security tools as this chapter demystifies their role in automating the identification and exploitation of path traversal vulnerabilities. The reader gains practical insights by orchestrating an automated assault on a Node.js application, unraveling the intricacies of path traversal exploitation in real-time. The chapter transcends the application layer, diving into the vulnerabilities endemic to the Node.js runtime. It advocates for a proactive stance, emphasizing the indispensable need to keep the runtime updated as a bulwark against potential security breaches.

Chapter 11

Mastering the Craft: Secure Coding Strategies to Prevent Path Traversal in Node.js

Dive deep into the intricate realm of Node.js security as this chapter meticulously crafts a compendium of secure coding best practices tailored to fortify against the looming specter of path traversal attacks. Each attack vector is met with pragmatic advice, empowering developers to navigate the subtleties of secure coding. The chapter concludes with an exploration of the symbiotic relationship between secure coding practices and robust security testing, emphasizing their pivotal role in the prevention of path traversal vulnerabilities. By the chapter's conclusion, you'll not only be adept at secure coding practices but also equipped to conduct comprehensive code reviews, backed by the ability to address critical questions that transcend Node.js boundaries.

Sharpen your Node.js Coding Skills

Here is a classic Fastify application code. Can you find the security vulnerability in the code below?

Vulnerable Code

Toggle Hint
    import fs from "node:fs"
    import path from "node:path"
    import fastify from "fastify"

    fastify.get("/static", async (req, rep) => {
        const filename = req.query.filename
        const filePath = path.join(
            "/opt/app/uploads", filename)

        const fileContents = fs.readFileSync(filePath)
        rep.code(200).send(fileContents)
    });

    fastify.listen({ port: 3000 })

The Impact of Path Traversal Vulnerabilities

Uncover the true threat of Path Traversal vulnerabilities! Despite their seemingly minor nature, these vulnerabilities extend far beyond a simple HTTP request, posing a significant risk to your application and infrastructure. By granting unauthorized access to your server's file system, the consequences are more severe than meets the eye.

Shooting Stars

Guarding Secrets in Configuration Files: Protect your application's vital details, like database credentials and API keys, stored in files like .env. Leaking this info could jeopardize your app's security—master secure coding to shield sensitive data.

The Catalyzer

Dependency Vulnerability Threats: Uncover potential risks in your app's dependencies by understanding manifest files like package.jsonAttackers armed with this knowledge can exploit vulnerabilities in your dependencies, making secure coding crucial for defense.

The 400 Blows

Securing Private Keys: Safeguard critical keys, like SSH keys, stored on servers. Prevent unauthorized access, as a breach could grant attackers entry to other systems in your network. Learn secure coding to fortify your server defenses—buy the book now!

Liran Tal

Meet Liran Tal, the Author.

Security Analyst for the Node.js Foundation

In his role as a security analyst in the Node.js Foundation's Security Working Group, Liran reviewed hundreds of vulnerability reports for npm packages and established processes for responsible security disclosures and vulnerability triage 🏴‍☠️.

Education is a core practice

Passionate about educating developers on application security and secure coding practices, Liran is a world-wide international speaker, workshop instructor, and author of several books on the subject. He occasionally speaks on software security topics at academic institutions, such as presenting to students at the Electrical and Computer Engineering School at Purdue University 🎓.

Award-winning GitHub Star ⭐️

Liran received the GitHub Star recognition award from GitHub for his work educating and inspiring developers and actively advocating for web security.

Recipient of the Pathfinder for Security Award 🎖️

Honored by the OpenJS Foundation with the Pathfinder for Security Award, Liran is recognized for his work advancing Node.js security.

I'm a Security Researcher

An accomplished security researcher, Liran has disclosed security vulnerabilities in various open source software projects, including being credited with CVEs to his name for vulnerabilities in npm packages with millions of downloads.

Acclaimed Recognition at Black Hat

Liran's discovery in supply chain security research, including Lockfile Injection, was presented at the prestigious Black Hat Europe 2021 cybersecurity conference. Liran is also the creator of several developer security tooling projects such as npq, is-website-vulnerable, and snync, which help developers and enterprises defend against dependency confusion attacks.

About Liran Tal

Liran Tal is an accomplished software developer, respected security researcher, and prominent advocate for open source software in the JavaScript community. As an experienced author and educator, Liran has written several widely respected books on software security. These include "Serverless Security" published by O'Reilly, as well as the self-published titles "Essential Node.js Security" and "Web Security: Learning HTTP Security Headers". Liran's leadership in open source security includes significant contributions to OWASP projects, recording supply chain security incidents at the CNCF, and various OpenSSF initiatives. Currently, Liran is a developer advocate at Snyk where he empowers developers with the knowledge and tools needed to build and deploy secure software.

Leading Developers Love Node.js Secure Coding

Read testimonials and learn what the developer community has to say about the books and their recommendations to skill up on Node.js Secure Coding practices.

"I have finished reading Node.js Secure Coding from Liran Tal. I read the whole thing in an hour without realizing it. I learned and discovered a few things along the way. I laughed at the IFS, didn't see it coming."


Thomas Gentilhomme

Thomas Gentilhomme

Node.js lead at MyUnisoft, Node Security WG

"Liran Tal, your book on Node.js security is an absolute gem! The abundance of real-world examples with commented fixes is incredibly valuable. Your practical solutions have enlightened me, especially the discovery of the shell-quote module! Recommended to all Node.js developers!"


Manuel Spigolon

Manuel Spigolon

Senior Software Developer at NearForm

"I wholeheartedly enjoyed working and learning from Liran's expertise in securing applications. With extensive experience speaking at global conferences and actively contributing code to the community, he is a true authority in the field. I highly endorse both his enlightening book and engaging workshop, as they are invaluable resources for anyone looking to enhance their understanding and implementation of application security"


Yoni Goldberg

Yoni Goldberg

Software Architect, Node.js Specialist

"Liran Tal just published a new book about Node.js secure coding. It is worth taking a look at!"


Daniel Garcia

Daniel Garcia

Cybersecurity & API Security Consultant

"I highly recommend the new Node.js Secure Coding book published by Liran Tal. Covers not only Node.js but also gives you another perspective on how to achieve good and secure applications, especially with understanding and handling SAST vulnerabilities. Liran - CHAPEAU!"


Eli (Tom) Lelonek

Eli (Tom) Lelonek

Application Security Manager at Allot

"Got my copy of Node.js secure coding! I already know I'll learn a lot 🔥"


Marco Ippolito

Marco Ippolito

Node.js Collaborator & Developer Experience Engineer @NearForm

"A very interesting book that I recommend if you are in the Node.js world is "Node.js Secure Coding" by Liran Tal. Laid out with explanations, examples and tips. Warmly recommended."


Diego Betto

Diego Betto

Founder & Senior Fullstack Developer

"Read trough first 3 chapters last night, nice work Liran!"


Aranđel Šarenac

Aranđel Šarenac

12+ years developer, focusing on Identity Security

"Highly recommend Liran Tal's ebooks for any Node developers who are serious about security (which should be all of you!)"


Alicia Sykes

Alicia Sykes

Principal Engineer @AND Digital

"Started reading the Prevention and Exploitation of Path Traversal and I am very happy with the quality. It is connecting me to some knowledge I had from working in AV company and now with code, very interesting."


Yana Ifraimov

Yana Ifraimov

NOC Engineer @Skai

"Node.js security rock-star Liran Tal drops another book on how to ship safe Node.js applications. I know it's hard to tell sometimes where to start from when it comes to security, as the internet is flooded with content. Well, look no more - trust content composed by Liran"


Gal Weizman

Gal Weizman

Browser JS Application Security at MetaMask & LavaMoat

"It's not every day that you can pay less than $20 for years of security wisdom. Just got this and will be using the book during my streams to improve my code."


Ray Fernando

Ray Fernando

AI app at TruthTorch.ai, ex-Apple Engineer

"The amount of content covering advanced topics in Node.js is so little, makes this a must-read"


Ruan Martinelli

Ruan Martinelli

Product engineer, Full-stack Freelancer & Consultant

"Outstanding book, can't wait."


Tiger Abrodi

Tiger Abrodi

TypeScript fanatic

"I've followed Liran Tal's work for years and definitely one of the top experts in Node.js security! Give these a look as they are essential for anyone serious about securing their Node.js applications."


Zac Rosenbauer

Zac Rosenbauer

CTO & Co-founder at Joggr

"Just got my hands on your new book and I'm thoroughly impressed! It's clear that your passion for application security and deep understanding of Node.js shines through every page"


Zeal Chhasatiya

Zeal Chhasatiya

Security Analyst at Shared Services Canada

"If you're a developer looking to better understand security vulnerabilities, this is one of the best books out there on the topic. While this book specifically focuses on Command Injection vulnerabilities in Node, the content contained within is broadly applicable to any developers writing software. It's an A++ book and absolutely worth the time to read and analyze. Liran is a top-tier security researcher and developer who's an icon in the security space. Seriously, look him up on Google, he's amazing."


Randall Degges

Randall Degges

Head of Developer Relations & Community at Snyk

"Psyched to get my copy of Liran Tal's book: "Node.js Secure Coding: Defending Against Command Injection Vulnerabilities" Do yourself a favor and grab a copy!"


Micah Silverman

Micah Silverman

Director, DevSecOps Acceleration at Snyk

"I am just starting to read it now that I am doing security patching in Express. The book looks amazing! I mean... all the series is an amazing work, thanks a lot for investing the time to write them."


Ulises Gascón

Ulises Gascón

Express TSC & Node.js Collaborator

"On point content, short book just for my liking. I like the interesting facts in the middle and code examples are good. I like the approach of Risk -> Solution -> Implementation"


Sumit Kumar

Sumit Kumar

Full-Stack Engineer at Optmyzr

"This was targeted at a perfect level for me, as someone who had exposure to these topics, had done some fiddling with helmet previously in node, but this was a great succinct guide to quickly and effectively teach "what" and "why"."


Luke Rasmussen

Luke Rasmussen

Software Engineer

Test your Node.js Secure Coding skills

Is the code below vulnerable to a Path Traversal attack?

Vulnerable code... is it?


    const fastify = require('fastify')
    const path = require('path')

    const downloadsPath = '/opt/downloads'
    const app = fastify()

    app.get('/download', async (req, rep) => {
        const file = req.query.file || 'default.png'

        if (file.includes('..')) {
          return rep.code(400)
            .send('Directory Traversal Detected')
        }

        const normalizedFilename = path.normalize(file)
        const downloadFilepath = path.resolve(
            downloadsPath, 
            'downloads',
            normalizedFilename)

        try {
          await rep.sendFile(downloadFilepath)
        } catch (err) {
            rep.code(404).
                send('Requested File Not Found')
        }
    })
    

Frequently Asked Questions

Why is Path Traversal Relevant to Node.js Developers?

Path traversal vulnerabilities pose a significant threat to Node.js applications, allowing attackers to navigate and access sensitive files like .env or package.json. My book is tailored to Node.js developers, providing practical insights, real-world vulnerable code examples, and secure coding practices to fortify your applications against these potentially devastating attacks.

What Makes This Book Stand Out for Secure Coding Practices?

This book goes beyond conventional secure coding guides. It not only reveals the hidden impacts of path traversal vulnerabilities but also offers hands-on examples, expert insights, and a deep dive into Node.js security. By exploring real-world vulnerable npm packages and best practices, you'll gain a robust understanding of secure coding, making this book an essential resource for Node.js developers looking to elevate their skills.

How Will This Book Enhance My Node.js Security Knowledge?

This book provides a comprehensive exploration of path traversal vulnerabilities specific to Node.js, offering practical solutions and insights tailored to this environment. Whether you're a beginner or an experienced developer, you'll gain a deep understanding of Node.js security, enabling you to proactively identify and mitigate path traversal risks in your applications.

Is This Book Suitable for Developers at Different Skill Levels?

Absolutely! My book is designed to cater to a wide range of developers. From those new to Node.js security to seasoned professionals, the content is structured to accommodate various skill levels. With a mix of foundational concepts and advanced techniques, every reader can benefit from the actionable insights and secure coding practices shared throughout the book.

How Does This Book Address the Latest Security Challenges in Node.js?

This book is not just a static guide; it evolves with the Node.js security landscape and the secure coding practices specific to Node.js. This book's content reviews security vulnerabilities, attack vectors, and security best practices. With real-world examples and practical insights, you'll be equipped to tackle the dynamic challenges of securing Node.js applications effectively. Stay ahead in the ever-changing world of web security with this 2023 up-to-date educational resource.

Can I contact the author for additional help or questions?

Anytime! I'm always happy to help. Reach out to me here [liran at lirantal dot com].

Hands-On Node.js Security

Master secure coding in Node.js with real-world vulnerable dependencies and experience firsthand secure coding techniques to mitigate Path Traversal vulnerabilities