Insecure Use Of Chroot High

Your code uses chroot function insecurely, risking security vulnerabilities. Ensure secure directory paths, proper error handling, and permissions to prevent unauthorized access. Review and enhance code for safer chroot usage.

Detector ID
c/insecure-use-of-chroot@v1.0
Category
Common Weakness Enumeration (CWE) external icon
Tags
-

Noncompliant example

1#include <stdlib.h>
2#include <unistd.h>
3#include <stdio.h>
4
5void insecureUseofChrootNoncompliant(){
6
7    const char* root_dir = "/jail/";
8    // Noncompliant: No chdir before or after chroot, and missing check of return value
9    chroot(root_dir); 
10}

Compliant example

1#include <stdio.h>
2void insecureUseofChrootCompliant(){
3
4    const char* root_dir = "/jail/";
5
6    if(chdir(root_dir) == -1) {
7      exit(-1);
8    }
9    // Compliant: the current dir is changed to the jail and the results of both functions are checked
10    if(chroot(root_dir) == -1) {  
11      exit(-1);
12    }
13
14}