Rule Definition
The function 'realpath()' is considered as very risky and must not be used since it is not possible to specify correctly the size for the output buffer. Using PATH_MAX constant or 'pathconf()' function may also lead to troubles because PATH_MAX can be undefined and, according to POSIX, 'pathconf()' can be too large to be used to allocate memory correctly and can return -1 if PATH_MAX is not bounded.
Remediation
Try to avoid using the 'realpath()' function. If it is not possible, then protect the code against buffer overflow and check if the possible max path size is compliant with the MAX_PATH constant.
Violation Code Sample
int main(int argc, char *argv[])
{
char *relat_path = argv[1];
char exp_path [strlen(relat_path)];
char *exp_path_ptr;
exp_path_ptr = realpath(relat_path, exp_path);
return 1;
}
Fixed Code Sample
int main(int argc, char *argv[])
{
char *relat_path = argv[1];
char exp_path [PATH_MAX];
char *exp_path_ptr;
exp_path_ptr = realpath(relat_path, exp_path);
return 1;
}
Reference
Build Security In (https://buildsecurityin.us-cert.gov/bsi/articles/knowledge/coding)
Related Technologies
C++
Technical Criterion
Secure Coding - API Abuse
About CAST Appmarq
CAST Appmarq is by far the biggest repository of data about real IT systems. It's built on thousands of analyzed applications, made of 35 different technologies, by over 300 business organizations across major verticals. It provides IT Leaders with factual key analytics to let them know if their applications are on track.