sbox-dtc-1.11.7/0000755000175000017500000000000012247552434012036 5ustar zigozigosbox-dtc-1.11.7/README.using_sbox.txt0000644000175000017500000000530412247552331015711 0ustar zigozigoTo use sbox-dtc, we advise the below example Apache vhost configuration. Note that /var/www/example.com should contain a full usable chroot disk, for example built using debootstrap, or an image of your favorite Unix system. With such a setup, both PHP, Python, Perl and Ruby scripts should work, served by the SBOX chroot. NameVirtualHost 10.0.0.1:80 ServerName www.example.com ScriptAlias /cgi-bin /usr/lib/cgi-bin AddHandler php-cgi-wrapper .php Action php-cgi-wrapper /cgi-bin/sbox AddHandler python-cgi-wrapper .py Action python-cgi-wrapper /cgi-bin/sbox AddHandler ruby-cgi-wrapper .rb Action ruby-cgi-wrapper /cgi-bin/sbox AddHandler ruby-cgi-wrapper .pl Action ruby-cgi-wrapper /cgi-bin/sbox Options +ExecCGI DocumentRoot /var/www/example.com/html RewriteEngine on RewriteCond %{REQUEST_URI} ^!/cgi-bin.* RewriteRule ^(.*) /cgi-bin/sbox/$1 [PT] DirectoryIndex index.php index.cgi index.pl index.py index.rb index.htm index.html index.php4 Then, you would have things like this in your disk: /var/www/example.com/{html,var,usr,tmp,...} On another setup, you can as well do: DocumentRoot /var/www/example.com/var/www This way, you can simply do: $ mkdir -p /var/www/example.com $ debootstrap --verbose --include=php5-cgi,wordpress \ --arch amd64 /var/www/example.com http://ftp.us.debian.org and then everything should follow, setup automatically, and work nicely, which is a quite cool setup! :) Note that now, what's annoying is apps that are hardly depending on a web server to be installed (eg: you wont want one in the chroot). Now, to start customizing SBOX for www.example.com, just do: cp /etc/sbox/sbox.conf /etc/sbox/vhosts.d/www.example.com and sbox will use this new file when it sees that HTTP_HOST value is for this vhost. This way, it is trivial to have different configurations for different sites on the same server. Also, if you intend to run PHP as cgi-bin in the chroot, there are couples of changes you have to make in your php.ini. Here's the directives: doc_root = /html cgi.force_redirect = 0 If you don't do that, PHP will complain about not having input. Also, I would like to add here that if you want unbreakable chroot, it is recommended to use the GR-Security kernels. Also, it is still possible to destroy any kind of setup within the chroot, which is still annoying. For example, your installed script would still be vulnerable to XSS scripting, MySQL insertions and so on. I would recommend to use mod_security at the same time as SBOX for these issues, so that you can have a chance to catch issues before they even reach your applicaiton. Enjoy the added security! -- Thomas Goirand Fri, 24 Jun 2011 20:32:12 +0800 sbox-dtc-1.11.7/env.c0000644000175000017500000000217212247552331012770 0ustar zigozigo#include #include #include #include #include #define MAXENV 1024 #ifdef PATH_MAX #define MAXPATH PATH_MAX #else #define MAXPATH 8192 #endif static char nm[MAXENV]; static char wd[MAXPATH+1]; int main(int argc, char** argv, char** e) { char *name,*delimiter; char timestr[1024]; DIR* dir; struct dirent* dirent; time_t now; printf("Content-type: text/plain\n\n"); printf("Arguments:\n"); printf("argc => %d, argv => ",argc); while (argc>0) { printf("%s ",*argv++); argc--; } printf("\n\n"); now = time(NULL); strftime(timestr,1024-1,"Localtime: %c %Z\n",localtime(&now)); puts(timestr); printf("Identity:\n"); printf("uid=%ld, gid=%ld\n\n",(long)getuid(),(long)getgid()); printf("Current Directory: %s\n\n",getcwd(wd,MAXPATH)); printf("Environment:\n"); while ((name = *e++)) { delimiter = (char*) strchr(name,'='); if (delimiter == 0) continue; if (delimiter - name >= MAXENV) continue; strncpy(nm,name,delimiter-name); nm[delimiter-name]='\0'; printf("%s => %s\n",nm,++delimiter); } return 0; } sbox-dtc-1.11.7/Makefile0000644000175000017500000000335512247552331013500 0ustar zigozigo# Makefile for sbox. # 1. Change the definition of CGI_DIRECTORY to point to your site-wide # cgi-bin directory # 2. Review the INSTALL_OPTS definitions if you need to (will install # sbox SUID to root) # 3. Change CFLAGS and CC definitions if you need to. # 4. "make" # 5. "make install" VERSION=1.11 CC=gcc COPTS= -O -g #COPTS = -g -DDEBUG #COPTS = -W -Wall -ansi -pedantic STATIC_FLAG=-static INSTALL_OPTS?= -o root -g bin -m 4111 -s INSTALL_TARGET_DIR?=/usr/lib/cgi-bin SYSCONFIG_DIR?=/etc INSTALL_MY_SYSCONF_DIR=$(DESTDIR)$(SYSCONFIG_DIR)/sbox INSTALL_DIRECTORY=$(DESTDIR)$(INSTALL_TARGET_DIR) CFLAGS += $(COPTS) -DVERSION=$(VERSION) INSTALL = install LYNX = lynx PURIFY = purify -chain-length="10" cc -g LIBS = -ldotconf default: sbox all: sbox env sbox: sbox.o $(CC) -Wall $(LDFLAGS) $(LDOPTS) -o sbox sbox.o $(LIBS) # strip sbox # strip -R .comment -R .note sbox chmod 4711 sbox sbox.o: sbox.c sbox.h Makefile sbox_pure: sbox.o $(PURIFY) -o $@ sbox.o env: env.o $(CC) $(STATIC_FLAG) -o env env.o README.txt: README.html $(LYNX) -nolist -underscore -dump $< > $@ clean: rm -rf *.o core sbox env *~ CVS_sbox* *.tar.gz build debian/tmp debian/substvars debian/files configure-stamp build-stamp # @-echo "OK, clean :)" install: sbox mkdir -p $(INSTALL_DIRECTORY) $(INSTALL) $(INSTALL_OPTS) sbox $(INSTALL_DIRECTORY) $(INSTALL) -D -m 0644 sbox.conf $(INSTALL_MY_SYSCONF_DIR)/sbox.conf dist: README.txt sbox.h sbox.c env.c Makefile -mkdir sbox-$(VERSION) cp README.html README.txt sbox.h sbox.c env.c Makefile sbox-$(VERSION) tar cvf - sbox-$(VERSION) | gzip -9c > sbox-$(VERSION).tgz rm -rf sbox-$(VERSION) deb: if [ -z $(SIGN)"" ] ; then \ ./deb ; \ else \ ./deb --sign ; \ fi .PHONY: clean install rpm dist deb sbox-dtc-1.11.7/README.html0000644000175000017500000012264212247552331013664 0ustar zigozigo sbox: Put CGI Scripts in a Box

sbox: Put CGI Scripts in a Box

Abstract

sbox is a CGI wrapper script that allows Web site hosting services to safely grant CGI authoring privileges to untrusted clients. In addition to changing the process privileges of client scripts to match their owners, it goes beyond other wrappers by placing configurable ceilings on script resource usage, avoiding unintentional (as well as intentional) denial of service attacks. It also optionally allows the Webmaster to place client's CGI scripts in a chroot'ed shell restricted to the author's home directories.

sbox is compatible with all Web servers running under BSD-derived flavors of Unix. You can use and redistribute it freely.

The current release is 1.10. Download it from the Web at http://stein.cshl.org/WWW/software/sbox/.

Older versions are also available.

Introduction

Poorly-written CGI scripts are the single major source of server security holes on the World Wide Web. Every CGI script should be scrutinized and extensively tested before installing it on a server, and subject to periodic review thereafter.

For Web hosting services, however, this advice is impractical. Hosting services must sponsor multiple Web authors of different levels of competence and reliability. Web authors do not trust each other, and the Web hosting service does not trust the authors. In such a situation, CGI scripts are even more problematic than usual. Because all CGI scripts run under the Web server's user ID, one author's scripts can interfere with another's. For example a malicious author could create a script that deletes files created by another author's script, or even cause another author's script to crash by sending it a kill signal. A poorly written script that contains a security hole can compromise the entire site's security by, for example, transmitting the contents of the system password file to a malicious remote user. The same problems are faced by large academic sites which provide Web pages for students.

For most Web hosting services it would be impossible to subject each and every author's CGI scripts to code review. Nor is it practical to cut off CGI scripting privileges entirely. In the competitive world of ISP's, customers will just move elsewhere.

The most popular solution to this problem is the use of "wrapper" scripts. In this system, untrusted author's CGI scripts are never invoked directly. Instead a small wrapper script is called on to execute the author's script, the target. The wrapper is SUID to root. When the wrapper runs, it subjects the target to certain safety checks (for example, checking that the script is not world-writable). The wrapper then changes its process ID to match the owner of the target and executes it. The result is that the author's script is executed with his own identity and privileges, preventing it from interfering with other author's scripts. The system also leads to increased accountability. Any files that an misbehaving script creates or modifies will bear the fingerprints of its creator. Without a wrapper, it can be impossible to determine which author's script is causing problems.

The limitations of wrapper scripts are three-fold:

  1. Wrappers provide little protection against attacks that involve reading confidential information on the site, for example sensitive system files or protected documents.
  2. Wrappers expose the author to increased risk from buggy scripts. By running the author's script with his owner permissions, the wrapper grants it the ability to read, write or delete any file in the author's home directory.
  3. There is no protection against denial-of-service attacks. A buggy script can go into an endless loop, write a huge file into /usr/tmp, or allocate an array as large as virtual memory, adversely affecting system responsiveness.
A better solution is to box author's CGI scripts. In this solution, the CGI script is executed in a restricted environment in which its access to the file system and to other system resources is limited. This is what sbox (Secure Box) accomplishes. When run, it does several things:
  1. It checks the environment for sanity. For example, the script must be run by the Web user and group, and not by anyone else.
  2. It checks the target script for vulnerabilities, such as being world writable or being located in a world writable directory.
  3. It performs a chroot to a directory that contains both the script and the author's HTML files, sealing the script off from the rest of the system.
  4. It changes its user ID and/or group ID to that of the target script.
  5. It sets ceilings on the target script's CPU, disk, memory and process usage.
  6. It lowers the priority of its process.
  7. It cleanses the environment so that only variables which are part of the CGI protocol are available to the script.
  8. It invokes the target script in this restricted context.

sbox is highly configurable. It can be configured to chroot without changing its process ID, to change its process ID without performing the chroot, to change its group ID without changing its user ID, to establish resource ceilings without doing anything else, or any other combination that suits you.

System Requirements

sbox is designed to run with any Unix-based Web server. The package should compile correctly on any standard Unix system; however the resource limits use the BSD-specific setrlimit() and setpriority() calls. If you do not know whether your system supports these calls, check for the existence of the file /usr/include/system/resource.h. If this file does not exist, then chances are slim that you can use the resource limits. You can run sbox without the limits by setting the preprocessor define SET_LIMITS to FALSE (see below).


Installation

After unpacking the package, you should have the following files:

Makefile
README.html (this file)
README.txt  (this file as text)
sbox.h
sbox.c
env.c
You will first examine and edit the Makefile, then change sbox.h to suit your site configuration and preferences. It is suggested that you keep copies of the unaltered files for future reference.

Adjusting the Makefile

Using your favorite text editor, examine and change the value of the INSTALL_DIRECTORY variable. This is the location in which sbox will be installed, and should correspond to your site-wide CGI directory.

You may also need to fiddle with the options for the install program. The default is to make sbox owned by user "root" and group "bin", and installed with permissions -rws--x--x. This configuration is SUID to root, necessary in order for the chroot and process ID changing functions to work.

If you wish to adjust the C compiler and its flags, change the CC and CFLAGS variables as needed.


Adjusting sbox.h

This is the fun part. sbox.h contains several dozen flags that affect the script's features. These flags are implemented as compile-time defines rather than as run-time configuration variables for security reasons. There is less chance that the behavior of sbox can be maliciously altered if it has no dependences on external configuration files.

You should review sbox.h with a text editor and change the settings as needed. A typical entry looks like this:

/*
 * ECHO_FAILURES  -- If set to TRUE, will echo fatal error messages
 *              to the browser.  Set to FALSE to inhibit error messages.
 */
#ifndef ECHO_FAILURES
#define ECHO_FAILURES TRUE
#endif

This section sets a feature called ECHO_FAILURES to TRUE. To change the value to FALSE, simply edit the line that begins with "#define" to read like this:

#define ECHO_FAILURES FALSE

General Settings

These variables correspond to general sbox settings such as logging and environment consistency checking.

WEB_USER (default "nobody")
This defines the name of the user that the Web server runs under, "nobody" by default. If your Web server uses a different user ID, you must change this define to match.

WEB_GROUP (default "nobody")
This defines the name of the group that the Web server runs under, "nobody" by default. If your Web server uses a different group ID, you must change this define to match.

UID_MIN, GID_MIN (defaults 100,100)
These define the lowest UID and GID that the script will run a target CGI script as. On most systems, low-numbered user and group IDs correspond to users with special privileges. Change these values to be the lowest valid unprivileged user and group ID. Under no circumstances will sbox run a target script as root (UID 0.)

SAFE_PATH (default "/bin:/usr/bin:/usr/local/bin")
This defines the search path that will be passed to the author's CGI scripts, overriding whatever was there before.

USE_ABSOLUTE_ROOT (no default)
If set to an absolute path, sbox will chroot to a hard-coded directory and use that as its root. Use this if you want to have sbox work on a particular directory not related to a user's directory or the web root.
NOTE: the sbox binary you compile will work for that directory ONLY. If you want to use it for another directory, recompile and use a different binary

Logging Settings

sbox can be set to log all its actions, including both failures and successful launches of author's scripts. Log entries are time stamped and labeled with the numeric IDs of the user and group that the target script was launched under.

LOG_FILE (default none)
This specifies a file to which sbox will log its successes and failures. Set this to the full path name of the file to log to. An empty string ("") will make sbox log to standard error, which will cause its log messages to be directed to the ordinary server error log. Leaving LOG_FILE undefined will cause sbox not to log any messages.

ECHO_FAILURES (default TRUE)
If this define is set to a true value, any fatal errors encountered during sbox's execution will be turned into a properly-formatted HTML message that is displayed for the remote user's benefit. Otherwise, the standard "An Internal Error occurred" message is displayed.

Chroot Settings

These variables controls sbox's chroot functionality. The path names are relative to the document root. In the case of virtual hosts, this will be whatever is specified by the DocumentRoot directive in the server's configuration file. In the case of user-supported directories, it will be the user's public_html directory.

DO_CHROOT (default TRUE)
If set to a true value, sbox will perform a chroot to a restricted directory prior to executing the CGI script. Otherwise no chroot will be performed.

ROOT (default "..")
This tells sbox where to chroot to relative to the document root. This directory should ordinarily be a level or two above the document tree so that the script can get access to the author's HTML documents for processing.

CGI_BIN (default "../cgi-bin")
This define tells sbox where to look for the author's scripts directory, relative to his site's document tree. This directory should be contained within the directory specified by ROOT. For best security, you should specify a directory that is outside the document tree. The default is a directory named "cgi-bin" located at the same level as the document root.

SUID/SGID Settings

DO_SUID, DO_SGID (defaults TRUE, TRUE)
These defines control whether the script will perform an SUID and/or an SGID to the user and group of the target CGI script. From the author's point of view it's safer to perform an SGID than an SUID, and usually is more than adequate. If no SUID or SGID is performed, the author's script will be run with the Web server's privileges.

SID_MODE (default DIRECTORY)
This define controls whether sbox should use the ownership of the target script or the directory containing the target script to determine whose user ID and/or group ID to run under. Use directory mode if several users have authoring privileges for a single virtual host.

Resource Limitation Settings

SET_LIMITS (default TRUE)
If set to a true value, sbox will set resource usage ceilings before running the target CGI script. You may need to set this to FALSE if you are using a system that does not implement the setpriority() and/or setrlimit() calls.

PRIORITY (default 10)
This controls the priority with which target scripts are run. Values can range from -20 to 20. Higher numbers have less priority.

LIMIT_CPU_HARD, LIMIT_CPU_SOFT, LIMIT_FSIZE_HARD, LIMIT_FSIZE_SOFT...
These and similar defines control the resource ceilings. The definitions set caps on CPU usage, the number of processes the script can spawn, the amount of memory it can use, the size of the largest file it can create, and other attributes. For each resource there are two caps, one hard, the other soft. Soft resources can be increased by any program that desires to do so by making the appropriate calls to setrlimit(). Hard limits are inviolable ceilings that cannot be lifted once established, even by a privileged user. The hard limits should be rather liberal, the soft limits more strict. See the setrlimit() man page for details on each of these resources.

If you use LIMIT_FSIZE_HARD or _SOFT and are logging to stderr, be careful! If your web server error log is larger than the limit, no logging will occur.


Making and Installing the Binary

Compile the sbox binary by typing make. If it compiles successfully, become root and type make install to install it in your site's cgi-bin directory (at the location specified in the Makefile.)

You can also install sbox manually by copying it into your cgi-bin directory and settings its permissions to ---s--x--x. This can be done with the following commands while logged in as the root user:

# chown root sbox
# chgrp bin  sbox
# chmod 4111 sbox

Configuring the Server and User Directories

In order for sbox to be effective, CGI scripts should be turned off in all user-supported directories and document directories. All CGI scripts should be placed in the main cgi-bin directory. No one but authorized site administrators should have write or listing privileges for this directory. If you are using the Apache server, a typical entry for a virtual host will look like this:

<VirtualHost *>
ServerName www.fred.com
ServerAdmin  fred@fred.com

DocumentRoot /home/fred/sbox_root/html
TransferLog  /home/fred/sbox_root/logs/access_log
ErrorLog     /home/fred/sbox_root/logs/error_log

<Directory /home/fred/sbox_root>
    Options        MultiViews Indexes SymLinksIfOwnerMatch IncludesNoExec
    AllowOverride Options AuthConfig Limit
    order allow,deny
    allow from all
</Directory>

</VirtualHost>

(Please be sure to use Options and AllowOverride directives that match the security policy of your site.)

For a site that uses UserDir-style home pages (http://www.your.site/~username), a typical configuration is:

UserDir sbox_root/html

<Directory /home/*/sbox_root>
    Options       MultiViews Indexes SymLinksIfOwnerMatch IncludesNoExec
    AllowOverride Options AuthConfig Limit
    order allow,deny
    allow from all
</Directory>

Note that in both cases, the user's document root (where his HTML files go) is "~fred/sbox_root/html", that is, two directory levels below his home directory. When sbox runs, it uses the position of the user's document root to find its root and the cgi-bin directory. The suggested defaults defined in sbox.h make the ROOT equal to "..", and CGI_BIN equal to "../cgi-bin", both relative to the document root. Hence in the examples given above, sbox's root will be ~fred/sbox_root, and sbox will look for his CGI scripts in the directory ~fred/sbox_root/cgi-bin. When sbox runs in chroot mode, ~fred/sbox_root becomes the new top level ("/") directory, insulating the user's CGI script from the rest of his home directory, as well as the rest of the file system. This prevents the CGI script from inadvertently (or deliberately) doing something antisocial, but gives the script access to the user's HTML files, for filtering and templating.

Because the user's CGI script is cut off from the rest of the filesystem after the chroot call, dynamically linked programs (including interpreters and the like) will not be happy unless they can find the shared libraries they rely on. Therefore, the sbox root directory should be set up like a miniature root directory, and contain whatever binaries, configuration files and shared libraries are necessary for programs to run. This list is different from system to system. See Using the Miniroot and Tips for advice on setting this directory up.

Below is the structure of Fred's directory, assuming that the virtual host uses ~fred/sbox_root/html as its document root.

% ls -l ~fred/sbox_root
total 10
drwxr-xr-x   2 fred   users  1024 Oct 23 06:27 bin/     system binaries
drwxr-xr-x   3 fred   users  1024 Oct 19 20:44 cgi-bin/ CGI scripts
drwxr-xr-x   2 fred   users  1024 Oct 12 16:59 dev/     device special files
drwxr-xr-x   2 fred   users  1024 Oct 19 17:57 etc/     configuration files
drwxr-xr-x   2 fred   users  1024 Oct 22 19:14 html/    HTML document root
drwxr-xr-x   3 fred   users  1024 Oct 19 20:35 lib/     shared libraries
drwxr-xr-x   3 fred   users  1024 Oct 19 20:35 logs/    log files
drwxr-xr-x   2 fred   users  1024 Oct 23 05:48 tmp/     temporary files
drwxr-xr-x   2 fred   users  1024 Oct 23 05:48 usr/     files that belong in usr
drwxr-xr-x   2 fred   users  1024 Oct 23 05:48 var/     files that belong in var

If you do not take advantage of sbox's chroot feature, but just use it for its ability to change to the user's UID and GID, then you do not have to do any special directory setup.

See Supporting Apache .htaccess files and Rewrite-Rule Tricks for additional common configuration setups that make sbox more transparent to use.


Calling sbox

To use sbox create URLs like this one:

http://www.virtual.host.com/cgi-bin/sbox/script_name
       ^^^^^^^^^^^^^^^^^^^^              ^^^^^^^^^^^
        virtual host name               user's script

The first part of the URL is the path to the sbox script. The second part is the path to the user's script, relative to the cgi-bin directory in his home directory. If the user's script needs access to additional path information, you can append it in the natural way:

http://www.virtual.host.com/cgi-bin/sbox/script_name/additional/path/info

For user-supported directories, use this format:

http://www.virtual.host.com/cgi-bin/sbox/~fred/script_name

Users are free to organize their script directories into a hierarchy. They need only modify script URLs to reflect the correct path:

http://www.virtual.host.com/cgi-bin/sbox/foo/bar/script_name

Supporting Apache .htaccess files

If you are using the Apache web server and wish the user to be able to password-protect or otherwise modify access to his cgi-bin directory using a .htaccess file, then you will need to activate and use Apache's mod_rewrite module. Otherwise any .htaccess file located in the user's cgi-bin directory will be ignored. This method will also make it so that if the requested executable is not found in the cgi-bin directory, the error condition will fall through to Apache's error handling system (using ErrorDocument) rather than raising an sbox error.

First make sure that Apache was compiled with the mod_rewrite module and that the module is loaded at startup time. The relevant directive is:

LoadModule rewrite_module lib/apache/mod_rewrite.so

Now assuming that user cgi-bin directories are installed in ~user/sbox_root/cgi-bin, that the sbox executable is installed in /cgi-bin/sbox, and that user directories are located at /home/username, enter the following into your httpd.conf file:

For Virtual Hosts

RewriteEngine on
RewriteLog "/var/log/apache/rewrite_log"
RewriteLogLevel 0

RewriteCond %{REQUEST_FILENAME} ^/cgi-bin/sbox/(.+)
RewriteCond %{DOCUMENT_ROOT}/../cgi-bin/%1 !-F
RewriteRule ^/cgi-bin/sbox/(.+) %{DOCUMENT_ROOT}/../cgi-bin/$1  [L]
RewriteRule ^(/cgi-bin/sbox/.+) $1 [PT,NS]
(This goes into each VirtualHost section)

For User Directories

RewriteEngine on
RewriteLog "/var/log/apache/rewrite_log"
RewriteLogLevel 0

RewriteCond %{REQUEST_FILENAME} ^/cgi-bin/sbox/~([^/]+)/(.+)
RewriteCond /home/%1/sbox_root/cgi-bin/%2 !-F
RewriteRule ^/cgi-bin/sbox/~([^/]+)/(.+) /home/$1/sbox_root/cgi-bin/$2  [L]
RewriteRule ^(/cgi-bin/sbox/~.+/.+) $1 [PT,NS]

(This goes into the main section of httpd.conf)

These pretty complicated looking pieces of code says that for URLs that begin with /cgi-bin/sbox/~username/filename, first check whether the file /home/username/sbox_root/cgi-bin/filename exists and is available via Apache's access rules. If it isn't available, then rewrite the URL as /home/username/sbox_root/cgi-bin/filename and perform the usual processing as if it were a file (which will result in a 403 or 404 error). Otherwise, don't rewrite the URL and pass it through to the CGI handler. You will need to tweak these a bit if users' home directories are somewhere else than /home/user or if you have changed the names or positions of the sbox root and cgi-bin directories from their defaults.

To support users' ability to change access rights using .htaccess, make sure to enable AuthConfig and Limit in sbox_root if you haven't done so already:

<Directory /home/*/sbox_root>
    AllowOverride +Options +AuthConfig +Limit
</Directory>

Using the Miniroot (Linux only)

For the convenience of Linux system administrators wishing to use the chroot features of sbox, I have placed a miniature root directory at stein.cshl.org/software/sbox/miniroot.img.gz. This is a gzipped ext2 filesystem image that contains essential system device files, shared libraries, and executables, including Perl version 5.8.7 and the most commonly used Perl libraries. The filesystem image is based on the one distributed with RIP.

You can use this image in several ways:

Install a copy of the image into each user's directory:

This way gives each user a skeleton root directory that he is free to modify, providing him with considerable flexibility. The downside is that you may not wish users to have so much flexibility; it also takes up about 45 megabytes of space per user directory:

  1. Download the miniroot from stein.cshl.org/software/sbox/miniroot.img.gz.
  2. Unzip it:
          gunzip miniroot.img.gz
          
  3. Mount the resulting disk image in loopback mode (you must be root to do this):
          mkdir /mnt/miniroot
          mount ./miniroot.img /mnt/miniroot -o ro,loop
          
  4. Copy the contents of the miniroot into each user's sbox root directory (assuming in this example that it is ~fred/sbox_root):
          cd /mnt/miniroot
          find . | cpio -p ~fred/sbox_root
          
  5. Create the user's html, cgi-bin and log directories:
          mkdir ~fred/sbox_root/{html,cgi-bin,log}
          
  6. Fix permissions of these directories:
          chown fred.users ~fred/sbox_root/{html,cgi-bin,log}
          

Mounting a copy of the miniroot in each user's directory

The alternative method avoids the waste of putting a complete copy of the root into each user's directory. One copy of the miniroot is mounted read-only into each user's sbox root, giving them read-only access to the mount. The main disadvantage of this strategy is that it generates a mount for each user, which in the case of very many user accounts might bump up against kernel limitations.

  1. Download the miniroot from stein.cshl.org/software/sbox/miniroot.img.gz.
  2. Unzip it:
          gunzip miniroot.img.gz
          
  3. Create the user's html and cgi-bin directories, as well as a directory called "mnt":
          mkdir ~fred/sbox_root/html
          mkdir ~fred/sbox_root/cgi-bin
          mkdir ~fred/sbox_root/mnt
          
  4. Mount the miniroot read-only on the user's mnt/ directory:
           mount ./miniroot.img ~fred/sbox_root/mnt -o ro,loop
           
  5. Create symlinks to the directories of the mounted filesystem:
           cd ~fred/sbox_root
           ln -s mnt/* .
           
  6. Fix permissions of html, cgi-bin and log.

At the end of this process, you should have a directory structure that looks like this:

lrwxrwxrwx  1 root root     7 Dec  4 18:18 bin -> mnt/bin
drwxrwxr-x  2 fred users   96 Dec  4 18:15 cgi-bin/
lrwxrwxrwx  1 root root     7 Dec  4 18:18 dev -> mnt/dev
lrwxrwxrwx  1 root root     7 Dec  4 18:18 etc -> mnt/etc
drwxr-xr-x  5 fred users 1136 Dec  4 18:15 html/
lrwxrwxrwx  1 root root     7 Dec  4 18:18 lib -> mnt/lib
lrwxrwxrwx  1 fred users    7 Dec  4 18:15 log/
drwxrwxr-x  2 root root    48 Dec  4 18:16 mnt/
lrwxrwxrwx  1 root root     7 Dec  4 18:18 tmp -> mnt/tmp
lrwxrwxrwx  1 root root     7 Dec  4 18:18 usr -> mnt/usr
lrwxrwxrwx  1 root root     7 Dec  4 18:18 var -> mnt/var

If you ever wish to modify the miniroot image, simply mount it read/write and make the changes you need. If you run out of space on the miniroot, you can create a new one with the following series of commands:

mount ./miniroot.img /mnt/miniroot -o ro,loop
dd if=/dev/zero of=./new_miniroot.img bs=1M count=100  # or whatever you want
mke2fs -F ./new_miniroot.img
mount ./new_miniroot.img /mnt/new_miniroot -o rw,loop
cd /mnt/miniroot
find . | cpio -p /mnt/new_miniroot

You are also free to burn the miniroot into a CDROM image, create a cramfs image, etc.


Tips

Here are a few pieces of advice and tips on making best use of sbox.

Setting up the Chroot directory

Many CGI scripts will not run correctly in a chroot environment unless they can find the resources they need. Compiled C programs often need access to shared libraries and/or device special files. Interpreted scripts need access to their interpreters, for example Perl. Feature-rich programs like sendmail depend on their configuration files being present in /etc.

As described above, you will need to turn the chroot directory into a miniature root file system, complete with /etc, /lib, /bin, /tmp and /dev directories. If the web server is running on a Linux system, then one option is to use the miniroot image provided with sbox as the basis for the root file system. If you prefer to do it yourself, I recommend that you create and test a chroot directory for one virtual host, then use it as a master copy for creating new virtual hosts every time you add a new user account. Both the cpio and the tar commands can be used to copy shared libraries and device special files safely.

Programs that check file ownerships may need access to password and/or group files in order for them to translate from numeric uid's and gid's to text names. In order to support CGI scripts that perform this type of action, you should place dummy copies of /etc/passwd and /etc/group in the author's /etc directory. These files should not contain real passwords, and should only contain standard system user accounts (e.g. "bin" and "mail"), plus any needed by the script. You probably don't want to make the complete list of user account names available to authors' CGI scripts!

If CGI scripts require access to the DNS system in order to resolve host names and IP addresses, you should place a copy of /etc/resolv.conf into the chroot directory. You may need to copy other configuration files to use certain feature-rich programs. For example, if scripts send e-mail using the sendmail program, you will need to install its configuration program, sendmail.cf.

Many programs redirect their output to the device special file /dev/null. Other programs need access to /dev/zero or other special files. You can copy these files from the real /dev directory using either cpio or tar. Alternately you can create the files from scratch using mknod, but only if you know what you're doing. You'll need to have superuser privileges to accomplish either of these tasks.

The Unix time system expects to find information about the local timezone in a compiled file named /etc/localtime. You may need to copy this into your chroot directory in order for the timezone to be correctly displayed. You can confirm that the correct timezone is being found by examining the output of the "env" executable.

There are two ways to finesse the problem of shared libraries. For compiled C scripts, one option is to link the program statically (by providing the -static flag to the linker). A less laborious solution is to place copies of the required shared libraries in the new root's /lib directory (or /slib, for systems that use that directory for shared libraries). Many systems have a utility that lists the shared libraries required by a binary. Use this program to determine which shared libraries are required, and copy them over into each author's /lib directory. In addition to the shared libraries, you may need to copy the dynamic linker itself into the /lib directory. On my linux system, this file is "ld-linux.so".

If a executable cannot find its shared libraries at run time, it will usually fail with a specific error message that will lead you to the problem -- look in the server error log. If you get silent failures, it's probably the dynamic linker itself that can't be found.

Linux, and possibly some other systems, uses a cache file named /etc/ld.so.cache to resolve the location of library files. If this file isn't found at run time, the system will generate a warning but find the correct shared libraries nevertheless. The quick and dirty way to get rid of this warning is to copy the current cache file from the real /etc directory to the chroot one. However, this may have bad side effects (I haven't actually encountered any, but I worry about it.) It's better to make this cache file from scratch in the chroot environment itself. To do this, run the ldconfig program with the command-line version of chroot. You'll need to be root to do this:

# cd /sbin
# chroot ~fred/pub ./ldconfig

Perl scripts, in addition to requiring the Perl interpreter, will often need access to the Perl lib directory in order to get at useful modules (such as CGI.pm). It's easiest to copy the whole Perl library tree to the correct location in the chroot directory, being careful to get the path right. For example, if the real Perl library is located in /usr/local/lib/perl5, you'll need to create a parallel /usr hierarchy in the chroot directory. On my system, I recompiled Perl to use /lib/perl5 and dumped the modules into that directory. If things get bolluxed up, you can always tell Perl where to look for its libraries by appending something like this to the top of CGI scripts:

#!/bin/perl
BEGIN { push(@INC,'/lib/perl5','/lib/perl5/i586-linux/5.004'); }

The Document Root and the chroot() directory

Some CGI scripts act as filters on static HTML documents. Examples include PHP and various guestbook scripts. Such scripts often include the path to the static document appended to the end of the script's URL as "additional path information." For example:

http://your.site/~fred/guestbook.cgi/~fred/guestbook/data.txt

The script will be passed two environment variables, PATH_INFO, containing the additional path information, and PATH_TRANSLATED, containing the path information translated into an absolute filename. In the example above, the values of these variables might be:

PATH_INFO/~fred/guestbook/data.txt
PATH_TRANSLATED/home/fred/public_html/guestbook/data.txt

When sbox is running it interprets the additional path information as relative to the user's document root. This means that a document located in Fred's public_html directory can be referred to this way:

http://your.site/cgi-bin/sbox/~fred/guestbook.cgi/guestbook/data.txt

After performing the chroot(), sbox attempts to adjust PATH_TRANSLATED so that it continues to point to a valid file. If the user's document root is located within the chroot directory, then PATH_TRANSLATED is trimmed so that it is relative to the new root directory:

PATH_INFO/guestbook/data.txt
PATH_TRANSLATED/public_html/guestbook/data.txt

However, if the document root is entirely outside the new root directory, then sbox will simply use the same value for PATH_INFO and PATH_TRANSLATED:

PATH_INFO/guestbook/data.txt
PATH_TRANSLATED/guestbook/data.txt

Users and Webmasters should be aware of this behavior, as it can cause some confusion.

The Resource Limitations

The default resource limits are reasonable. Most authors won't have problems with them unless they need to do number crunching or manipulate many files simultaneously. If need be, authors can raise the soft resource limits up to the levels imposed by the hard limit ceilings, which are very liberal. C programmers can do this directly by making calls to setrlimit(). Perl scripters should download and install Jarkko Hietaniemi's BSD::Resource module from CPAN.

Server-Side Includes

Because of design conflicts, the "#exec" style server-side include do not work correctly with sbox. However, the "#include virtual" command, which does almost exactly the same thing, does work correctly. To include the output of sbox-wrapped CGI scripts in server-side-include files, just write something like this:

&lt;!--#include virtual="/cgi-bin/sbox/~fred/guestbook"--&gt;

Rewrite-Rule Tricks

If you are running Apache 1.2 or higher, you can take advantage of the rewrite rule module to make sbox transparent. For virtual hosts, you can add something like the following to main or the <VirtualHost> section:

RewriteEngine on
RewriteRule ^/cgi/(.*) /cgi-bin/sbox/$1 [PT,NS]
This replaces all URLs that start with "/cgi" with "/cgi-bin/sbox". This lets authors refer to their scripts with:
http://www.virtual.host.com/cgi/script_name
and to main Web server scripts with:
http://www.virtual.host.com/cgi-bin/guestbook
For user-supported directories, this rewrite rule will allow users to refer to their scripts using http://www.host.com/~username/cgi/script_name:
RewriteEngine on
RewriteRule ^/~([^/]+)/cgi/(.+) /cgi-bin/sbox/~$1/$2 [PT,NS]

If you are already using rewrite rules to allow users to control access with a .htaccess file, place the appropriate RewriteRule before the first RewriteCond and omit the [PT,NS] flags. The following two examples show RewriteRule blocks that will correctly respect .htaccess files:

For Virtual Hosts

RewriteRule ^/cgi/(.+) /cgi-bin/sbox/$1
RewriteCond %{REQUEST_FILENAME} ^/cgi-bin/sbox/(.+)
RewriteCond %{DOCUMENT_ROOT}/../cgi-bin/%1 !-F
RewriteRule ^/cgi-bin/sbox/(.+) %{DOCUMENT_ROOT}/../cgi-bin/$1  [L]
RewriteRule ^(/cgi-bin/sbox/.+) $1 [PT,NS]

For User Directories

RewriteRule ^/~([^/]+)/cgi/(.+) /cgi-bin/sbox/~$1/$2
RewriteCond %{REQUEST_FILENAME} ^/cgi-bin/sbox/~([^/]+)/(.+)
RewriteCond /home/%1/sbox_root/cgi-bin/%2 !-F
RewriteRule ^/cgi-bin/sbox/~([^/]+)/(.+) /home/$1/sbox_root/cgi-bin/$2  [L]
RewriteRule ^(/cgi-bin/sbox/~.+/.+) $1 [PT,NS]

The env Script

This distribution comes with a small statically linked binary called "env" that you can call as a CGI script. It prints out some information about the current environment, including the user and group ID's, the current working directory, and the environment variables, to help you determine whether sbox is configured correctly and working as expected.


Author Information

This utility is ©1997-2005 Lincoln D. Stein. It can be used freely and redistributed in source code and binary form. I request that this documentation, including the copyright statement, remain attached to the utility if you redistribute it. You are free to make modifications, but please attach a note stating the changes you made.


Change History

Version 1.10
Revamped documentation to show how to get .htaccess and 404 Not Found errors to work correctly.
Added an example root directory for use in chroot mode.
Versions 1.08-1.09
Never released.
Version 1.07
Patch from Jukka Forsgren to cause script to chdir() into target directory in the same manner as Apache does.

Version 1.06
Fixed cross-scripting security vulnerability identified by Ivan Schmid (ivan.schmid@astalavista.ch)

Version 1.05
Lost version.

Version 1.04
Changes to make sbox compile with egcs version 1.1.2
Fixed problem of CGI scripts not being able to access command line variables (courtesy Sean Gabriel Heacock)
If logfile can't be opened, logs to standard error instead.

Version 1.03
Added USE_ABSOLUTE_ROOT functionality, contributed by Grant Kaufmann.

Version 1.02
Fixed a crash that occurred when configured userid or groupid is not in passwd/group file (patch provided by Terry Lorrah <delikon@itw.net>).

Version 1.01
Fixed minor bug in webmaster's error message.
Fixed minor bug in reporting gid to log file

Version 1.00
Replaced all occurrences of strcpy() and strcat() with strncpy() and strncat().
Changes to string constants to make more ANSI-compatible.
Code cleanup

Versons 0.98-0.99
Documentation fixes.

Version 0.97
Fixed bugs relating to automounter confusion.

Version 0.95
Fixes to compile and run on Solaris systems. Still not extensively tested, but no bug reports yet.

Version 0.90
Beta release. Use with caution.

Lincoln D. Stein, lstein@cshl.org
Cold Spring Harbor Laboratory
Last modified: Mon Dec 5 15:58:19 EST 2005 sbox-dtc-1.11.7/sbox.conf0000644000175000017500000000722712247552331013664 0ustar zigozigo# SBOX configuration file # This file let you set different limits of the sbox cgi-bin wrapper # Toggles can have values of On/Off, 1/0, Yes/No # Variable names are set to CASE_INSENSITIVE #******************* UID/GID CONFIG ******************# # user that the Web server runs as web_user dtc # group that the Web server runs as web_group dtcgrp # allows scripts to be executed if owned by WEB_USER or WEB_GROUP allow_web_owned_scripts Off # lowest UID that we will suid to uid_min 100 # highest UID that we will suid to uid_max 65535 # lowest GID that we will sgid to gid_min 100 # highest GID that we will sgid to gid_max 65535 # Determine whether to use the ownerships of the script or the _directory_ # that the script is found in for the SUID/SGID IDs. If off, it will use # the UID/GID of the script, if On, it will use the directory UID/GID sid_mode_directory Off #******************* PATH CONFIG ******************# # If set to on, then the user's script will have limited access to # only the paths defined in safe_path use_safe_path Off # SAFE_PATH -- this is the path that will be placed in the environment. # Script will be running chroot to the user's home directory, so these # directories may not be available. safe_path "/bin:/usr/bin:/usr/local/bin" # LOG_FILE -- log what sbox does. If undefined, won't log. # If an empty string, logs to standard error. log_file "/var/log/sbox.log" # To help debugging, you might want to print the environment # variables on sbox.log. To do so, set to "on" bellow. do_log_envvars Off # ECHO_FAILURES -- If set to 1, will echo fatal error messages # to the browser. Set to FALSE to inhibit error messages. echo_failures On #******************* CHROOT CONFIG ******************# # DO_CHROOT -- if set to 1, sbox will # do a chroot to the user's home directory. do_chroot On # ROOT # Directory to which sbox will chroot(), relative to the author's # document root. root ".." # CGI_BIN # Directory in which users' executables must reside, relative to their # document root. For best results, this must be contained within ROOT. #cgi_bin "../cgi-bin" cgi_bin "../html" # DO_SUID and DO_SGID -- if set to 1, sbox # will SUID and/or SGID to the user and group ownership of # the _directory_ in which the target script is found do_suid Off do_sgid Off #******************* RESOURCE LIMITS ******************# # Soft limits can be increased by the application. Hard limits cannot be # changed. # Whether or not you want to set limits at all. # If your sytem does not have , then you will # need to set this to 0. set_limits On # priority priority 10 # maximum CPU time in seconds limit_cpu_hard 1200 limit_cpu_soft 100 # maximum size of a single file that can be created (blocks) * 1024 limit_fsize_hard 204800 # This is 200MB limit_fsize_soft 102400 # This is 100MB # maximum amount of in-memory data * 1024 limit_data_hard 81920 # This is 80MB limit_data_soft 10240 # This is 10MB # maximum stack size * 1024 limit_stack_hard 81920 # This is 80MB limit_stack_soft 10240 # This is 10MB # core dump size * 1024 limit_core_hard 0 # 0 = don't allow core dumps limit_core_soft 0 # 0 = don't allow core dumps # maximum memory ("resident set") usage * 1024 limit_rss_hard 81920 # This is 80MB limit_rss_soft 20480 # This is 20MB # max number of processes script can spawn limit_nproc_hard 2560 limit_nproc_soft 320 # max number of open file descriptors limit_nofile_hard 2560 limit_nofile_soft 320 # PHP interpreter path php_path "/usr/lib/cgi-bin/php" # Python interpreter path python_path "/usr/bin/python" # Perl interpreter path perl_path "/usr/bin/perl" # Ruby interpreter path ruby_path "/usr/bin/ruby1.8" sbox-dtc-1.11.7/sbox.c0000644000175000017500000014750112247552331013161 0ustar zigozigo#include "sbox.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include //#if SET_LIMITS #include //#endif // The dotconf library to parse /etc/sbox.conf #include //#define DEBUG 1 /* DESCRIPTION sbox is designed to allow untrusted users to run CGI scripts without endangering the security of the site as a whole. $Revision: 1.8 $ Call as "http://your.site.com/cgi-bin/sbox/path/to/end_user/script" 1. sbox does a series of checks to confirm that it has been called in correct context a. user ID is WEB_USER b. group ID is WEB_GROUP c. neither of these is root 2. sbox fetches the target script named in PATH_TRANSLATED a. actually, it walks down the path until it finds the first executable file 3. sbox performs checks on the target script a. script is not SUID or SGID b. script is executable c. script is not writable by WEB_USER or WEB_GROUP d. directory that script lives in is not writable by WEB_USER or WEB_GROUP 4. sbox determines user and group of owner of the script file or its enclosing directory 5. sbox changes its uid and gid to match the script's file or directory 6. sbox checks that the script is within the owner's home directory 7. sbox chroots to the new root directory 8. sbox fixes PATH_TRANSLATED and SCRIPT_NAME for chroot change 9. sbox sets resource limits 10. sbox logs everything 11. sbox execs script */ /* Copyright info: * Copyright 1997, Lincoln D. Stein * * Parts of this code are derived from suexec.c, Copyright 1995-1997 The Apache Group */ #ifndef MAXPATHLEN #ifdef PATH_MAX #define MAXPATHLEN PATH_MAX #else #define MAXPATHLEN 8192 #endif #endif #ifndef NAME_MAX #define NAME_MAX 512 #endif #define AP_ENVBUF 256 extern char **environ; /* needed to compile with -ansi */ #ifndef strdup extern char *strdup (const char *); #endif #ifndef chroot extern int chroot (const char *path); #endif static char **cleanenv = NULL; static FILE *log; static void open_log(); static void log_error(const char* fmt, ...); static void fatal_error(const char* fmt, ...); static void check_consistency(); static char* fetch_target(char *root,char** additional_info, struct stat* targ,struct stat* dir); static char* to_abs(char* directory); static char* document_root (); static void check_target(const char* newroot, const char* target, const struct stat *file_stats, const struct stat *dir_stats); static char* fetch_newroot(char* docroot); static char* shave(char* newroot, char* target); static void clean_env(); static void tweak_environment(char* newroot, char* root, char* target, char* additional_info); static int set_env(const char *name, const char *value, int overwrite); static char* escape(const char* str); static void chdir_fix(char* newroot, char* target); //#if SET_LIMITS static void set_limits(); //#endif static char *safe_env_lst[] = { "AUTH_TYPE", "CONTENT_LENGTH", "CONTENT_TYPE", "DATE_GMT", "DATE_LOCAL", "DOCUMENT_NAME", "DOCUMENT_PATH_INFO", "DOCUMENT_URI", "FILEPATH_INFO", "GATEWAY_INTERFACE", "LAST_MODIFIED", "QUERY_STRING", "QUERY_STRING_UNESCAPED", "REMOTE_ADDR", "REMOTE_HOST", "REMOTE_IDENT", "REMOTE_PORT", "REMOTE_USER", "REDIRECT_QUERY_STRING", "REDIRECT_STATUS", "REDIRECT_URL", "REQUEST_METHOD", "REQUEST_URI", "SCRIPT_URI", "SCRIPT_URL", "SERVER_ADMIN", "SERVER_NAME", "SERVER_PORT", "SERVER_PROTOCOL", "SERVER_SOFTWARE", "USER_NAME", "TZ", // #if !DO_CHROOT // "SCRIPT_NAME", // "PATH_INFO", // "PATH_TRANSLATED", // "DOCUMENT_ROOT", // "SCRIPT_FILENAME", // #endif NULL }; /***************** SBOX libdotconf config ***************/ typedef struct{ // UID and GID that runs sbox by default char* web_user; char* web_group; int do_suid; int do_sgid; int do_log_envvars; int allow_web_owned_scripts; int uid_min; int uid_max; int gid_min; int gid_max; int sid_mode_directory; int echo_failures; int do_chroot; char* safe_path; int use_safe_path; char* log_file; char* root; char* cgi_bin; int set_limits; int priority; long limit_cpu_hard; long limit_cpu_soft; long limit_fsize_hard; long limit_fsize_soft; long limit_data_hard; long limit_data_soft; long limit_stack_hard; long limit_stack_soft; long limit_core_hard; long limit_core_soft; long limit_rss_hard; long limit_rss_soft; int limit_nproc_hard; int limit_nproc_soft; int limit_nofile_hard; int limit_nofile_soft; char* php_path; char* python_path; char* perl_path; char* ruby_path; }sbox_config_t; sbox_config_t sbox_config; DOTCONF_CB(cb_web_user); DOTCONF_CB(cb_web_group); DOTCONF_CB(cb_do_suid); DOTCONF_CB(cb_do_sgid); DOTCONF_CB(cb_do_log_envvars); DOTCONF_CB(cb_allow_web_owned_scripts); DOTCONF_CB(cb_uid_min); DOTCONF_CB(cb_uid_max); DOTCONF_CB(cb_gid_min); DOTCONF_CB(cb_gid_max); DOTCONF_CB(cb_sid_mode_directory); DOTCONF_CB(cb_echo_failures); DOTCONF_CB(cb_do_chroot); DOTCONF_CB(cb_safe_path); DOTCONF_CB(cb_use_safe_path); DOTCONF_CB(cb_log_file); DOTCONF_CB(cb_root); DOTCONF_CB(cb_cgi_bin); DOTCONF_CB(cb_set_limits); DOTCONF_CB(cb_priority); DOTCONF_CB(cb_limit_cpu_hard); DOTCONF_CB(cb_limit_cpu_soft); DOTCONF_CB(cb_limit_fsize_hard); DOTCONF_CB(cb_limit_fsize_soft); DOTCONF_CB(cb_limit_data_hard); DOTCONF_CB(cb_limit_data_soft); DOTCONF_CB(cb_limit_stack_hard); DOTCONF_CB(cb_limit_stack_soft); DOTCONF_CB(cb_limit_core_hard); DOTCONF_CB(cb_limit_core_soft); DOTCONF_CB(cb_limit_rss_hard); DOTCONF_CB(cb_limit_rss_soft); DOTCONF_CB(cb_limit_nproc_hard); DOTCONF_CB(cb_limit_nproc_soft); DOTCONF_CB(cb_limit_nofile_hard); DOTCONF_CB(cb_limit_nofile_soft); DOTCONF_CB(cb_php_path); DOTCONF_CB(cb_python_path); DOTCONF_CB(cb_perl_path); DOTCONF_CB(cb_ruby_path); static configoption_t options[] = { {"web_user", ARG_STR, cb_web_user, NULL, 0}, {"web_group", ARG_STR, cb_web_group, NULL, 0}, {"do_suid", ARG_TOGGLE, cb_do_suid, 0, 0}, {"do_sgid", ARG_TOGGLE, cb_do_sgid, 0, 0}, {"do_log_envvars", ARG_TOGGLE, cb_do_log_envvars, 0, 0}, {"allow_web_owned_scripts", ARG_TOGGLE, cb_allow_web_owned_scripts, 0, 0}, {"uid_min", ARG_INT, cb_uid_min, 0, 0}, {"uid_max", ARG_INT, cb_uid_max, 0, 0}, {"gid_min", ARG_INT, cb_gid_min, 0, 0}, {"gid_max", ARG_INT, cb_gid_max, 0, 0}, {"sid_mode_directory", ARG_TOGGLE, cb_sid_mode_directory, 0, 0}, {"echo_failures", ARG_TOGGLE, cb_echo_failures, 0, 0}, {"do_chroot", ARG_TOGGLE, cb_do_chroot, 0, 0}, {"safe_path", ARG_STR, cb_safe_path, NULL, 0}, {"use_safe_path", ARG_TOGGLE, cb_use_safe_path, 0, 0}, {"log_file", ARG_STR, cb_log_file, NULL, 0}, {"root", ARG_STR, cb_root, NULL, 0}, {"cgi_bin", ARG_STR, cb_cgi_bin, NULL, 0}, {"set_limits", ARG_TOGGLE, cb_set_limits, 0, 0}, {"priority", ARG_INT, cb_priority, 0, 0}, {"limit_cpu_hard", ARG_INT, cb_limit_cpu_hard, 0, 0}, {"limit_cpu_soft", ARG_INT, cb_limit_cpu_soft, 0, 0}, {"limit_fsize_hard", ARG_INT, cb_limit_fsize_hard, 0, 0}, {"limit_fsize_soft", ARG_INT, cb_limit_fsize_soft, 0, 0}, {"limit_data_hard", ARG_INT, cb_limit_data_hard, 0, 0}, {"limit_data_soft", ARG_INT, cb_limit_data_soft, 0, 0}, {"limit_stack_hard", ARG_INT, cb_limit_stack_hard, 0, 0}, {"limit_stack_soft", ARG_INT, cb_limit_stack_soft, 0, 0}, {"limit_core_hard", ARG_INT, cb_limit_core_hard, 0, 0}, {"limit_core_soft", ARG_INT, cb_limit_core_soft, 0, 0}, {"limit_rss_hard", ARG_INT, cb_limit_rss_hard, 0, 0}, {"limit_rss_soft", ARG_INT, cb_limit_rss_soft, 0, 0}, {"limit_nproc_hard", ARG_INT, cb_limit_nproc_hard, 0, 0}, {"limit_nproc_soft", ARG_INT, cb_limit_nproc_soft, 0, 0}, {"limit_nofile_hard", ARG_INT, cb_limit_nofile_hard, 0, 0}, {"limit_nofile_soft", ARG_INT, cb_limit_nofile_soft, 0, 0}, {"php_path", ARG_STR, cb_php_path, NULL, 0}, {"python_path", ARG_STR, cb_python_path, NULL, 0}, {"perl_path", ARG_STR, cb_perl_path, NULL, 0}, {"ruby_path", ARG_STR, cb_ruby_path, NULL, 0}, LAST_OPTION }; DOTCONF_CB(cb_web_user){ sbox_config.web_user = (char*)malloc(strlen(cmd->data.str)+1); strcpy(sbox_config.web_user,cmd->data.str); return NULL; } DOTCONF_CB(cb_web_group){ sbox_config.web_group = (char*)malloc(strlen(cmd->data.str)+1); strcpy(sbox_config.web_group,cmd->data.str); return NULL; } DOTCONF_CB(cb_do_suid){ sbox_config.do_suid = cmd->data.value; return NULL; } DOTCONF_CB(cb_do_sgid){ sbox_config.do_sgid = cmd->data.value; return NULL; } DOTCONF_CB(cb_do_log_envvars){ sbox_config.do_log_envvars = cmd->data.value; return NULL; } DOTCONF_CB(cb_allow_web_owned_scripts){ sbox_config.allow_web_owned_scripts = cmd->data.value; return NULL; } DOTCONF_CB(cb_uid_min){ sbox_config.uid_min = cmd->data.value; return NULL; } DOTCONF_CB(cb_uid_max){ sbox_config.uid_max = cmd->data.value; return NULL; } DOTCONF_CB(cb_gid_min){ sbox_config.gid_min = cmd->data.value; return NULL; } DOTCONF_CB(cb_gid_max){ sbox_config.gid_max = cmd->data.value; return NULL; } DOTCONF_CB(cb_sid_mode_directory){ sbox_config.sid_mode_directory = cmd->data.value; return NULL; } DOTCONF_CB(cb_echo_failures){ sbox_config.echo_failures = cmd->data.value; return NULL; } DOTCONF_CB(cb_do_chroot){ sbox_config.do_chroot = cmd->data.value; return NULL; } DOTCONF_CB(cb_safe_path){ sbox_config.safe_path = (char*)malloc(strlen(cmd->data.str)+1); strcpy(sbox_config.safe_path,cmd->data.str); return NULL; } DOTCONF_CB(cb_use_safe_path){ sbox_config.use_safe_path = cmd->data.value; return NULL; } DOTCONF_CB(cb_log_file){ sbox_config.log_file = (char*)malloc(strlen(cmd->data.str)+1); strcpy(sbox_config.log_file,cmd->data.str); return NULL; } DOTCONF_CB(cb_root){ sbox_config.root = (char*)malloc(strlen(cmd->data.str)+1); strcpy(sbox_config.root,cmd->data.str); return NULL; } DOTCONF_CB(cb_cgi_bin){ sbox_config.cgi_bin = (char*)malloc(strlen(cmd->data.str)+1); strcpy(sbox_config.cgi_bin,cmd->data.str); return NULL; } DOTCONF_CB(cb_set_limits){ sbox_config.set_limits = cmd->data.value; return NULL; } DOTCONF_CB(cb_priority){ sbox_config.priority = cmd->data.value; return NULL; } DOTCONF_CB(cb_limit_cpu_hard){ sbox_config.limit_cpu_hard = cmd->data.value; return NULL; } DOTCONF_CB(cb_limit_cpu_soft){ sbox_config.limit_cpu_soft = cmd->data.value; return NULL; } DOTCONF_CB(cb_limit_fsize_hard){ sbox_config.limit_fsize_hard = cmd->data.value * 1024; return NULL; } DOTCONF_CB(cb_limit_fsize_soft){ sbox_config.limit_fsize_soft = cmd->data.value * 1024; return NULL; } DOTCONF_CB(cb_limit_data_hard){ sbox_config.limit_data_hard = cmd->data.value * 1024; return NULL; } DOTCONF_CB(cb_limit_data_soft){ sbox_config.limit_data_soft = cmd->data.value * 1024; return NULL; } DOTCONF_CB(cb_limit_stack_hard){ sbox_config.limit_stack_hard = cmd->data.value * 1024; return NULL; } DOTCONF_CB(cb_limit_stack_soft){ sbox_config.limit_stack_soft = cmd->data.value * 1024; return NULL; } DOTCONF_CB(cb_limit_core_hard){ sbox_config.limit_core_hard = cmd->data.value * 1024; return NULL; } DOTCONF_CB(cb_limit_core_soft){ sbox_config.limit_core_soft = cmd->data.value * 1024; return NULL; } DOTCONF_CB(cb_limit_rss_hard){ sbox_config.limit_rss_hard = cmd->data.value * 1024; return NULL; } DOTCONF_CB(cb_limit_rss_soft){ sbox_config.limit_rss_soft = cmd->data.value * 1024; return NULL; } DOTCONF_CB(cb_limit_nproc_hard){ sbox_config.limit_nproc_hard = cmd->data.value; return NULL; } DOTCONF_CB(cb_limit_nproc_soft){ sbox_config.limit_nproc_soft = cmd->data.value; return NULL; } DOTCONF_CB(cb_limit_nofile_hard){ sbox_config.limit_nofile_hard = cmd->data.value; return NULL; } DOTCONF_CB(cb_limit_nofile_soft){ sbox_config.limit_nofile_soft = cmd->data.value; return NULL; } DOTCONF_CB(cb_php_path){ sbox_config.php_path = (char*)malloc(strlen(cmd->data.str)+1); strcpy(sbox_config.php_path,cmd->data.str); return NULL; } DOTCONF_CB(cb_python_path){ sbox_config.python_path = (char*)malloc(strlen(cmd->data.str)+1); strcpy(sbox_config.python_path,cmd->data.str); return NULL; } DOTCONF_CB(cb_perl_path){ sbox_config.perl_path = (char*)malloc(strlen(cmd->data.str)+1); strcpy(sbox_config.perl_path,cmd->data.str); return NULL; } DOTCONF_CB(cb_ruby_path){ sbox_config.ruby_path = (char*)malloc(strlen(cmd->data.str)+1); strcpy(sbox_config.ruby_path,cmd->data.str); return NULL; } void read_config_file(char* sboxconf_path){ configfile_t *configfile; configfile = dotconf_create(sboxconf_path, options, 0, CASE_INSENSITIVE); if (dotconf_command_loop(configfile) == 0){ fprintf(stderr, "Error reading config file\n"); exit(2); } dotconf_cleanup(configfile); return; } // Maxmimum string size for an environment name or value: #define MAXENV 1024 // Get the HTTP_HOST environment variable value // Returns NULL if not found char* get_http_host(char** e){ char *name,*delimiter; static char envvar_name[MAXENV+2]; // Stores the current env var name, make sure it's big enough by adding 2 safety chars while ((name = *e++)) { delimiter = (char*) strchr(name,'='); if (delimiter == NULL) continue; // If we don't find the "=" delimiter, then we didn't find anything... if (delimiter - name >= MAXENV) continue; // If our envvar name is too big, then it's as if we didn't find anything if (strlen(delimiter) > MAXENV) continue; strncpy(envvar_name,name,delimiter-name); // Copy the envvar name in a buffer, to check for it later envvar_name[delimiter-name]='\0'; // Make sure it terminates by a delimiting zero delimiter++; // Point just right after the = sign if( strcmp(envvar_name,"HTTP_HOST") == 0){ // Have we found the HTTP_HOST? // log_error("%s => %s\n",envvar_name,delimiter); // Log the HTTP_HOST in our sbox.log return delimiter; } } return NULL; } // Debug function to print the environment values in the sbox.log // Do not activate all the time, as its printing quite some stuff, // and flooding a logfile is never a good idea. void print_the_env(char** e){ char *name,*delimiter; static char nm[MAXENV+2]; while ((name = *e++)) { delimiter = (char*) strchr(name,'='); if (delimiter == NULL) continue; if (delimiter - name >= MAXENV) continue; if (strlen(delimiter) > MAXENV) continue; strncpy(nm,name,delimiter-name); nm[delimiter-name]='\0'; log_error("%s => %s\n",nm,++delimiter); } } int isToggleValueOn(char* t){ if( strcmp(t,"On") == 0 || strcmp(t,"on") == 0 || strcmp(t,"1") == 0 || strcmp(t,"ON") == 0) return 1; else return 0; } // This function will read the environment variables of // Apache, so that you can eventually set the configuration // of SBOX in it in order to overwrite what is in /etc/sbox.conf // // This gives the additional functionality to be able to have // specific values depending on which vhost you run. // // For example, in your apache config file, you can do: // SetEnv SBOX_DTC_CONF_web_user 100 // in order to overwrite the "web_user" value. // Of course, you will need the "mod_env" apache module to do that. void readEnvSboxConfig(char** e){ char *name,*delimiter; static char nm[MAXENV]; while ((name = *e++)) { delimiter = (char*) strchr(name,'='); if (delimiter == 0) continue; if (delimiter - name >= MAXENV) continue; if (strlen(delimiter) > MAXENV) continue; strncpy(nm,name,delimiter-name); nm[delimiter-name]='\0'; delimiter++; if( strcmp(nm,"SBOX_DTC_CONF_web_user") == 0) sbox_config.web_user = delimiter; if( strcmp(nm,"SBOX_DTC_CONF_web_group") == 0) sbox_config.web_group = delimiter; if( strcmp(nm,"SBOX_DTC_CONF_allow_web_owned_scripts") == 0) sbox_config.allow_web_owned_scripts = isToggleValueOn(delimiter); if( strcmp(nm,"SBOX_DTC_CONF_uid_min") == 0) sbox_config.uid_min = atoi(delimiter); if( strcmp(nm,"SBOX_DTC_CONF_uid_max") == 0) sbox_config.uid_max = atoi(delimiter); if( strcmp(nm,"SBOX_DTC_CONF_gid_min") == 0) sbox_config.gid_min = atoi(delimiter); if( strcmp(nm,"SBOX_DTC_CONF_gid_max") == 0) sbox_config.gid_max = atoi(delimiter); if( strcmp(nm,"SBOX_DTC_CONF_sid_mode_directory") == 0) sbox_config.sid_mode_directory = isToggleValueOn(delimiter); if( strcmp(nm,"SBOX_DTC_CONF_use_safe_path") == 0) sbox_config.use_safe_path = isToggleValueOn(delimiter); if( strcmp(nm,"SBOX_DTC_CONF_safe_path") == 0) sbox_config.safe_path = delimiter; if( strcmp(nm,"SBOX_DTC_CONF_log_file") == 0) sbox_config.log_file = delimiter; if( strcmp(nm,"SBOX_DTC_CONF_do_log_envvars") == 0) sbox_config.do_log_envvars = isToggleValueOn(delimiter); if( strcmp(nm,"SBOX_DTC_CONF_echo_failures") == 0) sbox_config.echo_failures = isToggleValueOn(delimiter); if( strcmp(nm,"SBOX_DTC_CONF_do_chroot") == 0) sbox_config.do_chroot = isToggleValueOn(delimiter); if( strcmp(nm,"SBOX_DTC_CONF_root") == 0) sbox_config.root = delimiter; if( strcmp(nm,"SBOX_DTC_CONF_cgi_bin") == 0) sbox_config.cgi_bin = delimiter; if( strcmp(nm,"SBOX_DTC_CONF_do_suid") == 0) sbox_config.do_suid = isToggleValueOn(delimiter); if( strcmp(nm,"SBOX_DTC_CONF_do_sgid") == 0) sbox_config.do_sgid = isToggleValueOn(delimiter); if( strcmp(nm,"SBOX_DTC_CONF_set_limits") == 0) sbox_config.set_limits = isToggleValueOn(delimiter); if( strcmp(nm,"SBOX_DTC_CONF_priority") == 0) sbox_config.priority = atoi(delimiter); if( strcmp(nm,"SBOX_DTC_CONF_limit_cpu_hard") == 0) sbox_config.limit_cpu_hard = atol(delimiter); if( strcmp(nm,"SBOX_DTC_CONF_limit_cpu_soft") == 0) sbox_config.limit_cpu_soft = atol(delimiter); if( strcmp(nm,"SBOX_DTC_CONF_limit_fsize_hard") == 0) sbox_config.limit_fsize_hard = 1024*atol(delimiter); if( strcmp(nm,"SBOX_DTC_CONF_limit_fsize_soft") == 0) sbox_config.limit_fsize_soft = 1024*atol(delimiter); if( strcmp(nm,"SBOX_DTC_CONF_limit_data_hard") == 0) sbox_config.limit_data_hard = 1024*atol(delimiter); if( strcmp(nm,"SBOX_DTC_CONF_limit_data_soft") == 0) sbox_config.limit_data_soft = 1024*atol(delimiter); if( strcmp(nm,"SBOX_DTC_CONF_stack_hard") == 0) sbox_config.limit_stack_hard = 1024*atol(delimiter); if( strcmp(nm,"SBOX_DTC_CONF_limit_stack_soft") == 0) sbox_config.limit_stack_soft = 1024*atol(delimiter); if( strcmp(nm,"SBOX_DTC_CONF_limit_core_hard") == 0) sbox_config.limit_core_hard = 1024*atol(delimiter); if( strcmp(nm,"SBOX_DTC_CONF_limit_core_soft") == 0) sbox_config.limit_core_soft = 1024*atol(delimiter); if( strcmp(nm,"SBOX_DTC_CONF_limit_rss_hard") == 0) sbox_config.limit_rss_hard = 1024*atol(delimiter); if( strcmp(nm,"SBOX_DTC_CONF_limit_rss_soft") == 0) sbox_config.limit_rss_soft = 1024*atol(delimiter); if( strcmp(nm,"SBOX_DTC_CONF_limit_nproc_hard") == 0) sbox_config.limit_nproc_hard = atol(delimiter); if( strcmp(nm,"SBOX_DTC_CONF_limit_nproc_soft") == 0) sbox_config.limit_nproc_soft = atol(delimiter); if( strcmp(nm,"SBOX_DTC_CONF_limit_nofile_hard") == 0) sbox_config.limit_nofile_hard = atol(delimiter); if( strcmp(nm,"SBOX_DTC_CONF_limit_nofile_soft") == 0) sbox_config.limit_nofile_soft = atol(delimiter); } } /***************** START OF CODE ****************/ char* getFileExtension(char* file){ int len,i; len = strlen(file); for(i=len-1 ; i>0 ; --i){ if( file[i] == '.'){ return &file[i]; } } return 0; } #define HOST_CONF_FILE_FOLDER "/etc/sbox/vhosts.d/" int main (int argc, char* argv[], char** e) { struct stat target_stat,dir_stat; char *target,*newroot,*root,*additional_info,*cmd,*new_cmd_interp; int gid,uid,i,return_int; char* my_http_host; char* ext; struct stat stat_buffer; char* http_host_config_file_path; int conf_file_path_string_size; char realpath_path[MAXPATHLEN+2]; char* dirname_path; char* dirname_path2; FILE* fp; ////////////////////////// GET THE PATH OF THE SBOX CONFIG DEPENDING ON THE HTTP_HOST ENV VAR ////////////////////////// //sbox_config.log_file = "/var/log/sbox.log"; //open_log(); //log_error("Testing log\n"); my_http_host = get_http_host(e); // Get the current vhost name if(my_http_host == NULL){ sbox_config.log_file = "/var/log/sbox.log"; open_log(); log_error("HTTP_HOST environment variable not found: exiting.\n"); exit(1); } if(strlen(my_http_host) > 1024){ sbox_config.log_file = "/var/log/sbox.log"; open_log(); log_error("HTTP_HOST environment variable too big: exiting.\n"); exit(1); } conf_file_path_string_size = strlen(HOST_CONF_FILE_FOLDER) + strlen(my_http_host) + 2; http_host_config_file_path = malloc(conf_file_path_string_size); if(http_host_config_file_path == NULL){ sbox_config.log_file = "/var/log/sbox.log"; open_log(); log_error("Could not alloc space for storing HTTP_HOST: exiting.\n"); exit(1); } strcpy(http_host_config_file_path,HOST_CONF_FILE_FOLDER); strcat(http_host_config_file_path,my_http_host); // log_error("Concat file is: \"%s\"\n",http_host_config_file_path); if(!realpath(http_host_config_file_path,realpath_path)){ // If not resolved, open the default config file //log_error("realpath returned NULL: opening default /etc/sbox/sbox.conf\n"); read_config_file("/etc/sbox/sbox.conf"); }else{ // If resolved, then there may be a vhost specific file that can be opened! log_error("Realpath is: %s\n",realpath_path); dirname_path = strdup(realpath_path); dirname_path2 = dirname(dirname_path); //log_error("dirname_path2 is: %s\n",dirname_path2); strcat(dirname_path2,"/"); if( strcmp(dirname_path,HOST_CONF_FILE_FOLDER) != 0 ){ sbox_config.log_file = "/var/log/sbox.log"; open_log(); log_error("Directory traversal attempt: exiting.\n"); exit(1); } // Get to know if the file exists, if it does use it as config file, if not use /etc/sbox/sbox.conf fp = fopen(realpath_path,"r"); if(fp == NULL){ //log_error("File %s doesn't exist or can't be read, using /etc/sbox/sbox.conf",realpath_path); read_config_file("/etc/sbox/sbox.conf"); }else{ //log_error("File exist: using %s\n",realpath_path); fclose(fp); read_config_file(realpath_path); } } // Used for debug purpose: do ont use in production, as this is very easy // to hack a change in the environment of Apache // readEnvSboxConfig(e); #if defined(DEBUG) printf("Web user: %s\n",sbox_config.web_user); printf("Web group: %s\n",sbox_config.web_group); printf("do_suid: %d\n",sbox_config.do_suid); printf("do_guid: %d\n",sbox_config.do_sgid); printf("uid_min: %d\n",sbox_config.uid_min); printf("uid_max: %d\n",sbox_config.uid_max); printf("gid_min: %d\n",sbox_config.gid_min); printf("gid_max: %d\n",sbox_config.gid_max); printf("sid_mode_directory: %d\n",sbox_config.sid_mode_directory); printf("echo_failures: %d\n",sbox_config.echo_failures); printf("do_chroot: %d\n",sbox_config.do_chroot); printf("safe_path: %s\n",sbox_config.safe_path); printf("safe_path_switch: %d\n",sbox_config.safe_path_switch); printf("log_file: %s\n",sbox_config.log_file); printf("root: %s\n",sbox_config.root); printf("cgi_bin: %s\n",sbox_config.cgi_bin); printf("set_limits: %d\n",sbox_config.set_limits); printf("priority: %d\n",sbox_config.priority); printf("limit_cpu_hard: %ld\n",sbox_config.limit_cpu_hard); printf("limit_cpu_soft: %ld\n",sbox_config.limit_cpu_soft); printf("limit_fsize_hard: %ld\n",sbox_config.limit_fsize_hard); printf("limit_fsize_soft: %ld\n",sbox_config.limit_fsize_soft); printf("limit_data_hard: %ld\n",sbox_config.limit_data_hard); printf("limit_data_soft: %ld\n",sbox_config.limit_data_soft); printf("limit_stack_hard: %ld\n",sbox_config.limit_stack_hard); printf("limit_stack_soft: %ld\n",sbox_config.limit_stack_soft); printf("limit_core_hard: %ld\n",sbox_config.limit_core_hard); printf("limit_core_soft: %ld\n",sbox_config.limit_core_soft); printf("limit_rss_hard: %ld\n",sbox_config.limit_rss_hard); printf("limit_rss_soft: %ld\n",sbox_config.limit_rss_soft); printf("limit_nproc_hard: %d\n",sbox_config.limit_nproc_hard); printf("limit_nproc_soft: %d\n",sbox_config.limit_nproc_soft); printf("limit_nofile_hard: %d\n",sbox_config.limit_nofile_hard); printf("limit_nofile_soft: %d\n",sbox_config.limit_nofile_soft); #endif open_log(); if(sbox_config.do_log_envvars){ print_the_env(e); } check_consistency(); /* figure out the base of the user's HTML document tree */ root = document_root(); /* resolve the additional path information correctly */ target = fetch_target(root,&additional_info,&target_stat,&dir_stat); if(sbox_config.do_chroot){ /* find the absolute path name of the root */ to_abs(root); /* calculate the new root for chroot*/ newroot = fetch_newroot(root); } /* check that the target is OK */ check_target(newroot,target,&target_stat,&dir_stat); if(sbox_config.do_chroot){ /* fix the environment */ tweak_environment(newroot,root,target,additional_info); #if !defined(DEBUG) /* change to the owner's root */ if (chroot(newroot) < 0) fatal_error("couldn't chroot to %s (%s)\n",escape(newroot),strerror(errno)); #endif } #if defined(DEBUG) cmd = target; #else if(sbox_config.do_chroot){ cmd = shave(newroot,target); }else{ cmd = target; } #endif clean_env(); /* set hard and soft limits on resource usage */ /* important to do this after log is closed because otherwise the log file size will be restricted by the LIMIT_FSIZE_SOFT value */ if(sbox_config.set_limits) set_limits(); /* set to the owner's uid and gid */ if(sbox_config.do_suid || sbox_config.do_sgid){ gid = sbox_config.sid_mode_directory == 1 ? dir_stat.st_gid : target_stat.st_gid; uid = sbox_config.sid_mode_directory == 1 ? dir_stat.st_uid : target_stat.st_uid; #if defined(DEBUG) if (setgid(getgid()) < 0) { fatal_error("couldn't setgid() to %d (%s)\n",getgid(),strerror(errno)); } #else if(sbox_config.do_sgid){ if (setgid(gid) < 0) { fatal_error("couldn't setgid() to %d (%s)\n",dir_stat.st_gid,strerror(errno)); } }else{ /* give up our sgid privileges if any*/ if (setgid(getgid()) < 0) { fatal_error("couldn't setgid() to %d (%s)\n",getgid(),strerror(errno)); } } #endif #if !defined(DEBUG) if(sbox_config.do_suid){ if (setuid(uid) < 0) { fatal_error("couldn't setuid() to %d (%s)\n",dir_stat.st_uid,strerror(errno)); } } #endif } /* give up our root privileges now */ if (setuid(getuid()) < 0) { fatal_error("couldn't setuid() to %d (%s)\n",getuid(),strerror(errno)); } /* fix up argv[] array and command depending on the extension */ ext = getFileExtension(cmd); if(ext == 0){ new_cmd_interp = cmd; argv[0] = cmd; if(strlen(sbox_config.log_file) > 0){ log_error("No extension found: starting as CGI: executing %s for uid %d, gid %d\n",target,getuid(),getgid()); } }else{ if( strcmp(ext,".php") == 0){ new_cmd_interp = sbox_config.php_path; }else if(strcmp(ext,".py") == 0){ new_cmd_interp = sbox_config.python_path; }else if(strcmp(ext,".pl") == 0){ new_cmd_interp = sbox_config.perl_path; }else if(strcmp(ext,".rb") == 0){ new_cmd_interp = sbox_config.ruby_path; }else{ log_error("Extension not recognised: will exit here!\n"); return -1; } argv[0] = new_cmd_interp; argv[1] = cmd; log_error("Found %s for %s: %s %s (%s for uid %d and gid %d)\n",ext,target,new_cmd_interp,argv[1],cleanenv[0],getuid(),getgid()); } /* chdir() to new directory */ chdir_fix(newroot,target); if(strlen(sbox_config.log_file) > 0 && ext == 0){ log_error("Going to try this: %s , %s, %s\n", new_cmd_interp, argv[1], cleanenv[0]); } /* close log file so we don't leak file descriptor */ if (log && log != stderr) { fp = log; log = NULL; fclose(fp); } /* execute the target */ return_int = execve(new_cmd_interp,argv,cleanenv); /* if we get here, then something went wrong -- we won't be able to reopen the log file because we've given up privileges, logging to stderr causes an Apache "Premature end of script" error because it's expecting a Content-Type header, so disable logging via write_log entirely by setting log to NULL. */ log = NULL; fatal_error("exec of %s failed (%s)\n",escape(new_cmd_interp),strerror(errno)); return -1; } /* Will error out if one of the consistency checks fails. */ void check_consistency() { struct passwd *pass; struct group *grp; int uid,gid; #if !defined(DEBUG) /* get our group and user ids */ uid = getuid(); if ((pass = getpwuid(uid)) == NULL) fatal_error("invalid uid: (%ld)\n", uid); gid = getgid(); if ((grp = getgrgid(gid)) == NULL) fatal_error("invalid gid: (%ld)\n", gid); /* exit if either the uid or gid are zero */ if (uid == 0) fatal_error("cannot be run as root\n"); if (gid == 0) fatal_error("cannot be run as the root group\n"); /* Make sure that we were invoked by the Web user and group */ if (strcmp(sbox_config.web_user,pass->pw_name)) fatal_error("invoked by %s, but must be run by %s\n",escape(pass->pw_name),escape(sbox_config.web_user)); if (strcmp(sbox_config.web_group,grp->gr_name)) fatal_error("invoked by group %s, but must be run by group %s\n",escape(grp->gr_name),escape(sbox_config.web_group)); #endif } void open_log () { if (strlen(sbox_config.log_file) > 0) { if ((log = fopen(sbox_config.log_file, "a")) == NULL) { fprintf(stderr, "sbox failed to open log file. Falling back to stderr.\n"); log = stderr; } } else { log = stderr; } // log = NULL; } static void write_log(const char* fmt, va_list ap) { time_t timevar; char* timestr; if (log == NULL) return; timevar = time(NULL); timestr = ctime(&timevar); timestr[strlen(timestr)-1]='\0'; fprintf(log,"[%s] sbox[%d]: ",timestr,getpid()); vfprintf(log, fmt, ap); fflush(log); return; } void log_error(const char* fmt, ...) { va_list ap; va_start(ap, fmt); write_log(fmt,ap); va_end(ap); } void fatal_error(const char* fmt, ...) { va_list ap; char* webmaster; va_start(ap, fmt); write_log(fmt,ap); if(sbox_config.echo_failures){ webmaster = (char*)getenv("SERVER_ADMIN"); fprintf(stdout,"Content-type: text/html\n\n"); fprintf(stdout,webmaster ? "%s (%s).": "%s", CANNED_ERROR_TOP,webmaster,webmaster); fprintf(stdout,"
"); vprintf(fmt, ap); fprintf(stdout,"
%s",CANNED_ERROR_BOTTOM); fprintf(stdout,"

sbox version %3.2f
%s


",VERSION,"$Id: sbox.c,v 1.8 2007/06/18 14:40:03 thomas Exp $"); }else{ fprintf(stdout,"Content-type: text/html\n\n%s",CANNED_ERROR); } fflush(stdout); va_end(ap); exit(-1); } /* Find the physical path of a directory, following symbolic and hard links. This transforms the argument in place, so it must be at least MAXPATHLEN in size! */ static char* to_abs(char* directory) { if (chdir(directory) < 0) fatal_error("Can't chdir() to %s: %s\n",escape(directory),strerror(errno)); if (!getcwd(directory,MAXPATHLEN)) fatal_error("Error during getcwd(): %s\n",strerror(errno)); return directory; } #ifdef USE_ABSOLUTE_ROOT char* document_root () { char *document_root; int pathlen; if (!(document_root = (char*) calloc(sizeof(char),MAXPATHLEN+1))) fatal_error("out of memory while allocating space for document root string\n"); pathlen = strlen(USE_ABSOLUTE_ROOT); strncpy(document_root,USE_ABSOLUTE_ROOT, pathlen+1); document_root[pathlen+1] = '\0'; return document_root; } #else /* Find the document root by subtracting PATH_INFO from PATH_TRANSLATED */ char* document_root () { char *path_info,*path_translated,*document_root; int p,v,common; int pathlen; /* fetch the PATH_TRANSLATED environment variable */ /* should print out usage information, actually */ path_translated = (char*) getenv("PATH_TRANSLATED"); if (path_translated == NULL) fatal_error("Please specify the script to run with the format: \"%s/script/to/run\".\n", escape((char*)getenv("SCRIPT_NAME"))); /* fetch the PATH_TRANSLATED environment variable */ /* should print out usage information, actually */ path_info = (char*) getenv("PATH_INFO"); if (path_info == NULL) fatal_error("please specify the script to run \"%s/script/to/run\"\n", escape((char*)getenv("SCRIPT_NAME"))); /* find the document root by proceeding from right to left */ for (common=p=strlen(path_translated),v=strlen(path_info); p>=0 && v>=0; p--,v--) { if (path_translated[p] != path_info[v]) break; if (path_translated[p] == '/') common = p; } if (path_translated[common] == '/') common--; /* now common points to the end of the document root */ if (common+2 > MAXPATHLEN) fatal_error("path translated is larger than MAXPATHLEN: \"%s\"",path_translated); /* at this point, common points to the end of the document root */ if (!(document_root = (char*) calloc(sizeof(char),MAXPATHLEN+1))) fatal_error("out of memory while allocating space for document root string\n"); strncpy(document_root,path_translated,common+1); document_root[common+1] = '\0'; return document_root; } #endif /* Find the path to the target script and return it, along * with the additional path info, if any. Also returns stat * structures for the target and its directory. * A side-effect is that the target's directory is made the current * working directory. */ char* fetch_target(char* root,char** additional,struct stat* starg,struct stat* sdir) { char *path_info,*path_translated,*dir=NULL,*path,*p; char *raw,*shaved,target[MAXPATHLEN+1],directory[MAXPATHLEN+1]; int valid = 0; int additional_length,max; /* fetch the PATH_{TRANSLATED,INFO} environment variables */ /* we will have errored out before this if these are undefined or zero length */ path_translated = (char*) getenv("PATH_TRANSLATED"); path_info = (char*) getenv("PATH_INFO"); // log_error("path_info %s , path_translated %s\n", path_info, path_translated ); if (path_info[0] != '/') fatal_error("PATH_INFO does not begin with a '/'\n"); /* if this is the /~user type of path info, then the translated path is the root, appended to CGI_BIN, appended to the shaved path */ if (path_info[1] == '~') shaved = shave(root,path_translated); else shaved = path_info; //log_error("shaved %s\n", shaved); //log_error("root %s\n", root); //log_error("sbox_config.cgi_bin %s\n", sbox_config.cgi_bin); if (strlen(root)+1+strlen(sbox_config.cgi_bin) > MAXPATHLEN) fatal_error("Script directory path larger than MAXPATHLEN\n"); strncpy(directory,root,MAXPATHLEN); directory[MAXPATHLEN] = '\0'; strncat(directory,"/",1); strncat(directory,sbox_config.cgi_bin,strlen(sbox_config.cgi_bin)); /* resolve symbolic links and relative paths */ to_abs(directory); max = strlen(directory) + strlen(shaved) + 1; if (!(raw = (char*)calloc(sizeof(char),max))) fatal_error("Unable to allocate memory for path to CGI script: %s\n",strerror(errno)); strncpy(raw,directory,max); strncat(raw,shaved,strlen(shaved)); raw[max-1] = '\0'; /* step down the path until we find the directory and the executable */ p = raw+1; while ((p = strchr(p,'/'))) { if ( (p-raw) > MAXPATHLEN) fatal_error("path_info too long\n"); strncpy(target,raw,p-raw); target[p-raw] = '\0'; /* make sure there are no ".." path components!!!! */ if (strncmp(p,"/..",3) == 0) fatal_error("path to CGI script (%s) must not contain relative path components\n",escape(raw)); if (stat(target,starg) < 0) fatal_error("Stat failed. %s: %s\n",escape(target),strerror(errno)); /* if it's a directory, then copy it into dir for safe keeping */ if (S_ISDIR(starg->st_mode)) memcpy((void*)sdir,(void*)starg,sizeof(struct stat)); else if ((valid = S_ISREG(starg->st_mode)) == TRUE ) break; dir = p; p++; } /* If the executable is the last item on the path, then we will not have found a valid partial path. Stat the whole thing. */ if (!valid) { if (stat(raw,starg) < 0) fatal_error("Stat failed. %s: %s\n",escape(raw),strerror(errno)); if (!S_ISREG(starg->st_mode)) fatal_error("Couldn't find a valid script to execute in %s\n",escape(raw)); p = raw + strlen(raw); strncpy(target,raw,MAXPATHLEN); target[MAXPATHLEN] = '\0'; } /* Everything to the right of the end of target is additional path info */ additional_length = strlen(raw) - strlen(target); if (!(*additional = (char*) calloc(sizeof(char),additional_length+1))) fatal_error("Unable to allocate memory for additional path info.\n"); strncpy(*additional,raw+strlen(target),additional_length); (*additional)[additional_length] = '\0'; /* turn the directory part of the target into a real directory, resolving symbolic paths */ strncpy(directory,target,dir-raw); directory[dir-raw]='\0'; to_abs(directory); max = strlen(directory)+(p-dir)+1; if (!(path = (char*)calloc(sizeof(char),max))) fatal_error("unable to allocate memory during calloc() of physical path: %s\n",strerror(errno)); strncpy(path,directory,max); strncat(path,dir,p-dir); path[max-1] = '\0'; if (raw != NULL) free((void*)raw); return path; } /* implement a variety of checks on the script before executing it */ void check_target(const char* newroot, const char* target, const struct stat *file_stats, const struct stat *dir_stats) { struct passwd *pass; struct group *grp; #if !defined(DEBUG) /* 1) script must not be SUID or SGID*/ if (file_stats->st_mode & S_ISUID) fatal_error("cannot run suid scripts (%s)\n",escape(target)); if (file_stats->st_mode & S_ISGID) fatal_error("cannot run sgid scripts (%s)\n",escape(target)); /* 2) script must be executable by other */ if (!( (file_stats->st_mode & S_IXOTH))) fatal_error("%s not world executable. Make sure your script is chmod +x!\n",escape(target)); /* 3) script is not owned by WEB_USER or WEB_GROUP */ if ((pass = getpwuid(file_stats->st_uid)) == NULL) fatal_error("%s is owned by an unknown user (%ld)\n",escape(target),file_stats->st_uid); if(sbox_config.allow_web_owned_scripts){ if (!(strcmp(pass->pw_name,sbox_config.web_user))) fatal_error("%s is owned by the Web user (%s)\n",escape(target),sbox_config.web_user); } if ((grp = getgrgid(file_stats->st_gid)) == NULL) fatal_error("%s is owned by an unknown group (%ld)\n",escape(target),file_stats->st_gid); if(sbox_config.allow_web_owned_scripts){ if (!(strcmp(grp->gr_name,sbox_config.web_group))) fatal_error("%s is owned by the Web group (%s)\n",escape(target),sbox_config.web_group); } /* 4) directory is not owned by WEB_USER or WEB_GROUP */ if ((pass = getpwuid(dir_stats->st_uid)) == NULL) fatal_error("the directory containing %s is owned by an unknown user (%ld)\n", escape(target),dir_stats->st_uid); if(sbox_config.allow_web_owned_scripts){ if (!(strcmp(pass->pw_name,sbox_config.web_user))) fatal_error("the directory containing %s is owned by the Web user (%s)\n",escape(target),sbox_config.web_user); } if ((grp = getgrgid(dir_stats->st_gid)) == NULL) fatal_error("the directory containing %s is owned by an unknown group (%ld)\n", escape(target),dir_stats->st_gid); if(sbox_config.allow_web_owned_scripts){ if (!(strcmp(grp->gr_name,sbox_config.web_group))) fatal_error("the directory containing %s is owned by the Web group (%s)\n",escape(target),sbox_config.web_group); } /* 5) Neither file nor the directory are writable by other */ if (file_stats->st_mode & S_IWOTH) fatal_error("%s is world writable\n",escape(target)); if (dir_stats->st_mode & S_IWOTH) fatal_error("the directory containing %s is world writable\n",escape(target)); if(sbox_config.do_chroot){ /* 6) target must be located within the new root */ if (strstr(target,newroot) != target) fatal_error("%s is not contained within the chroot directory %s\n",escape(target),newroot); } /* 7) owner and group must not be less than UID_MIN, GID_MIN */ if(sbox_config.do_suid){ if(sbox_config.sid_mode_directory){ if (dir_stats->st_uid < sbox_config.uid_min) fatal_error("the directory containing %s must not be owned by a UID less than %d\n",escape(target),sbox_config.uid_min); }else{ if (file_stats->st_uid < sbox_config.uid_min) fatal_error("the file containing %s must not be owned by a UID less than %d\n",escape(target),sbox_config.uid_min); } } if(sbox_config.do_sgid){ if(sbox_config.sid_mode_directory){ if (dir_stats->st_gid < sbox_config.gid_min) fatal_error("the directory containing %s must not be owned by a GID less than %d\n",escape(target),sbox_config.gid_min); }else{ if (file_stats->st_gid < sbox_config.gid_min) fatal_error("the file containing %s must not be owned by a GID less than %d\n",escape(target),sbox_config.gid_min); } } /* 8) owner and group must not be greater than UID_MAX, GID_MAX */ if(sbox_config.do_suid){ if(sbox_config.sid_mode_directory){ if (dir_stats->st_uid > sbox_config.uid_max) fatal_error("the directory containing %s must not be owned by a UID greater than %d\n",escape(target),sbox_config.uid_max); }else{ if (file_stats->st_uid > sbox_config.uid_max) fatal_error("the file containing %s must not be owned by a UID greater than %d\n",escape(target),sbox_config.uid_max); } } if(sbox_config.do_sgid){ if(sbox_config.sid_mode_directory){ if (dir_stats->st_gid > sbox_config.gid_max) fatal_error("the directory containing %s must not be owned by a GID greater than %d\n",escape(target),sbox_config.gid_max); }else{ if (file_stats->st_gid > sbox_config.gid_max) fatal_error("the file containing %s must not be owned by a GID greater than %d\n",escape(target),sbox_config.gid_max); } } #endif } char* fetch_newroot(char* docroot) { char newd[MAXPATHLEN+1],*newroot; int max; max = strlen(docroot) + 1 + strlen(sbox_config.root); if ( max > MAXPATHLEN) fatal_error("document root is too large: \"%s\"",docroot); strncpy(newd,docroot,max); strncat(newd,"/",1); strncat(newd,sbox_config.root,strlen(sbox_config.root)); /* tack on the new root component */ newd[MAXPATHLEN] = '\0'; if ((newroot = strdup(to_abs(newd))) == NULL) fatal_error("unable to allocate memory while making copy of new root directory path: %s\n", strerror(errno)); return newroot; } char* shave(char* newroot, char* target) { char* shaved = target; char* h = newroot; if (!newroot) return target; if (!target) return ""; while (*shaved && *h) { if (*shaved++ != *h++) break; } if (*h) return "/"; return shaved; } /* modify the environment in the following ways: * DOCUMENT_ROOT => shave(newroot,root) * SCRIPT_NAME => shave(root,target) * SCRIPT_FILENAME => shave(newroot,target) * PATH_INFO => shave(SCRIPT_NAME,env(path_info)) * PATH_TRANSLATED => SCRIPT_FILENAME,env(path_info) */ static void tweak_environment(char* newroot, char* root, char* target, char* additional_info) { char *s,*t,*path_info,*path_translated,*script_name; int r,max; /* per rfc3875: The SCRIPT_NAME variable MUST be set to a URI path (not URL-encoded) which could identify the CGI script ... No PATH_INFO segment is included in the SCRIPT_NAME value. */ script_name = shave(root,target); r = set_env("SCRIPT_NAME",script_name,1); if (r < 0) fatal_error("no room for SCRIPT_NAME environment variable"); /* Shave the chroot directory off the target. Will cause an error if the target is not contained within the new root. */ s = shave(newroot,target); r = set_env("SCRIPT_FILENAME",s,1); if (r < 0) fatal_error("no room for SCRIPT_FILENAME environment variable"); /* PATH_INFO Contains any client-provided pathname information trailing the actual script filename but preceding the query string, if available. It does not include the script name itsself (SCRIPT_NAME). */ s = (char*) getenv("PATH_INFO"); path_info = shave(script_name,s); // r = set_env("PATH_INFO",(strlen(path_info) ? path_info : "/"),1); // if (r < 0) // fatal_error("no room for PATH_INFO environment variable"); /* PATH_TRANSLATED "is derived by taking the PATH_INFO value, parsing it as a local URI in its own right, and performing any virtual-to-physical translation appropriate to map it onto the server's document repository structure." So says rfc3875. That would make it roughly DOCUMENT_ROOT/uri_encode(PATH_INFO) .. which seems fairly useless. Additionally, "If PATH_INFO is NULL, then the PATH_TRANSLATED variable MUST be set to NULL (or unset)." */ if (strlen(path_info)) { /* this is DOCUMENT_ROOT */ s = shave(newroot,root); /* PATH_TRANSLATED should already be properly URI-encoded */ path_translated = (char*) getenv("PATH_TRANSLATED"); t = shave(target,path_translated); //max = strlen(s)+((t[0] != '/')?1:0)+ strlen(t)+1 +strlen(script_name); max = strlen( shave(newroot,target) ) + strlen(path_info) + 1; if (!(path_translated = (char*) calloc(sizeof(char),max))) fatal_error("unable to allocate string for path translated: %s\n",strerror(errno)); sprintf(path_translated,"%s%s",shave(newroot,target),path_info); r = set_env("PATH_TRANSLATED",path_translated,1); if (r < 0) fatal_error("no room for PATH_TRANSLATED environment variable"); //script_name = shave(root,target); max = strlen( shave(root,target) ) + strlen(path_info) + 1; if (!(s = (char*) calloc(sizeof(char),max))) fatal_error("unable to allocate string for path_info: %s\n",strerror(errno)); sprintf(s,"%s%s", shave(root,target),path_info); r = set_env("PATH_INFO",s,1); free((void*)s); } s = shave(newroot,root); r = set_env("DOCUMENT_ROOT",s,1); if (r < 0) fatal_error("no room for DOCUMENT_ROOT environment variable"); } /* set_env() is a replacement for the BSD setenv() function. */ static int set_env(const char *name, const char *value, int overwrite) { char **ep,**var,*d; /* initialize cleanenv global if necessary */ if (cleanenv == NULL) { if ((cleanenv = (char **)calloc(AP_ENVBUF, sizeof(char *))) == NULL) return -1; } /* search for the string in the existing environment */ ep = cleanenv; while (((var = ep++) != NULL) && *var) { d = (char*) strchr(*var,'='); /* look for the "=" sign */ if (!d) continue; /* malformed entry */ if ((int)strlen(name) != abs(d-*var)) continue; if (0 != strncmp(*var,name,d-*var)) /* compare to target string */ continue; /* if we get here, we found the environment variable */ if (!overwrite) return 0; /* not allowed to overwrite the variable */ /* clear out the previous value */ free((void*) *var); *var = NULL; } /* when we get here var points to the place in the environment string for the new value */ /* First make sure we haven't run off the end of the buffer. Must be a terminal NULL in the array */ if (var - cleanenv >= AP_ENVBUF - 1) return -1; if ( (*var = (char*)calloc(strlen(name)+1+strlen(value)+1,sizeof(char))) == NULL) return -1; /* out of space */ /* copy */ if (sprintf(*var,"%s=%s",name,value) <= 0) return -1; /* don't know when this would happen */ return 0; } /* clean_env() is derived from similar routine in suexec.c, part of the Apache distribution */ void clean_env(){ char pathbuf[NAME_MAX]; char *name,*delimiter; char **ep; int cidx = 0; int idx; /* initialize cleanenv global if necessary */ if (cleanenv == NULL) { if ((cleanenv = (char **)calloc(AP_ENVBUF, sizeof(char *))) == NULL) fatal_error("failed to malloc env mem\n"); } /* check cleanenv name and value lengths, and position to first NULL entry */ for (cidx = 0; cleanenv[cidx] && cidx < AP_ENVBUF; cidx++) { name = cleanenv[cidx]; delimiter = (char*) strchr(name,'='); if (delimiter == 0) fatal_error("malformed cleanenv entry %d, not in name=value format\n",cidx); if (delimiter - name >= MAXENV) { name[MAXENV] = '\0'; fatal_error("env name too long: %s\n",name); } if (strlen(delimiter) > MAXENV) { delimiter[MAXENV] = '\0'; fatal_error("env value too long: %s = %s\n",name,++delimiter); } } /* copy the environment */ for (ep = environ; *ep && cidx < AP_ENVBUF; ep++) { if (!strncmp(*ep, "HTTP_", 5)) { cleanenv[cidx] = *ep; cidx++; }else{ for (idx = 0; safe_env_lst[idx]; idx++){ if (!strncmp(*ep, safe_env_lst[idx], strlen(safe_env_lst[idx]))) { cleanenv[cidx] = *ep; cidx++; break; } } } } if (strlen(sbox_config.safe_path)+strlen("PATH=")+1 > NAME_MAX) fatal_error("value of SAFE_PATH (%s) is too large (max %d bytes)\n",escape(sbox_config.safe_path),NAME_MAX); sprintf(pathbuf, "PATH=%s", sbox_config.safe_path); cleanenv[cidx] = strdup(pathbuf); cleanenv[++cidx] = NULL; } char* escape (const char* str) { char *escaped,*s,c; int count = 0; if (str == NULL) return NULL; if(sbox_config.echo_failures){ s = (char*) str; count = strlen(str); while (c = *s++) { if (c == '<' || c == '>') { count += 4; }else if (c == '&'){ count += 5; } } escaped = (char*) calloc(sizeof(char),count+1); s = escaped; while (c = *str++) { if (c == '<') { strcat(s,"<"); s+=4; }else if (c == '>') { strcat(s,">"); s+=4; }else if (c== '&') { strcat(s,"&"); s+=5; }else { *s++ = c; } } return escaped; }else{ return (char*) str; } } /* chdir() to the directory where CGI script is located so that most e.g. Perl scripts that use relative paths work. the function gets the the full path to the chroot() directory (newroot) and full path (target) to the CGI script and extracts the correct subdirectory where the script resides on and does chdir() there. */ static void chdir_fix(char* newroot, char* target) { char *chdir_path; int i,j; int start=0; int end=0; chdir_path = (char*) calloc(sizeof(char),MAXPATHLEN); if (chdir_path == NULL) fatal_error("failed to allocate memory for chdir path: %s\n",strerror(errno)); for (i=0; target[i]!='\0' && newroot[i]!='\0'; i++) { if (target[i] == newroot[i]) start++; else continue; } for (i=0; target[i]!='\0'; i++) if (target[i] == '/') end=i; j = 0; if (start>0 && end>0 && startSbox Error " \ "

Sbox Error

" \ "The sbox " \ "program encountered an error while processing this request. " \ "Please note the time of the error, anything you might have been " \ "doing at the time to trigger the problem, and forward the " \ "information to this site's Webmaster " #endif #ifndef CANNED_ERROR_BOTTOM #define CANNED_ERROR_BOTTOM \ "
" \ "" #endif #define CANNED_ERROR CANNED_ERROR_TOP CANNED_ERROR_BOTTOM #endif /* _SBOX_H */ sbox-dtc-1.11.7/README.txt0000644000175000017500000012103412247552331013531 0ustar zigozigo _________________________________________________________________ sbox: Put CGI Scripts in a Box Abstract sbox is a CGI wrapper script that allows Web site hosting services to safely grant CGI authoring privileges to untrusted clients. In addition to changing the process privileges of client scripts to match their owners, it goes beyond other wrappers by placing configurable ceilings on script resource usage, avoiding unintentional (as well as intentional) denial of service attacks. It also optionally allows the Webmaster to place client's CGI scripts in a chroot'ed shell restricted to the author's home directories. sbox is compatible with all Web servers running under BSD-derived flavors of Unix. You can use and redistribute it freely. The current release is 1.10. Download it from the Web at http://stein.cshl.org/WWW/software/sbox/. Older versions are also available. Introduction Poorly-written CGI scripts are the single major source of server security holes on the World Wide Web. Every CGI script should be scrutinized and extensively tested before installing it on a server, and subject to periodic review thereafter. For Web hosting services, however, this advice is impractical. Hosting services must sponsor multiple Web authors of different levels of competence and reliability. Web authors do not trust each other, and the Web hosting service does not trust the authors. In such a situation, CGI scripts are even more problematic than usual. Because all CGI scripts run under the Web server's user ID, one author's scripts can interfere with another's. For example a malicious author could create a script that deletes files created by another author's script, or even cause another author's script to crash by sending it a kill signal. A poorly written script that contains a security hole can compromise the entire site's security by, for example, transmitting the contents of the system password file to a malicious remote user. The same problems are faced by large academic sites which provide Web pages for students. For most Web hosting services it would be impossible to subject each and every author's CGI scripts to code review. Nor is it practical to cut off CGI scripting privileges entirely. In the competitive world of ISP's, customers will just move elsewhere. The most popular solution to this problem is the use of "wrapper" scripts. In this system, untrusted author's CGI scripts are never invoked directly. Instead a small wrapper script is called on to execute the author's script, the target. The wrapper is SUID to root. When the wrapper runs, it subjects the target to certain safety checks (for example, checking that the script is not world-writable). The wrapper then changes its process ID to match the owner of the target and executes it. The result is that the author's script is executed with his own identity and privileges, preventing it from interfering with other author's scripts. The system also leads to increased accountability. Any files that an misbehaving script creates or modifies will bear the fingerprints of its creator. Without a wrapper, it can be impossible to determine which author's script is causing problems. The limitations of wrapper scripts are three-fold: 1. Wrappers provide little protection against attacks that involve reading confidential information on the site, for example sensitive system files or protected documents. 2. Wrappers expose the author to increased risk from buggy scripts. By running the author's script with his owner permissions, the wrapper grants it the ability to read, write or delete any file in the author's home directory. 3. There is no protection against denial-of-service attacks. A buggy script can go into an endless loop, write a huge file into /usr/tmp, or allocate an array as large as virtual memory, adversely affecting system responsiveness. A better solution is to box author's CGI scripts. In this solution, the CGI script is executed in a restricted environment in which its access to the file system and to other system resources is limited. This is what sbox (Secure Box) accomplishes. When run, it does several things: 1. It checks the environment for sanity. For example, the script must be run by the Web user and group, and not by anyone else. 2. It checks the target script for vulnerabilities, such as being world writable or being located in a world writable directory. 3. It performs a chroot to a directory that contains both the script and the author's HTML files, sealing the script off from the rest of the system. 4. It changes its user ID and/or group ID to that of the target script. 5. It sets ceilings on the target script's CPU, disk, memory and process usage. 6. It lowers the priority of its process. 7. It cleanses the environment so that only variables which are part of the CGI protocol are available to the script. 8. It invokes the target script in this restricted context. sbox is highly configurable. It can be configured to chroot without changing its process ID, to change its process ID without performing the chroot, to change its group ID without changing its user ID, to establish resource ceilings without doing anything else, or any other combination that suits you. System Requirements sbox is designed to run with any Unix-based Web server. The package should compile correctly on any standard Unix system; however the resource limits use the BSD-specific setrlimit() and setpriority() calls. If you do not know whether your system supports these calls, check for the existence of the file /usr/include/system/resource.h. If this file does not exist, then chances are slim that you can use the resource limits. You can run sbox without the limits by setting the preprocessor define SET_LIMITS to FALSE (see below). _________________________________________________________________ Installation After unpacking the package, you should have the following files: Makefile README.html (this file) README.txt (this file as text) sbox.h sbox.c env.c You will first examine and edit the Makefile, then change sbox.h to suit your site configuration and preferences. It is suggested that you keep copies of the unaltered files for future reference. _________________________________________________________________ Adjusting the Makefile Using your favorite text editor, examine and change the value of the INSTALL_DIRECTORY variable. This is the location in which sbox will be installed, and should correspond to your site-wide CGI directory. You may also need to fiddle with the options for the install program. The default is to make sbox owned by user "root" and group "bin", and installed with permissions -rws--x--x. This configuration is SUID to root, necessary in order for the chroot and process ID changing functions to work. If you wish to adjust the C compiler and its flags, change the CC and CFLAGS variables as needed. _________________________________________________________________ Adjusting sbox.h This is the fun part. sbox.h contains several dozen flags that affect the script's features. These flags are implemented as compile-time defines rather than as run-time configuration variables for security reasons. There is less chance that the behavior of sbox can be maliciously altered if it has no dependences on external configuration files. You should review sbox.h with a text editor and change the settings as needed. A typical entry looks like this: /* * ECHO_FAILURES -- If set to TRUE, will echo fatal error messages * to the browser. Set to FALSE to inhibit error messages. */ #ifndef ECHO_FAILURES #define ECHO_FAILURES TRUE #endif This section sets a feature called ECHO_FAILURES to TRUE. To change the value to FALSE, simply edit the line that begins with "#define" to read like this: #define ECHO_FAILURES FALSE General Settings These variables correspond to general sbox settings such as logging and environment consistency checking. WEB_USER (default "nobody") This defines the name of the user that the Web server runs under, "nobody" by default. If your Web server uses a different user ID, you must change this define to match. WEB_GROUP (default "nobody") This defines the name of the group that the Web server runs under, "nobody" by default. If your Web server uses a different group ID, you must change this define to match. UID_MIN, GID_MIN (defaults 100,100) These define the lowest UID and GID that the script will run a target CGI script as. On most systems, low-numbered user and group IDs correspond to users with special privileges. Change these values to be the lowest valid unprivileged user and group ID. Under no circumstances will sbox run a target script as root (UID 0.) SAFE_PATH (default "/bin:/usr/bin:/usr/local/bin") This defines the search path that will be passed to the author's CGI scripts, overriding whatever was there before. USE_ABSOLUTE_ROOT (no default) If set to an absolute path, sbox will chroot to a hard-coded directory and use that as its root. Use this if you want to have sbox work on a particular directory not related to a user's directory or the web root. NOTE: the sbox binary you compile will work for that directory ONLY. If you want to use it for another directory, recompile and use a different binary Logging Settings sbox can be set to log all its actions, including both failures and successful launches of author's scripts. Log entries are time stamped and labeled with the numeric IDs of the user and group that the target script was launched under. LOG_FILE (default none) This specifies a file to which sbox will log its successes and failures. Set this to the full path name of the file to log to. An empty string ("") will make sbox log to standard error, which will cause its log messages to be directed to the ordinary server error log. Leaving LOG_FILE undefined will cause sbox not to log any messages. ECHO_FAILURES (default TRUE) If this define is set to a true value, any fatal errors encountered during sbox's execution will be turned into a properly-formatted HTML message that is displayed for the remote user's benefit. Otherwise, the standard "An Internal Error occurred" message is displayed. Chroot Settings These variables controls sbox's chroot functionality. The path names are relative to the document root. In the case of virtual hosts, this will be whatever is specified by the DocumentRoot directive in the server's configuration file. In the case of user-supported directories, it will be the user's public_html directory. DO_CHROOT (default TRUE) If set to a true value, sbox will perform a chroot to a restricted directory prior to executing the CGI script. Otherwise no chroot will be performed. ROOT (default "..") This tells sbox where to chroot to relative to the document root. This directory should ordinarily be a level or two above the document tree so that the script can get access to the author's HTML documents for processing. CGI_BIN (default "../cgi-bin") This define tells sbox where to look for the author's scripts directory, relative to his site's document tree. This directory should be contained within the directory specified by ROOT. For best security, you should specify a directory that is outside the document tree. The default is a directory named "cgi-bin" located at the same level as the document root. SUID/SGID Settings DO_SUID, DO_SGID (defaults TRUE, TRUE) These defines control whether the script will perform an SUID and/or an SGID to the user and group of the target CGI script. From the author's point of view it's safer to perform an SGID than an SUID, and usually is more than adequate. If no SUID or SGID is performed, the author's script will be run with the Web server's privileges. SID_MODE (default DIRECTORY) This define controls whether sbox should use the ownership of the target script or the directory containing the target script to determine whose user ID and/or group ID to run under. Use directory mode if several users have authoring privileges for a single virtual host. Resource Limitation Settings SET_LIMITS (default TRUE) If set to a true value, sbox will set resource usage ceilings before running the target CGI script. You may need to set this to FALSE if you are using a system that does not implement the setpriority() and/or setrlimit() calls. PRIORITY (default 10) This controls the priority with which target scripts are run. Values can range from -20 to 20. Higher numbers have less priority. LIMIT_CPU_HARD, LIMIT_CPU_SOFT, LIMIT_FSIZE_HARD, LIMIT_FSIZE_SOFT... These and similar defines control the resource ceilings. The definitions set caps on CPU usage, the number of processes the script can spawn, the amount of memory it can use, the size of the largest file it can create, and other attributes. For each resource there are two caps, one hard, the other soft. Soft resources can be increased by any program that desires to do so by making the appropriate calls to setrlimit(). Hard limits are inviolable ceilings that cannot be lifted once established, even by a privileged user. The hard limits should be rather liberal, the soft limits more strict. See the setrlimit() man page for details on each of these resources. If you use LIMIT_FSIZE_HARD or _SOFT and are logging to stderr, be careful! If your web server error log is larger than the limit, no logging will occur. _________________________________________________________________ Making and Installing the Binary Compile the sbox binary by typing make. If it compiles successfully, become root and type make install to install it in your site's cgi-bin directory (at the location specified in the Makefile.) You can also install sbox manually by copying it into your cgi-bin directory and settings its permissions to ---s--x--x. This can be done with the following commands while logged in as the root user: # chown root sbox # chgrp bin sbox # chmod 4111 sbox _________________________________________________________________ Configuring the Server and User Directories In order for sbox to be effective, CGI scripts should be turned off in all user-supported directories and document directories. All CGI scripts should be placed in the main cgi-bin directory. No one but authorized site administrators should have write or listing privileges for this directory. If you are using the Apache server, a typical entry for a virtual host will look like this: ServerName www.fred.com ServerAdmin fred@fred.com DocumentRoot /home/fred/sbox_root/html TransferLog /home/fred/sbox_root/logs/access_log ErrorLog /home/fred/sbox_root/logs/error_log Options MultiViews Indexes SymLinksIfOwnerMatch IncludesNoExec AllowOverride Options AuthConfig Limit order allow,deny allow from all (Please be sure to use Options and AllowOverride directives that match the security policy of your site.) For a site that uses UserDir-style home pages (http://www.your.site/~username), a typical configuration is: UserDir sbox_root/html Options MultiViews Indexes SymLinksIfOwnerMatch IncludesNoExec AllowOverride Options AuthConfig Limit order allow,deny allow from all Note that in both cases, the user's document root (where his HTML files go) is "~fred/sbox_root/html", that is, two directory levels below his home directory. When sbox runs, it uses the position of the user's document root to find its root and the cgi-bin directory. The suggested defaults defined in sbox.h make the ROOT equal to "..", and CGI_BIN equal to "../cgi-bin", both relative to the document root. Hence in the examples given above, sbox's root will be ~fred/sbox_root, and sbox will look for his CGI scripts in the directory ~fred/sbox_root/cgi-bin. When sbox runs in chroot mode, ~fred/sbox_root becomes the new top level ("/") directory, insulating the user's CGI script from the rest of his home directory, as well as the rest of the file system. This prevents the CGI script from inadvertently (or deliberately) doing something antisocial, but gives the script access to the user's HTML files, for filtering and templating. Because the user's CGI script is cut off from the rest of the filesystem after the chroot call, dynamically linked programs (including interpreters and the like) will not be happy unless they can find the shared libraries they rely on. Therefore, the sbox root directory should be set up like a miniature root directory, and contain whatever binaries, configuration files and shared libraries are necessary for programs to run. This list is different from system to system. See Using the Miniroot and Tips for advice on setting this directory up. Below is the structure of Fred's directory, assuming that the virtual host uses ~fred/sbox_root/html as its document root. % ls -l ~fred/sbox_root total 10 drwxr-xr-x 2 fred users 1024 Oct 23 06:27 bin/ system binaries drwxr-xr-x 3 fred users 1024 Oct 19 20:44 cgi-bin/ CGI scripts drwxr-xr-x 2 fred users 1024 Oct 12 16:59 dev/ device special files drwxr-xr-x 2 fred users 1024 Oct 19 17:57 etc/ configuration files drwxr-xr-x 2 fred users 1024 Oct 22 19:14 html/ HTML document root drwxr-xr-x 3 fred users 1024 Oct 19 20:35 lib/ shared libraries drwxr-xr-x 3 fred users 1024 Oct 19 20:35 logs/ log files drwxr-xr-x 2 fred users 1024 Oct 23 05:48 tmp/ temporary files drwxr-xr-x 2 fred users 1024 Oct 23 05:48 usr/ files that belong in us r drwxr-xr-x 2 fred users 1024 Oct 23 05:48 var/ files that belong in va r If you do not take advantage of sbox's chroot feature, but just use it for its ability to change to the user's UID and GID, then you do not have to do any special directory setup. See Supporting Apache .htaccess files and Rewrite-Rule Tricks for additional common configuration setups that make sbox more transparent to use. _________________________________________________________________ Calling sbox To use sbox create URLs like this one: http://www.virtual.host.com/cgi-bin/sbox/script_name ^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^ virtual host name user's script The first part of the URL is the path to the sbox script. The second part is the path to the user's script, relative to the cgi-bin directory in his home directory. If the user's script needs access to additional path information, you can append it in the natural way: http://www.virtual.host.com/cgi-bin/sbox/script_name/additional/pat h/info For user-supported directories, use this format: http://www.virtual.host.com/cgi-bin/sbox/~fred/script_name Users are free to organize their script directories into a hierarchy. They need only modify script URLs to reflect the correct path: http://www.virtual.host.com/cgi-bin/sbox/foo/bar/script_name _________________________________________________________________ Supporting Apache .htaccess files If you are using the Apache web server and wish the user to be able to password-protect or otherwise modify access to his cgi-bin directory using a .htaccess file, then you will need to activate and use Apache's mod_rewrite module. Otherwise any .htaccess file located in the user's cgi-bin directory will be ignored. This method will also make it so that if the requested executable is not found in the cgi-bin directory, the error condition will fall through to Apache's error handling system (using ErrorDocument) rather than raising an sbox error. First make sure that Apache was compiled with the mod_rewrite module and that the module is loaded at startup time. The relevant directive is: LoadModule rewrite_module lib/apache/mod_rewrite.so Now assuming that user cgi-bin directories are installed in ~user/sbox_root/cgi-bin, that the sbox executable is installed in /cgi-bin/sbox, and that user directories are located at /home/username, enter the following into your httpd.conf file: For Virtual Hosts RewriteEngine on RewriteLog "/var/log/apache/rewrite_log" RewriteLogLevel 0 RewriteCond %{REQUEST_FILENAME} ^/cgi-bin/sbox/(.+) RewriteCond %{DOCUMENT_ROOT}/../cgi-bin/%1 !-F RewriteRule ^/cgi-bin/sbox/(.+) %{DOCUMENT_ROOT}/../cgi-bin/$1 [L] RewriteRule ^(/cgi-bin/sbox/.+) $1 [PT,NS] (This goes into each VirtualHost section) For User Directories RewriteEngine on RewriteLog "/var/log/apache/rewrite_log" RewriteLogLevel 0 RewriteCond %{REQUEST_FILENAME} ^/cgi-bin/sbox/~([^/]+)/(.+) RewriteCond /home/%1/sbox_root/cgi-bin/%2 !-F RewriteRule ^/cgi-bin/sbox/~([^/]+)/(.+) /home/$1/sbox_root/cgi-bin/$2 [L] RewriteRule ^(/cgi-bin/sbox/~.+/.+) $1 [PT,NS] (This goes into the main section of httpd.conf) These pretty complicated looking pieces of code says that for URLs that begin with /cgi-bin/sbox/~username/filename, first check whether the file /home/username/sbox_root/cgi-bin/filename exists and is available via Apache's access rules. If it isn't available, then rewrite the URL as /home/username/sbox_root/cgi-bin/filename and perform the usual processing as if it were a file (which will result in a 403 or 404 error). Otherwise, don't rewrite the URL and pass it through to the CGI handler. You will need to tweak these a bit if users' home directories are somewhere else than /home/user or if you have changed the names or positions of the sbox root and cgi-bin directories from their defaults. To support users' ability to change access rights using .htaccess, make sure to enable AuthConfig and Limit in sbox_root if you haven't done so already: AllowOverride +Options +AuthConfig +Limit _________________________________________________________________ Using the Miniroot (Linux only) For the convenience of Linux system administrators wishing to use the chroot features of sbox, I have placed a miniature root directory at stein.cshl.org/software/sbox/miniroot.img.gz. This is a gzipped ext2 filesystem image that contains essential system device files, shared libraries, and executables, including Perl version 5.8.7 and the most commonly used Perl libraries. The filesystem image is based on the one distributed with RIP. You can use this image in several ways: Install a copy of the image into each user's directory: This way gives each user a skeleton root directory that he is free to modify, providing him with considerable flexibility. The downside is that you may not wish users to have so much flexibility; it also takes up about 45 megabytes of space per user directory: 1. Download the miniroot from stein.cshl.org/software/sbox/miniroot.img.gz. 2. Unzip it: gunzip miniroot.img.gz 3. Mount the resulting disk image in loopback mode (you must be root to do this): mkdir /mnt/miniroot mount ./miniroot.img /mnt/miniroot -o ro,loop 4. Copy the contents of the miniroot into each user's sbox root directory (assuming in this example that it is ~fred/sbox_root): cd /mnt/miniroot find . | cpio -p ~fred/sbox_root 5. Create the user's html, cgi-bin and log directories: mkdir ~fred/sbox_root/{html,cgi-bin,log} 6. Fix permissions of these directories: chown fred.users ~fred/sbox_root/{html,cgi-bin,log} Mounting a copy of the miniroot in each user's directory The alternative method avoids the waste of putting a complete copy of the root into each user's directory. One copy of the miniroot is mounted read-only into each user's sbox root, giving them read-only access to the mount. The main disadvantage of this strategy is that it generates a mount for each user, which in the case of very many user accounts might bump up against kernel limitations. 1. Download the miniroot from stein.cshl.org/software/sbox/miniroot.img.gz. 2. Unzip it: gunzip miniroot.img.gz 3. Create the user's html and cgi-bin directories, as well as a directory called "mnt": mkdir ~fred/sbox_root/html mkdir ~fred/sbox_root/cgi-bin mkdir ~fred/sbox_root/mnt 4. Mount the miniroot read-only on the user's mnt/ directory: mount ./miniroot.img ~fred/sbox_root/mnt -o ro,loop 5. Create symlinks to the directories of the mounted filesystem: cd ~fred/sbox_root ln -s mnt/* . 6. Fix permissions of html, cgi-bin and log. At the end of this process, you should have a directory structure that looks like this: lrwxrwxrwx 1 root root 7 Dec 4 18:18 bin -> mnt/bin drwxrwxr-x 2 fred users 96 Dec 4 18:15 cgi-bin/ lrwxrwxrwx 1 root root 7 Dec 4 18:18 dev -> mnt/dev lrwxrwxrwx 1 root root 7 Dec 4 18:18 etc -> mnt/etc drwxr-xr-x 5 fred users 1136 Dec 4 18:15 html/ lrwxrwxrwx 1 root root 7 Dec 4 18:18 lib -> mnt/lib lrwxrwxrwx 1 fred users 7 Dec 4 18:15 log/ drwxrwxr-x 2 root root 48 Dec 4 18:16 mnt/ lrwxrwxrwx 1 root root 7 Dec 4 18:18 tmp -> mnt/tmp lrwxrwxrwx 1 root root 7 Dec 4 18:18 usr -> mnt/usr lrwxrwxrwx 1 root root 7 Dec 4 18:18 var -> mnt/var If you ever wish to modify the miniroot image, simply mount it read/write and make the changes you need. If you run out of space on the miniroot, you can create a new one with the following series of commands: mount ./miniroot.img /mnt/miniroot -o ro,loop dd if=/dev/zero of=./new_miniroot.img bs=1M count=100 # or whatever you want mke2fs -F ./new_miniroot.img mount ./new_miniroot.img /mnt/new_miniroot -o rw,loop cd /mnt/miniroot find . | cpio -p /mnt/new_miniroot You are also free to burn the miniroot into a CDROM image, create a cramfs image, etc. _________________________________________________________________ Tips Here are a few pieces of advice and tips on making best use of sbox. Setting up the Chroot directory Many CGI scripts will not run correctly in a chroot environment unless they can find the resources they need. Compiled C programs often need access to shared libraries and/or device special files. Interpreted scripts need access to their interpreters, for example Perl. Feature-rich programs like sendmail depend on their configuration files being present in /etc. As described above, you will need to turn the chroot directory into a miniature root file system, complete with /etc, /lib, /bin, /tmp and /dev directories. If the web server is running on a Linux system, then one option is to use the miniroot image provided with sbox as the basis for the root file system. If you prefer to do it yourself, I recommend that you create and test a chroot directory for one virtual host, then use it as a master copy for creating new virtual hosts every time you add a new user account. Both the cpio and the tar commands can be used to copy shared libraries and device special files safely. Programs that check file ownerships may need access to password and/or group files in order for them to translate from numeric uid's and gid's to text names. In order to support CGI scripts that perform this type of action, you should place dummy copies of /etc/passwd and /etc/group in the author's /etc directory. These files should not contain real passwords, and should only contain standard system user accounts (e.g. "bin" and "mail"), plus any needed by the script. You probably don't want to make the complete list of user account names available to authors' CGI scripts! If CGI scripts require access to the DNS system in order to resolve host names and IP addresses, you should place a copy of /etc/resolv.conf into the chroot directory. You may need to copy other configuration files to use certain feature-rich programs. For example, if scripts send e-mail using the sendmail program, you will need to install its configuration program, sendmail.cf. Many programs redirect their output to the device special file /dev/null. Other programs need access to /dev/zero or other special files. You can copy these files from the real /dev directory using either cpio or tar. Alternately you can create the files from scratch using mknod, but only if you know what you're doing. You'll need to have superuser privileges to accomplish either of these tasks. The Unix time system expects to find information about the local timezone in a compiled file named /etc/localtime. You may need to copy this into your chroot directory in order for the timezone to be correctly displayed. You can confirm that the correct timezone is being found by examining the output of the "env" executable. There are two ways to finesse the problem of shared libraries. For compiled C scripts, one option is to link the program statically (by providing the -static flag to the linker). A less laborious solution is to place copies of the required shared libraries in the new root's /lib directory (or /slib, for systems that use that directory for shared libraries). Many systems have a utility that lists the shared libraries required by a binary. Use this program to determine which shared libraries are required, and copy them over into each author's /lib directory. In addition to the shared libraries, you may need to copy the dynamic linker itself into the /lib directory. On my linux system, this file is "ld-linux.so". If a executable cannot find its shared libraries at run time, it will usually fail with a specific error message that will lead you to the problem -- look in the server error log. If you get silent failures, it's probably the dynamic linker itself that can't be found. Linux, and possibly some other systems, uses a cache file named /etc/ld.so.cache to resolve the location of library files. If this file isn't found at run time, the system will generate a warning but find the correct shared libraries nevertheless. The quick and dirty way to get rid of this warning is to copy the current cache file from the real /etc directory to the chroot one. However, this may have bad side effects (I haven't actually encountered any, but I worry about it.) It's better to make this cache file from scratch in the chroot environment itself. To do this, run the ldconfig program with the command-line version of chroot. You'll need to be root to do this: # cd /sbin # chroot ~fred/pub ./ldconfig Perl scripts, in addition to requiring the Perl interpreter, will often need access to the Perl lib directory in order to get at useful modules (such as CGI.pm). It's easiest to copy the whole Perl library tree to the correct location in the chroot directory, being careful to get the path right. For example, if the real Perl library is located in /usr/local/lib/perl5, you'll need to create a parallel /usr hierarchy in the chroot directory. On my system, I recompiled Perl to use /lib/perl5 and dumped the modules into that directory. If things get bolluxed up, you can always tell Perl where to look for its libraries by appending something like this to the top of CGI scripts: #!/bin/perl BEGIN { push(@INC,'/lib/perl5','/lib/perl5/i586-linux/5.004'); } The Document Root and the chroot() directory Some CGI scripts act as filters on static HTML documents. Examples include PHP and various guestbook scripts. Such scripts often include the path to the static document appended to the end of the script's URL as "additional path information." For example: http://your.site/~fred/guestbook.cgi/~fred/guestbook/data.txt The script will be passed two environment variables, PATH_INFO, containing the additional path information, and PATH_TRANSLATED, containing the path information translated into an absolute filename. In the example above, the values of these variables might be: PATH_INFO /~fred/guestbook/data.txt PATH_TRANSLATED /home/fred/public_html/guestbook/data.txt When sbox is running it interprets the additional path information as relative to the user's document root. This means that a document located in Fred's public_html directory can be referred to this way: http://your.site/cgi-bin/sbox/~fred/guestbook.cgi/guestbook/data.tx t After performing the chroot(), sbox attempts to adjust PATH_TRANSLATED so that it continues to point to a valid file. If the user's document root is located within the chroot directory, then PATH_TRANSLATED is trimmed so that it is relative to the new root directory: PATH_INFO /guestbook/data.txt PATH_TRANSLATED /public_html/guestbook/data.txt However, if the document root is entirely outside the new root directory, then sbox will simply use the same value for PATH_INFO and PATH_TRANSLATED: PATH_INFO /guestbook/data.txt PATH_TRANSLATED /guestbook/data.txt Users and Webmasters should be aware of this behavior, as it can cause some confusion. The Resource Limitations The default resource limits are reasonable. Most authors won't have problems with them unless they need to do number crunching or manipulate many files simultaneously. If need be, authors can raise the soft resource limits up to the levels imposed by the hard limit ceilings, which are very liberal. C programmers can do this directly by making calls to setrlimit(). Perl scripters should download and install Jarkko Hietaniemi's BSD::Resource module from CPAN. Server-Side Includes Because of design conflicts, the "#exec" style server-side include do not work correctly with sbox. However, the "#include virtual" command, which does almost exactly the same thing, does work correctly. To include the output of sbox-wrapped CGI scripts in server-side-include files, just write something like this: <!--#include virtual="/cgi-bin/sbox/~fred/guestbook"--> Rewrite-Rule Tricks If you are running Apache 1.2 or higher, you can take advantage of the rewrite rule module to make sbox transparent. For virtual hosts, you can add something like the following to main or the section: RewriteEngine on RewriteRule ^/cgi/(.*) /cgi-bin/sbox/$1 [PT,NS] This replaces all URLs that start with "/cgi" with "/cgi-bin/sbox". This lets authors refer to their scripts with: http://www.virtual.host.com/cgi/script_name and to main Web server scripts with: http://www.virtual.host.com/cgi-bin/guestbook For user-supported directories, this rewrite rule will allow users to refer to their scripts using http://www.host.com/~username/cgi/script_name: RewriteEngine on RewriteRule ^/~([^/]+)/cgi/(.+) /cgi-bin/sbox/~$1/$2 [PT,NS] If you are already using rewrite rules to allow users to control access with a .htaccess file, place the appropriate RewriteRule before the first RewriteCond and omit the [PT,NS] flags. The following two examples show RewriteRule blocks that will correctly respect .htaccess files: For Virtual Hosts RewriteRule ^/cgi/(.+) /cgi-bin/sbox/$1 RewriteCond %{REQUEST_FILENAME} ^/cgi-bin/sbox/(.+) RewriteCond %{DOCUMENT_ROOT}/../cgi-bin/%1 !-F RewriteRule ^/cgi-bin/sbox/(.+) %{DOCUMENT_ROOT}/../cgi-bin/$1 [L] RewriteRule ^(/cgi-bin/sbox/.+) $1 [PT,NS] For User Directories RewriteRule ^/~([^/]+)/cgi/(.+) /cgi-bin/sbox/~$1/$2 RewriteCond %{REQUEST_FILENAME} ^/cgi-bin/sbox/~([^/]+)/(.+) RewriteCond /home/%1/sbox_root/cgi-bin/%2 !-F RewriteRule ^/cgi-bin/sbox/~([^/]+)/(.+) /home/$1/sbox_root/cgi-bin/$2 [L] RewriteRule ^(/cgi-bin/sbox/~.+/.+) $1 [PT,NS] The env Script This distribution comes with a small statically linked binary called "env" that you can call as a CGI script. It prints out some information about the current environment, including the user and group ID's, the current working directory, and the environment variables, to help you determine whether sbox is configured correctly and working as expected. _________________________________________________________________ Author Information This utility is ©1997-2005 Lincoln D. Stein. It can be used freely and redistributed in source code and binary form. I request that this documentation, including the copyright statement, remain attached to the utility if you redistribute it. You are free to make modifications, but please attach a note stating the changes you made. _________________________________________________________________ Change History Version 1.10 Revamped documentation to show how to get .htaccess and 404 Not Found errors to work correctly. Added an example root directory for use in chroot mode. Versions 1.08-1.09 Never released. Version 1.07 Patch from Jukka Forsgren to cause script to chdir() into target directory in the same manner as Apache does. Version 1.06 Fixed cross-scripting security vulnerability identified by Ivan Schmid (ivan.schmid@astalavista.ch) Version 1.05 Lost version. Version 1.04 Changes to make sbox compile with egcs version 1.1.2 Fixed problem of CGI scripts not being able to access command line variables (courtesy Sean Gabriel Heacock) If logfile can't be opened, logs to standard error instead. Version 1.03 Added USE_ABSOLUTE_ROOT functionality, contributed by Grant Kaufmann. Version 1.02 Fixed a crash that occurred when configured userid or groupid is not in passwd/group file (patch provided by Terry Lorrah ). Version 1.01 Fixed minor bug in webmaster's error message. Fixed minor bug in reporting gid to log file Version 1.00 Replaced all occurrences of strcpy() and strcat() with strncpy() and strncat(). Changes to string constants to make more ANSI-compatible. Code cleanup Versons 0.98-0.99 Documentation fixes. Version 0.97 Fixed bugs relating to automounter confusion. Version 0.95 Fixes to compile and run on Solaris systems. Still not extensively tested, but no bug reports yet. Version 0.90 Beta release. Use with caution. _________________________________________________________________ Lincoln D. Stein, lstein@cshl.org Cold Spring Harbor Laboratory Last modified: Mon Dec 5 15:58:19 EST 2005 sbox-dtc-1.11.7/bsd/0000755000175000017500000000000012247552331012602 5ustar zigozigosbox-dtc-1.11.7/bsd/Makefile0000644000175000017500000000211412247552331014240 0ustar zigozigo# Ports collection makefile for: sbox-dtc # Date created: 12 January 2005 # Whom: Thomas Goirand (thomas [ at ] goirand.fr) # # $FreeBSD$ # PORTNAME= sbox-dtc PORTVERSION= 1.11.6 CATEGORIES= www MASTER_SITES= ftp://ftp.gplhost.sg/pub/sbox/bsd/ \ ftp://qala-sg.apt-proxy.gplhost.sg/pub/sbox/bsd/ \ ftp://601.apt-proxy.gplhost.com/pub/sbox/bsd/ \ ftp://seattle.apt-proxy.gplhost.com/pub/sbox/bsd/ \ ftp://ftp.gplhost.com/pub/sbox/bsd/ \ ftp://ftp.gplhost.co.uk/pub/sbox/bsd/ \ ftp://ftp.gplhost.fr/pub/sbox/bsd/ \ ftp://972.apt-proxy.gplhost.com/pub/sbox/bsd/ \ http://ftp.gplhost.fr/pub/sbox/bsd/ MAINTAINER= thomas@goirand.fr COMMENT= A CGI wrapper for Web site hosting services to safely grant CGI RUN_DEPENDS= ${LOCALBASE}/sbin/httpd:${PORTSDIR}/${APACHE_PORT} PLIST_FILES= www/cgi-bin/sbox USE_APACHE= yes CFLAGS+= -DWEB_GROUP='\"nobody\"' MAKE_ARGS= CC="${CC}" COPTS="${CFLAGS}" \ INSTALL_DIRECTORY=${PREFIX}/www/cgi-bin .if defined(WITH_APACHE2) IGNORE= Untested .endif .include sbox-dtc-1.11.7/bsd/pkg-descr0000644000175000017500000000152112247552331014403 0ustar zigozigosbox is a CGI wrapper script that allows Web site hosting services to safely grant CGI authoring privileges to untrusted clients. In addition to changing the process privileges of client scripts to match their owners, it goes beyond other wrappers by placing configurable ceilings on script resource usage, avoiding unintentional (as well as intentional) denial of service attacks. It also optionally allows the Webmaster to place client's CGI scripts in a chroot'ed shell restricted to the author's home directories. sbox is compatible with all Web servers running under BSD-derived flavors of Unix. You can use and redistribute it freely. original sources, modified by Damien Mascord (tusker [ at ] tusker.org) are available at: http://stein.cshl.org/WWW/software/sbox/ Official patch website: www: http://www.gplhost.com/software-sboxdtc.html sbox-dtc-1.11.7/copyright0000644000175000017500000000051012247552331013761 0ustar zigozigoThis Debian package was done by the creator of DTC: Thomas GOIRAND See http://gplhost.com for details and project homepage. See http://stein.cshl.org/WWW/software/sbox/ for SBOX autor home. On Debian systems, a copy of the GNU General Public License (GPL) may be found in /usr/share/common-licenses/LGPL. sbox-dtc-1.11.7/makeBSD0000755000175000017500000000326612247552331013235 0ustar zigozigo#!/bin/sh # # Welcome to the sbox-dtc install maker for BSD! # Maintainer: Thomas GOIRAND # please do not ship with you packages # this is only a small coder tool... # set -e set -x PKGNAME="sbox-dtc" # Nothing to be configured after this line VERS=`head -n 1 debian/changelog | cut -d'(' -f2 | cut -d')' -f1 | cut -d'-' -f1` REL=`head -n 1 debian/changelog | cut -d'(' -f2 | cut -d')' -f1 | cut -d'-' -f2` PKGNAME=`head -n 1 debian/changelog | cut -d' ' -f1` VERSION=${VERS}.${REL} DIRNAME=$PKGNAME"-"$VERSION echo " --- Making sbox-dtc BSD package --- " # Make the directories rm -rf build mkdir -p build cd build rm -fr $DIRNAME mkdir -p $DIRNAME # Copy DTC's files in the good directories cp -rf ../create_chroot.sh ../Makefile ../README.html ../README.txt ../README.using_sbox.txt ../changelog ../copyright ../env.c ../sbox.h ../sbox.c ../sbox.conf $DIRNAME # Make the archive tar -czf ../$DIRNAME".tar.gz" $DIRNAME # Make the port archive mkdir $PKGNAME cp -rf ../bsd/* $PKGNAME rm -rf $PKGNAME/CVS # Make the md5 sum file in this distinfo BSDSUM=`md5sum "../"$PKGNAME"-"$VERSION".tar.gz" | cut -f1 -d" "` SIZE=`ls -ALln "../"$PKGNAME"-"$VERSION".tar.gz" | awk '{print $5}'` if [ -e /sbin/sha256 ] ; then SHA=`sha256 -r "../"$PKGNAME"-"$VERSION".tar.gz"| cut -f1 -d" "` else SHA=`sha256sum "../"$PKGNAME"-"$VERSION".tar.gz" | cut -f1 -d" "` fi echo "MD5 ("$PKGNAME"-"$VERSION".tar.gz) = "${BSDSUM}" SHA256 ("$PKGNAME"-"$VERSION".tar.gz) = "${SHA}" SIZE ("$PKGNAME"-"$VERSION".tar.gz) = "$SIZE >>""$PKGNAME"/distinfo" tar -cvzf ../$PKGNAME"BSDport-"$VERSION".tar.gz" $PKGNAME cd .. echo " -- Succesfully made BSD port "$DIRNAME".tar.gz and $PKGNAME"BSDport-"$VERSION".tar.gz" ---" sbox-dtc-1.11.7/changelog0000644000175000017500000000050012247552331013677 0ustar zigozigo3-3-2005: Increased default sbox.h soft limit to 1024kB. 1-2-2005: Modified a bit the BSD port so we don't need patch files anymore (thanks to vs [ at ] freebsd.org): it's now a shorter and more clean port. 12/1/2005: Added FreeBSD port packaging and repository. 17-08-2004: Start of debian package for SBOX project. sbox-dtc-1.11.7/sbox.spec0000755000175000017500000000344412247552331013671 0ustar zigozigoSummary: A CGI wrapper script for chrooted environment for hosting Name: sbox Version: 1.11 Release: 0.20090803 License: LGPL Group: System Environment/Daemons URL: http://git.gplhost.com/dtc.git Source: %{name}-%{version}.tar.gz BuildRoot:%{_tmppath}/%{name}-%{version}-%{release}-root BuildRequires: make dotconf-devel gcc Requires: dotconf %description Sbox is a CGI wrapper script that allows Web site hosting services to safely grant CGI authoring privileges to untrusted clients. In addition to changing the process privileges of client scripts to match their owners, it goes beyond other wrappers by placing configurable ceilings on script resource usage, avoiding unintentional (as well as intentional) denial of service attacks. It also optionally allows the Webmaster to place client's CGI scripts in a chroot'ed shell restricted to the author's home directories. %prep %setup -n sbox %build make make env %install %{__rm} -rf %{buildroot} mkdir -p %{buildroot} make DESTDIR=%{buildroot} INSTALL_TARGET_DIR=%{_libdir}/cgi-bin install INSTALL_OPTS="-s" INSTALL_SYSCONF_DIR=%{_sysconfdir} %clean %{__rm} -rf %{buildroot} %files %defattr(0644, root, root, 0755) %attr(4111, root, bin) %{_libdir}/cgi-bin/sbox %config(noreplace) %{_sysconfdir}/sbox.conf %changelog * Mon Aug 03 2009 Thomas Goirand (zigo) 1.11-0.20090803 - Now packaging the sbox.conf, patched the Makefile to use INSTALL_SYSCONF_DIR - Not using a patch file anymore - Build depends on gcc - Now the git includes sbox.spec directly - Reworked the summary and description - Bumped version to match reality * Tue Jan 08 2008 Manuel Amador (Rudd-O) $version-2.gplhost - Fixed x86_64 installation * Fri Dec 21 2007 Manuel Amador (Rudd-O) 0.0.1-1.gplhost - First construction for CentOS 5 sbox-dtc-1.11.7/buildrpm0000755000175000017500000000034112247552331013574 0ustar zigozigo#!/bin/bash set -e cd ` dirname "$0" ` ver=`grep Version: sbox.spec | awk ' { print $2 } ' ` cd .. echo "Compressing the SBOX source code..." tar --exclude sbox/.git -czf sbox-$ver.tar.gz sbox rpmbuild -ta sbox-$ver.tar.gz sbox-dtc-1.11.7/deb0000755000175000017500000000177412247552331012523 0ustar zigozigo#!/bin/sh set -e set -x VERS=`head -n 1 debian/changelog | cut -d'(' -f2 | cut -d')' -f1 | cut -d'-' -f1` REL=`head -n 1 debian/changelog | cut -d'(' -f2 | cut -d')' -f1 | cut -d'-' -f2` PKGNAME=`head -n 1 debian/changelog | cut -d' ' -f1` if [ -e /etc/redhat-release ] ; then MKTEMP="mktemp -d -p /tmp" else MKTEMP="mktemp -d -t" fi TMPDIR=`${MKTEMP} ${PKGNAME}.XXXXXX` DIRNAME=${PKGNAME}-${VERS} MYCWD=`pwd` mkdir -p ${TMPDIR}/${DIRNAME} cp -auxf * ${TMPDIR}/${DIRNAME} mv ${TMPDIR}/${DIRNAME}/debian ${TMPDIR} rm -rf ${TMPDIR}/${DIRNAME}/.git cd ${TMPDIR} tar -czf ${PKGNAME}_${VERS}.orig.tar.gz ${DIRNAME} mv debian ${TMPDIR}/${DIRNAME} cd ${DIRNAME} if [ "${1}" = "--sign" ] ; then dpkg-buildpackage else dpkg-buildpackage -uc -us fi cd ${MYCWD} mv ${TMPDIR}/${PKGNAME}_${VERS}.orig.tar.gz .. mv ${TMPDIR}/${PKGNAME}_${VERS}-${REL}.dsc .. mv ${TMPDIR}/${PKGNAME}_${VERS}-${REL}.diff.gz .. mv ${TMPDIR}/${PKGNAME}*_${VERS}-${REL}*.deb .. mv ${TMPDIR}/${PKGNAME}*_${VERS}-${REL}*.changes .. rm -rf ${TMPDIR} sbox-dtc-1.11.7/create_chroot.sh0000644000175000017500000002250412247552331015212 0ustar zigozigo#!/bin/sh # assign our variables CHROOT_DIR=$conf_chroot_path WEB_USER=nobody if [ $CHROOT_DIR"" = "" ] ; then CHROOT_DIR=/var/www/chroot fi if [ $UNIX_TYPE"" = "freebsd" -o $UNIX_TYPE"" = "redhat" ] ; then WEB_GROUP=nobody else WEB_GROUP=nogroup fi if [ ""$VERBOSE_INSTALL = "yes" ] ;then echo "===> Creating chroot tree in "$CHROOT_DIR fi # set our umask so things are created with the correct group perms umask 022 # now onto the creation mkdir -p $CHROOT_DIR cd $CHROOT_DIR # create directory structure mkdir -p etc dev bin lib tmp var/tmp var/run sbin mkdir -p usr/bin usr/lib usr/libexec usr/share usr/lib/zoneinfo # make devices - adjust MAJOR/MINOR as appropriate ( see ls -l /dev/* ) if ! [ -e dev/null ] then if [ $UNIX_TYPE"" = "freebsd" -o $UNIX_TYPE"" = "osx" ]; then mknod dev/null c 2 2 # FreeBSD? else mknod dev/null c 1 3 # Linux fi fi if [ $UNIX_TYPE"" = "freebsd" -o $UNIX_TYPE"" = "osx" ] ; then if [ $kernel"" = "OpenBSD" ] ; then if ! [ -e dev/urandom ] ; then mknod dev/urandom c 45 2 # OpenBSD ? fi else if ! [ -e dev/random ] ; then mknod dev/random c 2 3 # FreeBSD fi if ! [ -e dev/urandom ] ; then mknod dev/urandom c 2 3 fi fi else if ! [ -e dev/random ] ; then mknod dev/random c 1 8 # Linux fi if ! [ -e dev/urandom ] ; then mknod dev/urandom c 1 9 # Linux fi fi # some external programs may need these: if [ $UNIX_TYPE"" = "freebsd" -o $UNIX_TYPE"" = "osx" ] ; then if ! [ -e dev/stdin ] ; then mknod dev/stdin c 22 0 # FreeBSD, OpenBSD fi if ! [ -e dev/stdout ] ; then mknod dev/stdout c 22 1 # FreeBSD, OpenBSD fi if ! [ -e dev/stderr ] ; then mknod dev/stderr c 22 2 # FreeBSD, OpenBSD fi fi # copy required binaries to $CHROOT_DIR/usr/bin and $CHROOT_DIR/bin if [ -e /bin/bzip2 ] ; then cp -pf /bin/bzip2 usr/bin/ fi if [ -e /usr/bin/bzip2 ] ; then cp -pf /usr/bin/bzip2 usr/bin/ fi if [ -e /usr/bin/file ] ; then cp -pf /usr/bin/file usr/bin/ fi if [ $UNIX_TYPE"" = "freebsd" -o $UNIX_TYPE"" = "osx" ] ; then cp -pf /usr/bin/cpio usr/bin cp -pf /usr/bin/rm /usr/bin/mv /usr/bin/gunzip /usr/bin/tar /usr/bin/false bin/ else cp -pf /bin/rm /bin/mv /bin/gunzip bin/ cp -pf /bin/cpio usr/bin fi # copy zip and unzip if they are present if [ -e /usr/bin/zip ] ; then cp -pf /usr/bin/zip bin/ fi if [ -e /usr/bin/unzip ] ; then cp -pf /usr/bin/unzip bin/ fi if [ -e /bin/bash ] ; then cp -pf /bin/bash bin fi if [ -e /usr/bin/bash ] ; then cp -pf /usr/bin/bash bin fi if [ -e /usr/bin/tar ]; then cp -pf /usr/bin/tar bin fi if [ -e /bin/tar ]; then cp -pf /bin/tar bin fi if [ -e /usr/bin/false ]; then cp -pf /usr/bin/false bin fi if [ -e /bin/false ]; then cp -pf /bin/false bin fi if [ -e /usr/bin/sftp ]; then cp -pf /usr/bin/sftp bin/ fi # the sftp-server binary can be in /usr/lib or /lib, so check both places if [ -e /usr/lib/sftp-server ]; then cp -pf /usr/lib/sftp-server usr/lib/ fi if [ -e /lib/sftp-server ]; then cp -pf /lib/sftp-server lib/ fi if [ -e /usr/bin/scp ]; then cp -pf /usr/bin/scp bin/ fi # copy more required binaries to $CHROOT_DIR/bin cp -pf /bin/sh /bin/echo /bin/ls /bin/pwd /bin/cat bin/ # copy ldconfig from sbin to $CHROOT_DIR/sbin if ! [ $UNIX_TYPE"" = "osx" ] ; then cp -pf /sbin/ldconfig sbin/ fi # copy needed /etc files to $CHROOT_DIR/etc cp -pf /etc/protocols /etc/services /etc/hosts \ /etc/resolv.conf etc/ # generate /etc/passwd and /etc/group # ignore errors set +e grep daemon /etc/passwd > etc/passwd grep bin /etc/passwd >> etc/passwd grep sys /etc/passwd >> etc/passwd grep man /etc/passwd >> etc/passwd grep lp /etc/passwd >> etc/passwd grep mail /etc/passwd >> etc/passwd grep news /etc/passwd >> etc/passwd grep uucp /etc/passwd >> etc/passwd grep www-data /etc/passwd >> etc/passwd # generate this one manually: grep nobody /etc/passwd >> etc/passwd grep daemon /etc/group > etc/group grep bin /etc/group >> etc/group grep sys /etc/group >> etc/group grep man /etc/group >> etc/group grep lp /etc/group >> etc/group grep mail /etc/group >> etc/group grep news /etc/group >> etc/group grep uucp /etc/group >> etc/group grep www-data /etc/group >> etc/group grep $WEB_GROUP /etc/group >> etc/group grep $WEB_USER /etc/group >> etc/group set -e # fix entry for nobody in /etc/passwd echo "$WEB_USER:x:65534:65534:$WEB_USER:/html:/bin/bash" >> etc/passwd # create shadow account line for nobody echo "$WEB_USER::12719:0:99999:7:::" > etc/shadow chown $WEB_USER:$WEB_GROUP etc/shadow if [ -e /etc/host.conf ] ; then cp -pf /etc/host.conf etc/ fi if [ -e /etc/ld.conf ] ; then cp -pf /etc/ld.conf etc/ fi if [ -e /etc/nsswitch.conf ] ; then cp -pf /etc/nsswitch.conf etc/ fi if [ -e /etc/localtime ] ; then cp -pf /etc/localtime etc/ fi # copy shared libraries to $CHROOT_DIR/lib # (check: ldd /usr/bin/perl (or other binary) to see which ones are needed) # #FreeBSD: #for j in \ if [ $UNIX_TYPE"" = "freebsd" ] ; then cp -pf /usr/lib/libc.so* /usr/lib/libm.so* \ /usr/lib/libstdc\+\+.so* usr/lib/ if [ -e /usr/compat/linux/usr/lib/libz.so.1 ] ; then cp /usr/compat/linux/usr/lib/libz.so.1 usr/lib fi else if [ $UNIX_TYPE"" = "osx" ] ; then cp -pf /usr/lib/dyld /usr/lib/libSystem.B.dylib \ /usr/lib/libc.dylib /usr/lib/libdl.dylib \ /usr/lib/libncurses.5.dylib /usr/lib/libpam.dylib \ /usr/lib/libpthread.dylib usr/lib/ cp -pf /usr/lib/dylib1.o /usr/lib/libSystem.dylib \ /usr/lib/libcrypto.dylib /usr/lib/libm.dylib \ /usr/lib/libncurses.dylib /usr/lib/libpam_misc.dylib \ /usr/lib/libz.dylib usr/lib mkdir usr/lib/system cp -pf /usr/lib/system/libmathCommon.A.dylib usr/lib/system else FOUNDED_ARCH=`uname -m` if [ ""$FOUNDED_ARCH = "x86_64" ] ; then if [ ! -e lib64 ]; then ln -s lib lib64 fi fi if [ -e /lib/ld-linux.so.2 ] ; then cp -pf /lib/ld-linux.so.2 lib/ fi if [ -e /lib/ld-linux-x86-64.so.2 ] ; then cp -pf /lib/ld-linux-x86-64.so.2 lib/ fi cp -pf /lib/libdl.so.2 /lib/libm.so.6 /lib/libpthread.so.0 \ /lib/libc.so.6 /lib/libcrypt.so.1 \ /lib/librt.so.1 \ /lib/libnss_compat.so.2 /lib/libnsl.so.1 /lib/libnss_files.so.2 \ /lib/libpam.so.0 /lib/libpam_misc.so.0 lib/ if [ -e /lib/libncurses.so.5 ]; then cp /lib/libncurses.so.5 lib/ fi if [ -e /usr/lib/libncurses.so.5 ]; then cp /usr/lib/libncurses.so.5 lib/ fi if [ -e /lib/libacl.so.1 ]; then cp /lib/libacl.so.1 lib/ fi if [ -e /lib/libattr.so.1 ]; then cp /lib/libattr.so.1 lib/ fi if [ -e /lib/libcap.so.1 ]; then cp /lib/libcap.so.1 lib/ fi if [ -e /lib/libbz2.so.1.0 ]; then cp /lib/libbz2.so.1.0 lib/ fi if [ -e /usr/lib/libbz2.so.1.0 ]; then cp /usr/lib/libbz2.so.1.0 lib/ fi if [ -e /usr/lib/libmagic.so.1 ] then cp -pf /usr/lib/libmagic.so.1 lib/ fi if [ $UNIX_TYPE"" = "gentoo" ] ; then cp -pf /lib/libz.so.1 lib/ else cp -pf /usr/lib/libz.so.1 lib/ fi # libs for sftp and scp if [ -e /lib/libresolv.so.2 ]; then cp -pf /lib/libresolv.so.2 lib/ fi if [ -e /usr/lib/libcrypto.so.0.9.7 ]; then cp -pf /usr/lib/libcrypto.so.0.9.7 lib/ fi if [ -e /usr/lib/libcrypto.so.0.9.8 ]; then cp -pf /usr/lib/libcrypto.so.0.9.8 lib/ fi if [ -e /lib/libutil.so.1 ]; then cp -pf /lib/libutil.so.1 lib/ fi fi fi # magic files needed by file(1). Different versions and installations # expect magic files in different locations. Check the documentation. # Some usual locations are: if [ -e /usr/share/misc/file ] then #cp -pf /usr/local/share/file/* usr/local/share/file/ mkdir -p usr/share/misc/file cp -pf /usr/share/misc/file/magic* usr/share/misc/file #cp -pf /usr/share/magic usr/share/ fi # No need anymore - fix up pam.d into jail # if [ -e /etc/pam.d ]; then # mkdir -p ./etc/pam.d/ # cp /etc/pam.d/* ./etc/pam.d/ # fi # No need anymore - copy PAM-Modules to jail #if [ -e /lib/security ]; then #cp -r /lib/security ./lib/ #fi #if [ -e /etc/security ]; then # cp -r /etc/security ./etc/ #fi if [ -e /etc/login.defs ]; then cp /etc/login.defs ./etc/ fi # now we have come this far, make sure our chroot includes enough libs for this environment LDD=`which ldd` if [ -n "$LDD" ]; then for i in bin/*; do for j in `$LDD $i | cut -f 1 -d' '`; do if [ -e $j ]; then cp -pf $j lib/ fi if [ -e /lib/$j ]; then cp -pf /lib/$j lib/ fi if [ -e /usr/lib/$j ]; then cp -pf /usr/lib/$j lib/ fi if [ -e /usr/local/lib/$j ]; then cp -pf /usr/local/lib/$j lib/ fi done done fi # if we have a sudo binary around, then use it to create our chroot shell SUDO=`which sudo` if [ -n "$SUDO" ] ; then # create a chroot shell script echo "Creating chroot shell script..." SHELL=/bin/dtc-chroot-shell echo '#!/bin/sh' > $SHELL echo "`which sudo` -H `which chroot` \$HOME /bin/su - \$USER" \"\$@\" >> $SHELL chmod 755 $SHELL # fix sudoers # fix /etc/shells fi # set protections chmod 1770 tmp chmod 1770 var/tmp chmod 666 dev/null chmod 644 dev/*random #now need to copy over the perl binary and some modules cp -pf /usr/bin/perl usr/bin/ if ! [ $UNIX_TYPE"" = "osx" ] ;then # now create our ld.so cache mkdir -p $CHROOT_DIR/etc touch $CHROOT_DIR/etc/ld.so.cache touch $CHROOT_DIR/etc/ld.so.conf chroot $CHROOT_DIR ./sbin/ldconfig # just in case we have wiped our /etc/ld.so.cache (run locally) /sbin/ldconfig fi