bitcoin CVE semgrep_id:bandit.B603:119:119
Improper neutralization of special elements used in an OS Command ('OS Command Injection')
Ссылка на строку:
https://dev.gitsec.ru/crypto/bitcoin/-/blob/master/contrib/verify-commits/verify-commits.py#L119
Описание уязвимости
Тип уязвимости: Improper neutralization of special elements used in an OS Command ('OS Command Injection')
Категория: SAST (Static Application Security Testing)
Описание: В Python существует множество механизмов для вызова внешних исполняемых файлов. Однако это может представлять угрозу безопасности, если не предпринимаются соответствующие меры для очистки вводимых пользователем или переменных данных. Эта уязвимость связана с запуском подпроцесса без использования командной оболочки, что не подвержено атакам с внедрением оболочки, но всё равно требует проверки входных данных на валидность.
Уровень серьёзности: Высокий
Исходная строка с уязвимостью
check_root_older_res = subprocess.run([GIT, "merge-base", "--is-ancestor", verified_root, current_commit])
Варианты исправления
-
Использование безопасных методов для работы с подпроцессами:
Убедитесь, что все входные данные проверены и безопасны перед их использованием в командах. Можно использовать методы, которые обеспечивают более строгий контроль над вводом данных.
subprocess.run([GIT, "merge-base", "--is-ancestor", verified_root, current_commit], check=True) -
Проверка входных данных:
Перед тем как передать переменные в команду, убедитесь, что они не содержат специальных символов или потенциально опасных данных.
if verified_root.isalnum() and current_commit.isalnum(): subprocess.run([GIT, "merge-base", "--is-ancestor", verified_root, current_commit], check=True) else: raise ValueError("Invalid input detected") -
Использование параметризованных запросов:
Если возможно, используйте параметризованные запросы для обеспечения безопасности.
subprocess.run([GIT, "merge-base", "--is-ancestor", f"{verified_root}", f"{current_commit}"], check=True)
Ссылки на статьи
- Semgrep documentation
- CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')
- OWASP A03:2021 - Injection
Описание:
Python possesses many mechanisms to invoke an external executable. However, doing so may present a security issue if appropriate care is not taken to sanitize any user provided or variable input. This plugin test is part of a family of tests built to check for process spawning and warn appropriately. Specifically, this test looks for the spawning of a subprocess without the use of a command shell. This type of subprocess invocation is not vulnerable to shell injection attacks, but care should still be taken to ensure validity of input.Исходный JSON:
{
"id": "5a0e5014db50dcb9866f0e5256a13f14bc1febd90f7f5f68db59e359c1743e9f",
"category": "sast",
"name": "Improper neutralization of special elements used in an OS Command ('OS Command Injection')",
"description": "Python possesses many mechanisms to invoke an external executable. However,\ndoing so may present a security issue if appropriate care is not taken to\nsanitize any user provided or variable input. This plugin test is part of a\nfamily of tests built to check for process spawning and warn appropriately.\nSpecifically, this test looks for the spawning of a subprocess without the\nuse of a command shell. This type of subprocess invocation is not\nvulnerable to shell injection attacks, but care should still be taken to\nensure validity of input.\n",
"cve": "semgrep_id:bandit.B603:119:119",
"severity": "High",
"scanner": {
"id": "semgrep",
"name": "Semgrep"
},
"location": {
"file": "repo/contrib/verify-commits/verify-commits.py",
"start_line": 119
},
"identifiers": [
{
"type": "semgrep_id",
"name": "bandit.B603",
"value": "bandit.B603",
"url": "https://semgrep.dev/r/gitlab.bandit.B603"
},
{
"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"
},
{
"type": "bandit_test_id",
"name": "Bandit Test ID B603",
"value": "B603"
}
]
}
```