#!/bin/bash

# Build a chroot environment under AUFS
#
# Table of Contents
# 
#  1. Introduction
#  2. The inspiration or the first contact
#  3. The operation system and mount point structure
#  4. Start a GNOME Desktop session under AUFS chroot environment
#  5. Quit the GNOME Desktop session from the AUFS chroot environment
#  6. Restart the GNOME Desktop session in the non chroot environment
#  7. Unmount all parts of the AUFS chroot environment
#  8. Cleaning the directory /tmp
#  9. What to do if umount aborts with an error message?
# 10. The code of the script bldchraufs
#
#
#  1. Introduction
#
# This script builds a chroot environment with the aid of the AUFS (Another
# Union File System).
#
# It builds a directory structure of unions under the directory /tmp/jail.
# Every union in the directory /tmp/jail is a combination of two branches.
# The first branch is a writable directory and the second branch is a read
# only directory. The read only directory represents one of the directories
# of the running system. The read only directories are aliases of the system
# directories. The aliases are made with the mount -o bind command. The
# writable branches of every union are the container for the writes in the
# read only branches.
#
# The goal of this union is a chroot environment of the running system. In the
# built chroot environment the user can do what he want without damaging the
# running system. Changes on the stored data will go into the writable
# branches of the unions. The following hints are examples of the abilities
# the user has, if he use the chroot environment under AUFS:
#
#   1. Trying unknown programs and have a look what they do.
#   2. Run programs with different options and analysis the reaction.
#   3. Change configurations of the running system.
#   4. Install new program packages on the system.
#   5. Upgrade the whole system with new packages from the distributor.
#   6. Let other user play with the system.
#   7. Compile programs and build packages that needs many depended
#      packages for the build process.
#   8. Run the favorite desktop session in the chroot environment.
#
# After leaving the chroot environment the user can have a look into the wri-
# table branches of the unions. Created files can be copied from the temporary
# chroot directories in one of the system or home directories. This step should
# be done before the next reboot of the system, because all data under the di-
# rectory /tmp are really temporary. During the next reboot the boot process
# will clean up the directory /tmp.
#
#
#  2. The inspiration or the first contact
#
# The following script is based on Mr. J. R. Okajima example script auroot. The
# script auroot is stored in the Debian package aufs-tools version 20100601-1
# under the directory /usr/share/doc/auf-tools/examples/auroot. A version of
# the current script should be found under the following Internet address:
#
#                           http://aufs.sf.net
#
#
#  3. The operation system and mount point structure
#
# The script was tested under the following operation system and is based
# on the following mount point structure:
#
#    1. The Linux distribution and operation system specifications:
#
#       - Debian version:  Debian GNU/Linux testing "Squeeze"
#                          Official Snapshot amd64 DVD Binary-1 to 7
#                          20100531-04:18
#       - Kernel version:  Linux version 2.6.32-3-amd64
#                          (Debian 2.6.32-9)
#                          (maks@debian.org)
#                          (gcc version 4.3.4)
#                          #1 SMP Wed Feb 24 18:07:42 UTC 2010
#       - Desktop:         GNOME 2.30.0, 2010-04-26
#       - Interpreter:     GNU Bourne-Again SHell 4.1.5(1)-release
#
#    2. The mount point structure:
#
#       Directory                    Device
#       ------------------------------------------------------------
#       /                            /dev/sda5
#       /boot                        /dev/sda1
#       /home                        /dev/sda6
#       /opt                         /dev/sda7
#       /tmp                         /dev/sda8
#       /usr                         /dev/sda9
#       /usr/local                   /dev/sda10
#       /var                         /dev/sda11
#       /srv                         /dev/sda12
#       /lib/init/rw                 tmpfs
#       /proc                        proc
#       /sys                         sysfs
#       /dev                         udev
#       /dev/shm                     tmpfs
#       /dev/pts                     devpts
#       /sys/fs/fuse/connection      fusectl
#       /proc/sys/fs/binfmt_misc     binfmt_misc
#
# The script runs only with the above printed mount point structure. User
# with an other mount point layout on there machine must adapt the script.
# This task shouldn't be a great thing, because the script is very simple.
#
#
#  4. Start a GNOME Desktop session under AUFS chroot environment
#
# The following steps shows how to create a chroot environment under AUFS and
# how to start a GNOME Desktop session in the newly created chroot environment:
#
#    1. Log out from a running GNOME Desktop session. Select the menu entry
#       "Log Out <user name> ..." from the desktop menu entry "System" to log
#       out from the running session. The GNOME Desktop log in screen pops up.
#
#    2. Switch with the following key combination from the graphical log in
#       screen into the text console log in screen of the first console:
#
#                           [CTRL]+[ALT]+[F1]
#
#    3. Log in as normal user. A log in as user root is not necessary, but
#       the normal user must have access rights for system commands with
#       the command sudo. Without the proper access rights the user can't
#       execute the following steps.
#
#    4. Stop the running GNOME Desktop manager gdm with following command:
#
#       $> sudo invoke-rc.d gdm stop
#
#    5. Check the result of the above step with the following key combi-
#       nation:
#
#                           [ALT]+[F7] or [ALT]+[F8]
#
#       If the screen went black, the gdm is off. Come back to the text
#       console with the following key combination:
#
#                           [ALT]+[F1]
#
#       Hint: The following command is an alternative to the above check:
#
#             $> pgrep -lf gdm
#
#             If the answer is void, the command under step four was
#             successful.
#
#    6. Switch the running dbus daemon off.
#
#       $> sudo invoke-rc.d dbus stop
#
#    7. Call the script bldchraufs:
#
#       $> sudo /usr/local/sbin/bldchraufs
#
#    8. Change the access rights and the sticky bit of the directory
#       /tmp/:
#
#       $> sudo chroot /tmp/jail chmod 1777 /tmp
#
#       Hint: The above command gives all users unlimited access rights
#             in the directory /tmp of chroot environment. The sticky
#             bit - this is the first number of the string "1777" - reduce
#             the unlimited access write. With the sticky bit set, all users
#             can create files in the directory /tmp but can't change the
#             files of other users.
#
#    9. Replace the hal init script:
#
#       $> sudo cp /usr/local/share/bldchraufs/hal.new \
#          /tmp/jail/etc/init.d/hal
#
#       Hint: The replacement of the init script hal is necessary.
#             On the start the hal script checks if the script runs
#             under a chroot environment. If yes, it won't start the
#             hald daemon. A not running hald makes some trouble in
#             a GNOME Desktop session. According of some folks is the
#             chroot check only necessary during the restart of the hal
#             script. The script hal.new is the corrected version.
#             This script will only run in the chroot environment.
#             On the reboot of the system the unchanged script will
#             do it's work.
#
#   10. Start the dbus daemon in the chroot environment:
#
#       $> sudo chroot /tmp/jail invoke-rc.d dbus start
#
#   11. Start the GNOME Desktop manager gdm in the chroot environment:
#
#       $> sudo chroot /tmp/jail invoke-rc.d gdm start
#
#   12. Switch back into the text terminal session:
#
#                           [CTRL]+[ALT]+[F1]
#
#   13. Log out from the current text terminal session with following command:
#
#       $> exit
#
#   14. Call the graphic log in screen to log in in a GNOME Desktop session.
#       To go into the graphic log in screen use the following key combination:
#
#                           [ALT]+[F7] or [ALT]+[F8]
#
#   15. Fill out the user and password field and the GNOME Desktop pops up.
#       But now all things will run in the chroot environment.
#
#
#  5. Quit the GNOME Desktop session from the AUFS chroot environment
#
# The next steps shows how to leave the running session and how to stop the
# in the chroot environment running GNOME Desktop manager gdm and the dbus
# daemon.
#
#    1. Log out from a running Gnome desktop session. Select the menu entry
#       "Log Out <user name> ..." from the desktop menu entry "System" to log
#       out from the running session. The GNOME Desktop log in screen pops up.
#
#    2. Switch with the following key combination from the graphical log in
#       screen into the text console log in screen of the first console:
#
#                           [CTRL]+[ALT]+[F1]
#
#    3. Log in as normal user. A log in as user root is not necessary, but
#       the normal user must have access rights for system commands with
#       the command sudo. Without the proper access rights the user can't
#       execute the following steps.
#
#    4. Stop the running GNOME Desktop manager gdm with following command:
#
#       $> sudo chroot /tmp/jail invoke-rc.d gdm stop
#
#    5. Switch the running dbus daemon off:
#
#       $> sudo chroot /tmp/jail invoke-rc.d dbus stop
#
#
#  6. Restart the GNOME Desktop session in the non chroot environment
#
# Step five in chapter five was the last step to leave the GNOME Desktop
# session of the chroot environment. To get back into a GNOME Desktop ses-
# sion in a non chroot environment the user must execute the following steps:
#
#    1. Start the dbus deamon:
#
#       $> sudo invoke-rc.d dbus start
#
#    2. Start the GNOME Desktop manager gdm. This step will pop up the
#       graphical login screen of the GNOME Desktop session:
#
#       $> sudo invoke-rc.d gdm start
#
#    3. Switch back into the last text terminal session:
#
#                      [CTRL]+[ALT]+[F1]
#
#    4. Log out from the running text terminal session:
#
#       $> exit
#
#       Hint: The last two steps are not really necessary, but it's
#             always a good thing to close not used sessions.
#
#    5. Switch back into the GNOME Desktop log in screen:
#
#                      [ALT]+[F7] or [ALT]+[F8]
#
#
#  7. Unmount all parts of the AUFS chroot environment
#
# The following steps shows how to unmount the union, the process and the
# system file system and all with the option bind mounted directories.
#
# All of next steps must be executed in the described order. Calling the com-
# mands and there arguments in a the wrong order will abort the unmount pro-
# cess with an error message. This is not a disaster, but the unmounting
# after an faulty abort, is a bit difficult to handle. The chapter nine
# "What to do if umount aborts with an error message?" will give some hints
# how to handle this situation.
#
# For short, all following unmounts are done in the reverse order of the
# mounts that this script has done.
#
#    1. Unbind the shared memory /dev/shm, the pseudo-terminal slave /dev/
#       pts and the device node /dev directories from the directory /tmp/
#       jail:
#
#       $> sudo umount /tmp/jail/{dev/shm,dev/pts,dev}
#
#    2. Unmount all unions, the process and the system file system. In the
#       following list the name root must be the last name:
#
#       $> sudo umount {binfmt_misc,fusectl,sys,proc,srv,home,boot,usrlocal,\
#          usr,var,root}onaufs
#
#    3. Unbind all aliases of the system directories from the read only
#       branch:
#
#       $> sudo umount /tmp/jailcache.ro.{srv,home,boot,usr.local,usr,\
#          var,root}
#
#
#  8. Cleaning the directory /tmp
#
# After the unmounting the jail and jailcache directories can be removed. The
# cleaning is not really necessary, because a simple system reboot will do
# this but in some cases the cleaning could be necessary. In these cases the
# next steps shows how to do the cleaning.
#
# A last warning before the cleaning will be executed. The cleaning will remove
# all data that were created during the running chroot environment. This con-
# cerns all data in the writable branches of the directories jailcache. If
# the user want save some of the created data, it's now time to copy the con-
# cerned data to a save place outside the temporary directory /tmp.
#
# Hint: It's not a disaster if the user has forgotten to save the wanted data.
#       In the case the computer was shutdown without the above mentioned
#       cleaning, the user can rescue the wanted data. To rescue the data, the
#       computer must be booted from a live CD or USB stick. The boot from a
#       live CD or USB stick will prevent the cleaning of the directory /tmp.
#
#    1. The following commands will remove the mount point jail and the
#       read only branches of the jailcache:
#
#       $> cd /tmp
#
#       $> sudo rmdir ./jail ./jailcache.ro.{srv,home,boot,usr.local,\
#          usr,var,root}
#
#    2. Remove the directories from the writable branch of jailcache:
#
#       $> cd /tmp
#
#       $> sudo find . -xdev -depth -path ./jailcache.rw\* ! -type d -delete
#
#       Hint: The argument "! -type d" includes also unix sockets
#             and other particularities.
#
#       $> sudo find . -xdev -depth -path ./jailcache.rw\* -empty -type d \
#          -delete
#
#
#  9. What to do if umount aborts with an error message?
#
# This section gives some hints how to handle aborts of a running mount com-
# mand.
# 
# o Perhaps the frequent reason of an abort is the wrong order of the argu-
#   ments or a wrong device name in the list of arguments. In these cases
#   execute the mount command again, but without any argument after the com-
#   mand name. If the output shows device names with the character string
#   "onaufs" at the end of the device names, the cause of this abort could
#   be a wrong device name or another device(s) is(are) mounted above the
#   "onaufs" devices.
#
#   1. In the first case only some of the "onaufs" devices are unmounted. To
#      correct this problem, run the mount command from chapter seven, step
#      two again, but now without the already unmounted "onaufs" devices, like
#      the following example. In this example the misspelled device name proc
#      caused the abort. To correct this, execute the following command:
#
#      $> sudo umount {proc,root}onaufs
#
#      Then execute the third command from section seven, step three.
#
#   2. In the second case the output shows all mounted "onaufs" devices and
#      one of the bound shared memory or pseudo-terminal slave devices and
#      the device node device. The following example will correct this, if
#      the command was called with a the wrong pseudo-terminal slave name:
#
#      $> sudo umount /tmp/jail/{dev/pts,dev}
#
#      Then execute the second and third command from chapter seven.
#
#   3. No "onaufs" device was unmounted and the device node device couldn't
#      be unmounted. The reason for this case could be a mounted partition
#      from a CD-ROM device that was mounted during the running chroot envir-
#      onment. Find this partition and execute the command umount with the
#      device name as argument. Execute the command mount without any argu-
#      ments. Analysis the output of mount and run if necessary the proper
#      command from section chapter seven again.
#
# o In all other cases the commands ps and lsof could help to find the rea-
#   sons why a particular device or devices can't be unmounted.
#
#   If nothing helps, the last exit is a system reboot.
#
#
# 10. The code of the script bldchraufs
#
# The following lines contains the code of the script:

# Stop script on error
set -e

# Create the chroot directory /tmp/jail
mkdir -p /tmp/jail

# Build AUFS root in /tmp/jail/
mkdir -p /tmp/jailcache.rw.root /tmp/jailcache.ro.root
mount -o ro,bind / /tmp/jailcache.ro.root
mount -t aufs -o br:/tmp/jailcache.rw.root:/tmp/jailcache.ro.root \
      rootonaufs /tmp/jail/

# Build AUFS var in /tmp/jail/var
mkdir -p /tmp/jailcache.rw.var /tmp/jailcache.ro.var
mount -o ro,bind /var /tmp/jailcache.ro.var
mount -t aufs -o br:/tmp/jailcache.rw.var:/tmp/jailcache.ro.var \
      varonaufs /tmp/jail/var

# Build AUFS usr in /tmp/jail/usr
mkdir -p /tmp/jailcache.rw.usr /tmp/jailcache.ro.usr
mount -o ro,bind /usr /tmp/jailcache.ro.usr
mount -t aufs -o br:/tmp/jailcache.rw.usr:/tmp/jailcache.ro.usr \
      usronaufs /tmp/jail/usr

# Build AUFS usr/local in /tmp/jail/usr/local
mkdir -p /tmp/jailcache.rw.usr.local /tmp/jailcache.ro.usr.local
mount -o ro,bind /usr/local /tmp/jailcache.ro.usr.local
mount -t aufs -o br:/tmp/jailcache.rw.usr.local:/tmp/jailcache.ro.usr.local \
      usrlocalonaufs /tmp/jail/usr/local

# Build AUFS boot in /tmp/jail/boot
mkdir -p /tmp/jailcache.rw.boot /tmp/jailcache.ro.boot
mount -o ro,bind /boot /tmp/jailcache.ro.boot
mount -t aufs -o br:/tmp/jailcache.rw.boot:/tmp/jailcache.ro.boot \
      bootonaufs /tmp/jail/boot

# Build AUFS home in /tmp/jail/home
mkdir -p /tmp/jailcache.rw.home /tmp/jailcache.ro.home
mount -o ro,bind /home /tmp/jailcache.ro.home
mount -t aufs -o br:/tmp/jailcache.rw.home:/tmp/jailcache.ro.home \
      homeonaufs /tmp/jail/home

# Build AUFS srv in /tmp/jail/srv
mkdir -p /tmp/jailcache.rw.srv /tmp/jailcache.ro.srv
mount -o ro,bind /srv /tmp/jailcache.ro.srv
mount -t aufs -o br:/tmp/jailcache.rw.srv:/tmp/jailcache.ro.srv \
      srvonaufs /tmp/jail/srv

# Mount proc in /tmp/jail/proc
mount -t proc -o rw,noexec,nosuid,nodev proconaufs /tmp/jail/proc

# Mount sysfs in /tmp/jail/sys
mount -t sysfs -o rw,noexec,nosuid,nodev sysonaufs /tmp/jail/sys

# Mount fusectl in /tmp/jail/sys/fs/fuse/connections
mount -t fusectl -o rw fusectlonaufs /tmp/jail/sys/fs/fuse/connections

# Mount binfmt_misc in /tmp/jail/proc/sys/fs/binfmt_misc
mount -t binfmt_misc -o rw,noexec,nosuid,nodev binfmt_misconaufs \
      /tmp/jail/proc/sys/fs/binfmt_misc

# Bind /dev to /tmp/jail/dev
mount -o bind /dev /tmp/jail/dev

# Bind /dev/pts to /tmp/jail/dev/pts
mount -o bind /dev/pts /tmp/jail/dev/pts

# Bind /dev/shm to /tmp/jail/dev/shm
mount -o bind /dev/shm /tmp/jail/dev/shm

