2.13. Restricting Filesystem and Network Access on FreeBSD

Problem

Your program runs primarily (if not exclusively) on FreeBSD, and you want to impose restrictions on your program’s filesystem and network capabilities that are above and beyond what chroot( ) can do. (See Recipe 2.12.)

Solution

FreeBSD implements a system call known as jail( ) , which will “imprison” a process and its descendants. It does all that chroot( ) does and more.

Discussion

Ordinarily, a jail is constructed on FreeBSD by the system administrator using the jail program, which is essentially a wrapper around the jail( ) system call. (Discounting comments and blank lines, the code is a mere 35 lines.) However, it is possible to use the jail( ) system call in your own programs.

The FreeBSD jail does everything that chroot( ) does, and then some. It restricts much of the superuser’s normal abilities, and it restricts the IP address that programs running inside the jail may use.

Creating a jail is as simple as filling in a data structure with the appropriate information and calling jail( ). The same caveats that apply to chroot( ) also apply to jail( ) because jail( ) calls chroot( ) internally. In particular, only the superuser may create a jail successfully.

Presently, the jail configuration structure contains only four fields: version, path, hostname, and ip_number. The version field must be set to 0, and the path field is treated the same as chroot( )’s argument is. The hostname field sets the hostname of the ...

Get Secure Programming Cookbook for C and C++ 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.