ton CVE semgrep_id:flawfinder.realpath-1:48:48
Function does not ensure destination buffer length is sufficient before copying
Описание уязвимости
Уязвимость связана с использованием функции realpath, которая может привести к переполнению буфера, если длина пути превышает заданный размер буфера.
Причина уязвимости
В представленном коде функция realpath используется с потенциально недостаточным буфером для хранения результата, что может привести к переполнению и уязвимости типа buffer overflow.
Варианты исправления
Чтобы устранить уязвимость, следует вызывать realpath с NULL в качестве второго аргумента. В этом случае функция выделит буфер самостоятельно, а результат будет возвращён в виде указателя. После использования возвращённого указателя его необходимо освободить с помощью free.
Пример исправленного кода:
char const *symlink_path = "/tmp/symlink";
char *resolved_path = NULL;
resolved_path = realpath(symlink_path, NULL);
if (resolved_path != NULL) {
// ... использование resolved_path ...
free(resolved_path);
} else {
// Обработка ошибки
}
Ссылки на дополнительную информацию
- Документация по функции
realpath - CWE-120: Buffer Copy without Checking Size of Input (‘Classic Buffer Overflow’)
Issue в GitLab
# Уязвимость: функция не проверяет достаточность длины буфера перед копированием (CWE-120)
## Описание
В файле `repo/tdutils/td/utils/FileLog.cpp` на строке 48 обнаружено использование функции `realpath` с потенциально недостаточным буфером, что может привести к переполнению буфера.
## Причина
Функция `realpath` вызывается без должной проверки размера буфера, что создаёт риск переполнения.
## Предложение по исправлению
Использовать `realpath` с `NULL` в качестве второго аргумента и управлять памятью вручную:
```cpp
char const *symlink_path = "/tmp/symlink";
char *resolved_path = NULL;
resolved_path = realpath(symlink_path, NULL);
if (resolved_path != NULL) {
// ... использование resolved_path ...
free(resolved_path);
} else {
// Обработка ошибки
}
Ссылки
<hr><details><summary>Описание: </summary>The `realpath` function should not be called with a destination buffer as it could
lead to overflowing if the path is greater than PATH_LEN. It is instead recommended
to call `realpath` with the destination buffer set to NULL and use the return value
as the resolved path. Be sure to free the returned pointer as realpath will allocate
the buffer internally using `malloc`.
For more information see: https://linux.die.net/man/3/realpath
Example:
char const *symlink_path = "/tmp/symlink"; char *resolved_path = NULL;
resolved_path = realpath(symlink_path, NULL); if (errno == 0) { // ... use resolved_path... free(resolved_path); }
</details><details><summary>Исходный JSON: </summary><pre><code lang='json'>{
"id": "b152b2c12e5ae0b370a93b424b249976aabc1d5cef28b00b4f47d10562aee10e",
"category": "sast",
"name": "Function does not ensure destination buffer length is sufficient before copying",
"description": "The `realpath` function should not be called with a destination buffer as it could\nlead to overflowing if the path is greater than PATH_LEN. It is instead recommended\nto call `realpath` with the destination buffer set to NULL and use the return value\nas the resolved path. Be sure to free the returned pointer as realpath will allocate\nthe buffer internally using `malloc`.\n\nFor more information see: https://linux.die.net/man/3/realpath\n\nExample:\n\n```\nchar const *symlink_path = \"/tmp/symlink\";\nchar *resolved_path = NULL;\n\nresolved_path = realpath(symlink_path, NULL);\nif (errno == 0) {\n // ... use resolved_path...\n free(resolved_path);\n}\n```\n",
"cve": "semgrep_id:flawfinder.realpath-1:48:48",
"severity": "High",
"scanner": {
"id": "semgrep",
"name": "Semgrep"
},
"location": {
"file": "repo/tdutils/td/utils/FileLog.cpp",
"start_line": 48
},
"identifiers": [
{
"type": "semgrep_id",
"name": "flawfinder.realpath-1",
"value": "flawfinder.realpath-1"
},
{
"type": "cwe",
"name": "CWE-120",
"value": "120",
"url": "https://cwe.mitre.org/data/definitions/120.html"
},
{
"type": "owasp",
"name": "A03:2021 - Injection",
"value": "A03:2021"
},
{
"type": "owasp",
"name": "A1:2017 - Injection",
"value": "A1:2017"
},
{
"type": "flawfinder_func_name",
"name": "Flawfinder - realpath",
"value": "realpath"
}
]
}
```</code></pre></details>
/severity high