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
typescript/sendfile-injection@v1.0
Category
Common Weakness Enumeration (CWE) external icon

Noncompliant example

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

Compliant example

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