Sendfile injection High

User-provided inputs must be sanitized before being passed to res.sendFile. Otherwise an attacker could arbitrarily read files on the system through path traversal.

Detector ID
javascript/sendfile-injection@v1.0
Category
Common Weakness Enumeration (CWE) external icon

Noncompliant example

1var express = require("express")
2var path = require("path")
3var app = express()
4function sendfileInjectionNoncompliant() {
5    app.get('www.example.com', (req, res) => {
6        var fileName = req.params.file
7        // Noncompliant: tainted-data is passed into 'res.sendfile'.
8        res.sendFile(fileName)
9    })
10}

Compliant example

1var express = require("express")
2var path = require("path")
3var app = express()
4function sendfileInjectionCompliant() {
5    app.get('www.example.com', (req, res) => {
6        var fileName = "file.txt"
7        if (fileName !== req.params.file) {
8            // Compliant: validated fileName before passing into 'res.sendFile'.
9            res.sendFile(fileName)
10            console.log("Valid file name.")
11        } else {
12            throw new Error("Invalid file name.")
13        }
14    })
15}