wg-easy CVE semgrep_id:javascript_exec_rule-child-process:22:22
Improper neutralization of special elements used in an OS command ('OS Command Injection')
Описание уязвимости
Название: Improper neutralization of special elements used in an OS command ('OS Command Injection')
Категория: SAST (Static Application Security Testing)
Описание: Уязвимость заключается в возможности внедрения команд операционной системы через пользовательский ввод. Это может привести к полному компрометации системы, позволяя злоумышленнику выполнять произвольные команды или аргументы.
Серьёзность: Высокая
Исправление уязвимости
-
Использование жёстко заданных аргументов: Убедитесь, что приложение использует заранее определённый набор аргументов для передачи в системные команды, а не пользовательский ввод.
Пример кода:
const child_process = require('child_process'); const fs = require('fs'); const crypto = require('node:crypto'); const { mkdtempSync } = require('node:fs'); function executeCommand(userFileData) { const fileDir = mkdtempSync('/tmp/tmpdir-'); const filePath = fileDir + path.sep + crypto.randomUUID(); fs.writeFileSync(filePath, userFileData); child_process.exec(`/bin/cat ${filePath}`, (error, stdout, stderr) => { fs.rmSync(fileDir, { recursive: true, force: true }); if (error) { console.error(`exec error: ${error}`); return; } console.log(`stdout: ${stdout}`); console.error(`stderr: ${stderr}`); }); }
-
Использование нативной библиотеки: Вместо использования системных команд рекомендуется использовать нативную библиотеку, которая реализует ту же функциональность.
-
Указание полного пути к команде: При указании команды ОС убедитесь, что приложение использует полный путь к исполняемому файлу, чтобы избежать уязвимостей, связанных с ненадёжными путями поиска.
Ссылка на статью
Для более подробной информации о внедрении команд ОС см. руководство OWASP: OS Command Injection Defense Cheat Sheet
Расположение уязвимости
Файл: repo/src/server/utils/cmd.ts Строка: 22
Идентификаторы уязвимости
- Semgrep ID: javascript_exec_rule-child-process
- CWE: 78 (CWE-78)
- OWASP: A03:2021 - Injection
- OWASP: A1:2017 - Injection
Описание:
OS command injection is a critical vulnerability that can lead to a full system compromise as it may allow an adversary to pass in arbitrary commands or arguments to be executed.User input should never be used in constructing commands or command arguments to functions which execute OS commands. This includes filenames supplied by user uploads or downloads.
Ensure your application does not:
- Use user-supplied information in the process name to execute.
- Use user-supplied information in an OS command execution function which does not escape shell meta-characters.
- Use user-supplied information in arguments to OS commands.
The application should have a hardcoded set of arguments that are to be passed to OS commands. If filenames are being passed to these functions, it is recommended that a hash of the filename be used instead, or some other unique identifier. It is strongly recommended that a native library that implements the same functionality be used instead of using OS system commands, due to the risk of unknown attacks against third-party commands.
When specifying the OS command, ensure the application uses the full path information, otherwise the OS may attempt to look up which process to execute and could be vulnerable to untrusted search path vulnerabilities (CWE-426).
Example of safely executing an OS command:
const child_process = require('child_process');
const fs = require('fs');
const crypto = require('node:crypto');
const { mkdtempSync } = require('node:fs');
function executeCommand(userFileData) {
// Create a temporary directory, preferably in an application directory
// that only the application has access to.
const fileDir = mkdtempSync('/tmp/tmpdir-');
// Generate a random filename, do not use user input
const filePath = fileDir + path.sep + crypto.randomUUID();
// Write the user-supplied data to the temporary file.
fs.writeFileSync(filePath, userFileData);
// Execute a program with a hardcoded path to the binary
child_process.exec(`/bin/cat ${filePath}`, (error, stdout, stderr) => {
// Delete the temporary directory and file if no longer needed
fs.rmSync(fileDir, { recursive: true, force: true });
if (error) {
console.error(`exec error: ${error}`);
return;
}
console.log(`stdout: ${stdout}`);
console.error(`stderr: ${stderr}`);
});
}
For more information on OS command injection, see OWASP's guide: https://cheatsheetseries.owasp.org/cheatsheets/OS_Command_Injection_Defense_Cheat_Sheet.html
Detected non-literal calls to child_process.exec(). This could lead to a command injection vulnerability.
Исходный JSON:
{
"id": "fa645411e598b8d25b6b97675a3d18e4b43d85e2c16cf909600ee24640665bf5",
"category": "sast",
"name": "Improper neutralization of special elements used in an OS command ('OS Command Injection')",
"description": "OS command injection is a critical vulnerability that can lead to a full system\ncompromise as it may allow an adversary to pass in arbitrary commands or arguments\nto be executed.\n\nUser input should never be used in constructing commands or command arguments\nto functions which execute OS commands. This includes filenames supplied by\nuser uploads or downloads.\n\nEnsure your application does not:\n\n- Use user-supplied information in the process name to execute.\n- Use user-supplied information in an OS command execution function which does\nnot escape shell meta-characters.\n- Use user-supplied information in arguments to OS commands.\n\nThe application should have a hardcoded set of arguments that are to be passed\nto OS commands. If filenames are being passed to these functions, it is\nrecommended that a hash of the filename be used instead, or some other unique\nidentifier. It is strongly recommended that a native library that implements\nthe same functionality be used instead of using OS system commands, due to the\nrisk of unknown attacks against third-party commands.\n\nWhen specifying the OS command, ensure the application uses the full path\ninformation, otherwise the OS may attempt to look up which process to execute\nand could be vulnerable to untrusted search path vulnerabilities (CWE-426).\n\nExample of safely executing an OS command:\n```\nconst child_process = require('child_process');\nconst fs = require('fs');\nconst crypto = require('node:crypto');\nconst { mkdtempSync } = require('node:fs');\n\nfunction executeCommand(userFileData) {\n // Create a temporary directory, preferably in an application directory\n // that only the application has access to.\n const fileDir = mkdtempSync('/tmp/tmpdir-');\n // Generate a random filename, do not use user input\n const filePath = fileDir + path.sep + crypto.randomUUID();\n // Write the user-supplied data to the temporary file.\n fs.writeFileSync(filePath, userFileData);\n // Execute a program with a hardcoded path to the binary\n child_process.exec(`/bin/cat ${filePath}`, (error, stdout, stderr) => {\n // Delete the temporary directory and file if no longer needed\n fs.rmSync(fileDir, { recursive: true, force: true });\n if (error) {\n console.error(`exec error: ${error}`);\n return;\n }\n console.log(`stdout: ${stdout}`);\n console.error(`stderr: ${stderr}`);\n });\n}\n```\n\nFor more information on OS command injection, see OWASP's guide:\nhttps://cheatsheetseries.owasp.org/cheatsheets/OS_Command_Injection_Defense_Cheat_Sheet.html\n\nDetected non-literal calls to child_process.exec(). This could lead to a command\ninjection vulnerability.\n",
"cve": "semgrep_id:javascript_exec_rule-child-process:22:22",
"severity": "High",
"scanner": {
"id": "semgrep",
"name": "Semgrep"
},
"location": {
"file": "repo/src/server/utils/cmd.ts",
"start_line": 22
},
"identifiers": [
{
"type": "semgrep_id",
"name": "javascript_exec_rule-child-process",
"value": "javascript_exec_rule-child-process"
},
{
"type": "cwe",
"name": "CWE-78",
"value": "78",
"url": "https://cwe.mitre.org/data/definitions/78.html"
},
{
"type": "owasp",
"name": "A03:2021 - Injection",
"value": "A03:2021"
},
{
"type": "owasp",
"name": "A1:2017 - Injection",
"value": "A1:2017"
}
]
}
```