IgnorantGuru's Blog

Linux software, news, and tips

Script: sandfox

«Downloads

Download Links:
Script: downloadbrowseauthenticateinstructions
Debian/Ubuntu: packagesPPA
Arch Linux: AUR
Description: Runs Firefox and other apps in a sandbox, limiting their access to the filesystem
Recommended For: Linux
Requires: inotify-tools lsof
License: GNU GPL v3     * SEE DISCLAIMER *
Related: kscrubber
News: What’s New?
Feedback: commentsissues

Contents

Overview

Sandfox runs programs within sandboxes which limit the programs’ access to only the folders you specify. Programs and their child processes, like Firefox plugins, Flash, and Java, are only able to access files within the sandbox. Sandfox supports the use of custom profiles which determine what folders and files are included in each program’s sandbox, and includes default profiles for Firefox, Skype, and Google-Earth. Sandfox can create separate sandboxes for each program, or can run multiple programs in one sandbox. Programs are run in a chroot jail as a normal user, providing a substantial level of security. Sandfox is designed to be very easy to use. It handles the details for you while still giving you the ability to construct custom sandboxes easily.

Why run Firefox or other programs in a sandbox? In the Firefox example, there are many components running: Java, Flash, and third-party plugins. All of these can open vulnerabilities due to bugs and malicious code; under certain circumstances these components can run anything on your computer and can access, modify, and delete your files. It’s nice to know that when such vulnerabilities are exploited, these components can only see and access a limited subset of your files. In the case of Skype and Google-Earth, these programs contain closed source binaries (no one knows what they contain). As discussed in Fear Not Root, the root mechanism in Linux offers very limited protection for your PC and data. Sandfox uses the power of the root mechanism to protect not only system files, but all of the files you choose to protect.

sandfox --help

Usage: sandfox [OPTIONS] [COMMAND [ARG]...]
Runs COMMAND as a normal user within a chroot jail sandbox with limited
access to the filesystem.  Supports profiles for apps and includes a default
Firefox profile. Must be run as root when creating sandbox.  Examples:
 sudo sandfox firefox                    # Runs Firefox in a sandbox
 sudo sandfox bash                       # Shell to explore a sandbox
OPTIONS:
--bindro TARGET           Include TARGET (a file or folder) in the sandbox
                            bind-mounting it as a read-only filesystem
--bind TARGET             Include TARGET (a file or folder) in the sandbox
                            with same ownership and permissions when possible
--copy TARGET             Place a disposable copy of TARGET (a file or folder)
                            in the sandbox
--hide TARGET             Include TARGET (a file or folder) in the sandbox
                            by bind-mounting an empty file or folder onto it
                            Effectively hides the real TARGET from the sandbox
                            Also provides a writable dummy folder
--profile PROFILE         Load PROFILE (a profile name or pathname).  By
                            default profiles are stored in /etc/sandfox
--make                    Force creation or update of a sandbox (make is
                            implied if you specify binds or profiles)
--sandbox NAME            Specify name of sandbox to use, create, or update
--close NAME              Unmount and remove sandbox NAME
--closeall                Unmount and remove ALL sandboxes
--status                  Show the status of all current sandboxes
--shell                   Run COMMAND in a shell and wait.  Requires root.
                            (bash is always run in a shell)
--user USERNAME           Run command as USER in the sandbox - useful if
                            auto-detection does not work or to override
--profilefolder FOLDER    Use FOLDER instead of the default profile folder
                            IMPORTANT: should be root owned & write-protected
--logfile LOGFILE         Also append messages to LOGFILE.  sandfox daemons
                            will also update this file provided it is
                            accessible from within the sandbox.
--verbose                 Provide detailed feedback
--quiet                   Minimize output messages
NOTES: OPTIONS must precede COMMAND; you can also use OPTION=VALUE; binds are
processed in this order: bindro bind copy hide; missing binds are ignored; if
a profile for COMMAND exists it will be automatically loaded; default profile
is always loaded; profiles may contain any options valid on the command line;
if COMMAND is omitted, a sandbox will be created for use.

In order to create, modify, or close sandboxes, Sandfox must be run as root, which enables it to mount filesystems as root and create a secure chroot jail that a normal user cannot break out of. Once the sandbox is created, you may run Sandfox as a normal user in order to start programs within the sandbox(es). Sandfox always runs programs as a normal user in the sandbox, even when you run Sandfox as root.

For example, to build a sandbox for Firefox and start Firefox running in the sandbox, close all running windows of Firefox, then:

sudo sandfox firefox

(sudo indicates ‘run this command as root’ – sudo is not specifically required)

Sandfox has a default profile for Firefox, so it will automatically load that profile. The profile tells Sandfox how to build a sandbox which provides the system and user folders that Firefox requires. (For full functionality of your version of Firefox, you may want to edit this profile to add more folders and files. The profile is stored in /etc/sandfox/firefox.profile) Tip: If “Save Page As…” and “Save Image As…” don’t respond in Firefox, go into Edit|Preferences|General|Downloads and set “Save files to…” a folder which exists in the sandbox.

IMPORTANT NOTE: Be sure to close all running instances of Firefox before running Firefox in a sandbox. If you don’t, then when you or Sandfox starts Firefox, the already-running instance will simply open another Firefox window, which will not be sandboxed. You can always test if the Firefox window you’re using is running in the sandbox by entering “/” as the URL in Firefox and pressing Enter. If you are able to navigate your complete filesystem, and all of your home folders appear, then Firefox is not running in the sandbox.

Sandfox can also start additional programs in the sandbox. For this, you may run Sandfox as either a normal user or as root. For example, to start Speedcrunch in an already-created sandbox:

sandfox speedcrunch

If you would like to explore a sandbox using the shell, you can run bash. Running a program in a shell requires you to run Sandfox as root. For example:

sudo sandfox bash

You will note that not all folders exist when you are in this shell, and not all programs may run properly due to missing files. When you are done with the shell, enter “exit” to return to the non-sandboxed shell.

When you are done with the sandbox, close all programs running in the sandbox, then run

sudo sandfox --closeall

This closes all sandboxes. It is recommended that you close all sandboxes before rebooting in order to avoid any shutdown delays.

Profiles And Binds


Profiles are text files in /etc/sandfox which tell Sandfox how to build sandboxes. The “default” profile is always loaded. Other profiles are loaded if the name of the profile is the same as the command you run when you create the sandbox. For example, “sudo sandfox firefox” will automatically load the firefox profile (as well as the default profile) when building the sandbox. You can edit the profiles in /etc/sandfox, and you can create your own.

Any option valid on the command line can also be placed in a profile (in the form OPTION=VALUE). You can also design a profile to include other profiles using the “profile=” option within a profile.

Profiles (and/or the command line) contain four types of options (binds) which define what files and folders appear in your sandbox.

bindro and bind
bindro=target and bind=target (where target is the full pathname of a file or folder) cause Sandfox to bind-mount the target into the sandbox’s filesystem. A bind-mount is similar to a link – it makes the folder or file accessible without actually copying any files. Unlike a link, programs see the bind-mount as an actual file or folder. The only difference between bindro and bind is that bindro makes the target a root-enforced read-only filesystem in the sandbox, whereas bind gives the target the same read/write permissions and ownership in the sandbox that it has in the original filesystem. Unless your program needs to modify files in a folder, it is best to use bindro for greater security. When files in a bind folder are modified, the files in the original filesystem are modified.

copy
Copy is used to place a disposable copy of the target into the sandbox. If these files are deleted or modified in the sandbox, it will not effect the original target. Copy provides a way to give a program read/write access to a file or folder which you don’t want changed in the original filesystem.

When copying a folder, Sandfox will bind-mount a tmpfs filesystem (aka ram drive) into the sandbox and copy the files to it. This allows you to copy a folder which may already exist in the sandbox – the bind-mount will make the original invisible. However, note that each tmpfs is limited to 100MB and consumes memory instead of disk space (this limit can be adjusted by changing “tmpfslimit=” in the script). Thus copying large folders is not recommended – this is primarily intended for small config files and the like. For larger folders, consider manually making a copy in the original filesystem first, then binding the copy.

When copying a file target, the file is simply copied into the sandbox. However, a copy directive will be ignored if the file already exists in the sandbox. Thus unlike a folder, you cannot copy a file onto its sandbox version using copy. To do so, consider manually making a copy in the original filesystem first, then binding the copy.

bind, bindro, and copy directives whose targets do not exist in the original filesystem when the sandbox is created are silently ignored by Sandfox.

hide
hide will bind-mount an empty file or folder into the sandbox. This has several uses. For one, it can hide a subfolder. For example, if you bind /var but don’t want /var/tmp to be accessible, you can hide /var/tmp. Likewise, you can hide a single file within a bind folder. Another use of hide is to create an empty folder for a program to use, rather than the original. Unlike bind, bindro, and copy, the target of a hide need not exist in the original filesystem for it to be added to the sandbox.

When hiding a folder or a non-existent target, a tmpfs filesystem is bind-mounted into the sandbox. When hiding a file, /dev/null is bind-mounted onto a file in the sandbox. If the file or folder already exists in the sandbox, it is thus hidden.

Order And Layers
Sandfox always processes all bindros, then binds, copies, and hides in this order. Note that a sandbox may consist of layers of binds, as in the /var/tmp example above.

Order is important because, for example, if you (read-write) bind your home folder, then bindro a subfolder, the subfolder WILL be read-write accessible (the bindro is performed first and the bind is laid over it). In this case you may want to bindro the home folder and bind subfolders and files which you want to be read-write accessible. It is helpful to test the sandbox filesystem you create before relying on its behavior.

If the same binds appear in multiple loaded profiles or on the command line, they will only be mounted once. Thus profiles may safely have some overlap in terms of binds.

The variable “$user” can be used in profiles (but not on the command line) to represent the sandbox user when the sandbox is created. Thus “bind=/home/$user” will bind the sandbox creator’s home folder. You can see an example of this in /etc/sandfox/firefox.profile

In addition to binds in the default profile and your profiles, Sandfox may also bind a few programs which it requires to run in the sandbox, such as /usr/bin/inotifywait.

Getting Programs To Run Well In A Sandbox


Sometimes it takes a little research to determine what folders and files a program needs to run successfully in a sandbox. While it is best to make the final sandbox as constrictive as possible, it can be helpful to use a more liberal sandbox initially. Also note that many programs, such as Firefox, will write useful error messages to stdout. Normally, Sandfox does not display the stdout messages, but you can tell it to do so by including the “––verbose” option.

Include “––verbose” when you create the sandbox, then leave that shell open and check it for messages. Even if you start additional sandboxed programs from another shell, their stdout messages may be displayed in the original shell that created the sandbox. (This is because when Sandfox is run without root, it uses a daemon to start programs inside the sandbox.)

For example, with no sandbox open, create an initial sandbox with:

sudo sandfox --verbose firefox

Leave that shell window open. You may see some messages from Firefox in it. Now close Firefox, and open a second shell window. As a normal user run:

sandfox firefox

Firefox should start again (running in the sandbox). Any stdout messages will appear in the first shell window.

Another method for capturing stdout from sandboxed programs is to redirect stdout to a file. Just note that the file must be writable from within the sandbox. For example:

sandfox "ls / > /tmp/ls-output.txt"

The quotes are required. /tmp/ls-output.txt should contain a directory listing of the / folder within the sandbox.

You can also start programs in shell mode to see their output:

sudo sandfox --shell ls /

Or, just start a shell and run programs from within it:

sudo sandfox bash

You can use /etc/sandfox/firefox.profile as a starting point for building your own custom sandboxes, as it includes many of the folders commonly required.

Also, the inotifywait program can be used directly to see what files are accessed and/or changed while a program is running. For example, to see what files in user‘s home folder are being accessed, open an extra terminal window and leave this running:

inotifywait -rm /home/user

 
Firefox Themes
The firefox profile binds most of the files needed for your KDE and Gnome themes to work in Firefox. If not, try running ‘env’ in a shell as user, and examine the values of these variables: GTK2_RC_FILES GTK_RC_FILES XCURSOR_THEME Files or folders listed in those variables may need to be binded for themes to work.

Securing SpaceFM


The SpaceFM File Manager allows scripts and programs run by the same user to interact with its socket to run custom commands and get information about currently shown tabs. Although SpaceFM will not normally accept socket commands from within a Sandfox sandbox, it is possible (though difficult) for a specially crafted program to do so, which would allow such a program full access to the filesystem outside of the sandbox. To secure sandboxes so there is no access to SpaceFM’s sockets, use of a custom SpaceFM tmp folder is recommended.

First, create a custom tmp folder for SpaceFM at boot time. For example, add the following lines to the /etc/rc.local file (add these lines before the ‘exit’ line in that file):

    mkdir /tmp/spacefm-temp
    chmod ugo+rwx,+t /tmp/spacefm-temp

Also run the above commands once now as root to create the directory for immediate use, and kill all running instances of SpaceFM:

    mkdir /tmp/spacefm-temp
    chmod ugo+rwx,+t /tmp/spacefm-temp
    killall spacefm
    rm -rf /tmp/spacefm.tmp

Next, edit /etc/spacefm/spacefm.conf, or create it if needed, adding the following line:

    tmp_dir=/tmp/spacefm-temp

Finally, add the following line to /etc/sandfox/default.profile:

    hide=/tmp/spacefm-temp

Now close and recreate all your Sandfox sandboxes, or reboot. All access to SpaceFM sockets will be prevented inside sandboxes.

Examples


This section contains many examples to demonstrate Sandfox usage. You won’t necessarily do all of these in the order presented. When root is required, sudo is shown, but it is always okay to run Sandfox as root even when not required – programs will always be run as user (unless “––user root” is explicitly included, which is not recommended).

# Create a sandbox if none are open and run Firefox
sudo sandfox firefox

# Create a Firefox sandbox but don't start Firefox
sudo sandfox --profile=firefox

# Create a dual-use sandbox for both Firefox and Google-Earth, and start them
sudo sandfox --profile=firefox --profile=google-earth
sandfox firefox
sandfox google-earth

# Create a sandbox using a "myprogram" profile you have created
sudo sandfox --profile=myprogram

# Create a sandbox using a "myprogram" profile you have created
# and run myprogram
sudo sandfox myprogram

# Create a sandbox using a "myprogram" profile you have created
# and also load the firefox profile, and run myprogram
sudo sandfox --profile=firefox myprogram

# Add an additional bind to an existing sandbox named "firefox"
# (or create one if it doesn't exist)
sudo sandfox --sandbox=firefox --bind /user/data

# Force update of the firefox sandbox after editing its profile
# to add new binds.  (missing binds will be added, but existing
# binds will NOT be removed)
sudo sandfox --sandbox=firefox --make

# Manually create a sandbox without using a profile (although
# the default profile is always loaded in addition to the binds
# listed)
sudo sandfox --bindro=/bin --bindro=/lib --bindro=/etc \
 --bind=/tmp --copy=/home/myuser/.bashrc

# Show the name and status of all open sandboxes
sandfox --status

# Run ls in shell mode to see the output
sudo sandfox --shell ls /

# Redirect output of a command to a file (quotes required)
sandfox "ls / > /tmp/ls-output.txt"

# Start an additional program in an available sandbox as a normal user
# (This can also be done as a command from an icon or keyboard shortcut)
sandfox firefox

# Start a command with a quoted argument
# (equivalent to  myprogram "name with spaces")
sandfox myprogram \"name with spaces\"

# Start an additional program in a specific sandbox
sandfox --sandbox=firefox firefox

# Close a specific sandbox (close all windows running in it first)
sudo sandfox --close=firefox

# Close all sandboxes (close all programs first)
sudo sandfox --closeall

Example session:

myuser:/$ ls /

total 102
drwxr-xr-x  24 root root  4096 Dec 12 10:22 .
drwxr-xr-x  24 root root  4096 Dec 12 10:22 ..
drwxr-xr-x   2 root root  4096 Feb  1 09:34 bin
drwxr-xr-x   3 root root  4096 Jan 22 10:21 boot
drwxr-xr-x  17 root root  6080 Feb  1 14:08 dev
drwxr-xr-x  62 root root  4096 Feb  2 09:59 etc
drwxr-xr-x   4 root root  4096 Feb  1 17:19 home
drwxr-xr-x   8 root root  4096 Feb  1 13:45 lib
drwxr-xr-x   2 root root  4096 Dec 12 00:09 lib64
drwx------   2 root root 16384 Nov 16 10:41 lost+found
drwxr-xr-x   6 root root  4096 Jan 22 08:52 media
drwxr-xr-x  12 root root  4096 Feb  1 16:41 mnt
drwxr-xr-x   6 root root  4096 Jan 26 18:58 opt
dr-xr-xr-x 168 root root     0 Feb  1 06:47 proc
drwx------  11 root root  4096 Jan 22 13:48 root
drwxr-xr-x   2 root root  4096 Jan 24 22:38 sbin
drwxr-xr-x   5 root root  4096 Jan 22 08:52 srv
drwxr-xr-x  13 root root     0 Feb  1 06:47 sys
drwxrwxrwt  13 root root   380 Feb  2 08:53 tmp
drwxr-xr-x  11 root root  4096 Jan 22 10:21 usr
drwxr-xr-x  14 root root  4096 Jan 28 09:38 var

myuser:/$ sudo sandfox bash
Loading profile "default"
Loading profile "bash"
Creating new sandbox "bash"

>>> shell - you are myuser in sandbox "bash" <<<
myuser:/$ ls /
total 36
drwxr-xr-x 10 root root 4096 Feb  2 09:59 .
drwxr-xr-x 10 root root 4096 Feb  2 09:59 ..
drwxr-xr-x  2 root root 4096 Feb  1 09:34 bin
drwxr-xr-x  3 root root 4096 Feb  2 09:59 dev
drwxr-xr-x 62 root root 4096 Feb  2 09:59 etc
drwxr-xr-x  3 root root 4096 Feb  2 09:59 home
drwxr-xr-x  8 root root 4096 Feb  1 13:45 lib
drwxr-xr-x  2 root root 4096 Feb  1 00:09 lib64
drwxrwxrwt 13 root root  380 Feb  2 08:53 tmp
drwxr-xr-x 11 root root 4096 Jan 25 10:21 usr

myuser:/$ ls /dev
total 8
drwxr-xr-x  3 root root 4096 Feb  2 09:59 .
drwxr-xr-x 10 root root 4096 Feb  2 09:59 ..
crw-rw-rw-  1 root root 1, 3 Sep  7 00:15 null
drwxrwxrwt  6 root root  120 Feb  1 14:24 shm
crw-rw-rw-  1 root root 1, 9 Feb  1 13:47 urandom
crw-rw-rw-  1 root root 1, 5 Sep 17 00:15 zero

myuser:/$ exit
exit

<<< exit - you are myuser out of the sandbox >>>
myuser:/$ _

How It Works


The Sandfox program is written entirely in bash, itself a well-tested core Linux component. You can open the sandfox script in any text editor to examine its commands or to make careful modifications. Sandfox uses only core Linux programs such as mount and chroot to create sandboxes. Rather than attempting to recreate the security these hardened programs provide, Sandfox simply inherits those qualities. Sandfox does nothing you can’t do directly in a console using mount, chroot, and similar commands. It simply automates the process and helps you organize and use sandboxes easily. Sandfox is a 1300-line program which does extensive error- and safety-checking and provides detailed feedback.

One way to learn more about how Sandfox works is to use the ––verbose option. Although the output is a bit messy, it will show you the exact commands as they are being issued.

In creating a sandbox, Sandfox creates a folder in /mnt/sandfox/SANDBOXNAME, which is used as the false root folder of a chroot jail. Then, using bind-mounts and tmpfs mounts, it adds folders and files to this false root.

Once the false root folder has been created, Sandfox starts a normal-user daemon version of itself in a chroot jail. This Sandfox daemon runs with your normal user privileges in the root-enforced chroot jail, which is a highly secure environment. See below for what this daemon does.

If you include a command on the command line when creating a sandbox, Sandfox will also start the command (such as firefox) in a chroot jail as a normal user. If you later run Sandfox as root to start additional programs, it will start additional chroot jails for these programs.

However, it is more convenient to be able to start programs as a user. This allows you to have clickable icons and keyboard shortcuts for starting your programs, without the need of entering the root password every time. This is where the Sandfox daemon comes in.

The Sandfox daemon runs as a normal user in the chroot jail – one instance for each sandbox you create. Using the inotifywait program, it efficiently monitors the folder /tmp/sandfox-events/SANDBOXNAME for changes. Anytime an executable file in that folder is modified or added, it will execute the file, then delete it. The daemon will run any file that is owned by its own user and is executable, and will also execute .desktop files. Links are not followed. This folder works similarly to KDE’s Autostart folder, which executes all the files in Autostart on login, except in this case they are executed as soon as they are placed there. The file that the daemon runs (generally a script to run your program) will inherit the daemon’s privileges – namely it will run as a normal user in the chroot jail.

When you run Sandfox as a normal user to start a program in a sandbox (eg “sandfox firefox” without sudo), Sandfox composes a script which will run the program, and drops it into the daemon’s event folder, where it will be detected and executed by the daemon running inside the chroot jail. This provides a mechanism for running additional programs without root. The script will also pass the current environment variables of the caller to the program called.

When closing a sandbox, Sandfox checks for existing mounts and attempts to umount all the mounts in the reverse order.

Installation Instructions


Follow the standard Script Installation Instructions. Alternatively, for Debian and Ubuntu a deb package and a PPA repository are available. On Arch Linux, sandfox can be installed automatically using the AUR.

Before running sandfox, install required packages using your package manager. For example, on Debian/Ubuntu:

apt-get install inotify-tools lsof

If you use SpaceFM, see Securing SpaceFM.

Related Forum Threads:

Startup Scripts – Create A Sandbox At Boot


It is possible to automatically open a sandbox during boot, and automatically close all sandboxes on shutdown. In this way you can start programs in the sandbox(es) as a normal user without ever having to enter the root password. When starting Sandfox during boot, you generally MUST specify the “––user USERNAME” option to tell Sandfox what user will be using the sandbox.

Example startup scripts and installation instructions are shown below for Arch Linux and Ubuntu. A CrunchBang HowTo is also available.

Arch Linux
Create a new text file named “/etc/rc.d/sandfox” (sudo nano /etc/rc.d/sandfox) and paste the following text into it:

#!/bin/bash
# Sandfox boot startup script for Arch Linux

sandfoxuser=myuser
sandfoxprofile=firefox
sandfoxbin=sandfox

. /etc/rc.conf
. /etc/rc.d/functions

start() {
	stat_busy "Starting Sandfox"
	$sandfoxbin --profile $sandfoxprofile --user $sandfoxuser
	if [ $? -gt 0 ]; then
		stat_fail
	else
		add_daemon sandfox
		stat_done
	fi
}

stop() {
	stat_busy "Stopping Sandfox"
	$sandfoxbin --closeall --user $sandfoxuser
	if [ $? -gt 0 ]; then
		stat_fail
	else
		rm_daemon sandfox
		stat_done
	fi
}

case "$1" in
	start)
		start
		;;
	stop)
		stop
		;;
	restart)
		stop
		sleep 3
		start
		;;
	*)
		echo "Usage: $0 {start|stop|restart}"
esac
exit 0

Edit the values of the sandfoxuser, sandfoxprofile, and sandfoxbin variables at the top. sandfoxuser is the normal user who will be running programs in the sandbox, sandfoxprofile is the profile name from /etc/sandfox to create the sandbox, and sandfoxbin is the location of the sandfox script on your system. Feel free to customize the above startup script with additional profiles or have it run sandfox multiple times to create multiple sandboxes.

Next, execute the following commands:

# Make startup script executable
sudo chmod +x /etc/rc.d/sandfox

# Add sandfox to DAEMONS array in rc.conf
sudo sed -i 's/^\(DAEMONS=.*\))/\1 sandfox)/' /etc/rc.conf

(Alternatively, you can use the /etc/rc.local and /etc/rc.local.shutdown scripts on Arch Linux to open and close sandboxes.)

A Potential Problem: Some Arch users have encountered a problem due to the lack of a ~/.Xauthority file in their sandbox user’s home folder at boot time, as described here. To remedy this you may need to change this line in the script:

$sandfoxbin --profile $sandfoxprofile --user $sandfoxuser

to something like:

( while [ ! -e /home/$sandfoxuser/.Xauthority ]; do sleep 1; done; \
  $sandfoxbin --profile $sandfoxprofile --user $sandfoxuser ) &

 

Ubuntu And Similar
Create a new text file named “/etc/init.d/sandfox” (sudo nano /etc/init.d/sandfox) and paste the following text into it:

#!/bin/bash
# Sandfox boot startup script for Ubuntu and similar

sandfoxuser=myuser
sandfoxprofile=firefox
sandfoxbin=sandfox

start() {
	echo -n "Starting Sandfox: "
	$sandfoxbin --profile $sandfoxprofile --sandbox $sandfoxprofile --user $sandfoxuser
	if [ $? -gt 0 ]; then
		echo "failure"
		RETVAL=$?
	else
		echo "success"
		RETVAL=0
	fi
}

stop() {
	echo -n "Stopping Sandfox: "
	$sandfoxbin --closeall --user $sandfoxuser
	if [ $? -gt 0 ]; then
		echo "failure"
		RETVAL=$?
	else
		echo "success"
		RETVAL=0
	fi
}

case "$1" in
	start)
		start
		;;
	stop)
		stop
		;;
	restart)
		stop
		sleep 3
		start
		;;
	*)
		echo "Usage: $0 {start|stop|restart}"
		RETVAL=1
esac
exit $RETVAL

Edit the values of the sandfoxuser, sandfoxprofile, and sandfoxbin variables at the top. sandfoxuser is the normal user who will be running programs in the sandbox, sandfoxprofile is the profile name from /etc/sandfox to create the sandbox, and sandfoxbin is the location of the sandfox script on your system.

Next, execute the following commands:

# Make startup script executable
sudo chmod +x /etc/init.d/sandfox

# Add sandfox to runlevels
sudo update-rc.d sandfox defaults

If you decide you DON’T want Sandfox to start at boot, you can cancel the startup script with:

# Remove from runlevels
sudo update-rc.d -f sandfox remove 

Feel free to customize the above startup script with additional profiles or have it run sandfox multiple times to create multiple sandboxes.

126 Comments

  1. Fantastic idea and script… but what with .Xauthority cookie, which is needed to connect the display? When using your daemon, sandbox is created before cookie and there is some problems with using X display.

    Using sandfox manually after login works just perfect.

    Comment by CeCeron | August 31, 2010

    • Maybe you could have the daemon delay sandfox startup for awhile using the sleep command, or have it wait until a login is detected. Or place the sandfox startup elsewhere in your startup scripts so it is run post-login.

      Another more cumbersome option would be to bind your entire home folder to the sandbox, then hide the files and folders you don’t want included. You may need to lower the default size of hide’s tmpfs in order to reduce the memory usage.

      Also, touching the .Xauthority file before starting sandfox (so that the file exists) may help the issue, since sandfox will ignore any binds for files that don’t exist when it is started.

      Comment by igurublog | August 31, 2010

  2. Ok, thanks. I added one loop checking if $sandfoxuser is logged and waiting if not. Now it is perfect ;)

    Comment by CeCeron | August 31, 2010

    • good solution – thanks for your feedback

      Comment by igurublog | August 31, 2010

  3. Why don’t you create a new user with limited privileges and run the app with that user?

    Comment by Mike | September 24, 2010

    • That’s another approach – it requires not only creating a new user but also groups and changing the default permissions on files created by other users, and it doesn’t limit access to the root user or overall system as much as the sandfox approach.

      Comment by igurublog | September 25, 2010

  4. Is there a way to run a sandfoxed app without adding the user to the sudoers group?

    Comment by Mike | September 27, 2010

    • Yes – sandfox needs to be run as root (not necessarily with sudo) when it creates the sandbox. After that you can run it as a normal user to start apps in the sandbox.

      To create the sandbox, you can add it to your startup scripts which alleviates the need to enter a root password at all, or you can run it with sudo or via su.

      Comment by igurublog | September 27, 2010

      • I’m currently using Crunchbang. Root account is disabled, you have normally a sudoer user.
        What I want is create a new user with the less permissions possible and run the sandbox there. I tried “sudo ./sandbox.sh skype –user limiteduser” and the sandbox is created with the permissions of the sudoer and not limiteduser.

        Adding it to the startup would, correct me if wrong, start it at boot when I would like to run the sandbox occacionally.

        Comment by Mike | September 27, 2010

        • Options must precede the command, so you’ll want to use

          sudo ./sandfox.sh --user limiteduser skype

          Otherwise you are passing the –user option to skype rather than to Sandfox.

          Comment by igurublog | September 27, 2010

          • Agh, how I missed that!. Thanks :)

            Comment by Mike | September 27, 2010

  5. There is something flawed about this sandboxes, they don’t protect you if you run an untrusted app that takes screenshots and act as a keylogger in user space. Am I wrong?

    Comment by Mike | October 3, 2010

    • More of a limitation than a flaw – you are correct that Sandfox creates a filesystem sandbox only. You can also limit an app’s access to services by denying access to some system files – basically tightening the sandbox down more.

      Comment by igurublog | October 4, 2010

      • What if…you use an Xserver like xephyr.
        Then make the apps launched under sandfox use an instance of xephir. Maybe by setting $DISPLAY variable and running it with a new user.
        Then you would efectively sandbox the app all.

        Comment by Mike | October 4, 2010

        • And it’s easy to do :)
          I just did!
          Skype with sandfox and xephyr
          Check http://ubuntuforums.org/showthread.php?t=620003 for how to use it.
          Xephyr launches instantly and doesn’t use much memory.

          Comment by Mike | October 4, 2010

          • Sounds like a good solution. As you say, you can use a combination of limited user accounts and servers to further limit the apps. Thanks for sharing your idea – I’ll take a look at that.

            Comment by igurublog | October 4, 2010

  6. I like your sandbox-script.
    I have some trouble with skype and camera, unfortunately skype doesn’t have any verbose output afaik.

    When testing video inside the options-tab of skype, everything is fine: the camera switches on and I can see the output. But when I make a call nothing is seen and the camera doesn’t even power up (indicator-LED is off).
    Outside the sandbox everything works fine.
    Does anyone have the same problem, or a hint for a solution?

    Comment by nanos | February 4, 2011

    • I don’t use Skype so I can’t help you directly. The person who contributed sandfox’s Skype profile did tell me that he hadn’t used it for video.

      One thing I would suggest is to have a look at AppArmor profiles for Skype, as this should give you an idea of what folders it requires access to. For example, this AppArmor profile for Skype from here looks promising as it includes /dev/video.

      Edit /etc/sandfox/skype.profile to include additional folders or files suggested by the AppArmor profile (using the correct syntax for sandfox). If you do get it working with video I would appreciate a copy of the profile so I can include it in Sandfox by default – thanks.

      Comment by igurublog | February 4, 2011

      • Okay, the solution is quite simple: you have to bind the video-device-knot itself, not the symlink. In my situation:
        bind /dev/video0
        instead of /dev/video

        Now I’m able to make video-calls inside a sandbox! :-)

        Comment by nanos | February 6, 2011

        • Nice- thanks for the tip.

          Comment by igurublog | February 7, 2011

  7. Hi!

    I’ve followed your instructions on Ubuntu 10.04, but get a nasty warning:

    “sandfox: Warning: Could not start daemon – you may not be able
    to run additional programs in this sandbox”

    Somehow I’m still able to launch flash videos in my firefox browser.

    Comment by pipy | February 17, 2011

    • The daemon that error refers to is used to start additional programs in the sandbox as a normal user. Not sure why you’re getting that error. You can try

      sandfox --status

      and should see something like:

      Sandbox:     firefox
        Daemon:    running (myusername)
        Mounts:    96   /mnt/sandfox/firefox/
        Root Dirs: bin dev etc home lib lib64 opt proc tmp usr var

      If that doesn’t report “running”, then the daemon doesn’t appear to be running, which means you would need ‘sudo sandfox’ to start additional programs in that sandbox.

      You can also check

      ps -eo user,cmd | grep "sandfox .*--daemon"

      to see if something like this is running:

      myusername     /bin/bash /tmp/sandfox-events/tmp/sandfox --daemon --watch /tmp/sandfox-events/firefox

      If you see a process like that running, but sandfox ––status doesn’t say “running”, please send me the output of the ps command above – thanks. You may also get more error information by adding the ––verbose option to sandfox.

      Also, before assuming firefox is sandboxed, try browsing the filesystem in the browser (just enter / as the url). Thanks for your feedback.

      Comment by igurublog | February 17, 2011

      • Sandfox does say that it is running. I am unable to browse my filesystem from within firefox — so I assume that it is sandboxed.
        I can Adobe Flash videos, but npviewer.bin doesn’t show up on my sandfox status.

        $ sandfox --status
        
        Sandbox:     firefox
          Daemon:    running (1000)
          Mounts:    23   /mnt/sandfox/firefox/
          Root Dirs: bin dev etc home lib lib32 lib64 proc tmp usr var
        $ ps -eo user,cmd | grep "sandfox .*--daemon"
        1000     /bin/su xxxxx -c /tmp/sandfox-events/tmp/sandfox --daemon   --watch /tmp/sandfox-events/firefox
        1000     /bin/bash /tmp/sandfox-events/tmp/sandfox --daemon --watch /tmp/sandfox-events/firefox
        1000     /bin/bash /tmp/sandfox-events/tmp/sandfox --daemon --watch /tmp/sandfox-events/firefox
        1000     grep --color=auto sandfox .*--daemon
        
        

        Comment by pipy | February 17, 2011

        • I think you’re getting the error because your ps is returning the user ID instead of the username – this fools sandfox into thinking the daemon isn’t running for your user.

          I’ll take a look to see if I can accommodate that ps behavior, and please make sure you’re using the latest version of sandfox. Until that is corrected you might have problems running additional programs in the sandbox unless you use sudo.

          Comment by igurublog | February 17, 2011

          • Thanks for your support and for writing a great program! )))
            It was fun to find your sandboxing idea on Ubuntu Brainstorm with lots of minuses. It looks like Ubuntu Brainstorm guys don’t give a shit about security!

            I’m running sandfox 1.0.7 on a more or less standard Lucid installation. I guess It’s the latest version out there.. ^-^

            Comment by pipy | February 17, 2011

        • It appears that if a username is longer than 8 characters that ps will substitute the user ID for the username, which may be the problem.

          If you could tell me what this outputs:

          ps -o uid,user -o "%u %U" -A

          that would help. You can substitute x’s for your real username, but please retain the number of characters. Thanks.

          It’s also possible you have ps aliased.

          Comment by igurublog | February 17, 2011

          • I’ve sent you my output via SourceForge messenger.

            Comment by pipy | February 17, 2011

          • Thanks – I received it. Since your username is longer than 8 characters, ps returned the userID instead. Please let me know if Sandfox 1.0.8 doesn’t correct the problem for you – thanks.

            Comment by igurublog | February 17, 2011

        • Sandfox 1.0.8 should correct this problem.

          Comment by igurublog | February 17, 2011

          • Now everything works flawlessly!

            Thanks, that is brilliant! Decent Firefox sandbox was the feature I long missed! *Adjusts tinfoil hat while speaking*

            Comment by pipy | February 17, 2011

          • Thanks. With the likes of Flash around, tinfoil hats are highly indicated.

            And thanks to your feedback I think I finally resolved this issue – I couldn’t understand why for some users ps was returning userids!

            Comment by igurublog | February 17, 2011

  8. Hi I have created the sandfox script in etc/rc.d. And added sandfox as daemon.
    The problem I have is that the sandbox isn’t deleted when shutting down. I have to do it by hand. How could I solve this?

    Comment by Paul | March 21, 2011

  9. Sorry, I should have added, that it is a firefox sandbox and an Arch installation

    Comment by Paul | March 21, 2011

    • Not sure why it won’t close the sandboxes for you – make sure you close all programs using the sandbox, but during shutdown I would think that would happen already. Sometimes a process will hang on too long.

      You might try adding the close command to /etc/rc.local.shutdown:

          sandfox --closeall --user myuser

      You could run

          lsof | grep sandfox > somefilesomewhere

      in the shutdown script and see if anything is reported running in the sandbox. You might also try logging sandfox with ––verbose enabled and see if that gives any clues. Try to determine a) if the closeall command is executed, b) if any error is given by it.

      Comment by igurublog | March 21, 2011

  10. I have searched hours for a sandboxie alternative and was about to fool around with chroot jails myself. Luckily I found your nice piece of software.

    This should be put into the Arch wiki somewhere, so it will be easier to find for people like me (“sandfox” still doesn’t return that many relevant hits on google).

    Thanks a lot for the work you have put into this.

    Comment by Admirer | March 27, 2011

    • Thanks – I’m not sure if there are any direct links to it in the wiki, although there are some general links to this site. Feel free to add a link in the wiki if you find a good spot for it.

      Comment by igurublog | March 27, 2011

  11. Running sandfox in Debian Squeeze with Xfce4. In addition to package inotify-tools, I also needed to install package uuid-runtime.

    And, while redundant, I added the following to ‘firefox.profile’ for Xfce4:

    bind=/home/$user/.config/gtk-2.0/xfce4

    Also, I install firefox in /opt, so I added the following to ‘default.profile’:

    # root folders and files
    bindro=/opt

    and the following to ‘firefox.profile’:

    # root folders and files required by firefox
    bindro=/opt/firefox

    Very nice work. Previously used two shell scripts I hacked together in an attempt to emulate Ubuntu’s guest-session (a great feature btw) on Debian but, as you say, this requires managing a new user and group, logging in and out and one has to to run outside of their normal user environment.

    Comment by RHM | April 25, 2011

    • Thanks for the notes – I’ll remove uuid dependence on the next update.

      Comment by IgnorantGuru | April 25, 2011

  12. Hi IG, do you know Qubes?
    “Qubes implements Security by Isolation approach. To do this, Qubes utilizes virtualization technology, to be able to isolate various programs from each other, and even sandbox many system-level components, like networking or storage subsystem, so that their compromise don’t affect the integrity of the rest of the system.

    Qubes lets the user define many security domains implemented as lightweight Virtual Machines (VMs), or “AppVMs”. E.g. user can have “personal”, “work”, “shopping”, “bank”, and “random” AppVMs and can use the applications from within those VMs just like if they were executing on the local machine, but at the same time they are well isolated from each other. ” http://qubes-os.org/
    Might be interesting for you…I’m curious what you make of it.

    Comment by Pablo | April 27, 2011

    • Hi Pablo, Thanks for the summary. I have heard of Qubes and I did look their site over a few months ago – seems to be in heavy dev but it has some promising ideas. Linux can definitely do better from a security standpoint. I do intend to keep an eye on Qubes.

      Comment by IgnorantGuru | April 28, 2011

  13. Thank you for sandfox. I run it on Linux Mint 10 (=Ubuntu 10.10 maverick).

    This might be useful information:
    how to open url in preferred / default web browser in sandboxed firefox in Gnome2
    gconf-editor
    /desktop/gnome/url-handlers/http/command
    sandfox firefox %s
    The same you can do for your default email client. If you wish to run Thunderbird in the same sandbox as Firefox:
    /desktop/gnome/url-handlers/mailto/command
    sandfox ––sandbox=firefox thunderbird %s
    Or create separate sandbox for your email client.
    I use Thunderbird for email and also for RSS, so it is useful to close it in sandbox.
    Share your ideas :)
    Cheers

    Comment by arapaho | May 22, 2011

    • Sorry, I was to fast sharing this trick.
      For some reason gconf-editor doesn’t want to save this configuration and when I click on url in Tomboy it opens normal Firefox session without sandfox. If you know how to deal with it, let me know.

      Comment by arapaho | May 22, 2011

      • I’m not very familiar with gnome, but in general you need to learn how to change your default browser (in some cases this is set in the options of individual apps, and there are also system-wide settings – eg the BROWSER variable, gnome settings, etc). You can set the default browser to “sandfox firefox”, or if that causes problems, create a script called “firefox-start” which contains something like:

            #!/bin/bash
            sandfox firefox "$@" &
        

        Then set your default browser as firefox-start. (Be sure to install your custom “firefox-start” script for good security.)

        Using the same sandbox for email and web browsing might not be a good idea from a privacy/security perspective. I would suggest creating a separate sandbox profile and sandbox for Thunderbird.

        Comment by IgnorantGuru | May 22, 2011

  14. I tried running the script on Gentoo.
    It works fine with Firefox, however, does not seem to work with Skype, due to

    >>> mount –bind “/usr/share/skype” “/mnt/sandfox/skype/usr/share/skype”
    >>> mount -o remount,noatime,nosuid “/mnt/sandfox/skype/usr/share/skype”
    sandfox: Error: bind mount failed on /mnt/sandfox/skype/usr/share/skype

    I am not quite sure what to do about that. I do have /usr/share/skype.

    Comment by prok | June 28, 2011

    • It also seems to bind mount /opt/skype onto /opt/skype

      Comment by prok | June 28, 2011

    • From what you pasted, it doesn’t appear that mount is producing an error msg, so sandfox may be having problems interpreting mtab (perhaps it thinks it isn’t mounted when it is). Sandfox uses ‘mount | grep’ for this, as you can see in the script. But I don’t see why it would do this for just that one folder. ‘mount’ should produce lines like this:

          /usr/share/skype on /mnt/sandfox/skype/usr/share/skype type none (nosuid,bind,noatime)

      You could also try removing the line “bind=/usr/share/skype” from the skype profile (in /etc/sandfox/skype.profile). Since all of /usr is already bindro, it may not be necessary to bind /usr/share/skype. But I don’t use skype so I can’t say for sure.

      As for /opt/skype, I don’t see how it could be attempting to bind mount it onto itself. I’ll need to see the profile line containing /opt/skype (or the whole profile), the verbose output (use ––verbose), and the mtab line containing /opt/skype (mount | grep /opt/skype). You can email them if you prefer. Thanks.

      Comment by IgnorantGuru | June 29, 2011

      • Thank you for your help. I started debugging the script, and found out that the problem was specific to Gentoo.
        In Gentoo’s ebuild one of the last lines is

        dosym /opt/skype /usr/share/skype

        which was the cause of all problems. Replacing /usr/share/skype with /opt/skype in /etc/sandfox/skype.profile fixed the problem

        Comment by prok | June 30, 2011

        • Ok thanks for letting me know the solution.

          Comment by IgnorantGuru | June 30, 2011

  15. Hi, wow very nice script. I’m lovin it … it’s really helpful …
    but one question i have …

    How can i activate to log?
    I’ using “sandfox firefox –logfile test.log”

    Problem is, the log file is empty …
    I have set the permission to: -rw-rw-rw- …

    Comment by Jim | September 28, 2011

    • Sandfox’s options must preceed the command:

          sandfox --logfile /tmp/sandfox.log firefox

      Otherwise you’re passing the logfile option to firefox rather than to sandfox. Also note that the logfile should be accessible from within the sandbox (/tmp is a good location). Thanks for your feedback.

      Comment by IgnorantGuru | September 28, 2011

      • Thanks for you quick support … No it work’s … :)

        Comment by Jim | September 28, 2011

  16. Sandfox worked flawlessly for me in Debian Testing – after swapping over to systemd from sysvinit running sandfox now gives errors “/mnt/sandfox: cannot mount read only file system” – & /root becomes read only until after a reboot. Something to do maybe with /etc/mtab being a symlink to /proc/self/mounts ?

    Comment by Stuart. | October 4, 2011

    • That error appears to be coming from mount, but I’ve never seen that. If this problem occurs when starting sandfox during boot using an init script, does it work normally when starting sandfox later after login? If it works normally later, you probably need to run sandfox later in the boot process when the filesystems are rw (I can show you how to create a delay from an init script if needed).

      If that doesn’t help, please have sandfox save a verbose logfile and email that to me (you can obfuscate any personal info or usernames in the logfile). Or you can just post it here if you prefer. To generate the logfile, run sandfox something like this (adding any additional arguments at the end):

          sandfox --verbose --logfile /tmp/sandfox.log

      FYI, sandfox does not read mtab directly but reads the output of mount.

      Comment by IgnorantGuru | October 5, 2011

  17. I could never get sandfox to start cleanly during the boot process – I always manually started the service after logging in with no problems. After a clean boot with no sandfox service running & deleting /mnt/sandfox I ran the following from a root prompt:

    sandfox started 2011-10-05 23:13:24 on my-machine
    /usr/bin/sandfox --verbose --logfile /tmp/sandfox.log --sandbox firefox /path/to/firefox/firefox
    -- SNIP --
    2011-10-05 23:13:24: Creating new sandbox "firefox"
    2011-10-05 23:13:24: Processing bindro /bin
    2011-10-05 23:13:24: >>> mount --bind "/bin" "/mnt/sandfox/firefox/bin"
    2011-10-05 23:13:24: >>> mount -o remount,noatime,nosuid,ro "/mnt/sandfox/firefox/bin"
    2011-10-05 23:13:25: sandfox: Error: bindro mount failed on /mnt/sandfox/firefox/bin
    2011-10-05 23:13:25: >>> umount "/mnt/sandfox/firefox/bin"
    2011-10-05 23:13:25: Removing /mnt/sandfox/firefox
    2011-10-05 23:13:25: >>> find "/mnt/sandfox/firefox" -xdev | sort -r
    2011-10-05 23:13:25: sandfox: Error: Not all files could be safely removed from /mnt/sandfox/firefox
    2011-10-05 23:13:25:          This may indicate a hidden bind mount.  It is recommended
    2011-10-05 23:13:25:          that you reboot or backup original folders before
    2011-10-05 23:13:25:          manually removing /mnt/sandfox/firefox as root.
    

    I’ve noticed during the recent problems that sometimes /bin does get mounted but then /etc fails as /root has become read only (I used to mount /root in fstab as remount-ro on errors but have since removed this option)

    Comment by Stuart. | October 5, 2011

    • Please close all open sandboxes or reboot, then run the following series of commands as root and post the output:

      mkdir -p /mnt/sandfox/firefox/bin
      mount --bind "/bin" "/mnt/sandfox/firefox/bin"
      mount -o remount,noatime,nosuid,ro "/mnt/sandfox/firefox/bin"
      mount | grep /mnt/sandfox/firefox/bin
      mount -V
      umount /mnt/sandfox/firefox/bin
      rmdir /mnt/sandfox/firefox/bin /mnt/sandfox/firefox /mnt/sandfox
      

      I don’t understand what you mean by /root becoming read-only – I don’t think that would have to do with sandfox. Thanks.

      Comment by IgnorantGuru | October 5, 2011

      • root@my-machine:/home/the-user# mkdir -p /mnt/sandfox/firefox/bin
        root@my-machine:/home/the-user# mount --bind "/bin" "/mnt/sandfox/firefox/bin"
        root@my-machine:/home/the-user# mount -o remount,noatime,nosuid,ro "/mnt/sandfox/firefox/bin"
        root@my-machine:/home/the-user# mount | grep /mnt/sandfox/firefox/bin
        /dev/disk/by-uuid/707187b4-d8c5-44ab-a818-9f8d5f951e26 on /mnt/sandfox/firefox/bin type ext4 (ro,nosuid,noatime,user_xattr,acl,barrier=1,data=ordered)
        root@my-machine:/home/the-user# mount -V
        mount from util-linux 2.19.1 (with libblkid and selinux support)
        root@my-machine:/home/the-user# umount /mnt/sandfox/firefox/bin
        root@my-machine:/home/the-user# rmdir /mnt/sandfox/firefox/bin /mnt/sandfox/firefox /mnt/sandfox
        rmdir: failed to remove `/mnt/sandfox/firefox/bin': Read-only file system
        rmdir: failed to remove `/mnt/sandfox/firefox': Read-only file system
        rmdir: failed to remove `/mnt/sandfox': Read-only file system
        

        It’s something to do with booting with systemd, with sysvinit I have no problems. I think I’ll revert back to it as I’d rather have sandfox working again than a slightly quicker boot.

        If you can let me know how to create a delay in the init script you mentioned in your first reply I would be most grateful.

        Comment by Stuart. | October 5, 2011

        • It doesn’t appear that bind mounts, or perhaps the remount, is being performed correctly on your system, despite the fact that you’re using the same version of mount as I. If you want to try it, these commands might give me a little more info on the situation (also as root, with no sandboxes open):

          mkdir -p /mnt/sandfox/firefox/bin
          mount --bind "/bin" "/mnt/sandfox/firefox/bin"
          mount | grep /mnt/sandfox/firefox/bin
          mount -o remount,noatime,nosuid,ro "/mnt/sandfox/firefox/bin"
          mount | grep /mnt/sandfox/firefox/bin
          umount /mnt/sandfox/firefox/bin
          rmdir /mnt/sandfox/firefox/bin /mnt/sandfox/firefox /mnt/sandfox
          

          At any rate, I’ll keep this in mind if I get a chance to try systemd.

          To background the startup of sandfox and create a delay in the init script, you can do something like this:

              ( sleep 10 ; /usr/bin/sandfox --profile firefox --sandbox firefox --user myuser ) &

          The only caveat is that the init script will always return ‘success’. The above line will wait 10 seconds, then run sandfox. The entire script inside the parentheses will be backgrounded.

          Comment by IgnorantGuru | October 5, 2011

          • I think I “get to keep both pieces” after playing with systemd – now i have the same errors with both init systems. Will try again on a clean install. Thank you for the note on the init script.

            Comment by Stuart | October 5, 2011

  18. I have the latest version of sandfox installed but already from before this update the startup script for doesn’t work fr me anymore.
    When I start sandfox up after booting with sudo sandfox firefox with the daemon blocked in the daemon list in rc.conf no problem.
    But when I use the daemon and startup script sandfox firefox doesn’t work and no useful error messages. When I use firefox a non -sandboxed version of firefox starts. A message that could point to the error that everytime sandfox starts firefox up, there is the message there is already a firefox running even if I have just killed all firefox processes. I suppose it has something to do with sandfox not propery closing as I regularly have to delete obsolete firefox sessions in sandfox.

    Comment by Pablo | December 7, 2011

    • To get error messages during startup, change this line in the startup script:

          $sandfoxbin --profile $sandfoxprofile --user $sandfoxuser

      to:

          $sandfoxbin --profile $sandfoxprofile --user $sandfoxuser --verbose --logfile /tmp/sandfox.log

      OR, you can try:

          $sandfoxbin --profile $sandfoxprofile --user $sandfoxuser --verbose &> /tmp/sandfox.log

      After startup, run:

         sandfox --status

      to see if a sandbox was created. (You may want to remove /mnt/sandfox prior to booting for a clean test.)

      Have a look in /tmp/sandfox.log for error messages. Try to start firefox as a normal user with:

        sandfox firefox

      then look at the end of /tmp/sandfox.log again for any new error messages.

      As for the warning that firefox is already running, it is just a warning so it won’t interfere. It’s not a perfect method, but this is what sandfox runs to determine if firefox is already running:

          ps -u USERNAME -o "%U %a" | grep -v "grep" | grep -e " *firefox$" -e " *firefox "

      Change USERNAME to your username and run that command yourself. If it produces any output, sandfox issues the warning.

      If you can give me more info on “sandfox not properly closing” I might be able to address that – what message do you receive when closing the sandbox(es), and what files remain in /mnt/sandfox/SANDBOXNAME ? Thanks.

      Comment by IgnorantGuru | December 8, 2011

  19. This last bit of the log might give a clue:
    commandline: Option watch /tmp/sandfox-events/firefox
    >>> inotifywait -eq modify “/tmp/sandfox-events/firefox”
    Executing /tmp/sandfox-events/firefox/firefox-8165.sh…
    Deleting /tmp/sandfox-events/firefox/firefox-8165.sh…
    >>> inotifywait -eq modify “/tmp/sandfox-events/firefox”
    No protocol specified
    No protocol specified
    Error: cannot open display: :0
    No protocol specified

    When I look into tmp/sandfox-events/firefox as root I can find nothing there.
    This log I provide was after sandfox was properly removed in an earlier session.

    Btw I have found the reason, I think, why sf doesn’t often doesn’t close down properly. I could only remove the sandfox folder in mnt after I closed pcmanfm-mod with the sf_download folder open in which I store all my firefox downloads and that is often open.

    Comment by Pablo | December 8, 2011

    • It looks like the xserver is refusing Firefox permission to access the display. This is usually caused by a missing or stale (outdated) ~/.Xauthority file in the sandbox. When the sandbox is created during startup, that file is either not present or it later changes. In some cases you can simply touch ~/.Xauthority to create it prior to running sandfox in the startup script. eg:

          su $sandfoxuser -c "touch /home/$sandfoxuser/.Xauthority"

      In other cases you need to delay the sandbox creation until after your user has logged in. eg a line like this in your startup script:

          ( while [ ! -e /home/$sandfoxuser/.Xauthority ]; do sleep 1; done; \
            $sandfoxbin --profile $sandfoxprofile --user $sandfoxuser ) &

      (That says while .Xauthority file doesn’t exist, sleep, then create the sandbox.)

      If the problem is a stale .Xauthority file, you may need to delete that file during shutdown for this to work ( perhaps delete it in /etc/rc.local.shutdown ). Alternatively you can use some other test to determine when the user has logged in. If you work out a startup script that works well with Arch I can update the example above. However, it would be good to know if the problem is Arch-wide or specific to some aspect of your particular setup.

      > I could only remove the sandfox folder in mnt after I closed pcmanfm-mod with the sf_download folder open

      Like a drive unmount, you must close programs accessing the sandbox (usually closing the tab in pcmanfm-mod is sufficient). pcmanfm-mod uses fam or gamin to monitor any open folder, which is probably what is stopping the sandbox closure. This is unavoidable.

      Comment by IgnorantGuru | December 8, 2011

  20. This alteration of the start section of the startup script in /etc/rc.d solves the problem for me:
    start() {
    stat_busy “Starting Sandfox”
    ( while [ ! -e /home/$sandfoxuser/.Xauthority ]; do sleep 1; done; \
    $sandfoxbin –profile $sandfoxprofile –user $sandfoxuser ) &
    if [ $? -gt 0 ]; then
    stat_fail
    else
    add_daemon sandfox
    stat_done
    fi

    Comment by Pablo | December 8, 2011

    • I forgot to add that I have no idea if my problem is specific to my set up.. the only thing that points that way that while advertising sandfox regularly on the AB forum, – I think it is indispensable-, I haven’t encountered help questions like mine. For the rest I don’t think I have such a unique set up. Thanks, IG, for helping me solve this.

      Comment by Pablo | December 8, 2011

      • Thanks – I’ll at least add a note about the issue to the example.

        Comment by IgnorantGuru | December 9, 2011

  21. Again unable to start sandfox using firefox; error message after closeall message to be sure no sandfoxes running anymore:
    There are no usable sandbox daemons running for paul – make has been enabled
    Loading profile “default”
    Loading profile “firefox”
    Creating new sandbox “firefox-a3bd”
    mount: /mnt/sandfox/firefox-a3bd/bin is busy
    sandfox: Error: bindro mount failed on /mnt/sandfox/firefox-a3bd/bin

    These are the errors that I get using the steps as described in comment 17:
    mount -o remount,noatime,nosuid,ro “/mnt/sandfox/firefox/bin”
    mount: /mnt/sandfox/firefox/bin is busy

    mount | grep /mnt/sandfox/firefox/bin
    /dev/sda11 on /mnt/sandfox/firefox/bin type ext4 (rw,relatime,user_xattr,acl,barrier=1,data=ordered)

    mount from util-linux 2.20.1 (with libblkid support)

    rmdir /mnt/sandfox/firefox/bin /mnt/sandfox/firefox /mnt/sandfox
    rmdir: failed to remove `/mnt/sandfox/firefox’: Directory not empty
    rmdir: failed to remove `/mnt/sandfox’: Directory not empty

    The only change in the system I made before errors started, was this install:
    http://www.archlinux.org/news/filesystem-upgrade-manual-intervention-required/

    Comment by Pablo | December 22, 2011

    • with the verbose option I get this feedback:
      >>> mount –bind “/bin” “/mnt/sandfox/firefox/bin”
      >>> mount -o remount,noatime,nosuid,ro “/mnt/sandfox/firefox/bin”
      mount: /mnt/sandfox/firefox/bin is busy
      sandfox: Error: bindro mount failed on /mnt/sandfox/firefox/bin
      >>> umount “/mnt/sandfox/firefox/bin”
      Removing /mnt/sandfox/firefox
      find “/mnt/sandfox/firefox” -xdev | sort -r

      Comment by Pablo | December 26, 2011

      • It appears that remounting bind mounts as readonly isn’t working normally, which may mean they broke something in util-linux 2.20, or that Arch broke something. I’ll look into this further when I have a chance – thanks for the report.

        Comment by IgnorantGuru | December 26, 2011

        • I see that a dependency of util-linux is filesystem which may indicate that the updated filesytem may be involved.

          Comment by Pablo | December 26, 2011

          • If there has been no improvement on this, you might try changing the bindro mounts in your profiles (default.profile and firefox.profile at least) to bind mounts. It seems your problem is specifically on the error when sandfox attempts to remount a bind mount read-only. Not sure what else I can do about this as sandfox requires that. The difference is that with a bindro mount, even if your user can write to a file based on permissions, they will be denied because of the ro mount, whereas with a bind mount they can change the file if permissions allow (which also affects the original filesystem). So if your permissions and ownership are set carefully, bind is nearly as good.

            Comment by IgnorantGuru | January 21, 2012

            • Tried sudo sandfox –verbose firefox with bindro replaced by bind in default.profile and firefox.profile

              and get this error:

              Creating new sandbox “firefox”
              Processing bind /bin
              >>> mount –bind “/bin” “/mnt/sandfox/firefox/bin”
              >>> mount -o remount,noatime,nosuid “/mnt/sandfox/firefox/bin”
              sandfox: Error: bind mount failed on /mnt/sandfox/firefox/bin

              So this doesn’t seem to solve the issue.

              Comment by Anonymous | January 21, 2012

              • So it looks like any remount, at least of a bind mount, is failing. mount is not working correctly on your system.

                Comment by IgnorantGuru | January 21, 2012

                • Strange that I don’t have problems mounting partitions or external hard drives.
                  But if I’m the only one having this problem, it should be on my side.
                  I will ask people on the AB forums to try and find out if they can replicate my error.

                  Comment by Pablo | January 21, 2012

                  • I had the same problem appear on Crunchbang running Debian Testing about 2-3 weeks ago. I did a clean install of Antix Linux Base (also based on Testing) – same errors.The errors caused my entire root partition to become mounted read-only. I have no problems with external drives mounting automatically in PCManFM-mod.

                    Comment by Stuart. | January 21, 2012

                  • Sandfox uses bind mounts and remounts them, which is a somewhat obscure use of mount – not something most people do just when mounting drives, etc. So it’s possible they broke something and no one has noticed it yet.

                    Since you can’t give options when creating a bind mount, you have to remount it for those options, such as ro (as in bindro). So remounting is important to the use of bind mounts. A bug should be filed on this inability to remount bind mounts.

                    Here’s your test which should succeed but does not:

                        # as root:
                        mkdir /mnt/testbind
                        mount --bind /bin /mnt/testbind
                        mount -o remount,nosuid /mnt/testbind

                    Comment by IgnorantGuru | January 21, 2012

                    • This test goes well without errors…

                      Comment by Pablo | January 22, 2012

                    • > This test goes well without errors…

                      Ahh… maybe it’s the noatime (which probably doesn’t apply to bind mounts anyway), although the error isn’t right. See what this says:

                          # as root:
                          umount /mnt/testbind 2> /dev/null
                          mkdir -p /mnt/testbind
                          mount --bind /bin /mnt/testbind
                          mount -o remount,nosuid /mnt/testbind
                          mount -o remount,noatime /mnt/testbind
                          mount -o remount,ro /mnt/testbind
                          mount -o remount,noatime,nosuid,ro /mnt/testbind
                          umount /mnt/testbind

                      Comment by IgnorantGuru | January 22, 2012

                    • Others on the AB forum face the same problem: http://bbs.archbang.org/viewtopic.php?pid=10152#p10152

                      Comment by Pablo | January 22, 2012

                    • I tried and here it goes wrong:
                      [root@archbang paul]# mount -o remount,noatime /mnt/testbind
                      [root@archbang paul]# mount -o remount,ro /mnt/testbind
                      mount: /mnt/testbind is busy

                      Comment by Pablo | January 22, 2012

                    • Make sure /mnt/testbind is NOT mounted, then run:

                          # as root:
                          umount /mnt/testbind  # should produce a 'not mounted' error
                          mkdir -p /mnt/testbind
                          mount --bind /bin /mnt/testbind
                          mount -o remount,ro /mnt/testbind
                          umount /mnt/testbind

                      If the remount,ro line produces an error, then that is what is failing which should not be.

                      Comment by IgnorantGuru | January 22, 2012

                • Indeed, what you predicted happened:
                  root@archbang paul]# mount -o remount,ro /mnt/testbind
                  mount: /mnt/testbind is busy

                  Comment by Pablo | January 23, 2012

                  • That is what should be reported as a bug, and that is your test case which should not fail. There may be other issues too but that one is a start.

                    Comment by IgnorantGuru | January 23, 2012

                  • Matbe a dumb question. Should this be reported on the Arch forums or to the devs of which application ?

                    Comment by Pablo | January 23, 2012

                    • I suggest reporting it against util-linux in Arch Bugs as a start, and maybe also mention that it coincided with that filesystem update you underwent. Give them the test below and tell them it’s breaking scripts such as sandfox that use bind mounts. Don’t let anyone tell you this is normal because you should be able to remount a bind mount ro.

                          # as root with /mnt/testbind UNmounted:
                          umount /mnt/testbind  # should produce a 'not mounted' error
                          mkdir -p /mnt/testbind
                          mount --bind /bin /mnt/testbind
                          mount -o remount,ro /mnt/testbind  # fails here
                          umount /mnt/testbind

                      Comment by IgnorantGuru | January 23, 2012

  22. Thanks for this simple, elegant gem.

    There’s a few changes I had to make to run it for firefox 7 in backtrack 5. Sandfox wouldn’t run optified versions of Firefox (e.g. Firefox 7) because the actual Firefox executable is located at /opt/firefox/firefox-bin, and that path wasn’t allowed in the default Firefox profile. Also, it would show a warning that Firefox was already running when it wasn’t. Apparently, this was because the daemon names the profile ‘firefox’ by default, and so has the word in its command line, which the script greps for the word ‘firefox’. Here is my patch:

    Step 1 – Patch the multiple instance check

    In sandbox-1.1.1.sh, find lines 1445-1446 which should look like this:

    testrunning=`ps -u $user -o “%U %a” | grep -v “grep” \
    | grep -e ” *${bcmd%% *}$” -e ” *${bcmd%% *} “`

    Change them to this:

    testrunning=`ps -u $user -o “%U %a” | grep -v “\bgrep\b” \
    | grep -v “\bsandfox\b” \
    | grep -e “\b${bcmd%% *}\b”`

    Step 2 – Patch the Firefox default profile generator

    In sandbox-1.1.1.sh, find lines 629-631 which should look like this:

    # root folders and files required by firefox
    bindro=/bin
    bind=/dev/null

    Insert ‘bindro=/opt/firefox’ at line 631, so it now looks like this:

    # root folders and files required by firefox
    bindro=/bin
    bindro=/opt/firefox
    bind=/dev/null

    Step 3 – Patch the actual Firefox default profile

    NOTE: This step is only necessary if you have already run sandfox and it generated the /etc/sandfox directory.

    In /etc/sandfox/firefox.profile, find lines 14-16 which should look like this:

    # root folders and files required by firefox
    bindro=/bin
    bind=/dev/null

    Insert ‘bindro=/opt/firefox’ at line 16, so it now looks like this:

    # root folders and files required by firefox
    bindro=/bin
    bindro=/opt/firefox
    bind=/dev/null

    IgnorantGuru: This patch should be backward compatible, and you are welcome to apply it to the mainline if you wish.

    Comment by drifter | December 29, 2011

    • I’ll look this behavior over the next time I work on sandfox, which should be shortly. It is true that for some setups you’ll need to add a few binds, but I think /opt/firefox is a reasonable default, so I’ll add that. As for the ‘firefox is running’ warning, I thought I had it more discriminating than that, but it’s a rudimentary test – if you’re sure firefox isn’t running it can be ignored. Thanks for letting us know what worked for you and for your patches.

      Comment by IgnorantGuru | December 30, 2011

  23. After a recent upgrade of my archlinux system, sandfox didn’t work anymore.

    Loading profile “default”

    Creating new sandbox “niko”
    mount: /mnt/sandfox/niko/bin is busy
    sandfox: Error: bindro mount failed on /mnt/sandfox/niko/bin

    Also, it remounted my root dir as read-only.

    I found that /etc/mtab is now a symlink to /proc/self/mounts which may be the cause.

    $ mount –version
    mount from util-linux 2.20.1 (with libblkid support)

    The remounting of a bound mount point now needs to include the bind flag
    (the mount man page has a note about that):
    mount -o remount,ro,bind

    Also, the fs type of a bound target doesn’t appear as ‘none’ as it used to, but as the
    original fs type.

    So I just made these changes to make it work again:

    #mopt=”remount,noatime,nosuid,ro”
    mopt=”remount,noatime,nosuid,ro,bind”
    else
    #mopt=”remount,noatime,nosuid”
    mopt=”remount,noatime,nosuid,bind”

    if [ “$1” = “bindro” ] && [ “$2” != “/dev/random” ] && [ “$2” != “/dev/urandom” ]; then
    #test=`mount | grep ” on $3 type none (.*ro.*)”`
    test=`mount | grep ” on $3 type .* (.*ro.*)”`
    else
    #test=`mount | grep ” on $3 type none “`
    test=`mount | grep ” on $3 type .* “`
    fi

    Comment by niko | January 23, 2012

    • Thanks for the info on this. I just updated debian sid and while the bind in remount isn’t required here, the type did change as you describe. I’ll update sandfox later today.

      EDIT: These problems should now be corrected in sandfox 1.1.2

      Comment by IgnorantGuru | January 24, 2012

  24. @ niko: Having the same problem I thought this would solve it for me.
    But where do you put this code, how did you use it?

    Comment by Pablo | January 24, 2012

    • Found it in sandfox.sh in /usr/bin/. lines 436 and 452. Get this error after changing sandfox.sh and sudo sandfox firefox:
      There are no usable sandbox daemons running for paul – make has been enabled
      Loading profile “default”
      Loading profile “firefox”
      Creating new sandbox “firefox”
      mount: /dev/sda11 already mounted or /mnt/sandfox/firefox/bin busy
      mount: according to mtab, /dev/sda11 is already mounted on /mnt/sandfox/firefox/bin
      grep: on: No such file or directory
      grep: type: No such file or directory
      grep: “: No such file or directory
      sandfox: Error: bind mount failed on /mnt/sandfox/firefox/bin

      Sda11 is the Arch partition.

      Comment by Anonymous | January 24, 2012

      • sandfox 1.1.2 works for me. Thanks..

        Comment by Pablo | January 24, 2012

        • Yes 1.1.2 fixed it for me also on Debian Testing ;o)

          Comment by Stuart | January 24, 2012

  25. Howdy. How do I let a regular, non-root user SSH in and when they login automatically load “sandfox firefox” ?

    Comment by noisome | April 13, 2012

    • I haven’t tried sandfox with ssh so I can’t think of anything specific to suggest. Sandfox just creates mounts, so any problems via ssh are likely due to missing environment variables, or directories not accessible in the sandbox which are required by the ssh user. You might try the ‘Gettings Programs To Run Well In a Sandbox’ section above for general tips.

      Comment by IgnorantGuru | April 14, 2012

  26. Just a tip to get ALSA sound running correctly:
    After having set up a new system, I noticed that Youtube videos had no sound when Firefox was running within sandfox.
    I found out that the gnash plugin was using the wrong ALSA sound device (my motherboard has two sound devices).
    I solved it by adding
    bindro=/home/$user/.asoundrc
    to my firefox profile.

    Comment by mikan | June 30, 2012

    • Thanks for the tip – next time sandfox is updated I’ll probably add that to the default config.

      Comment by IgnorantGuru | July 1, 2012

  27. I managed to get the init script running properly on every boot in Debian with “update-rc.d sandfox start 70 4 5 . stop 70 0 1 6 . ” – I’ve put a script up to load multiple profiles & also example profiles for Thunderbird / Pidgin & a list of directories to make Sandfox work with Skype 4.0 at:

    http://crunchbanglinux.org/forums/post/241891/#p241891

    For Skype 4.0 it would be nice to be able to wildcard numerical directories under /proc. Apparmor achieves this with:

    owner @{PROC}/[0-9]*/task/ r,
    owner @{PROC}/[0-9]*/task/[0-9]*/stat r,

    Comment by Stuart | July 12, 2012

  28. In Firefox under sandfox doesn’t work user compose settings from ~/.XCompose, though I added “bind=/home/$user/.XCompose” in firefox profile. System default compose settings from /usr/share/X11/locale/en_US.UTF-8/Compose are working fine. Any help please?

    Comment by DaarkWel | October 23, 2012

    • I don’t have any experience with those settings specifically, but this is almost always due to another file or folder being needed. stdout might have some info as suggested here.

      Comment by IgnorantGuru | October 24, 2012

      • I kinda figured it out — firefox needs environment variable “GTK_IM_MODULE=xim” to properly work with ~/.XCompose, and I set

        export “GTK_IM_MODULE=xim”

        in my ~/.xinitrc file. But sandfox doesn’t copy this variable:

        sudo sandfox –profile firefox.profile bash

        and then “env” — there’s no “GTK_IM_MODULE=xim”. I have to export GTK_IM_MODULE=xim manually in sandfox and then variable is set. Now I can to run firefox in sandfox by

        sudo sandfox –profile firefox.profile “GTK_IM_MODULE=xim firefox”

        It works all right but it’s kinda ugly I guess. Is there way to set environment variables in profile?

        Comment by DaarkWel | November 9, 2012

        • You cannot set env vars in the profile. When a user runs sandfox to start Firefox, the environment variables present are passed to the sandfox user daemon so the program sees them. So iow setup the sandbox, then run firefox like this (as your non-root user):

              GTK_IM_MODULE=xim sandfox firefox

          I’ll take a better look at this shortly – thanks for the info.

          Comment by IgnorantGuru | November 9, 2012

  29. IgnorantGuru,
    Is there any way to add code to your script to transfer downloaded files from the sandbox to the actual download location besides navigating into the sandbox to retrieve the file(s), like Sandboxie does in Windows? I haven’t tried to write any code yet myself.

    BTW,
    You’re quite a code writer. Also, Sandfox seems to work well in Precise. I couldn’t get it to work in Cinnarch with systemd.

    Thank you. :).

    Later…

    Bob

    Comment by Bob Good | December 26, 2012

    • Hi, You can bind a download location into the sandbox such that any files written there are written to the real filesystem, so no need to transfer them. See /etc/sandfox/firefox.profile and add a bind=

      Sandfox should work with just about any setup – but I haven’t explored the particulars of starting it with systemd. Thanks for the feedback.

      Comment by IgnorantGuru | December 27, 2012

  30. Hey IgnorantGuru,
    I really like your program, exactly what I was looking for. Thanks a lot for that!

    On my system, the sandbox is created just fine, if I initialize it myself but I have some problems to initialize it during the boot process. Sometimes it even deletes my whole firefox profile when booting but that is only a minor setback.
    The real problem I have is, that I cannot use the sandbox created at start-up. I have a fresh Arch-Linux installation in systemd-configuration so I first had to enable the parallel use of the rc.d-initscripts by installing the initscripts package.
    This seems to work, since the folder /mnt/sandfox is created and when I type “sandfox –status”, I get this message:
    firefox
    Daemon: running (boris)
    Mounts: 24 /mnt/sandfox/firefox/
    Root Dirs: bin dev etc home lib lib64 proc tmp usr var
    By enabling the verbose command in your rc.d-script, I couldn’t detect any errors in the .log-file except for a warning that there is no /var/lib/mlocate.
    Typing “sandfox firefox” delivers the message “Starting firefox as boris in sandbox “firefox”…” but nothing happens after that. In the .log-file now appear the lines:
    2013-01-12 14:52:05: sandfox-daemon(): Started >>> /tmp/sandfox-events/tmp/sandfox –daemon –logfile /tmp/sandfox.log –verbose –watch /tmp/sandfox-events/firefox
    2013-01-12 14:52:05: sandfox-daemon(): commandline: Option verbose
    2013-01-12 14:52:05: sandfox-daemon(firefox): commandline: Option watch /tmp/sandfox-events/firefox
    2013-01-12 14:52:05: sandfox-daemon(firefox): >>> inotifywait -eq modify “/tmp/sandfox-events/firefox”
    2013-01-12 14:53:54: sandfox-daemon(firefox): Executing /tmp/sandfox-events/firefox/firefox-9931.sh…
    2013-01-12 14:53:54: sandfox-daemon(firefox): Deleting /tmp/sandfox-events/firefox/firefox-9931.sh…
    2013-01-12 14:53:54: sandfox-daemon(firefox): >>> inotifywait -eq modify “/tmp/sandfox-events/firefox”

    Since there is neither a detection of a display failure nor of a failure at all, it cannot be the .Xauthority-issue. I’m a bit clueless how to analyze the problem further so thanks in advance for any tips!

    Comment by boris321 | January 12, 2013

    • Hi, It looks like the sandbox is created okay and the user daemon is running firefox okay, so firefox is likely missing some file or folder that wasn’t adding to the sandbox at startup (usually because the user is not yet logged in, similar to the Xauthority issue). You might compare the files/folders in the sandbox created at startup with one created later to observe differences in their content.

      You also might try capturing the output in the init script – not sure if this works or not but it might provide you with any error being produced by firefox when you attempt to start it. eg:

          $sandfoxbin --profile $sandfoxprofile --user $sandfoxuser &>/tmp/sandfox-output

      You can also try starting firefox in the sandbox created at boot using root, so it will not use the user daemon. This means that you should see firefox’s error. eg:

          sudo sandfox --verbose firefox

      (firefox will be started as your normal user, not as root)

      Also, it should be possible to skip the rc.d script and just use systemd instead. If you come up with a systemd configuration for this let me know and I’ll consider adding it to this page and/or the tarball. sandfox has a new issue tracker here. You might also inquire about this in the Arch thread to see if others have this working with systemd.

      Comment by IgnorantGuru | January 14, 2013

  31. Hello, I installed your script in /usr/bin, I’ve added sandfox to init.d as you indicate, apparently everything works normally but when trying to do sandfox firefox or sudo sandfox firefox does not run the application (but not mark an error), the system monitor and sandbox –status indicates that it is in execution. The only way I have found to run the browser is:

    sudo service sandfox restart && sandfox firefox

    What do you think is the problem? My OS is Ubuntu 12.04 (x86)

    Comment by Perseo (@icaroperseo) | July 19, 2013

    • Expanding a bit, I installed the script in another PC using the same procedure and no problems even though both have similar characteristics, second on the problematic computer I had installed previously apparmor (I purged it before you install and configure your script) so I do not know if have relationship :-/

      Comment by Perseo (@icaroperseo) | July 19, 2013

      • I answer to myself, apparently this did the magic:

        sudo update-rc.d sandfox defaults 98 02

        Thank you for everything! :)

        Comment by Perseo (@icaroperseo) | July 20, 2013

  32. Me again, I thought I had found the solution to my problem but apparently did not. You will see, I followed to the letter what exposed here (with the exception of which I have adapted the startup script to start firefox and then fogger into a separate sandbox, is to say that I make 2 sandbox for 2 applications at startup -firefox and fogger-) but I noticed that when reviewing the firefox and fogger folder contents (after having started the system) same found in /mnt within the home folder of each one are only macromedia and adobe folders that is not “create” files and folders that other applications require, as expected causing applications to not run. So I can run my applications need to restart the sandfox service, once this is done all works very well.

    I have tried different solutions trying to solve the problem but have not found anything useful.

    I provide more information with the intention of you can guide me with my problem in the best way possible: My system is elementary OS (distribution based on Ubuntu 12.04) x86, previously had installed apparmor but purged from my system, also I have encrypted (encfs) my home folder and swap.

    If I missed something you might need, just let me know.

    Comment by Perseo | July 21, 2013

    • Hi, sorry for the delay. It sounds like apparmor might be blocking something on that one system. I don’t have any experience running it as a service. Usually with problems like this it’s trial and error to determine what required file(s) are not in the sandbox. Also note that sandfox has a new issue tracker here – your issue might get more visibility with other users there.

      Comment by IgnorantGuru | October 18, 2013

    • Have a look at my notes here http://crunchbang.org/forums/viewtopic.php?pid=241891%23p241891#p241891

      Comment by Stuart | October 18, 2013

  33. Hi IG….

    Firstly, thanks for this excellent tool, I came across it recently and it’s very impressive.

    I do have some set up questions, and some general ones… I hope this is the best place to ask them…?

    1) At first, I couldn’t get youtube and flash videos to run in the sandbox, and trying to setup Flash at the adobe manager page (http://www.macromedia.com/support/documentation/en/flashplayer/help/settings_manager07.html) just said I need to install Flash player. (Outside the sandbox it works fine). I played around a bit, and I can’t remember when/how it changed, but at some point I was able to run Flash… I was happy about that, until…
    I realized “sudo sandfox –closeall” wasn’t removing the /mnt/sandfox/firefox folder. I continued rebooting always using the same sandbox and that was ok, but then I figured if anything is left behind in the sandbox it would be better to follow the warnings from –closeall, so I removed the folder manually. After doing that, I can no longer run flash from inside the sandbox.

    Please can you tell me what I’m missing to get Flash and Youtube videos (I guess they’re mostly Flash or the ones that fail are, anyway) working?

    2) Question: I think you do recommend to completely remove the /mnt folder that sandfox creates each time. If I don’t do that, am I leaving shared objects and/or similar things that could compromise my privacy? Would that mean I need to install/use an add-on like Better Privacy?

    3) Conversely, if I do remove the /mnt folder, is that equivalent to “cleaning” out any intrusive objects? I imagine regular cookies are stored in my /home somewhere because the ones I allow are still allowed after removing the sandbox, but how about other cached data?

    4) I use tab groups and like to have a number of them open on startup, I keep history as well. So, I do want some stuff to remain. Perhaps I’m shooting myself in the foot, is it feasible to use sandfox in such a way that *only* allowed cookies remain, no image caches (perhaps I have to use about:config for this), no other data except my own tabs and history?

    Thanks for any help, I plan to set up startup/shutdown scripts once I have it working correctly!

    Comment by Tomas | January 24, 2014

    • > I do have some set up questions, and some general ones… I hope this is the best place to ask them…?

      This is fine, or for issues or technical questions you can use the new issue tracker.

      It’s not necessary to remove /mnt/sandfox in general. If you do want to remove it and closeall doesn’tremove it, I strongly suggest rebooting first. Usually it’s just a safety limit that triggers it to not be removed, but if certain mounts still exist, forcefully removing /mnt/sandfox can remove legitimate files. This is why closeall has a safety limit. I almost always hit that safety limit though, so at some point I may revise that.

      Aside from the directories listed in /etc/sandfox/firefox.profile, I can’t say what else would be required for Flash. Just a matter of trial and error to get it working, and you can see suggestions in the instructions above (how to make apps run well in a sandbox). If deleting /mnt/sandfox seems to have caused it, it may be an original file was removed, though in that case the unsandboxed firefox should show the same problem.

      > 2) Question: I think you do recommend to completely remove the /mnt folder that sandfox creates each time. If I don’t do that, am I leaving shared objects and/or similar things that could compromise my privacy? Would that mean I need to install/use an add-on like Better Privacy?

      It shouldn’t affect privacy, but you can examine the contents of /mnt/sandfox to see what remains. It will depend on the mounts used. Also be sure to distinguish between bind mounts that may exist there, and actual files that were copied there, or that are in bind mount trees. A bind mount looks very much like a file or directory to Linux, which is why removing them can have consequences for the original files. This is why sandfox treads lightly when removing /mnt/sandfox and files within it. mtab can also be deceiving.

      > 4) I use tab groups and like to have a number of them open on startup, I keep history as well. So, I do want some stuff to remain. Perhaps I’m shooting myself in the foot, is it feasible to use sandfox in such a way that *only* allowed cookies remain, no image caches (perhaps I have to use about:config for this), no other data except my own tabs and history?

      Any privacy settings would be configured within Firefox. Mostly sandfox determines what files in your home folder Firefox can access (and in some cases, create copies of files). If you like, you can create a separate Firefox profile with tighter security (see firefox ––profile), and use that from within the sandbox. This will allow you to adjust Firefox’s privacy settings for that session. Trying to tightly control Firefox’s internal behavior via sandfox is not practical. sandfox mostly determines what parts of the filesystem can be accessed by Firefox and processes it starts.

      Comment by IgnorantGuru | January 25, 2014

      • Awesome, thanks for those responses. Ok, more investigations re: flash required.
        And you made it clearer that sandfox is exactly what it says it is, a sandbox. I should use other methods to get privacy, although my primary concern is the security of the system, and I think you have that really well covered!

        Comment by Tomas | January 25, 2014

  34. Just thought I would drop this Debian Virtualization link here. It describes using the newer kernel namespaces from scripts and simple C programs. I didn’t realize they were so accessible from scripts. This is something that could make script-based sandboxes that much more contained.

    Comment by IgnorantGuru | February 17, 2014

  35. Hello. Just read the information about this promising software, and pending to test it, I want to suggest two possible improvements: (1) Using Xephyr as nest X server (it is used by selinux sandbox for security reasons), and (2) Using OpenVZ (or even Xen / UML / KVM) instead of chroot (OpenVZ is quite safer than chroot: for example OpenVZ offers (and chroot no) root privilege isolation, network isolation and full file system isolation. Note I don’t mention Linux-VServer or LXC because LXC has no root privilege isolation and full file system isolation and Linux-VServer has not full root privilege isolation and network isolation. More information about chroot: https://securityblog.redhat.com/2013/03/27/is-chroot-a-security-feature/ http://slashdot.org/story/07/09/27/2256235/when-not-to-use-chroot ). Much encouragement!

    Comment by Alexis | March 16, 2014

  36. An interesting post I came across on Reddit, where they were discussing SELinux:

    ‘chroot on linux isn’t a security feature, unlike for example freebsd jails it wasn’t designed to prevent access to the rest of the system, its just a convenience feature.

    Having it can give you a false sense of security thinking that you’re “protected” when you’re really not. Better to restrict access with selinux, which was actually designed for that purpose.’

    Comment
    byu/iheartrms from discussion
    inlinux

    Comment by omegaphil | March 17, 2014

    • Running as root in a chroot jail on Linux is not generally very secure – root may break out of the jail. Running as a non-root user in a root-created chroot jail (as sandfox does) is quite secure, at least in terms of limiting filesystem access, which is all that sandfox provides. It’s comparable to making a directory owned by root and inaccessible to non-root users – unless your system is broken, the user should not have access.

      SELinux, etc. are much more comprehensive and complex solutions, and Sandfox is not a replacement for them. Sandfox merely limits filesystem access using root-enforcement via a chroot jail, and unlike SELinux, etc it uses virtually no resources and doesn’t affect performance. It does not limit network access, limit root use, etc., except where these can be limited by limiting filesystem access (eg you can lock down sandboxes more tightly by restricting access to additional executables).

      Comment by IgnorantGuru | March 17, 2014

    • Also, it should be noted for those who aren’t aware – SELinux was written by the NSA. Stands to reason that they included their own (deniable, “oops we goofed”) backdoors/exploits, and I doubt very many people have reviewed the source, which is likely complex, meaning it’s easy to introduce an obscure exploit undetected. The NSA also authors malware intended to compromise your system security, so putting them in charge of your system security is highly questionable imo. Ofc people will argue and deny this but use some common sense.

      That’s not say Sandfox will keep out the NSA, but at least it doesn’t give them or anyone an engraved invitation or introduce backdoors possibly exploitable by others. Sandfox is mostly geared toward keeping Flash and other oft-exploited browser components limited.

      Comment by IgnorantGuru | March 18, 2014

  37. Ok, but modify Sandfox to use Xephyr as nest X server is easy and it add a additional level of security (for example: http://ubuntuforums.org/showthread.php?t=620003 http://nims11.wordpress.com/2012/06/24/nested-x-servers-with-xephyr/ ).
    Moreover, view the reasons given for using chroot in Sandfox, I still think OpenVZ (or else Linux-VServer or LXC) could be used instead of chroot (its complexity is not much higher than chroot). But I would not focus the debate only on this last point, because I would like the proposal to use Xephyr seriously take into account.

    Comment by Alexis | March 18, 2014

    • You can already use xephyr with sandfox – one person mentioned above that they had done so. Sandfox simply creates the sandbox – what you run in it is up to you, as is what parts of the filesystem are available. No plans to hard-code this into sandfox – you can create a profile for it.

      I agree that the new namespaces would be useful as applied to sandfox, but it would need to be rewritten.

      Comment by IgnorantGuru | March 18, 2014

    • Just something to note – theres no hardware acceleration what so ever for Xephyr (not even the host 2D acceleration from what I understand?), until Xephyr gets updated with a later X Server release, then GLAMOR acceleration will be available presumably through the builtin X library, which by that point will hopefully be faster than software…

      Comment by omegaphil | March 18, 2014

  38. Hi,

    On update-rc.d in Tanglu (Debian testing) I got the following errors:

    # update-rc.d sandfox defaults
    insserv: warning: script ‘K01sandfox’ missing LSB tags and overrides
    insserv: warning: script ‘sandfox’ missing LSB tags and overrides

    I’ve solved this by adding “INIT INFO” to the sandfox init script

    #!/bin/sh
    ### BEGIN INIT INFO
    # Provides: sandfox
    # Required-Start: $local_fs $network
    # Required-Stop: $local_fs
    # Default-Start: 2 3 4 5
    # Default-Stop: 0 1 6
    # Short-Description: sandfox
    # Description: Sandfox boot startup script for Ubuntu and similar
    ### END INIT INFO

    Cheers

    Comment by Alad Wenter | April 15, 2014

  39. You can run torBrowser in sandfox mode? command “sudo sandfox ./start-tor-browser” not work. :( .. Does anyone know how to do?

    Comment by Rogério | April 22, 2014

  40. Hey, @ignorantguru, I absolutely love your work. Sandfox is forever now a security essential for me. But I think that I may have had a chroot break last night. My computer (ubuntu vivid) told me that updates were available, so I clicked ‘install’… my kernel was overwritten and suddently lots of commands would not work, such as ‘who’ and ‘which’, also network-manager & nautilus completely stopped working. I ran ‘mount’ and saw that there were about 15 different sandfox box’s mounted. My computer was completely dysfunctional at this point so I don’t have the ouput of that commands. HOWEVER, I navigated to /mnt/sandfox and ran ‘tree > output’, which printed a HUGE list of directories that neither sandfox nor firefox had any business accessing. I did manage to save that output file, it’s about 3 or 4 MB’s long. I thought maybe you’d like to check it out and help me figure out what happened. I managed to remove to kernel that messed everything up and install the correct kernel, and than after a reboot everything went back to normal. Since there is sensitve information the output, I don’t want to post it here. Would you mind taking a look at this? I will email it to you. Thanks.

    Comment by xnemisis | July 1, 2015

    • Hi, Sandfox is fairly simple in terms of what it adds to the sandboxes in /mnt/sandfox. It should simply reflect the directories added in default.profile, and in firefox.profile. It could be bind mounts weren’t working properly on the system and it caused some unexpected behavior by mount. It sounds like there was a system problem due to your kernel issues – that’s really nothing to do with Sandfox directly, which just runs ‘mount’ and other basic programs (use verbose mode to see the exact commands it runs).

      If looking over the included dirs in the profiles doesn’t explain mounted dirs, you’re welcome to email me the log and I can take a quick look. I’ll also need to see the profiles, the sandfox command line, and preferably the verbose output from sandfox.

      Also, it’s normal for Sandfox to create multiple bind mounts which will appear in mtab. However, they should only reflect the dirs in the profiles. There haven’t been any problems with this for years, so it’s likely a system problem or possibly a usage or formatting change somewhere.

      Comment by IgnorantGuru | July 2, 2015