Example #1
0
def get_file_equiv(fc_path=selinux.selinux_file_context_path()):
    global file_equiv
    if file_equiv:
        return file_equiv
    file_equiv = get_file_equiv_modified(fc_path)
    file_equiv = read_file_equiv(file_equiv, fc_path + ".subs_dist", modify=False)
    return file_equiv
    def __init__(self,
                 domainname,
                 path="/tmp",
                 root="/",
                 source_files=False,
                 html=False):
        self.html = html
        self.source_files = source_files
        self.root = root
        self.portrecs = sepolicy.gen_port_dict()[0]
        self.domains = gen_domains()
        self.all_domains = sepolicy.get_all_domains()
        self.all_attributes = sepolicy.get_all_attributes()
        self.all_bools = sepolicy.get_all_bools()
        self.all_port_types = sepolicy.get_all_port_types()
        self.all_roles = sepolicy.get_all_roles()
        self.all_users = get_all_users_info()[0]
        self.all_users_range = get_all_users_info()[1]
        self.all_file_types = sepolicy.get_all_file_types()
        self.role_allows = sepolicy.get_all_role_allows()
        self.types = _gen_types()

        if self.source_files:
            self.fcpath = self.root + "file_contexts"
        else:
            self.fcpath = self.root + selinux.selinux_file_context_path()

        self.fcdict = sepolicy.get_fcdict(self.fcpath)

        if not os.path.exists(path):
            os.makedirs(path)

        self.path = path

        if self.source_files:
            self.xmlpath = self.root + "policy.xml"
        else:
            self.xmlpath = self.root + "/usr/share/selinux/devel/policy.xml"
        self.booleans_dict = sepolicy.gen_bool_dict(self.xmlpath)

        self.domainname, self.short_name = sepolicy.gen_short_name(domainname)

        self.type = self.domainname + "_t"
        self._gen_bools()
        self.man_page_path = "%s/%s_selinux.8" % (path, self.domainname)
        self.fd = open(self.man_page_path, 'w')
        if self.domainname + "_r" in self.all_roles:
            self.__gen_user_man_page()
            if self.html:
                manpage_roles.append(self.man_page_path)
        else:
            if self.html:
                manpage_domains.append(self.man_page_path)
            self.__gen_man_page()
        self.fd.close()

        for k in equiv_dict.keys():
            if k == self.domainname:
                for alias in equiv_dict[k]:
                    self.__gen_man_page_link(alias)
Example #3
0
def get_file_equiv_modified(fc_path=selinux.selinux_file_context_path()):
    global file_equiv_modified
    if file_equiv_modified:
        return file_equiv_modified
    file_equiv_modified = {}
    file_equiv_modified = read_file_equiv(file_equiv_modified, fc_path + ".subs", modify=True)
    return file_equiv_modified
Example #4
0
    def relabel(self, ksselinux):
        # touch some files which get unhappy if they're not labeled correctly
        for fn in ("/etc/resolv.conf", ):
            path = self.path(fn)
            if not os.path.islink(path):
                f = open(path, "a")
                os.chmod(path, 0o644)
                f.close()

        if ksselinux.selinux == ksconstants.SELINUX_DISABLED:
            return

        try:
            rc = subprocess.call([
                'setfiles', '-p', '-e', '/proc', '-e', '/sys', '-e', '/dev',
                selinux.selinux_file_context_path(), '/'
            ],
                                 preexec_fn=self.chroot)
        except OSError as e:
            if e.errno == errno.ENOENT:
                logging.info('The setfiles command is not available.')
                return
        if rc:
            if ksselinux.selinux == ksconstants.SELINUX_ENFORCING:
                raise errors.KickstartError("SELinux relabel failed.")
            else:
                logging.error("SELinux relabel failed.")
Example #5
0
    def __create_selinuxfs(self):
        # if selinux exists on the host we need to lie to the chroot
        if os.path.exists("/selinux/enforce"):
            selinux_dir = self._instroot + "/selinux"

            # enforce=0 tells the chroot selinux is not enforcing
            # policyvers=999 tell the chroot to make the highest version of policy it can

            files = [('/enforce', '0'),
                     ('/policyvers', '999'),
                     ('/commit_pending_bools', ''),
                     ('/mls', str(selinux.is_selinux_mls_enabled()))]

            for (file, value) in files + self.__getbooleans():
                fd = os.open(selinux_dir + file, os.O_WRONLY | os.O_TRUNC | os.O_CREAT)
                os.write(fd, value)
                os.close(fd)

            # we steal mls from the host system for now, might be best to always set it to 1????
            # make /load -> /dev/null so chroot policy loads don't hurt anything
            os.mknod(selinux_dir + "/load", 0666 | stat.S_IFCHR, os.makedev(1, 3))

        # selinux is on in the kickstart, so clean up as best we can to start
        if kickstart.selinux_enabled(self.ks):
            # label the fs like it is a root before the bind mounting
            arglist = ["/sbin/setfiles", "-F", "-r", self._instroot, selinux.selinux_file_context_path(), self._instroot]
            subprocess.call(arglist, close_fds = True)
            # these dumb things don't get magically fixed, so make the user generic
            for f in ("/proc", "/sys", "/selinux"):
                arglist = ["/usr/bin/chcon", "-u", "system_u", self._instroot + f]
                subprocess.call(arglist, close_fds = True)
Example #6
0
def get_file_equiv(fc_path=selinux.selinux_file_context_path()):
    global file_equiv
    if file_equiv:
        return file_equiv
    file_equiv = get_file_equiv_modified(fc_path)
    file_equiv = read_file_equiv(file_equiv, fc_path + ".subs_dist", modify=False)
    return file_equiv
Example #7
0
    def __create_selinuxfs(self):
        if not os.path.exists(self.__selinux_mountpoint):
            return

        arglist = [
            "/bin/mount", "--bind", "/dev/null",
            self._instroot + self.__selinux_mountpoint + "/load"
        ]
        subprocess.call(arglist, close_fds=True)

        if kickstart.selinux_enabled(self.ks):
            # label the fs like it is a root before the bind mounting
            arglist = [
                "/sbin/setfiles", "-F", "-r", self._instroot,
                selinux.selinux_file_context_path(), self._instroot
            ]
            subprocess.call(arglist, close_fds=True)
            # these dumb things don't get magically fixed, so make the user generic
        # if selinux exists on the host we need to lie to the chroot
        if selinux.is_selinux_enabled():
            for f in ("/proc", "/sys"):
                arglist = [
                    "/usr/bin/chcon", "-u", "system_u", self._instroot + f
                ]
                subprocess.call(arglist, close_fds=True)
Example #8
0
def get_local_file_paths(fc_path=selinux.selinux_file_context_path()):
    global local_files
    if local_files:
        return local_files
    local_files = []
    try:
        with open(fc_path + ".local", "r") as fd:
            fc = fd.readlines()
    except OSError as e:
        if e.errno != errno.ENOENT:
            raise
        return []
    for i in fc:
        rec = i.split()
        if len(rec) == 0:
            continue
        try:
            if len(rec) > 2:
                ftype = trans_file_type_str[rec[1]]
            else:
                ftype = "a"

            local_files.append((rec[0], ftype))
        except KeyError:
            pass
    return local_files
Example #9
0
def get_local_file_paths(fc_path=selinux.selinux_file_context_path()):
    global local_files
    if local_files:
        return local_files
    local_files = []
    try:
        with open(fc_path + ".local", "r") as fd:
            fc = fd.readlines()
    except OSError as e:
        if e.errno != errno.ENOENT:
            raise
        return []
    for i in fc:
        rec = i.split()
        if len(rec) == 0:
            continue
        try:
            if len(rec) > 2:
                ftype = trans_file_type_str[rec[1]]
            else:
                ftype = "a"

            local_files.append((rec[0], ftype))
        except KeyError:
            pass
    return local_files
Example #10
0
def _gen_fcdict(fc_path = selinux.selinux_file_context_path()):
	global fcdict
	if fcdict:
		return fcdict
	fd = open(fc_path, "r")
	fc = fd.readlines()
	fd.close()
	fd = open(fc_path+".homedirs", "r")
	fc += fd.readlines()
	fd.close()
	fcdict = {}
	for i in fc:
		rec = i.split()
		try:
			t = rec[-1].split(":")[2]
			if t in fcdict:
				fcdict[t].append(rec[0])
			else:
				fcdict[t] = [ rec[0] ]
		except:
			pass
	fcdict["logfile"] = [ "all log files" ]
	fcdict["user_tmp_type"] = [ "all user tmp files" ]
	fcdict["user_home_type"] = [ "all user home files" ]
	fcdict["virt_image_type"] = [ "all virtual image files" ]
	fcdict["noxattrfs"] = [ "all files on file systems which do not support extended attributes" ]
	fcdict["sandbox_tmpfs_type"] = [ "all sandbox content in tmpfs file systems" ]
	fcdict["user_tmpfs_type"] = [ "all user content in tmpfs file systems" ]
	fcdict["file_type"] = [ "all files on the system" ]
	fcdict["samba_share_t"] = [ "use this label for random content that will be shared using samba" ]
	return fcdict
Example #11
0
def get_file_equiv_modified(fc_path=selinux.selinux_file_context_path()):
    global file_equiv_modified
    if file_equiv_modified:
        return file_equiv_modified
    file_equiv_modified = {}
    file_equiv_modified = read_file_equiv(file_equiv_modified, fc_path + ".subs", modify=True)
    return file_equiv_modified
Example #12
0
    def __init__(self, domainname, path="/tmp", root="/", source_files=False, html=False):
        self.html = html
        self.source_files = source_files
        self.root = root
        self.portrecs = sepolicy.gen_port_dict()[0]
        self.domains = gen_domains()
        self.all_domains = sepolicy.get_all_domains()
        self.all_attributes = sepolicy.get_all_attributes()
        self.all_bools = sepolicy.get_all_bools()
        self.all_port_types = sepolicy.get_all_port_types()
        self.all_roles = sepolicy.get_all_roles()
        self.all_users = get_all_users_info()[0]
        self.all_users_range = get_all_users_info()[1]
        self.all_file_types = sepolicy.get_all_file_types()
        self.role_allows = sepolicy.get_all_role_allows()
        self.types = _gen_types()
        self.exec_types = _gen_exec_types()
        self.entry_types = _gen_entry_types()
        self.mcs_constrained_types = _gen_mcs_constrained_types()

        if self.source_files:
            self.fcpath = self.root + "file_contexts"
        else:
            self.fcpath = self.root + selinux.selinux_file_context_path()

        self.fcdict = sepolicy.get_fcdict(self.fcpath)

        if not os.path.exists(path):
            os.makedirs(path)

        self.path = path

        if self.source_files:
            self.xmlpath = self.root + "policy.xml"
        else:
            self.xmlpath = self.root + "/usr/share/selinux/devel/policy.xml"
        self.booleans_dict = sepolicy.gen_bool_dict(self.xmlpath)

        self.domainname, self.short_name = sepolicy.gen_short_name(domainname)

        self.type = self.domainname + "_t"
        self._gen_bools()
        self.man_page_path = "%s/%s_selinux.8" % (path, self.domainname)
        self.fd = open(self.man_page_path, 'w')
        if self.domainname + "_r" in self.all_roles:
            self.__gen_user_man_page()
            if self.html:
                manpage_roles.append(self.man_page_path)
        else:
            if self.html:
                manpage_domains.append(self.man_page_path)
            self.__gen_man_page()
        self.fd.close()

        for k in equiv_dict.keys():
            if k == self.domainname:
                for alias in equiv_dict[k]:
                    self.__gen_man_page_link(alias)
Example #13
0
def get_fcdict(fc_path=selinux.selinux_file_context_path()):
    global fcdict
    if fcdict:
        return fcdict
    fd = open(fc_path, "r")
    fc = fd.readlines()
    fd.close()
    fd = open(fc_path + ".homedirs", "r")
    fc += fd.readlines()
    fd.close()
    fcdict = {}
    try:
        with open(fc_path + ".local", "r") as fd:
            fc += fd.readlines()
    except OSError as e:
        if e.errno != errno.ENOENT:
            raise

    for i in fc:
        rec = i.split()
        try:
            if len(rec) > 2:
                ftype = trans_file_type_str[rec[1]]
            else:
                ftype = "a"

            t = rec[-1].split(":")[2]
            if t in fcdict:
                fcdict[t]["regex"].append(rec[0])
            else:
                fcdict[t] = {"regex": [rec[0]], "ftype": ftype}
        except:
            pass

    fcdict["logfile"] = {"regex": ["all log files"]}
    fcdict["user_tmp_type"] = {"regex": ["all user tmp files"]}
    fcdict["user_home_type"] = {"regex": ["all user home files"]}
    fcdict["virt_image_type"] = {"regex": ["all virtual image files"]}
    fcdict["noxattrfs"] = {
        "regex":
        ["all files on file systems which do not support extended attributes"]
    }
    fcdict["sandbox_tmpfs_type"] = {
        "regex": ["all sandbox content in tmpfs file systems"]
    }
    fcdict["user_tmpfs_type"] = {
        "regex": ["all user content in tmpfs file systems"]
    }
    fcdict["file_type"] = {"regex": ["all files on the system"]}
    fcdict["samba_share_t"] = {
        "regex":
        ["use this label for random content that will be shared using samba"]
    }
    return fcdict
Example #14
0
    def __create_selinuxfs(self):
        arglist = ["/bin/mount", "--bind", "/dev/null", self._instroot + self.__selinux_mountpoint + "/load"]
        subprocess.call(arglist, close_fds = True)

        if kickstart.selinux_enabled(self.ks):
            # label the fs like it is a root before the bind mounting
            arglist = ["/sbin/setfiles", "-F", "-r", self._instroot, selinux.selinux_file_context_path(), self._instroot]
            subprocess.call(arglist, close_fds = True)
            # these dumb things don't get magically fixed, so make the user generic
        # if selinux exists on the host we need to lie to the chroot
        if selinux.is_selinux_enabled():
            for f in ("/proc", "/sys"):
                arglist = ["/usr/bin/chcon", "-u", "system_u", self._instroot + f]
                subprocess.call(arglist, close_fds = True)
Example #15
0
    def __init__(self, domainname, path = "/tmp", html = False):
	self.html = html
	self.portrecs = network.portrecs

	fcpath = path + "/file_contexts"
	if os.path.exists(fcpath):
		self.fcpath = fcpath
	else:
		self.fcpath = selinux.selinux_file_context_path()
	self.fcdict = _gen_fcdict(self.fcpath)

	if not os.path.exists(path):
		os.makedirs(path)
	self.path = path

	xmlpath = path + "/policy.xml"
	if os.path.exists(xmlpath):
		self.xmlpath = xmlpath
	else:
		self.xmlpath = "/usr/share/selinux/devel/policy.xml"
	self.booleans_dict = gen_bool_dict(self.xmlpath)

	if domainname.endswith("_t"):
		self.domainname = domainname[:-2]
	else:
		self.domainname = domainname

	if self.domainname + "_t" not in self.all_domains:
		raise  ValueError("domain %s_t does not exist" % self.domainname)
	self.short_name = self.domainname

	self.type = self.domainname + "_t"
	self._gen_bools()
	self.man_page_path = "%s/%s_selinux.8" % (path, self.domainname)
	self.fd = open(self.man_page_path, 'w')
	if domainname + "_r" in self.all_roles:
	    self.__gen_user_man_page()
	    if self.html:
		manpage_roles.append(self.man_page_path)
	else:
	    if self.html:
		manpage_domains.append(self.man_page_path)
	    self.__gen_man_page()
	self.fd.close()

	for k in equiv_dict.keys():
		if k == self.domainname:
			for alias in equiv_dict[k]:
				self.__gen_man_page_link(alias)
Example #16
0
    def relabel(self, ksselinux):
        # touch some files which get unhappy if they're not labeled correctly
        for fn in ("/etc/resolv.conf", ):
            path = self.path(fn)
            f = file(path, "w+")
            os.chmod(path, 0644)
            f.close()

        if ksselinux.selinux == ksconstants.SELINUX_DISABLED:
            return

        if not os.path.exists(self.path("/sbin/setfiles")):
            return

        self.call([
            "/sbin/setfiles", "-p", "-e", "/proc", "-e", "/sys", "-e", "/dev",
            selinux.selinux_file_context_path(), "/"
        ])
Example #17
0
def get_fcdict(fc_path=selinux.selinux_file_context_path()):
    global fcdict
    if fcdict:
        return fcdict
    fd = open(fc_path, "r")
    fc = fd.readlines()
    fd.close()
    fd = open(fc_path + ".homedirs", "r")
    fc += fd.readlines()
    fd.close()
    fcdict = {}
    try:
        with open(fc_path + ".local", "r") as fd:
            fc += fd.readlines()
    except OSError as e:
        if e.errno != errno.ENOENT:
            raise

    for i in fc:
        rec = i.split()
        try:
            if len(rec) > 2:
                ftype = trans_file_type_str[rec[1]]
            else:
                ftype = "a"

            t = rec[-1].split(":")[2]
            if t in fcdict:
                fcdict[t]["regex"].append(rec[0])
            else:
                fcdict[t] = {"regex": [rec[0]], "ftype": ftype}
        except:
            pass

    fcdict["logfile"] = {"regex": ["all log files"]}
    fcdict["user_tmp_type"] = {"regex": ["all user tmp files"]}
    fcdict["user_home_type"] = {"regex": ["all user home files"]}
    fcdict["virt_image_type"] = {"regex": ["all virtual image files"]}
    fcdict["noxattrfs"] = {"regex": ["all files on file systems which do not support extended attributes"]}
    fcdict["sandbox_tmpfs_type"] = {"regex": ["all sandbox content in tmpfs file systems"]}
    fcdict["user_tmpfs_type"] = {"regex": ["all user content in tmpfs file systems"]}
    fcdict["file_type"] = {"regex": ["all files on the system"]}
    fcdict["samba_share_t"] = {"regex": ["use this label for random content that will be shared using samba"]}
    return fcdict
Example #18
0
def get_local_file_paths(fc_path = selinux.selinux_file_context_path()):
    global local_files
    if local_files:
        return local_files
    local_files=[]
    fd = open(fc_path+".local", "r")
    fc = fd.readlines()
    fd.close()
    for i in fc:
        rec = i.split()
        if len(rec) == 0:
            continue
        try:
            if len(rec) > 2:
                ftype = trans_file_type_str[rec[1]]
            else:
                ftype = "a"

            local_files.append((rec[0], ftype))
        except KeyError:
            pass
    return local_files
Example #19
0
def get_local_file_paths(fc_path=selinux.selinux_file_context_path()):
    global local_files
    if local_files:
        return local_files
    local_files = []
    fd = open(fc_path + ".local", "r")
    fc = fd.readlines()
    fd.close()
    for i in fc:
        rec = i.split()
        if len(rec) == 0:
            continue
        try:
            if len(rec) > 2:
                ftype = trans_file_type_str[rec[1]]
            else:
                ftype = "a"

            local_files.append((rec[0], ftype))
        except KeyError:
            pass
    return local_files
Example #20
0
    def relabel(self, ksselinux):
        # touch some files which get unhappy if they're not labeled correctly
        for fn in ("/etc/resolv.conf", ):
            path = self.path(fn)
            f = file(path, "w+")
            os.chmod(path, 0644)
            f.close()

        if ksselinux.selinux == ksconstants.SELINUX_DISABLED:
            return

        if not os.path.exists(self.path("/sbin/setfiles")):
            return

        rc = self.call([
            "/sbin/setfiles", "-p", "-e", "/proc", "-e", "/sys", "-e", "/dev",
            selinux.selinux_file_context_path(), "/"
        ])
        if rc:
            if ksselinux.selinux == ksconstants.SELINUX_ENFORCING:
                raise errors.KickstartError("SELinux relabel failed.")
            else:
                logging.error("SELinux relabel failed.")
Example #21
0
def file_context_path():
    if __enabled < 0:
        return None
    return selinux.selinux_file_context_path()
Example #22
0
    def relabel(self, ksselinux):
        # touch some files which get unhappy if they're not labeled correctly
        for fn in ("/etc/resolv.conf",):
            path = self.path(fn)
            f = file(path, "w+")
            os.chmod(path, 0644)
            f.close()

        if ksselinux.selinux == ksconstants.SELINUX_DISABLED:
            return

        if not os.path.exists(self.path("/sbin/setfiles")):
            return

        rc = self.call(["/sbin/setfiles", "-p", "-e", "/proc", "-e", "/sys", "-e", "/dev", selinux.selinux_file_context_path(), "/"])
        if rc:
            if ksselinux.selinux == ksconstants.SELINUX_ENFORCING:
                raise errors.KickstartError("SELinux relabel failed.")
            else:
                logging.error("SELinux relabel failed.")
Example #23
0
    def relabel(self, ksselinux):
        # touch some files which get unhappy if they're not labeled correctly
        for fn in ("/etc/resolv.conf",):
            path = self.path(fn)
            f = file(path, "w+")
            os.chmod(path, 0644)
            f.close()

        if ksselinux.selinux == ksconstants.SELINUX_DISABLED:
            return

        if not os.path.exists(self.path("/sbin/setfiles")):
            return

        self.call(["/sbin/setfiles", "-p", "-e", "/proc", "-e", "/sys", "-e", "/dev", selinux.selinux_file_context_path(), "/"])
Example #24
0
def file_context_path():
    if __enabled < 0:
        return None
    return selinux.selinux_file_context_path()