pax_global_header00006660000000000000000000000064131410734240014511gustar00rootroot0000000000000052 comment=1bac758bf6cf884c112b80545d5fc5b668fc7d71 selinux-sandbox-2.7/000077500000000000000000000000001314107342400145045ustar00rootroot00000000000000selinux-sandbox-2.7/.gitignore000066400000000000000000000000121314107342400164650ustar00rootroot00000000000000seunshare selinux-sandbox-2.7/COPYING000066400000000000000000000431311314107342400155410ustar00rootroot00000000000000 GNU GENERAL PUBLIC LICENSE Version 2, June 1991 Copyright (C) 1989, 1991 Free Software Foundation, Inc. 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Library General Public License instead.) You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. 4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. 7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. 10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) year name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker. , 1 April 1989 Ty Coon, President of Vice This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Library General Public License instead of this License. selinux-sandbox-2.7/Makefile000066400000000000000000000021271314107342400161460ustar00rootroot00000000000000PYTHON ?= python # Installation directories. PREFIX ?= $(DESTDIR)/usr SYSCONFDIR ?= $(DESTDIR)/etc/sysconfig LIBDIR ?= $(PREFIX)/lib BINDIR ?= $(PREFIX)/bin SBINDIR ?= $(PREFIX)/sbin MANDIR ?= $(PREFIX)/share/man LOCALEDIR ?= /usr/share/locale SHAREDIR ?= $(PREFIX)/share/sandbox override CFLAGS += -DPACKAGE="\"policycoreutils\"" -Wall -Werror -Wextra -W override LDLIBS += -lselinux -lcap-ng SEUNSHARE_OBJS = seunshare.o all: sandbox seunshare sandboxX.sh start seunshare: $(SEUNSHARE_OBJS) install: all -mkdir -p $(BINDIR) install -m 755 sandbox $(BINDIR) -mkdir -p $(MANDIR)/man8 install -m 644 sandbox.8 $(MANDIR)/man8/ install -m 644 seunshare.8 $(MANDIR)/man8/ -mkdir -p $(MANDIR)/man5 install -m 644 sandbox.5 $(MANDIR)/man5/ -mkdir -p $(SBINDIR) install -m 4755 seunshare $(SBINDIR)/ -mkdir -p $(SHAREDIR) install -m 755 sandboxX.sh $(SHAREDIR) install -m 755 start $(SHAREDIR) -mkdir -p $(SYSCONFDIR) install -m 644 sandbox.conf $(SYSCONFDIR)/sandbox test: @$(PYTHON) test_sandbox.py -v clean: -rm -f seunshare *.o *~ indent: ../../scripts/Lindent $(wildcard *.[ch]) relabel: selinux-sandbox-2.7/VERSION000066400000000000000000000000041314107342400155460ustar00rootroot000000000000002.7 selinux-sandbox-2.7/sandbox000066400000000000000000000431201314107342400160650ustar00rootroot00000000000000#! /usr/bin/python -Es # Authors: Dan Walsh # Authors: Thomas Liu # Authors: Josh Cogliati # # Copyright (C) 2009,2010 Red Hat # see file 'COPYING' for use and warranty information # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License as # published by the Free Software Foundation; version 2 only # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # import os import stat import sys import socket import random import fcntl import shutil import re import subprocess import selinux import signal from tempfile import mkdtemp import pwd import sepolicy SEUNSHARE = "/usr/sbin/seunshare" SANDBOXSH = "/usr/share/sandbox/sandboxX.sh" PROGNAME = "policycoreutils" try: import gettext kwargs = {} if sys.version_info < (3,): kwargs['unicode'] = True gettext.install(PROGNAME, localedir="/usr/share/locale", codeset='utf-8', **kwargs) except: try: import builtins builtins.__dict__['_'] = str except ImportError: import __builtin__ __builtin__.__dict__['_'] = unicode DEFAULT_WINDOWSIZE = "1000x700" DEFAULT_TYPE = "sandbox_t" DEFAULT_X_TYPE = "sandbox_x_t" SAVE_FILES = {} random.seed(None) def sighandler(signum, frame): signal.signal(signum, signal.SIG_IGN) os.kill(0, signum) raise KeyboardInterrupt def setup_sighandlers(): signal.signal(signal.SIGHUP, sighandler) signal.signal(signal.SIGQUIT, sighandler) signal.signal(signal.SIGTERM, sighandler) def error_exit(msg): sys.stderr.write("%s: " % sys.argv[0]) sys.stderr.write("%s\n" % msg) sys.stderr.flush() sys.exit(1) def copyfile(file, srcdir, dest): import re if file.startswith(srcdir): dname = os.path.dirname(file) bname = os.path.basename(file) if dname == srcdir: dest = dest + "/" + bname else: newdir = re.sub(srcdir, dest, dname) if not os.path.exists(newdir): os.makedirs(newdir) dest = newdir + "/" + bname try: if os.path.isdir(file): shutil.copytree(file, dest) else: shutil.copy2(file, dest) except shutil.Error as elist: for e in elist.message: sys.stderr.write(e[2]) SAVE_FILES[file] = (dest, os.path.getmtime(dest)) def savefile(new, orig, X_ind): copy = False if(X_ind): import gi gi.require_version('Gtk', '3.0') from gi.repository import Gtk dlg = Gtk.MessageDialog(None, 0, Gtk.MessageType.INFO, Gtk.ButtonsType.YES_NO, _("Do you want to save changes to '%s' (Y/N): ") % orig) dlg.set_title(_("Sandbox Message")) dlg.set_position(Gtk.WindowPosition.MOUSE) dlg.show_all() rc = dlg.run() dlg.destroy() if rc == Gtk.ResponseType.YES: copy = True else: try: input = raw_input except NameError: pass ans = input(_("Do you want to save changes to '%s' (y/N): ") % orig) if(re.match(_("[yY]"), ans)): copy = True if(copy): shutil.copy2(new, orig) def reserve(level): sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) sock.bind("\0%s" % level) fcntl.fcntl(sock.fileno(), fcntl.F_SETFD, fcntl.FD_CLOEXEC) def get_range(): try: level = selinux.getcon_raw()[1].split(":")[4] lowc, highc = level.split(".") low = int(lowc[1:]) high = int(highc[1:]) + 1 if high - low == 0: raise IndexError return low, high except IndexError: raise ValueError(_("User account must be setup with an MCS Range")) def gen_mcs(): low, high = get_range() level = None ctr = 0 total = high - low total = (total * (total - 1)) / 2 while ctr < total: ctr += 1 i1 = random.randrange(low, high) i2 = random.randrange(low, high) if i1 == i2: continue if i1 > i2: tmp = i1 i1 = i2 i2 = tmp level = "s0:c%d,c%d" % (i1, i2) try: reserve(level) except socket.error: continue break if level: return level raise ValueError(_("Failed to find any unused category sets. Consider a larger MCS range for this user.")) def fullpath(cmd): for i in ["/", "./", "../"]: if cmd.startswith(i): return cmd for i in os.environ["PATH"].split(':'): f = "%s/%s" % (i, cmd) if os.access(f, os.X_OK): return f return cmd class Sandbox: SYSLOG = "/var/log/messages" def __init__(self): self.setype = DEFAULT_TYPE self.__options = None self.__cmds = None self.__init_files = [] self.__paths = [] self.__mount = False self.__level = None self.__homedir = None self.__tmpdir = None def __validate_mount(self): if self.__options.level: if not self.__options.homedir or not self.__options.tmpdir: self.usage(_("Homedir and tempdir required for level mounts")) if not os.path.exists(SEUNSHARE): raise ValueError(_(""" %s is required for the action you want to perform. """) % SEUNSHARE) def __mount_callback(self, option, opt, value, parser): self.__mount = True def __x_callback(self, option, opt, value, parser): self.__mount = True setattr(parser.values, option.dest, True) if not os.path.exists(SEUNSHARE): raise ValueError(_(""" %s is required for the action you want to perform. """) % SEUNSHARE) if not os.path.exists(SANDBOXSH): raise ValueError(_(""" %s is required for the action you want to perform. """) % SANDBOXSH) def __validdir(self, option, opt, value, parser): if not os.path.isdir(value): raise IOError("Directory " + value + " not found") setattr(parser.values, option.dest, value) self.__mount = True def __include(self, option, opt, value, parser): rp = os.path.realpath(os.path.expanduser(value)) if not os.path.exists(rp): raise IOError(value + " not found") if rp not in self.__init_files: self.__init_files.append(rp) def __includefile(self, option, opt, value, parser): fd = open(value, "r") for i in fd.readlines(): try: self.__include(option, opt, i[:-1], parser) except IOError as e: sys.stderr.write(str(e)) except TypeError as e: sys.stderr.write(str(e)) fd.close() def __copyfiles(self): files = self.__init_files + self.__paths homedir = pwd.getpwuid(os.getuid()).pw_dir for f in files: copyfile(f, homedir, self.__homedir) copyfile(f, "/tmp", self.__tmpdir) copyfile(f, "/var/tmp", self.__tmpdir) def __setup_sandboxrc(self, wm="/usr/bin/openbox"): execfile = self.__homedir + "/.sandboxrc" fd = open(execfile, "w+") if self.__options.session: fd.write("""#!/bin/sh #TITLE: /etc/gdm/Xsession /etc/gdm/Xsession """) else: command = self.__paths[0] + " " for p in self.__paths[1:]: command += "'%s' " % p fd.write("""#! /bin/sh #TITLE: %s # /usr/bin/test -r ~/.xmodmap && /usr/bin/xmodmap ~/.xmodmap %s & WM_PID=$! if which dbus-run-session >/dev/null 2>&1; then dbus-run-session -- %s else dbus-launch --exit-with-session %s fi kill -TERM $WM_PID 2> /dev/null """ % (command, wm, command, command)) fd.close() os.chmod(execfile, 0o700) def usage(self, message=""): error_exit("%s\n%s" % (self.__parser.usage, message)) def __parse_options(self): from optparse import OptionParser types = "" try: types = _(""" Policy defines the following types for use with the -t: \t%s """) % "\n\t".join(next(sepolicy.info(sepolicy.ATTRIBUTE, "sandbox_type"))['types']) except StopIteration: pass usage = _(""" sandbox [-h] [-l level ] [-[X|M] [-H homedir] [-T tempdir]] [-I includefile ] [-W windowmanager ] [ -w windowsize ] [[-i file ] ...] [ -t type ] command sandbox [-h] [-l level ] [-[X|M] [-H homedir] [-T tempdir]] [-I includefile ] [-W windowmanager ] [ -w windowsize ] [[-i file ] ...] [ -t type ] -S %s """) % types parser = OptionParser(usage=usage) parser.disable_interspersed_args() parser.add_option("-i", "--include", action="callback", callback=self.__include, type="string", help=_("include file in sandbox")) parser.add_option("-I", "--includefile", action="callback", callback=self.__includefile, type="string", help=_("read list of files to include in sandbox from INCLUDEFILE")) parser.add_option("-t", "--type", dest="setype", action="store", default=None, help=_("run sandbox with SELinux type")) parser.add_option("-M", "--mount", action="callback", callback=self.__mount_callback, help=_("mount new home and/or tmp directory")) parser.add_option("-d", "--dpi", dest="dpi", action="store", help=_("dots per inch for X display")) parser.add_option("-S", "--session", action="store_true", dest="session", default=False, help=_("run complete desktop session within sandbox")) parser.add_option("-s", "--shred", action="store_true", dest="shred", default=False, help=_("Shred content before tempory directories are removed")) parser.add_option("-X", dest="X_ind", action="callback", callback=self.__x_callback, default=False, help=_("run X application within a sandbox")) parser.add_option("-H", "--homedir", action="callback", callback=self.__validdir, type="string", dest="homedir", help=_("alternate home directory to use for mounting")) parser.add_option("-T", "--tmpdir", dest="tmpdir", type="string", action="callback", callback=self.__validdir, help=_("alternate /tmp directory to use for mounting")) parser.add_option("-w", "--windowsize", dest="windowsize", type="string", default=DEFAULT_WINDOWSIZE, help="size of the sandbox window") parser.add_option("-W", "--windowmanager", dest="wm", type="string", default="/usr/bin/openbox", help=_("alternate window manager")) parser.add_option("-l", "--level", dest="level", help=_("MCS/MLS level for the sandbox")) parser.add_option("-C", "--capabilities", action="store_true", dest="usecaps", default=False, help="Allow apps requiring capabilities to run within the sandbox.") self.__parser = parser self.__options, cmds = parser.parse_args() if self.__options.X_ind: self.setype = DEFAULT_X_TYPE else: try: next(sepolicy.info(sepolicy.TYPE, "sandbox_t")) except StopIteration: raise ValueError(_("Sandbox Policy is not currently installed.\nYou need to install the selinux-policy-sandbox package in order to run this command")) if self.__options.setype: self.setype = self.__options.setype if self.__mount: self.__validate_mount() if self.__options.session: if not self.__options.setype: self.setype = selinux.getcon()[1].split(":")[2] if not self.__options.homedir or not self.__options.tmpdir: self.usage(_("You must specify a Homedir and tempdir when setting up a session sandbox")) if len(cmds) > 0: self.usage(_("Commands are not allowed in a session sandbox")) self.__options.X_ind = True self.__homedir = self.__options.homedir self.__tmpdir = self.__options.tmpdir else: if self.__options.level: self.__homedir = self.__options.homedir self.__tmpdir = self.__options.tmpdir if len(cmds) == 0: self.usage(_("Command required")) cmds[0] = fullpath(cmds[0]) if not os.access(cmds[0], os.X_OK): self.usage(_("%s is not an executable") % cmds[0]) self.__cmds = cmds for f in cmds: rp = os.path.realpath(f) if os.path.exists(rp): self.__paths.append(rp) else: self.__paths.append(f) def __gen_context(self): if self.__options.level: level = self.__options.level else: level = gen_mcs() con = selinux.getcon()[1].split(":") self.__execcon = "%s:%s:%s:%s" % (con[0], con[1], self.setype, level) self.__filecon = "%s:object_r:sandbox_file_t:%s" % (con[0], level) def __setup_dir(self): selinux.setfscreatecon(self.__filecon) if self.__options.homedir: self.__homedir = self.__options.homedir else: self.__homedir = mkdtemp(dir="/tmp", prefix=".sandbox_home_") if self.__options.tmpdir: self.__tmpdir = self.__options.tmpdir else: self.__tmpdir = mkdtemp(dir="/tmp", prefix=".sandbox_tmp_") self.__copyfiles() selinux.chcon(self.__homedir, self.__filecon, recursive=True) selinux.chcon(self.__tmpdir, self.__filecon, recursive=True) selinux.setfscreatecon(None) def __execute(self): try: cmds = [SEUNSHARE, "-Z", self.__execcon] if self.__options.usecaps: cmds.append('-C') if self.__mount: cmds += ["-t", self.__tmpdir, "-h", self.__homedir] if self.__options.X_ind: if self.__options.dpi: dpi = self.__options.dpi else: import gi gi.require_version('Gtk', '3.0') from gi.repository import Gtk dpi = str(Gtk.Settings.get_default().props.gtk_xft_dpi / 1024) xmodmapfile = self.__homedir + "/.xmodmap" xd = open(xmodmapfile, "w") subprocess.Popen(["/usr/bin/xmodmap", "-pke"], stdout=xd).wait() xd.close() self.__setup_sandboxrc(self.__options.wm) cmds += ["--", SANDBOXSH, self.__options.windowsize, dpi] else: cmds += ["--"] + self.__paths return subprocess.Popen(cmds).wait() pid = os.fork() if pid == 0: rc = os.setsid() if rc: return rc selinux.setexeccon(self.__execcon) os.execv(self.__cmds[0], self.__cmds) rc = os.waitpid(pid, 0) return os.WEXITSTATUS(rc[1]) finally: for i in self.__paths: if i not in SAVE_FILES: continue (dest, mtime) = SAVE_FILES[i] if os.path.getmtime(dest) > mtime: savefile(dest, i, self.__options.X_ind) if self.__homedir and not self.__options.homedir: if self.__options.shred: self.shred(self.__homedir) shutil.rmtree(self.__homedir) if self.__tmpdir and not self.__options.tmpdir: if self.__options.shred: self.shred(self.__homedir) shutil.rmtree(self.__tmpdir) def shred(self, path): for root, dirs, files in os.walk(path): for f in files: dest = root + "/" + f subprocess.Popen(["/usr/bin/shred", dest]).wait() def main(self): try: self.__parse_options() self.__gen_context() if self.__mount: self.__setup_dir() return self.__execute() except KeyboardInterrupt: sys.exit(0) if __name__ == '__main__': setup_sighandlers() if selinux.is_selinux_enabled() != 1: error_exit("Requires an SELinux enabled system") try: sandbox = Sandbox() rc = sandbox.main() except OSError as error: error_exit(error) except ValueError as error: error_exit(error.args[0]) except KeyError as error: error_exit(_("Invalid value %s") % error.args[0]) except IOError as error: error_exit(error) except KeyboardInterrupt: rc = 0 sys.exit(rc) selinux-sandbox-2.7/sandbox.5000066400000000000000000000023451314107342400162340ustar00rootroot00000000000000.TH sandbox.conf "5" "June 2010" "sandbox.conf" "Linux System Administration" .SH NAME sandbox.conf \- user config file for the SELinux sandbox .SH DESCRIPTION .PP When running sandbox with the -C argument, it will be confined using control groups and a system administrator can specify how the sandbox is confined. .PP Everything after "#" is ignored, as are empty lines. All arguments should be separated by and equals sign ("="). .PP These keywords are allowed. .RS .TP .B NAME The name of the sandbox control group. Default is "sandbox". .TP .B CPUAFFINITY Which cpus to assign sandbox to. The default is ALL, but users can specify a comma-separated list with dashes ("-") to represent ranges. Ex: 0-2,5 .TP .B MEMUSAGE How much memory to allow sandbox to use. The default is 80%. Users can specify either a percentage or a value in the form of a number followed by one of the suffixes K, M, G to denote kilobytes, megabytes or gigabytes respectively. Ex: 50% or 100M .TP .B CPUUSAGE Percentage of cpu sandbox should be allowed to use. The default is 80%. Specify a value followed by a percent sign ("%"). Ex: 50% .SH "SEE ALSO" .TP sandbox(8) .PP .SH AUTHOR This manual page was written by .I Thomas Liu selinux-sandbox-2.7/sandbox.8000066400000000000000000000076211314107342400162410ustar00rootroot00000000000000.TH SANDBOX "8" "May 2010" "sandbox" "User Commands" .SH NAME sandbox \- Run cmd under an SELinux sandbox .SH SYNOPSIS .B sandbox [\-C] [\-s] [ \-d DPI ] [\-l level ] [[\-M | \-X] \-H homedir \-T tempdir ] [\-I includefile ] [ \-W windowmanager ] [ \-w windowsize ] [[\-i file ]...] [ \-t type ] cmd .br .B sandbox [\-C] [\-s] [ \-d DPI ] [\-l level ] [[\-M | \-X] \-H homedir \-T tempdir ] [\-I includefile ] [ \-W windowmanager ] [ \-w windowsize ] [[\-i file ]...] [ \-t type ] \-S .br .SH DESCRIPTION .PP Run the .I cmd application within a tightly confined SELinux domain. The default sandbox domain only allows applications the ability to read and write stdin, stdout and any other file descriptors handed to it. It is not allowed to open any other files. The \-M option will mount an alternate homedir and tmpdir to be used by the sandbox. If you have the .I policycoreutils-sandbox package installed, you can use the \-X option and the \-M option. .B sandbox \-X allows you to run X applications within a sandbox. These applications will start up their own X Server and create a temporary home directory and /tmp. The default SELinux policy does not allow any capabilities or network access. It also prevents all access to the users other processes and files. Files specified on the command that are in the home directory or /tmp will be copied into the sandbox directories. If directories are specified with \-H or \-T the directory will have its context modified with chcon(1) unless a level is specified with \-l. If the MLS/MCS security level is specified, the user is responsible to set the correct labels. .PP .TP \fB\-h\ \fB\-\-help\fR display usage message .TP \fB\-H\ \fB\-\-homedir\fR Use alternate homedir to mount over your home directory. Defaults to temporary. Requires \-X or \-M. .TP \fB\-i\fR \fB\-\-include\fR Copy this file into the appropriate temporary sandbox directory. Command can be repeated. .TP \fB\-I\fR \fB\-\-includefile\fR Copy all files listed in inputfile into the appropriate temporary sandbox directories. .TP \fB\-l\fR \fB\-\-level\fR Specify the MLS/MCS Security Level to run the sandbox with. Defaults to random. .TP \fB\-M\fR \fB\-\-mount\fR Create a Sandbox with temporary files for $HOME and /tmp. .TP \fB\-s\fR \fB\-\-shred\fR Shred temporary files created in $HOME and /tmp, before deleting. .TP \fB\-t\fR \fB\-\-type\fR Use alternate sandbox type, defaults to sandbox_t or sandbox_x_t for \-X. \fBExamples:\fR .br sandbox_t \- No X, No Network Access, No Open, read/write on passed in file descriptors. .br sandbox_min_t \- No Network Access .br sandbox_x_t \- Ports for X applications to run locally .br sandbox_web_t \- Ports required for web browsing .br sandbox_net_t \- Network ports (for server software) .br sandbox_net_client_t \- All network ports .TP \fB\-T\fR \fB\-\-tmpdir\fR Use alternate temporary directory to mount on /tmp. Defaults to tmpfs. Requires \-X or \-M. .TP \fB\-S\fR \fB\-\-session\fR Run a full desktop session, Requires level, and home and tmpdir. .TP \fB\-w\fR \fB\-\-windowsize\fR Specifies the windowsize when creating an X based Sandbox. The default windowsize is 1000x700. .TP \fB\-W\fR \fB\-\-windowmanager\fR Select alternative window manager to run within .B sandbox \-X. Default to /usr/bin/openbox. .TP \fB\-X\fR Create an X based Sandbox for gui apps, temporary files for $HOME and /tmp, secondary Xserver, defaults to sandbox_x_t .TP \fB\-d\fR \fB\-\-dpi\fR Set the DPI value for the sandbox X Server. Defaults to the current X Sever DPI. .TP \fB\-C\fR \fB\-\-capabilities\fR Use capabilities within the sandbox. By default applications executed within the sandbox will not be allowed to use capabilities (setuid apps), with the \-C flag, you can use programs requiring capabilities. .PP .SH "SEE ALSO" .TP runcon(1), seunshare(8), selinux(8) .PP .SH AUTHOR This manual page was written by .I Dan Walsh and .I Thomas Liu selinux-sandbox-2.7/sandbox.conf000066400000000000000000000001251314107342400170070ustar00rootroot00000000000000# Control group configuration NAME=sandbox CPUAFFINITY=ALL MEMUSAGE=80% CPUUSAGE=80% selinux-sandbox-2.7/sandbox.config000066400000000000000000000000631314107342400173300ustar00rootroot00000000000000# Space separate list of homedirs HOMEDIRS="/home" selinux-sandbox-2.7/sandbox.init000066400000000000000000000025321314107342400170310ustar00rootroot00000000000000#!/bin/bash ## BEGIN INIT INFO # Provides: sandbox # Default-Start: 3 4 5 # Default-Stop: 0 1 2 3 4 6 # Required-Start: # ## END INIT INFO # sandbox: Set up / mountpoint to be shared, /var/tmp, /tmp, /home/sandbox unshared # # chkconfig: 345 1 99 # # description: sandbox, xguest and other apps that want to use pam_namespace \ # require this script be run at boot. This service script does \ # not actually run any service but sets up: \ # / to be shared by any app that starts a separate namespace # If you do not use sandbox, xguest or pam_namespace you can turn \ # this service off.\ # # Source function library. . /etc/init.d/functions LOCKFILE=/var/lock/subsys/sandbox base=${0##*/} start() { echo -n "Starting sandbox" [ -f "$LOCKFILE" ] && return 0 touch $LOCKFILE mount --make-rshared / || return $? return 0 } stop() { echo -n "Stopping sandbox" [ -f "$LOCKFILE" ] || return 1 } status() { if [ -f "$LOCKFILE" ]; then echo "$base is running" else echo "$base is stopped" fi exit 0 } case "$1" in restart) start && success || failure ;; start) start && success || failure echo ;; stop) stop && success || failure echo ;; status) status ;; *) echo $"Usage: $0 {start|stop|status|restart}" exit 3 ;; esac selinux-sandbox-2.7/sandboxX.sh000066400000000000000000000017371314107342400166360ustar00rootroot00000000000000#!/bin/bash trap "" TERM context=`id -Z | secon -t -l -P` export TITLE="Sandbox $context -- `grep ^#TITLE: ~/.sandboxrc | /usr/bin/cut -b8-80`" [ -z $1 ] && export SCREENSIZE="1000x700" || export SCREENSIZE="$1" [ -z $2 ] && export DPI="96" || export DPI="$2" trap "exit 0" HUP mkdir -p ~/.config/openbox cat > ~/.config/openbox/rc.xml << EOF no all yes EOF (/usr/bin/Xephyr -resizeable -title "$TITLE" -terminate -screen $SCREENSIZE -dpi $DPI -nolisten tcp -displayfd 5 5>&1 2>/dev/null) | while read D; do export DISPLAY=:$D cat > ~/seremote << __EOF #!/bin/sh DISPLAY=$DISPLAY "\$@" __EOF chmod +x ~/seremote /usr/share/sandbox/start $HOME/.sandboxrc export EXITCODE=$? kill -TERM 0 break done exit 0 selinux-sandbox-2.7/seunshare.8000066400000000000000000000024221314107342400165720ustar00rootroot00000000000000.TH SEUNSHARE "8" "May 2010" "seunshare" "User Commands" .SH NAME seunshare \- Run cmd with alternate homedir, tmpdir and/or SELinux context .SH SYNOPSIS .B seunshare [ -v ] [ -C ] [ -k ] [ -t tmpdir ] [ -h homedir ] [ -Z context ] -- executable [args] .br .SH DESCRIPTION .PP Run the .I executable within the specified context, using the alternate home directory and /tmp directory. The seunshare command unshares from the default namespace, then mounts the specified homedir and tmpdir over the default homedir and /tmp. Finally it tells the kernel to execute the application under the specified SELinux context. .TP \fB\-h homedir\fR Alternate homedir to be used by the application. Homedir must be owned by the user. .TP \fB\-t\ tmpdir Use alternate tempory directory to mount on /tmp. tmpdir must be owned by the user. .TP \fB\-C --capabilities\fR Allow apps executed within the namespace to use capabilities. Default is no capabilities. .TP \fB\-k --kill\fR Kill all processes with matching MCS level. .TP \fB\-Z\ context Use alternate SELinux context while running the executable. .TP \fB\-v\fR Verbose output .SH "SEE ALSO" .TP runcon(1), sandbox(8), selinux(8) .PP .SH AUTHOR This manual page was written by .I Dan Walsh and .I Thomas Liu selinux-sandbox-2.7/seunshare.c000066400000000000000000000505051314107342400166520ustar00rootroot00000000000000/* * Authors: Dan Walsh * Authors: Thomas Liu */ #define _GNU_SOURCE #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include /* for getopt_long() form of getopt() */ #include #include #include #include #include #include /* for context-mangling functions */ #include #ifdef USE_NLS #include /* for setlocale() */ #include /* for gettext() */ #define _(msgid) gettext (msgid) #else #define _(msgid) (msgid) #endif #ifndef MS_REC #define MS_REC 1<<14 #endif #ifndef MS_SLAVE #define MS_SLAVE 1<<19 #endif #ifndef PACKAGE #define PACKAGE "policycoreutils" /* the name of this package lang translation */ #endif #define BUF_SIZE 1024 #define DEFAULT_PATH "/usr/bin:/bin" #define USAGE_STRING _("USAGE: seunshare [ -v ] [ -C ] [ -k ] [ -t tmpdir ] [ -h homedir ] [ -Z CONTEXT ] -- executable [args] ") static int verbose = 0; static int child = 0; static capng_select_t cap_set = CAPNG_SELECT_CAPS; /** * This function will drop all capabilities. */ static int drop_caps(void) { if (capng_have_capabilities(cap_set) == CAPNG_NONE) return 0; capng_clear(cap_set); if (capng_lock() == -1 || capng_apply(cap_set) == -1) { fprintf(stderr, _("Failed to drop all capabilities\n")); return -1; } return 0; } /** * This function will drop all privileges. */ static int drop_privs(uid_t uid) { if (drop_caps() == -1 || setresuid(uid, uid, uid) == -1) { fprintf(stderr, _("Failed to drop privileges\n")); return -1; } return 0; } /** * If the user sends a siginto to seunshare, kill the child's session */ void handler(int sig) { if (child > 0) kill(-child,sig); } /** * Take care of any signal setup. */ static int set_signal_handles(void) { sigset_t empty; /* Empty the signal mask in case someone is blocking a signal */ if (sigemptyset(&empty)) { fprintf(stderr, "Unable to obtain empty signal set\n"); return -1; } (void)sigprocmask(SIG_SETMASK, &empty, NULL); /* Terminate on SIGHUP */ if (signal(SIGHUP, SIG_DFL) == SIG_ERR) { perror("Unable to set SIGHUP handler"); return -1; } if (signal(SIGINT, handler) == SIG_ERR) { perror("Unable to set SIGINT handler"); return -1; } return 0; } #define status_to_retval(status,retval) do { \ if ((status) == -1) \ retval = -1; \ else if (WIFEXITED((status))) \ retval = WEXITSTATUS((status)); \ else if (WIFSIGNALED((status))) \ retval = 128 + WTERMSIG((status)); \ else \ retval = -1; \ } while(0) /** * Spawn external command using system() with dropped privileges. * TODO: avoid system() and use exec*() instead */ static int spawn_command(const char *cmd, uid_t uid){ int childpid; int status = -1; if (verbose > 1) printf("spawn_command: %s\n", cmd); childpid = fork(); if (childpid == -1) { perror(_("Unable to fork")); return status; } if (childpid == 0) { if (drop_privs(uid) != 0) exit(-1); status = system(cmd); status_to_retval(status, status); exit(status); } waitpid(childpid, &status, 0); status_to_retval(status, status); return status; } /** * Check file/directory ownership, struct stat * must be passed to the * functions. */ static int check_owner_uid(uid_t uid, const char *file, struct stat *st) { if (S_ISLNK(st->st_mode)) { fprintf(stderr, _("Error: %s must not be a symbolic link\n"), file); return -1; } if (st->st_uid != uid) { fprintf(stderr, _("Error: %s not owned by UID %d\n"), file, uid); return -1; } return 0; } static int check_owner_gid(gid_t gid, const char *file, struct stat *st) { if (S_ISLNK(st->st_mode)) { fprintf(stderr, _("Error: %s must not be a symbolic link\n"), file); return -1; } if (st->st_gid != gid) { fprintf(stderr, _("Error: %s not owned by GID %d\n"), file, gid); return -1; } return 0; } #define equal_stats(one,two) \ ((one)->st_dev == (two)->st_dev && (one)->st_ino == (two)->st_ino && \ (one)->st_uid == (two)->st_uid && (one)->st_gid == (two)->st_gid && \ (one)->st_mode == (two)->st_mode) /** * Sanity check specified directory. Store stat info for future comparison, or * compare with previously saved info to detect replaced directories. * Note: This function does not perform owner checks. */ static int verify_directory(const char *dir, struct stat *st_in, struct stat *st_out) { struct stat sb; if (st_out == NULL) st_out = &sb; if (lstat(dir, st_out) == -1) { fprintf(stderr, _("Failed to stat %s: %s\n"), dir, strerror(errno)); return -1; } if (! S_ISDIR(st_out->st_mode)) { fprintf(stderr, _("Error: %s is not a directory: %s\n"), dir, strerror(errno)); return -1; } if (st_in && !equal_stats(st_in, st_out)) { fprintf(stderr, _("Error: %s was replaced by a different directory\n"), dir); return -1; } return 0; } /** * This function checks to see if the shell is known in /etc/shells. * If so, it returns 0. On error or illegal shell, it returns -1. */ static int verify_shell(const char *shell_name) { int rc = -1; const char *buf; if (!(shell_name && shell_name[0])) return rc; while ((buf = getusershell()) != NULL) { /* ignore comments */ if (*buf == '#') continue; /* check the shell skipping newline char */ if (!strcmp(shell_name, buf)) { rc = 0; break; } } endusershell(); return rc; } /** * Mount directory and check that we mounted the right directory. */ static int seunshare_mount(const char *src, const char *dst, struct stat *src_st) { int flags = 0; int is_tmp = 0; if (verbose) printf(_("Mounting %s on %s\n"), src, dst); if (strcmp("/tmp", dst) == 0) { flags = flags | MS_NODEV | MS_NOSUID | MS_NOEXEC; is_tmp = 1; } /* mount directory */ if (mount(src, dst, NULL, MS_BIND | flags, NULL) < 0) { fprintf(stderr, _("Failed to mount %s on %s: %s\n"), src, dst, strerror(errno)); return -1; } /* verify whether we mounted what we expected to mount */ if (verify_directory(dst, src_st, NULL) < 0) return -1; /* bind mount /tmp on /var/tmp too */ if (is_tmp) { if (verbose) printf(_("Mounting /tmp on /var/tmp\n")); if (mount("/tmp", "/var/tmp", NULL, MS_BIND | flags, NULL) < 0) { fprintf(stderr, _("Failed to mount /tmp on /var/tmp: %s\n"), strerror(errno)); return -1; } } return 0; } /* If path is empy or ends with "/." or "/.. return -1 else return 0; */ static int bad_path(const char *path) { const char *ptr; ptr = path; while (*ptr) ptr++; if (ptr == path) return -1; // ptr null ptr--; if (ptr != path && *ptr == '.') { ptr--; if (*ptr == '/') return -1; // path ends in /. if (*ptr == '.') { if (ptr != path) { ptr--; if (*ptr == '/') return -1; // path ends in /.. } } } return 0; } static int rsynccmd(const char * src, const char *dst, char **cmdbuf) { char *buf = NULL; char *newbuf = NULL; glob_t fglob; fglob.gl_offs = 0; int flags = GLOB_PERIOD; unsigned int i = 0; int rc = -1; /* match glob for all files in src dir */ if (asprintf(&buf, "%s/*", src) == -1) { fprintf(stderr, "Out of memory\n"); return -1; } if (glob(buf, flags, NULL, &fglob) != 0) { free(buf); buf = NULL; return -1; } free(buf); buf = NULL; for ( i=0; i < fglob.gl_pathc; i++) { const char *path = fglob.gl_pathv[i]; if (bad_path(path)) continue; if (!buf) { if (asprintf(&newbuf, "\'%s\'", path) == -1) { fprintf(stderr, "Out of memory\n"); goto err; } } else { if (asprintf(&newbuf, "%s \'%s\'", buf, path) == -1) { fprintf(stderr, "Out of memory\n"); goto err; } } free(buf); buf = newbuf; newbuf = NULL; } if (buf) { if (asprintf(&newbuf, "/usr/bin/rsync -trlHDq %s '%s'", buf, dst) == -1) { fprintf(stderr, "Out of memory\n"); goto err; } *cmdbuf=newbuf; } else { *cmdbuf=NULL; } rc = 0; err: free(buf); buf = NULL; globfree(&fglob); return rc; } /** * Clean up runtime temporary directory. Returns 0 if no problem was detected, * >0 if some error was detected, but errors here are treated as non-fatal and * left to tmpwatch to finish incomplete cleanup. */ static int cleanup_tmpdir(const char *tmpdir, const char *src, struct passwd *pwd, int copy_content) { char *cmdbuf = NULL; int rc = 0; /* rsync files back */ if (copy_content) { if (asprintf(&cmdbuf, "/usr/bin/rsync --exclude=.X11-unix -utrlHDq --delete '%s/' '%s/'", tmpdir, src) == -1) { fprintf(stderr, _("Out of memory\n")); cmdbuf = NULL; rc++; } if (cmdbuf && spawn_command(cmdbuf, pwd->pw_uid) != 0) { fprintf(stderr, _("Failed to copy files from the runtime temporary directory\n")); rc++; } free(cmdbuf); cmdbuf = NULL; } /* remove files from the runtime temporary directory */ if (asprintf(&cmdbuf, "/bin/rm -r '%s/' 2>/dev/null", tmpdir) == -1) { fprintf(stderr, _("Out of memory\n")); cmdbuf = NULL; rc++; } /* this may fail if there's root-owned file left in the runtime tmpdir */ if (cmdbuf && spawn_command(cmdbuf, pwd->pw_uid) != 0) rc++; free(cmdbuf); cmdbuf = NULL; /* remove runtime temporary directory */ if ((uid_t)setfsuid(0) != 0) { /* setfsuid does not return errror, but this check makes code checkers happy */ rc++; } if (rmdir(tmpdir) == -1) fprintf(stderr, _("Failed to remove directory %s: %s\n"), tmpdir, strerror(errno)); if ((uid_t)setfsuid(pwd->pw_uid) != 0) { fprintf(stderr, _("unable to switch back to user after clearing tmp dir\n")); rc++; } return rc; } /** * seunshare will create a tmpdir in /tmp, with root ownership. The parent * process waits for it child to exit to attempt to remove the directory. If * it fails to remove the directory, we will need to rely on tmpreaper/tmpwatch * to clean it up. */ static char *create_tmpdir(const char *src, struct stat *src_st, struct stat *out_st, struct passwd *pwd, security_context_t execcon) { char *tmpdir = NULL; char *cmdbuf = NULL; int fd_t = -1, fd_s = -1; struct stat tmp_st; security_context_t con = NULL; /* get selinux context */ if (execcon) { if ((uid_t)setfsuid(pwd->pw_uid) != 0) goto err; if ((fd_s = open(src, O_RDONLY)) < 0) { fprintf(stderr, _("Failed to open directory %s: %s\n"), src, strerror(errno)); goto err; } if (fstat(fd_s, &tmp_st) == -1) { fprintf(stderr, _("Failed to stat directory %s: %s\n"), src, strerror(errno)); goto err; } if (!equal_stats(src_st, &tmp_st)) { fprintf(stderr, _("Error: %s was replaced by a different directory\n"), src); goto err; } if (fgetfilecon(fd_s, &con) == -1) { fprintf(stderr, _("Failed to get context of the directory %s: %s\n"), src, strerror(errno)); goto err; } /* ok to not reach this if there is an error */ if ((uid_t)setfsuid(0) != pwd->pw_uid) goto err; } if (asprintf(&tmpdir, "/tmp/.sandbox-%s-XXXXXX", pwd->pw_name) == -1) { fprintf(stderr, _("Out of memory\n")); tmpdir = NULL; goto err; } if (mkdtemp(tmpdir) == NULL) { fprintf(stderr, _("Failed to create temporary directory: %s\n"), strerror(errno)); goto err; } /* temporary directory must be owned by root:user */ if (verify_directory(tmpdir, NULL, out_st) < 0) { goto err; } if (check_owner_uid(0, tmpdir, out_st) < 0) goto err; if (check_owner_gid(getgid(), tmpdir, out_st) < 0) goto err; /* change permissions of the temporary directory */ if ((fd_t = open(tmpdir, O_RDONLY)) < 0) { fprintf(stderr, _("Failed to open directory %s: %s\n"), tmpdir, strerror(errno)); goto err; } if (fstat(fd_t, &tmp_st) == -1) { fprintf(stderr, _("Failed to stat directory %s: %s\n"), tmpdir, strerror(errno)); goto err; } if (!equal_stats(out_st, &tmp_st)) { fprintf(stderr, _("Error: %s was replaced by a different directory\n"), tmpdir); goto err; } if (fchmod(fd_t, 01770) == -1) { fprintf(stderr, _("Unable to change mode on %s: %s\n"), tmpdir, strerror(errno)); goto err; } /* re-stat again to pick change mode */ if (fstat(fd_t, out_st) == -1) { fprintf(stderr, _("Failed to stat directory %s: %s\n"), tmpdir, strerror(errno)); goto err; } /* copy selinux context */ if (execcon) { if (fsetfilecon(fd_t, con) == -1) { fprintf(stderr, _("Failed to set context of the directory %s: %s\n"), tmpdir, strerror(errno)); goto err; } } if ((uid_t)setfsuid(pwd->pw_uid) != 0) goto err; if (rsynccmd(src, tmpdir, &cmdbuf) < 0) { goto err; } /* ok to not reach this if there is an error */ if ((uid_t)setfsuid(0) != pwd->pw_uid) goto err; if (cmdbuf && spawn_command(cmdbuf, pwd->pw_uid) != 0) { fprintf(stderr, _("Failed to populate runtime temporary directory\n")); cleanup_tmpdir(tmpdir, src, pwd, 0); goto err; } goto good; err: free(tmpdir); tmpdir = NULL; good: free(cmdbuf); cmdbuf = NULL; freecon(con); con = NULL; if (fd_t >= 0) close(fd_t); if (fd_s >= 0) close(fd_s); return tmpdir; } #define PROC_BASE "/proc" static int killall (security_context_t execcon) { DIR *dir; security_context_t scon; struct dirent *de; pid_t *pid_table, pid, self; int i; int pids, max_pids; int running = 0; self = getpid(); if (!(dir = opendir(PROC_BASE))) { return -1; } max_pids = 256; pid_table = malloc(max_pids * sizeof (pid_t)); if (!pid_table) { (void)closedir(dir); return -1; } pids = 0; context_t con; con = context_new(execcon); const char *mcs = context_range_get(con); printf("mcs=%s\n", mcs); while ((de = readdir (dir)) != NULL) { if (!(pid = (pid_t)atoi(de->d_name)) || pid == self) continue; if (pids == max_pids) { pid_t *new_pid_table = realloc(pid_table, 2*pids*sizeof(pid_t)); if (!new_pid_table) { free(pid_table); (void)closedir(dir); return -1; } pid_table = new_pid_table; max_pids *= 2; } pid_table[pids++] = pid; } (void)closedir(dir); for (i = 0; i < pids; i++) { pid_t id = pid_table[i]; if (getpidcon(id, &scon) == 0) { context_t pidcon = context_new(scon); /* Attempt to kill remaining processes */ if (strcmp(context_range_get(pidcon), mcs) == 0) kill(id, SIGKILL); context_free(pidcon); freecon(scon); } running++; } context_free(con); free(pid_table); return running; } int main(int argc, char **argv) { int status = -1; security_context_t execcon = NULL; int clflag; /* holds codes for command line flags */ int kill_all = 0; char *homedir_s = NULL; /* homedir spec'd by user in argv[] */ char *tmpdir_s = NULL; /* tmpdir spec'd by user in argv[] */ char *tmpdir_r = NULL; /* tmpdir created by seunshare */ struct stat st_curhomedir; struct stat st_homedir; struct stat st_tmpdir_s; struct stat st_tmpdir_r; const struct option long_options[] = { {"homedir", 1, 0, 'h'}, {"tmpdir", 1, 0, 't'}, {"kill", 1, 0, 'k'}, {"verbose", 1, 0, 'v'}, {"context", 1, 0, 'Z'}, {"capabilities", 1, 0, 'C'}, {NULL, 0, 0, 0} }; uid_t uid = getuid(); /* if (!uid) { fprintf(stderr, _("Must not be root")); return -1; } */ #ifdef USE_NLS setlocale(LC_ALL, ""); bindtextdomain(PACKAGE, LOCALEDIR); textdomain(PACKAGE); #endif struct passwd *pwd=getpwuid(uid); if (!pwd) { perror(_("getpwduid failed")); return -1; } if (verify_shell(pwd->pw_shell) < 0) { fprintf(stderr, _("Error: User shell is not valid\n")); return -1; } while (1) { clflag = getopt_long(argc, argv, "Ccvh:t:Z:", long_options, NULL); if (clflag == -1) break; switch (clflag) { case 't': tmpdir_s = optarg; break; case 'k': kill_all = 1; break; case 'h': homedir_s = optarg; break; case 'v': verbose++; break; case 'C': cap_set = CAPNG_SELECT_CAPS; break; case 'Z': execcon = optarg; break; default: fprintf(stderr, "%s\n", USAGE_STRING); return -1; } } if (! homedir_s && ! tmpdir_s) { fprintf(stderr, _("Error: tmpdir and/or homedir required\n %s\n"), USAGE_STRING); return -1; } if (argc - optind < 1) { fprintf(stderr, _("Error: executable required\n %s\n"), USAGE_STRING); return -1; } if (execcon && is_selinux_enabled() != 1) { fprintf(stderr, _("Error: execution context specified, but SELinux is not enabled\n")); return -1; } if (set_signal_handles()) return -1; /* set fsuid to ruid */ /* Changing fsuid is usually required when user-specified directory is * on an NFS mount. It's also desired to avoid leaking info about * existence of the files not accessible to the user. */ if (((uid_t)setfsuid(uid) != 0) && (errno != 0)) { fprintf(stderr, _("Error: unable to setfsuid %m\n")); return -1; } /* verify homedir and tmpdir */ if (homedir_s && ( verify_directory(homedir_s, NULL, &st_homedir) < 0 || check_owner_uid(uid, homedir_s, &st_homedir))) return -1; if (tmpdir_s && ( verify_directory(tmpdir_s, NULL, &st_tmpdir_s) < 0 || check_owner_uid(uid, tmpdir_s, &st_tmpdir_s))) return -1; if ((uid_t)setfsuid(0) != uid) return -1; /* create runtime tmpdir */ if (tmpdir_s && (tmpdir_r = create_tmpdir(tmpdir_s, &st_tmpdir_s, &st_tmpdir_r, pwd, execcon)) == NULL) { fprintf(stderr, _("Failed to create runtime temporary directory\n")); return -1; } /* spawn child process */ child = fork(); if (child == -1) { perror(_("Unable to fork")); goto err; } if (child == 0) { char *display = NULL; char *LANG = NULL; char *RUNTIME_DIR = NULL; int rc = -1; char *resolved_path = NULL; if (unshare(CLONE_NEWNS) < 0) { perror(_("Failed to unshare")); goto childerr; } /* Remount / as SLAVE so that nothing mounted in the namespace shows up in the parent */ if (mount("none", "/", NULL, MS_SLAVE | MS_REC , NULL) < 0) { perror(_("Failed to make / a SLAVE mountpoint\n")); goto childerr; } /* assume fsuid==ruid after this point */ if ((uid_t)setfsuid(uid) != 0) goto childerr; resolved_path = realpath(pwd->pw_dir,NULL); if (! resolved_path) goto childerr; if (verify_directory(resolved_path, NULL, &st_curhomedir) < 0) goto childerr; if (check_owner_uid(uid, resolved_path, &st_curhomedir) < 0) goto childerr; /* mount homedir and tmpdir, in this order */ if (homedir_s && seunshare_mount(homedir_s, resolved_path, &st_homedir) != 0) goto childerr; if (tmpdir_s && seunshare_mount(tmpdir_r, "/tmp", &st_tmpdir_r) != 0) goto childerr; if (drop_privs(uid) != 0) goto childerr; /* construct a new environment */ if ((display = getenv("DISPLAY")) != NULL) { if ((display = strdup(display)) == NULL) { perror(_("Out of memory")); goto childerr; } } /* construct a new environment */ if ((LANG = getenv("LANG")) != NULL) { if ((LANG = strdup(LANG)) == NULL) { perror(_("Out of memory")); goto childerr; } } if ((RUNTIME_DIR = getenv("XDG_RUNTIME_DIR")) != NULL) { if ((RUNTIME_DIR = strdup(RUNTIME_DIR)) == NULL) { perror(_("Out of memory")); goto childerr; } } if ((rc = clearenv()) != 0) { perror(_("Failed to clear environment")); goto childerr; } if (display) rc |= setenv("DISPLAY", display, 1); if (LANG) rc |= setenv("LANG", LANG, 1); if (RUNTIME_DIR) rc |= setenv("XDG_RUNTIME_DIR", RUNTIME_DIR, 1); rc |= setenv("HOME", pwd->pw_dir, 1); rc |= setenv("SHELL", pwd->pw_shell, 1); rc |= setenv("USER", pwd->pw_name, 1); rc |= setenv("LOGNAME", pwd->pw_name, 1); rc |= setenv("PATH", DEFAULT_PATH, 1); if (rc != 0) { fprintf(stderr, _("Failed to construct environment\n")); goto childerr; } if (chdir(pwd->pw_dir)) { perror(_("Failed to change dir to homedir")); goto childerr; } setsid(); /* selinux context */ if (execcon) { /* try dyntransition, since no_new_privs can interfere * with setexeccon */ if (setcon(execcon) != 0) { /* failed; fall back to setexeccon */ if (setexeccon(execcon) != 0) { fprintf(stderr, _("Could not set exec context to %s. %s\n"), execcon, strerror(errno)); goto childerr; } } } execv(argv[optind], argv + optind); fprintf(stderr, _("Failed to execute command %s: %s\n"), argv[optind], strerror(errno)); childerr: free(resolved_path); free(display); free(LANG); free(RUNTIME_DIR); exit(-1); } drop_caps(); /* parent waits for child exit to do the cleanup */ waitpid(child, &status, 0); status_to_retval(status, status); /* Make sure all child processes exit */ kill(-child,SIGTERM); if (execcon && kill_all) killall(execcon); if (tmpdir_r) cleanup_tmpdir(tmpdir_r, tmpdir_s, pwd, 1); err: free(tmpdir_r); return status; } selinux-sandbox-2.7/start000066400000000000000000000003711314107342400155650ustar00rootroot00000000000000#! /usr/bin/python -Es try: from subprocess import getstatusoutput except ImportError: from commands import getstatusoutput import sys rc = [-1, ''] try: rc = getstatusoutput(sys.argv[1]) except: pass if rc[0] == 0: print(rc[1]) selinux-sandbox-2.7/test_sandbox.py000066400000000000000000000105041314107342400175530ustar00rootroot00000000000000import unittest import os import shutil import sys from tempfile import mkdtemp from subprocess import Popen, PIPE class SandboxTests(unittest.TestCase): def assertDenied(self, err): self.assertTrue(b'Permission denied' in err, '"Permission denied" not found in %r' % err) def assertNotFound(self, err): self.assertTrue(b'not found' in err, '"not found" not found in %r' % err) def assertFailure(self, status): self.assertTrue(status != 0, '"Succeeded when it should have failed') def assertSuccess(self, status, err): self.assertTrue(status == 0, '"Sandbox should have succeeded for this test %r' % err) def test_simple_success(self): "Verify that we can read file descriptors handed to sandbox" p1 = Popen(['cat', '/etc/passwd'], stdout=PIPE) p2 = Popen([sys.executable, 'sandbox', 'grep', 'root'], stdin=p1.stdout, stdout=PIPE) p1.stdout.close() out, err = p2.communicate() self.assertTrue(b'root' in out) def test_cant_kill(self): "Verify that we cannot send kill signal in the sandbox" pid = os.getpid() p = Popen([sys.executable, 'sandbox', 'kill', '-HUP', str(pid)], stdout=PIPE, stderr=PIPE) out, err = p.communicate() self.assertDenied(err) def test_cant_ping(self): "Verify that we can't ping within the sandbox" p = Popen([sys.executable, 'sandbox', 'ping', '-c 1 ', '127.0.0.1'], stdout=PIPE, stderr=PIPE) out, err = p.communicate() self.assertDenied(err) def test_cant_mkdir(self): "Verify that we can't mkdir within the sandbox" p = Popen([sys.executable, 'sandbox', 'mkdir', '~/test'], stdout=PIPE, stderr=PIPE) out, err = p.communicate() self.assertFailure(p.returncode) def test_cant_list_homedir(self): "Verify that we can't list homedir within the sandbox" p = Popen([sys.executable, 'sandbox', 'ls', '~'], stdout=PIPE, stderr=PIPE) out, err = p.communicate() self.assertFailure(p.returncode) def test_cant_send_mail(self): "Verify that we can't send mail within the sandbox" p = Popen([sys.executable, 'sandbox', 'mail'], stdout=PIPE, stderr=PIPE) out, err = p.communicate() self.assertDenied(err) def test_cant_sudo(self): "Verify that we can't run sudo within the sandbox" p = Popen([sys.executable, 'sandbox', 'sudo'], stdout=PIPE, stderr=PIPE) out, err = p.communicate() self.assertFailure(p.returncode) def test_mount(self): "Verify that we mount a file system" p = Popen([sys.executable, 'sandbox', '-M', 'id'], stdout=PIPE, stderr=PIPE) out, err = p.communicate() self.assertSuccess(p.returncode, err) def test_set_level(self): "Verify that we set level a file system" p = Popen([sys.executable, 'sandbox', '-l', 's0', 'id'], stdout=PIPE, stderr=PIPE) out, err = p.communicate() self.assertSuccess(p.returncode, err) def test_homedir(self): "Verify that we set homedir a file system" homedir = mkdtemp(dir=".", prefix=".sandbox_test") p = Popen([sys.executable, 'sandbox', '-H', homedir, '-M', 'id'], stdout=PIPE, stderr=PIPE) out, err = p.communicate() shutil.rmtree(homedir) self.assertSuccess(p.returncode, err) def test_tmpdir(self): "Verify that we set tmpdir a file system" tmpdir = mkdtemp(dir="/tmp", prefix=".sandbox_test") p = Popen([sys.executable, 'sandbox', '-T', tmpdir, '-M', 'id'], stdout=PIPE, stderr=PIPE) out, err = p.communicate() shutil.rmtree(tmpdir) self.assertSuccess(p.returncode, err) def test_include_file(self): "Verify that sandbox can copy a file in the sandbox home and use it" p = Popen([sys.executable, 'sandbox', '-i' ,'test_sandbox.py' , '-M', '/bin/cat', 'test_sandbox.py'], stdout=PIPE, stderr=PIPE) out, err = p.communicate() self.assertSuccess(p.returncode, err) if __name__ == "__main__": import selinux if selinux.is_selinux_enabled() and selinux.security_getenforce() == 1: unittest.main() else: print("SELinux must be in enforcing mode for this test")