I have a node.js webapp in which I need to concatenate two paths in a safe way. The first one (leftmost) is a constant, and the second one (rightmost) is relative to the first one and comes from untrusted user input. The resulting path should be something that is below the first path. So the situation is this:
path1 = "public/html"; // Hardcoded path.
path2 = req.query.path; // Untrusted user input.
result = safePathJoin(path1, path2); // Result can be e.g. public/html/index.htm,
// but never private/config.xml
What I need is the function safePathJoin()
that is safe against directory traversal attacks. My first naive approach is this:
safePathJoin = function(path1, path2) {
path1 = path.normalize(path1);
var result = path.join(path1, path2);
return result.startsWith(path1) ? result : undefined;
}
Is this good enough? Is there a standard way to do this? Any suggestions?