vladimirkrstulja:guides:microjails

A "micro jail" Example

The following example creates and runs an nginx “micro jail”, a service jail, which is a jail containing only the files and paths that are required for the jail to perform its function, in this case running an instance of nginx. In essence, it bootstraps the jail with basic required directories like /dev and /var/run, and most importantly copies from the host system libc and ld-elf shared libs, as well as any other may be required for the program inside the jail to run.

This can be expanded with making the root readonly and mounting from the host any read-write paths, for example /var/log/nginx for nginx, for better security.

If the service in the jail requires syslog (eg. Postfix only logs through syslog), a listening socket can be created in the jail, from the host's syslogd(8), by using -l (lowercase L) for syslogd_flags. The flag can be added more than once, so the host's syslogd can listen in multiple jails.

syslogd_flags = "-s -l /path/to/the/jail/root/var/run/log"
#!/bin/sh
 
ROOT="/path/to/the/jail/root"
 
bootstrap() {
	mkdir -p ${ROOT}/dev
	mkdir -p ${ROOT}/etc
	mkdir -p ${ROOT}/lib
	mkdir -p ${ROOT}/libexec
	mkdir -p ${ROOT}/sbin
	mkdir -p ${ROOT}/var/run
 
	# Temporarily hardcoded here for this example, use ldd to automatically find needed base libs
	cp /lib/libthr.so.3 ${ROOT}/lib/
	cp /lib/libcrypt.so.5 ${ROOT}/lib/
	cp /lib/libz.so.6 ${ROOT}/lib/
	cp /lib/libc.so.7 ${ROOT}/lib/
	cp /libexec/ld-elf.so.1 ${ROOT}/libexec/
 
	# At minimum the root user is needed, assuming pkg will install whatever additional user is required
	echo "root:*:0:0::0:0:Charlie &:/root:/bin/csh" > ${ROOT}/etc/master.passwd
	echo "wheel:*:0:root" > ${ROOT}/etc/group
	pwd_mkdb -d ${ROOT}/etc -p /${ROOT}/etc/master.passwd
}
 
install_pkg() {
	pkg -r ${ROOT} install -y nginx
}
 
configure() {
	mkdir -p ${ROOT}/usr/local/www/nginx/
 
	cp ${ROOT}/usr/local/etc/nginx/nginx.conf-dist ${ROOT}/usr/local/etc/nginx/nginx.conf
	cp ${ROOT}/usr/local/etc/nginx/mime.types-dist ${ROOT}/usr/local/etc/nginx/mime.types
	cp ${ROOT}/usr/local/www/nginx-dist/index.html ${ROOT}/usr/local/www/nginx/
 
	ldconfig -f ${ROOT}/var/run/ld-elf.so.hints /usr/local/lib
}
 
run() {
	jail \
		-c path=${ROOT} \
		mount.devfs \
		securelevel=3 \
		host.hostname=nginx \
		ip4=inherit \
		exec.jail_user=www \
		command=/usr/local/sbin/nginx
}
 
bootstrap
install_pkg
configure
run
  • vladimirkrstulja/guides/microjails.txt
  • Last modified: 2017/09/25 14:55
  • by VladimirKrstulja