SV.TAINTED.PATH_TRAVERSALUnvalidated input in path constructionIf a program uses external input to construct a pathname without special character neutralization, it can be left open to a path traversal attack. This checker reports defects when external strings that are used as parts of file paths are not checked properly. Vulnerability and riskA path traversal attack aims to get access to arbitrary files and directories including critical system or application data. A path traversal attack can also be used to provide malicious configuration for a program. It has been ranked as #13 in the Top 25 Most Dangerous Programming Errors. Mitigation and preventionTo avoid this issue, it's best to add validation code before raw input is used as a pathname. The validation code must contain checks for the following cases:
Vulnerable code example1 main.c 2 #include <stdio.h> 3 int main(int argc, char **argv) { 4 char *name = argv[1]; 5 FILE *user_config = fopen(name, "r"); 6 if (user_config == NULL) { 7 return 1; 8 } 9 fclose(user_config); 10 return 0; 11 } Klocwork reports a defect in this example because the "name" string is received through the "argv" argument and is used as a pathname without being validated. Fixed code example1 check.h 2 char* neutralize(char *); 3 main.c 4 #include <stdio.h> 5 #include "check.h" 6 int main(int argc, char **argv) { 7 char *name = argv[1]; 8 name = neutralize(name); 9 FILE *user_config = fopen(name, "r"); 10 if (user_config == NULL) { 11 return 1; 12 } 13 fclose(user_config); 14 return 0; 15 } 16 17 check.kb 18 neutralize - TSCheckPT 1 : $1 : 1 Klocwork will not report a defect in this example because the external input is passed to the "neutralize" function and is validated, making the path safe. ExtensionThis checker can be extended through the Klocwork knowledge base. See Tuning C/C++ analysis and C/C++ knowledge base reference for more information. Related checkers |