The purpose of changing the current working directory is to modify the base path when the process performs relative path resolutions. When the
working directory cannot be changed, the process keeps the directory previously defined as the active working directory. Thus, verifying the success
of chdir() type of functions is important to prevent unintended relative paths and unauthorized access.
Ask Yourself Whether
- The success of changing the working directory is relevant for the application.
- Changing the working directory is required by chroot to make the new root effective.
- Subsequent disk operations are using relative paths.
There is a risk if you answered yes to any of those questions.
Recommended Secure Coding Practices
After changing the current working directory verify the success of the operation and handle errors.
Sensitive Code Example
The chdir
operation could fail and the process still has access to unauthorized resources. The return code should be verified:
const char* any_dir = "/any/";
chdir(any_dir); // Sensitive: missing check of the return value
int fd = open(any_dir, O_RDONLY | O_DIRECTORY);
fchdir(fd); // Sensitive: missing check of the return value
Compliant Solution
Verify the return code of chdir
and handle errors:
const char* root_dir = "/jail/";
if (chdir(root_dir) == -1) {
exit(-1);
} // Compliant
int fd = open(any_dir, O_RDONLY | O_DIRECTORY);
if(fchdir(fd) == -1) {
exit(-1);
} // Compliant
See