def mkpolydir(dir_name, poly_dir_name, level): dir_context = None (rc, context) = selinux.getcon() if rc < 0: raise Exception("Error getting context.") rc = selinux.matchpathcon_init(None) if rc < 0: raise Exception("Error calling matchpathcon_init.") (rc, dir_context) = selinux.matchpathcon(dir_name, 0) selinux.matchpathcon_fini() if rc < 0: raise Exception("Error in matchpathcon for %s." % (dir_name)) (rc, dir_context) = selinux.security_compute_create(context, dir_context, selinux.SECCLASS_FILE) if rc < 0: raise Exception( "Error in security_compute_create context: %s directory context: %s" % (context, dir_context)) context_array = dir_context.split(":") context_array[3] = level dir_context = ':'.join(context_array) rc = selinux.setfscreatecon(dir_context) if rc < 0: raise Exception("Error in setfscreatecon for %s %s." % (poly_dir_name, dir_context)) try: if not os.path.isdir(poly_dir_name): os.mkdir(poly_dir_name) except (IOError, OSError), (errno, strerror): raise Exception("Error creating directory %s with context %s: %s %s" % (poly_dir_name, dir_context, errno, strerror))
def mkpolydir(dir_name, poly_dir_name, level): dir_context = None (rc, context) = selinux.getcon() if rc < 0: raise Exception("Error getting context.") rc = selinux.matchpathcon_init(None) if rc < 0: raise Exception("Error calling matchpathcon_init.") (rc, dir_context) = selinux.matchpathcon(dir_name, 0) selinux.matchpathcon_fini() if rc < 0: raise Exception("Error in matchpathcon for %s." % (dir_name)) (rc, dir_context) = selinux.security_compute_create(context, dir_context, selinux.SECCLASS_FILE) if rc < 0: raise Exception("Error in security_compute_create context: %s directory context: %s" % (context, dir_context)) context_array = dir_context.split(":") context_array[3] = level dir_context = ':'.join(context_array) rc = selinux.setfscreatecon(dir_context) if rc < 0: raise Exception("Error in setfscreatecon for %s %s." % (poly_dir_name, dir_context)) try: if not os.path.isdir(poly_dir_name): os.mkdir(poly_dir_name) except (IOError, OSError), (errno, strerror): raise Exception("Error creating directory %s with context %s: %s %s" % (poly_dir_name, dir_context, errno, strerror))
def __init__(self, src_path, filename=None): self._src_path = src_path self._filename = filename or basename(src_path) self._con = getcon()[1].split(":") setfscreatecon(self.filecon(self.COMPILE_LEVEL)) self._tempdir = mkdtemp(prefix=self.TEMPDIR_PREFIX) setfscreatecon(None)
def selinux_role(self): """Setup proper selinux role. this must be called at beginning of process to adjust proper roles for selinux. it will re-execute the process with same arguments. This has similar effect of: # chcon -t rpm_exec_t executable.py We must do this dynamic as this class is to be used at bootstrap stage, so we cannot put any persistent selinux policy changes, and have no clue if filesystem where we put scripts supports extended attributes, or if we have proper role for chcon. """ try: import selinux except ImportError: with self.transaction(): self.install(['libselinux-python']) if self.buildTransaction(): self.processTransaction() # # on fedora-18 for example # the selinux core is updated # so we fail resolving symbols # solution is re-execute the process # after installation. # self._sink.reexec() os.execv(sys.executable, [sys.executable] + sys.argv) os._exit(1) if selinux.is_selinux_enabled(): rc, ctx = selinux.getcon() if rc != 0: raise Exception(_('Cannot get selinux context')) ctx1 = selinux.context_new(ctx) if not ctx1: raise Exception(_('Cannot create selinux context')) if selinux.context_type_get(ctx1) != 'rpm_t': if selinux.context_type_set(ctx1, 'rpm_t') != 0: raise Exception( _('Cannot set type within selinux context')) if selinux.context_role_set(ctx1, 'system_r') != 0: raise Exception( _('Cannot set role within selinux context')) if selinux.context_user_set(ctx1, 'unconfined_u') != 0: raise Exception( _('Cannot set user within selinux context')) if selinux.setexeccon(selinux.context_str(ctx1)) != 0: raise Exception(_('Cannot set selinux exec context')) self._sink.reexec() os.execv(sys.executable, [sys.executable] + sys.argv) os._exit(1)
def selinux_role(self): """Setup proper selinux role. this must be called at beginning of process to adjust proper roles for selinux. it will re-execute the process with same arguments. This has similar effect of: # chcon -t rpm_exec_t executable.py We must do this dynamic as this class is to be used at bootstrap stage, so we cannot put any persistent selinux policy changes, and have no clue if filesystem where we put scripts supports extended attributes, or if we have proper role for chcon. """ try: import selinux except ImportError: with self.transaction(): self.install(['libselinux-python']) if self.buildTransaction(): self.processTransaction() # # on fedora-18 for example # the selinux core is updated # so we fail resolving symbols # solution is re-execute the process # after installation. # self._sink.reexec() os.execv(sys.executable, [sys.executable] + sys.argv) os._exit(1) if selinux.is_selinux_enabled(): rc, ctx = selinux.getcon() if rc != 0: raise Exception(_('Cannot get selinux context')) ctx1 = selinux.context_new(ctx) if not ctx1: raise Exception(_('Cannot create selinux context')) if selinux.context_role_get(ctx1) != 'system_r': if selinux.context_role_set(ctx1, 'system_r') != 0: raise Exception( _('Cannot set role within selinux context') ) if selinux.setexeccon(selinux.context_str(ctx1)) != 0: raise Exception( _('Cannot set selinux exec context') ) self._sink.reexec() os.execv(sys.executable, [sys.executable] + sys.argv) os._exit(1)
def main(): global preserve_environment, cmd, args, debug try: opts, args = getopt.getopt(sys.argv[1:], "l:m:t:cdnuf:shb", [ "level=", "max-level-or-clearance=", "title=", "current-level", "debug", "no-environment", "use-execv", "file-level=", "selinux-user-range", "clearance", "dont-background" ]) except getopt.GetoptError: error_dialog( _("An error occurred while processing command line arguments.")) print "usage: ml-launch [--level=<level> --max-level-or-clearance=<level> --title=<window title> --current-level --debug --no-environment --use-execv --file-level=<file name> --selinux-user-range --clearance --dont-background] <command> <command arguments ...>" sys.exit(-1) if len(args) == 0: error_dialog( "usage: ml-launch [--level=<level>] [--max-level-or-clearance=<level>] [--title=<window title>] [--debug] [--no-environment] [--use-execv] [--current-level] [--file-level=<file name>] [--selinux-user-range] [--clearance] {--dont-background] <command> <command arguments ...>" ) sys.exit(-1) level = None title = None use_execv = False dont_background = False argptr = 0 for o, a in opts: if o in ("-l", "--level"): if level == None: level = a else: error_dialog( "ml-launch: use only one level setting command argument") sys.exit(-1) argptr = argptr + 1 elif o in ("-b", "--dont-background"): dont_background = True argptr = argptr + 1 elif o in ("-t", "--title"): title = a argptr = argptr + 1 elif o in ("-f", "--file-level"): if level == None: level = get_file_level(a) if level.startswith("Cancel"): error_dialog("ml-launch: error getting file level for %s" % level.split(" - ")[1]) sys.exit(-1) else: error_dialog( "ml-launch: use only one level setting command argument") sys.exit(-1) argptr = argptr + 1 elif o in ("-d", "--debug"): debug = True argptr = argptr + 1 elif o in ("-n", "--no-environment"): preserve_environment = False argptr = argptr + 1 elif o in ("-u", "--use-execv"): use_execv = True argptr = argptr + 1 elif o in ("-c", "--current-level"): if level != None: error_dialog( "ml-launch: use only one level setting command argument") sys.exit(-1) (rc, context) = selinux.getcon() context_array = context.split(":") range = context_array[3] range_array = range.split("-") level = range_array[0] argptr = argptr + 1 elif o in ("-s", "--selinux-user-range"): if level != None: error_dialog( "ml-launch: use only one level setting command argument") sys.exit(-1) user = pwd.getpwuid(os.getuid()).pw_name (rc, seuser, level) = selinux.getseuserbyname(user) (rc, tcon) = selinux_raw_to_trans_context("a:b:c:" + level) context_array = tcon.split(":") level = context_array[3] argptr = argptr + 1 elif o in ("-h", "--clearance"): if level != None: error_dialog( "ml-launch: use only one level setting command argument") sys.exit(-1) user_range = get_trans_range() range_array = user_range.split("-") level = range_array[1] argptr = argptr + 1 elif o in ("-m", "--max-level-or-clearance"): if level != None: error_dialog( "ml-launch: use only one level setting command argument") sys.exit(-1) level = a # if the users clearance doesn't dominate the specified level use the clearance if check_level_dominance(level): user_range = get_trans_range() range_array = user_range.split("-") level = range_array[1] argptr = argptr + 1 else: error_dialog( "usage: ml-launch [--level=<level>] [--max-level-or-clearance=<level>] [--title=<window title>] [--debug] [--no-environment] [--use-execv] [--current-level] [--file-level=<file name>] [--selinux-user-range] [--clearance] [--dont-background] <command> <command arguments ...>" ) sys.exit(-1) cmd = sys.argv[argptr + 1] args = sys.argv[argptr + 2:] if debug: print >> sys.stderr, ("cmd: %s\nargc: %s") % (cmd, args) signal.signal(signal.SIGCLD, signal.SIG_DFL) if level == None: p = subprocess.Popen(["/usr/share/mls-tools/label-dialog"], stderr=subprocess.PIPE, stdout=subprocess.PIPE, close_fds=True) level = p.communicate()[0].strip() if debug: logging.debug("label-dialog: %s" % (level)) if level == "Cancel": sys.exit(1) if check_level_dominance(level): error_dialog( "ml-launch: attempting to run a command at a level beyond your clearance." ) sys.exit(1) if dont_background: pid = 0 else: try: pid = os.fork() except e: print >> sys.stderr, _("Failed to fork new process: %d (%s)") % ( e.errno, e.strerror) sys.exit(1) if not pid: if debug: logging.basicConfig( level=logging.DEBUG, format='%(asctime)s %(levelname)s %(message)s %(filename)s', filename='/tmp/ml-launch.log', filemode='w') if use_execv: return newrole_execv(level, cmd, args, dont_background) else: return newrole(level, cmd, args, None)
import threading import time from setroubleshoot.config import get_config from setroubleshoot.errcode import * from setroubleshoot.util import * from setroubleshoot.audit_data import * try: getattr(audit, "AUDIT_EOE") except AttributeError: audit.AUDIT_EOE = 1320 # ------------------------------------------------------------------------------ my_context = AvcContext(selinux.getcon()[1]) def verify_avc(avc): if avc.scontext.type == None or avc.tcontext.type == None: return False if my_context.type == avc.scontext.type: syslog.syslog( syslog.LOG_ERR, "setroubleshoot generated AVC, exiting to avoid recursion, context=%s, AVC scontext=%s" % (my_context, avc.scontext), ) syslog.syslog(syslog.LOG_ERR, "audit event\n%s" % (avc.audit_event.format())) import sys
def getcontext(): (rc, ctx) = selinux.getcon() if rc < 0: raise OSError(_("getcontext: Failed getting current process context.")) return ctx
import logging import selinux SECCLASS_CONTEXT = selinux.string_to_security_class("context") CONTEXT__CONTAINS = selinux.string_to_av_perm(SECCLASS_CONTEXT, "contains") (rc, dom_context) = selinux.getcon() (rc, dom_raw_context) = selinux.selinux_trans_to_raw_context(dom_context) def check_level_dominance2(level1, level2, debug=False): context_array = dom_context.split(":") context_array[3] = level1 level1_con = ':'.join(context_array) context_array[3] = level2 level2_con = ':'.join(context_array) return check_dominance2(level1_con, level2_con, debug) def check_level_dominance(level, debug=False): context_array = dom_context.split(":") context_array[3] = level con = ':'.join(context_array) if debug: logging.debug("check_level_dominance: %s" % (con)) return check_dominance(con, debug) def check_dominance(con, debug=False): (rc, raw_con) = selinux.selinux_trans_to_raw_context(con) if rc != 0: raise Exception("selinux.selinux_trans_to_raw_context failed: %d" % rc) avd = selinux.av_decision()
def main(): global preserve_environment, cmd, args, debug try: opts, args = getopt.getopt(sys.argv[1:], "l:m:t:cdnuf:shb", ["level=", "max-level-or-clearance=", "title=","current-level", "debug", "no-environment", "use-execv", "file-level=", "selinux-user-range", "clearance", "dont-background"]) except getopt.GetoptError: error_dialog( _("An error occurred while processing command line arguments.")) print "usage: ml-launch [--level=<level> --max-level-or-clearance=<level> --title=<window title> --current-level --debug --no-environment --use-execv --file-level=<file name> --selinux-user-range --clearance --dont-background] <command> <command arguments ...>" sys.exit(-1) if len(args) == 0: error_dialog("usage: ml-launch [--level=<level>] [--max-level-or-clearance=<level>] [--title=<window title>] [--debug] [--no-environment] [--use-execv] [--current-level] [--file-level=<file name>] [--selinux-user-range] [--clearance] {--dont-background] <command> <command arguments ...>") sys.exit(-1) level = None title = None use_execv = False dont_background = False argptr = 0 for o, a in opts: if o in ("-l", "--level"): if level == None: level = a else: error_dialog("ml-launch: use only one level setting command argument") sys.exit(-1) argptr = argptr + 1 elif o in ("-b", "--dont-background"): dont_background = True argptr = argptr + 1 elif o in ("-t", "--title"): title = a argptr = argptr + 1 elif o in ("-f", "--file-level"): if level == None: level = get_file_level(a) if level.startswith("Cancel"): error_dialog("ml-launch: error getting file level for %s" % level.split(" - ")[1]) sys.exit(-1) else: error_dialog("ml-launch: use only one level setting command argument") sys.exit(-1) argptr = argptr + 1 elif o in ("-d", "--debug"): debug = True argptr = argptr + 1 elif o in ("-n", "--no-environment"): preserve_environment = False argptr = argptr + 1 elif o in ("-u", "--use-execv"): use_execv = True argptr = argptr + 1 elif o in ("-c", "--current-level"): if level != None: error_dialog("ml-launch: use only one level setting command argument") sys.exit(-1) (rc, context) = selinux.getcon() context_array = context.split(":") range = context_array[3] range_array = range.split("-") level = range_array[0] argptr = argptr + 1 elif o in ("-s", "--selinux-user-range"): if level != None: error_dialog("ml-launch: use only one level setting command argument") sys.exit(-1) user = pwd.getpwuid(os.getuid()).pw_name (rc, seuser, level) = selinux.getseuserbyname(user) (rc, tcon) = selinux_raw_to_trans_context("a:b:c:" + level) context_array = tcon.split(":") level = context_array[3] argptr = argptr + 1 elif o in ("-h", "--clearance"): if level != None: error_dialog("ml-launch: use only one level setting command argument") sys.exit(-1) user_range = get_trans_range() range_array = user_range.split("-") level = range_array[1] argptr = argptr + 1 elif o in ("-m", "--max-level-or-clearance"): if level != None: error_dialog("ml-launch: use only one level setting command argument") sys.exit(-1) level = a # if the users clearance doesn't dominate the specified level use the clearance if check_level_dominance(level): user_range = get_trans_range() range_array = user_range.split("-") level = range_array[1] argptr = argptr + 1 else: error_dialog("usage: ml-launch [--level=<level>] [--max-level-or-clearance=<level>] [--title=<window title>] [--debug] [--no-environment] [--use-execv] [--current-level] [--file-level=<file name>] [--selinux-user-range] [--clearance] [--dont-background] <command> <command arguments ...>") sys.exit(-1) cmd = sys.argv[argptr+1] args = sys.argv[argptr+2:] if debug: print >>sys.stderr, ("cmd: %s\nargc: %s") % (cmd, args) signal.signal(signal.SIGCLD, signal.SIG_DFL) if level == None: p = subprocess.Popen(["/usr/share/mls-tools/label-dialog"], stderr=subprocess.PIPE, stdout=subprocess.PIPE, close_fds=True) level = p.communicate()[0].strip() if debug: logging.debug("label-dialog: %s" % (level)) if level == "Cancel": sys.exit(1) if check_level_dominance(level): error_dialog("ml-launch: attempting to run a command at a level beyond your clearance.") sys.exit(1) if dont_background: pid = 0 else: try: pid = os.fork() except e: print >>sys.stderr, _("Failed to fork new process: %d (%s)") % (e.errno, e.strerror) sys.exit(1) if not pid: if debug: logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(levelname)s %(message)s %(filename)s', filename='/tmp/ml-launch.log', filemode='w') if use_execv: return newrole_execv(level, cmd, args, dont_background) else: return newrole(level, cmd, args, None)
import logging import selinux SECCLASS_CONTEXT = selinux.string_to_security_class("context") CONTEXT__CONTAINS = selinux.string_to_av_perm(SECCLASS_CONTEXT, "contains") (rc, dom_context) = selinux.getcon() (rc, dom_raw_context) = selinux.selinux_trans_to_raw_context(dom_context) def check_level_dominance2(level1, level2, debug=False): context_array = dom_context.split(":") context_array[3] = level1 level1_con = ':'.join(context_array) context_array[3] = level2 level2_con = ':'.join(context_array) return check_dominance2(level1_con, level2_con, debug) def check_level_dominance(level, debug=False): context_array = dom_context.split(":") context_array[3] = level con = ':'.join(context_array) if debug: logging.debug("check_level_dominance: %s" % (con)) return check_dominance(con, debug) def check_dominance(con, debug=False): (rc, raw_con) = selinux.selinux_trans_to_raw_context(con) if rc != 0:
import threading import time from setroubleshoot.config import get_config from setroubleshoot.errcode import * from setroubleshoot.util import * from setroubleshoot.audit_data import * try: getattr(audit, 'AUDIT_EOE') except AttributeError: audit.AUDIT_EOE = 1320 #------------------------------------------------------------------------------ my_context = AvcContext(selinux.getcon()[1]) def verify_avc(avc): if avc.scontext.type == None or avc.tcontext.type == None: return False if my_context.type == avc.scontext.type: syslog.syslog( syslog.LOG_ERR, "setroubleshoot generated AVC, exiting to avoid recursion, context=%s, AVC scontext=%s" % (my_context, avc.scontext)) syslog.syslog(syslog.LOG_ERR, "audit event\n%s" % (avc.audit_event.format())) import sys sys.exit(0)