Creating file paths from untrusted input could allow a malicious actor to access arbitrary files on a disk by manipulating the file name in the path.
1var express = require('express')
2var app = express()
3var path = require('path')
4function pathTraversalNoncompliant() {
5 app.get('/products', (req, res) => {
6 const basePath = '/data/product/images/'
7 // Noncompliant: user-supplied path is not sanitized and could contain malicious characters.
8 var targetPath = path.join(basePath, req.query.path)
9 retrieveProduct(targetPath)
10 res.send('Here is your requested product!')
11 })
12}
1var express = require('express')
2var app = express()
3var path = require('path')
4function pathTraversalCompliant() {
5 app.get('/products', (req, res) => {
6 const basePath = '/data/product/images/'
7 // Compliant: user-supplied relative-path is sanitized.
8 const queryPath = sanitizer(req.query.path)
9 if(queryPath) {
10 const targetPath = path.join(basePath, queryPath)
11 retrieveProduct(targetPath)
12 res.send('Here is your requested product!')
13 }
14 else
15 res.send('Invalid product!')
16 })
17}
18function sanitizer(path) {
19 return path.match(/^[a-z]+$/) ? path : null
20}