Using chroot( )

You can enhance the security of your programs by using the chroot( ) system call. The chroot( ) call changes the root directory of a process to a specified subdirectory within your filesystem. This change essentially gives the calling process a private world from which it cannot escape.[252] Several widely-used network daemons, such as the BIND nameserver, are written so they can run in a chroot( ) environment.

For example, if you have a program that only needs to listen to the network and write into a log file that is stored in the directory /usr/local/logs, then you could execute the following code to restrict the program to that directory:

assert(chdir("/usr/local/logs") == 0);
assert(chroot("/usr/local/logs") == 0);
assert(chdir("/") == 0);

There are several issues that you must be aware of when using the chroot( ) system call that are not immediately obvious:

  1. It is imperative that you successfully chdir( ) into the chroot area before doing anything important (and best if you chdir( ) there before you call chroot( )). chroot( ) does not change the working directory, and a privileged program can break out of a chroot area if its working directory is outside the area.

  2. With some systems, it is also critical that you set the current working directory to be “/” after the chdir is executed. Otherwise, it is possible to break out of the chroot( ) system in some cases.

  3. If your operating system supports shared libraries and you are able to statically link your program, you ...

Get Practical UNIX and Internet Security, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.