Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Code Block
bgColor#ccccff

/*
 * Make sure that the ~/chroot/jail directory exists within the  current working directory 
 *  Also assign appropriate permissions to the directory to restrict access
 *  Close all filesystem descriptors to outside resources lest they escape the jail
 */

 if (setuid(0) == -1)       
{
   /* Report that setuid failed and note the errno value */
 }

 if (chroot("/chroot/jail") == -1) {   /* Operation failed, handle error */  }

 if (chdir("/") == -1) {   /* Operation failed, handle error */   }

 /* Drop privileges permanently to those of the file owner */ 

 if (setuid(getuid()) == -1)  {   /* Operation failed, handle error */   }

 /* Perform unprivileged operations */

 FILE* fp = fopen(argv[1], "w");

The chdir() system call may be susceptible to a race condition if called before chroot(). This is because an attacker with sufficient privileges can delete the 'jail' directory so that the chdir() operation fails and then recreate it so that chroot() succeeds. Consequently, the program will not start in its sandboxed environment (~/chroot/jail) and will have its current working directory not set to ~/chroot/jail. One mitigation strategy is to incorporate error checking to detect if chdir() failed. A more fool proof method is to use chdir() after chroot() so that it guarantees that the current working directory will be set to the chroot'ed directory, that is the new root.

...