Unnecessary use ofcat process¶
ID: js/unnecessary-use-of-catKind: problemSecurity severity: 6.3Severity: errorPrecision: highTags: - correctness - security - maintainability - external/cwe/cwe-078Query suites: - javascript-code-scanning.qls - javascript-security-extended.qls - javascript-security-and-quality.qls
Click to see the query in the CodeQL repository
Using the unix commandcat only to read a file is an unnecessarily complex way to achieve something that can be done in a simpler and safer manner using the Node.jsfs.readFile API.
The use ofcat for simple file reads leads to code that is unportable, inefficient, complex, and can lead to subtle bugs or even security vulnerabilities.
Recommendation¶
Usefs.readFile orfs.readFileSync to read files from the file system.
Example¶
The following example shows code that reads a file usingcat:
varchild_process=require('child_process');module.exports=function(name){returnchild_process.execSync("cat "+name).toString();};
The code in the example will break if the inputname contains special characters (including space). Additionally, it does not work on Windows and if the input is user-controlled, a command injection attack can happen.
Thefs.readFile API should be used to avoid these potential issues:
varfs=require('fs');module.exports=function(name){returnfs.readFileSync(name).toString();};
References¶
OWASP:Command Injection.
Node.js:File System API.
Common Weakness Enumeration:CWE-78.