Example #1
0
    def __gen_man_page(self):
        self.anon_list = []

        self.attributes = {}
        self.ptypes = []
        self._get_ptypes()

        for domain_type in self.ptypes:
            try:
                if typealias_types[domain_type]:
                    fd = self.fd
                    man_page_path =  self.man_page_path
                    for t in typealias_types[domain_type]:
                        self._typealias_gen_man(t)
                    self.fd = fd
                    self.man_page_path = man_page_path
            except KeyError:
                continue
            self.attributes[domain_type] = next(sepolicy.info(sepolicy.TYPE, ("%s") % domain_type))["attributes"]

        self._header()
        self._entrypoints()
        self._process_types()
        self._mcs_types()
        self._booleans()
        self._nsswitch_domain()
        self._port_types()
        self._writes()
        self._file_context()
        self._public_content()
        self._footer()
Example #2
0
    def __gen_user_man_page(self):
        self.role = self.domainname + "_r"
        if not self.modules_dict:
            self.modules_dict = gen_modules_dict(self.xmlpath)

        try:
            self.desc = self.modules_dict[self.domainname]
        except:
            self.desc = "%s user role" % self.domainname

        if self.domainname in self.all_users:
            self.attributes = next(sepolicy.info(sepolicy.TYPE, (self.type)))["attributes"]
            self._user_header()
            self._user_attribute()
            self._can_sudo()
            self._xwindows_login()
            # until a new policy build with login_userdomain attribute
        #self.terminal_login()
            self._network()
            self._booleans()
            self._home_exec()
            self._transitions()
        else:
            self._role_header()
            self._booleans()

        self._port_types()
        self._mcs_types()
        self._writes()
        self._footer()
    def __gen_user_man_page(self):
        self.role = self.domainname + "_r"
        if not self.modules_dict:
            self.modules_dict = gen_modules_dict(self.xmlpath)

        try:
            self.desc = self.modules_dict[self.domainname]
        except:
            self.desc = "%s user role" % self.domainname

        if self.domainname in self.all_users:
            self.attributes = next(sepolicy.info(sepolicy.TYPE,
                                                 (self.type)))["attributes"]
            self._user_header()
            self._user_attribute()
            self._can_sudo()
            self._xwindows_login()
            # until a new policy build with login_userdomain attribute
            #self.terminal_login()
            self._network()
            self._booleans()
            self._home_exec()
            self._transitions()
        else:
            self._role_header()
            self._booleans()

        self._port_types()
        self._mcs_types()
        self._writes()
        self._footer()
    def __gen_man_page(self):
        self.anon_list = []

        self.attributes = {}
        self.ptypes = []
        self._get_ptypes()

        for domain_type in self.ptypes:
            try:
                if typealias_types[domain_type]:
                    fd = self.fd
                    man_page_path = self.man_page_path
                    for t in typealias_types[domain_type]:
                        self._typealias_gen_man(t)
                    self.fd = fd
                    self.man_page_path = man_page_path
            except KeyError:
                continue
            self.attributes[domain_type] = next(
                sepolicy.info(sepolicy.TYPE,
                              ("%s") % domain_type))["attributes"]

        self._header()
        self._entrypoints()
        self._process_types()
        self._mcs_types()
        self._booleans()
        self._nsswitch_domain()
        self._port_types()
        self._writes()
        self._file_context()
        self._public_content()
        self._footer()
Example #5
0
    def __call__(self, parser, namespace, values, option_string=None):
        global all_classes
        if not all_classes:
            all_classes = [x['name'] for x in sepolicy.info(sepolicy.TCLASS)]
        if values not in all_classes:
            raise ValueError("%s must be an SELinux class:\nValid classes: %s" % (values, ", ".join(all_classes)))

        setattr(namespace, self.dest, values)
Example #6
0
    def __call__(self, parser, namespace, values, option_string=None):
        global all_classes
        if not all_classes:
            all_classes = map(lambda x: x['name'], sepolicy.info(sepolicy.TCLASS))
        if values not in all_classes:
            raise ValueError("%s must be an SELinux class:\nValid classes: %s" % (values, ", ".join(all_classes)))

        setattr(namespace, self.dest, values)
Example #7
0
def _gen_mcs_constrained_types():
    global mcs_constrained_types
    if mcs_constrained_types is None:
        try:
            mcs_constrained_types = next(
                sepolicy.info(sepolicy.ATTRIBUTE, "mcs_constrained_type"))
        except StopIteration:
            mcs_constrained_types = []
    return mcs_constrained_types
Example #8
0
    def _mcs_types(self):
        attributes = sepolicy.info(sepolicy.TYPE, (self.type))[0]["attributes"]
        if "mcs_constrained_type" not in attributes:
            return
        self.fd.write ("""
.SH "MCS Constrained"
The SELinux process type %(type)s_t is an MCS (Multi Category Security) constrained type.  Sometimes this separation is referred to as sVirt. These types are usually used for securing multi-tenant environments, such as virtualization, containers or separation of users.  The tools used to launch MCS types, pick out a different MCS label for each process group.

For example one process might be launched with %(type)s_t:s0:c1,c2, and another process launched with %(type)s_t:s0:c3,c4. The SELinux kernel only allows these processes can only write to content with a matching MCS label, or a MCS Label of s0. A process running with the MCS level of s0:c1,c2 is not allowed to write to content with the MCS label of s0:c3,c4
""" % {'type': self.domainname})
Example #9
0
    def _mcs_types(self):
        attributes = sepolicy.info(sepolicy.TYPE, (self.type))[0]["attributes"]
        if "mcs_constrained_type" not in attributes:
            return
        self.fd.write("""
.SH "MCS Constrained"
The SELinux process type %(type)s_t is an MCS (Multi Category Security) constrained type.  Sometimes this separation is referred to as sVirt. These types are usually used for securing multi-tenant environments, such as virtualization, containers or separation of users.  The tools used to launch MCS types, pick out a different MCS label for each process group.

For example one process might be launched with %(type)s_t:s0:c1,c2, and another process launched with %(type)s_t:s0:c3,c4. The SELinux kernel only allows these processes can only write to content with a matching MCS label, or a MCS Label of s0. A process running with the MCS level of s0:c1,c2 is not allowed to write to content with the MCS label of s0:c3,c4
""" % {'type': self.domainname})
def _gen_types():
    global types
    if types:
        return types
    all_types = sepolicy.info(sepolicy.TYPE)
    types = {}
    for rec in all_types:
        try:
            types[rec["name"]] = rec["attributes"]
        except:
            types[rec["name"]] = []
    return types
Example #11
0
def _gen_types():
    global types
    if types:
        return types
    all_types = sepolicy.info(sepolicy.TYPE)
    types = {}
    for rec in all_types:
        try:
            types[rec["name"]] = rec["attributes"]
        except:
            types[rec["name"]] = []
    return types
Example #12
0
    def __gen_man_page(self):
        self.anon_list = []

        self.attributes = {}
        self.ptypes = []
        self._get_ptypes()

        for domain_type in self.ptypes:
            self.attributes[domain_type] = sepolicy.info(sepolicy.TYPE, ("%s") % domain_type)[0]["attributes"]

        self._header()
        self._entrypoints()
        self._process_types()
        self._booleans()
        self._nsswitch_domain()
        self._port_types()
        self._writes()
        self._file_context()
        self._public_content()
        self._footer()
def get_all_users_info():
    global users
    global users_range
    if users and users_range:
        return users, users_range

    users = []
    users_range = {}
    allusers = []
    allusers_info = sepolicy.info(sepolicy.USER)

    for d in allusers_info:
        allusers.append(d['name'])
        users_range[d['name'].split("_")[0]] = d['range']

    for u in allusers:
        if u not in ["system_u", "root", "unconfined_u"]:
            users.append(u.replace("_u", ""))
    users.sort()
    return users, users_range
Example #14
0
def get_all_users_info():
    global users
    global users_range
    if users and users_range:
        return users, users_range

    users = []
    users_range = {}
    allusers = []
    allusers_info = sepolicy.info(sepolicy.USER)

    for d in allusers_info:
        allusers.append(d['name'])
        if 'range' in d:
            users_range[d['name'].split("_")[0]] = d['range']

    for u in allusers:
        if u not in ["system_u", "root", "unconfined_u"]:
            users.append(u.replace("_u", ""))
    users.sort()
    return users, users_range
Example #15
0
    def __gen_man_page(self):
        self.anon_list = []

        self.attributes = {}
        self.ptypes = []
        self._get_ptypes()

        for domain_type in self.ptypes:
            self.attributes[domain_type] = sepolicy.info(
                sepolicy.TYPE, ("%s") % domain_type)[0]["attributes"]

        self._header()
        self._entrypoints()
        self._process_types()
        self._booleans()
        self._nsswitch_domain()
        self._port_types()
        self._writes()
        self._file_context()
        self._public_content()
        self._footer()
def get_entrypoints():
    global all_entrypoints
    if not all_entrypoints:
        all_entrypoints = next(sepolicy.info(sepolicy.ATTRIBUTE,
                                             "entry_type"))["types"]
    return all_entrypoints
Example #17
0
    for i in info(sepolicy.PORT):
        if i['low'] == i['high']:
            port = str(i['low'])
        else:
            port = "%s-%s" % (str(i['low']), str(i['high']))

        if (i['type'], i['protocol']) in portrecs:
            portrecs [(i['type'], i['protocol'])].append(port)
        else:
            portrecs [(i['type'], i['protocol'])] = [port]

        portrecsbynum[(i['low'], i['high'],i['protocol'])] = (i['type'], i['range'])
    return ( portrecs, portrecsbynum )
portrecs, portrecsbynum = _gen_port_dict()

port_types =  sepolicy.info(sepolicy.ATTRIBUTE,"port_type")[0]["types"]
domains =  sepolicy.info(sepolicy.ATTRIBUTE,"domain")[0]["types"]

def get_types(src, tclass, perm):
    allows=search([sepolicy.ALLOW],{sepolicy.SOURCE:src,sepolicy.CLASS:tclass, sepolicy.PERMS:perm})
    nlist=[]
    if allows:
        for i in map(lambda y: y[sepolicy.TARGET], filter(lambda x: set(perm).issubset(x[sepolicy.PERMS]) and x['enabled'], allows)):
            if i not in nlist:
                nlist.append(i)
    return nlist
   

def get_network_connect(src, protocol, perm):
    d={}
    tlist = get_types(src, "%s_socket" % protocol, [perm])
Example #18
0
def selinux_label_port(port, remove_label=False):
    """
    Either set or remove an SELinux label(ldap_port_t) for a TCP port

    :param port: The TCP port to be labelled
    :type port: str
    :param remove_label: Set True if the port label should be removed
    :type remove_label: boolean
    :raises: ValueError: Error message
    """
    try:
        import selinux
    except ImportError:
        log.debug('selinux python module not found, skipping port labeling.')
        return

    try:
        import sepolicy
    except ImportError:
        log.debug('sepolicy python module not found, skipping port labeling.')
        return

    if not selinux.is_selinux_enabled():
        log.debug('selinux is disabled, skipping port relabel')
        return

    # We only label ports that ARE NOT in the default policy that comes with
    # a RH based system.
    selinux_default_ports = [389, 636, 3268, 3269, 7389]
    if port in selinux_default_ports:
        log.debug('port %s already in %s, skipping port relabel' %
                  (port, selinux_default_ports))
        return

    label_set = False
    label_ex = None

    policies = [
        p for p in sepolicy.info(sepolicy.PORT) if p['protocol'] == 'tcp'
        if port in range(p['low'], p['high'] + 1) if p['type'] not in
        ['unreserved_port_t', 'reserved_port_t', 'ephemeral_port_t']
    ]

    for policy in policies:
        if "ldap_port_t" == policy['type']:
            label_set = True  # Port already has our label
            if policy['low'] != policy['high']:
                # We have a range
                if port in range(policy['low'], policy['high'] + 1):
                    # The port is within the range, just return
                    return
            break
        elif not remove_label:
            # Port belongs to someone else (bad)
            # This is only an issue during setting a label, not removing a label
            raise ValueError(
                "Port {} was already labelled with: ({})  Please choose a different port number"
                .format(port, policy['type']))

    if (remove_label and label_set) or (not remove_label and not label_set):
        for i in range(5):

            try:
                subprocess.check_call([
                    "semanage", "port", "-d" if remove_label else "-a", "-t",
                    "ldap_port_t", "-p", "tcp",
                    str(port)
                ])
                return
            except (OSError, subprocess.CalledProcessError) as e:
                label_ex = e
                time.sleep(3)
        raise ValueError("Failed to mangle port label: " + str(label_ex))
Example #19
0
def get_entrypoints():
    global all_entrypoints
    if not all_entrypoints:
        all_entrypoints = next(sepolicy.info(sepolicy.ATTRIBUTE, "entry_type"))["types"]
    return all_entrypoints
Example #20
0
def expand_attribute(attribute):
    try:
        return sepolicy.info(sepolicy.ATTRIBUTE, attribute)[0]["types"]
    except RuntimeError:
        return [attribute]
Example #21
0
def sepolicy_port_json_generator():
    ports = sepolicy.info(sepolicy.PORT)
    for port in ports:
        yield port
Example #22
0
def _gen_entry_types():
    global entry_types
    if entry_types is None:
        entry_types = next(sepolicy.info(sepolicy.ATTRIBUTE, "entry_type"))["types"]
    return entry_types
Example #23
0
def expand_attribute(attribute):
    try:
        return sepolicy.info(sepolicy.ATTRIBUTE, attribute)[0]["types"]
    except RuntimeError:
        return [attribute]
Example #24
0
def expand_attribute(attribute):
    try:
        return list(next(sepolicy.info(sepolicy.ATTRIBUTE, attribute))["types"])
    except StopIteration:
        return [attribute]
Example #25
0
def _gen_entry_types():
    global entry_types
    if entry_types is None:
        entry_types = next(sepolicy.info(sepolicy.ATTRIBUTE, "entry_type"))["types"]
    return entry_types
Example #26
0
def _gen_mcs_constrained_types():
    global mcs_constrained_types
    if mcs_constrained_types is None:
        mcs_constrained_types = next(sepolicy.info(sepolicy.ATTRIBUTE, "mcs_constrained_type"))
    return mcs_constrained_types
Example #27
0
def expand_attribute(attribute):
    try:
        return list(
            next(sepolicy.info(sepolicy.ATTRIBUTE, attribute))["types"])
    except StopIteration:
        return [attribute]
Example #28
0
def _gen_mcs_constrained_types():
    global mcs_constrained_types
    if mcs_constrained_types is None:
        mcs_constrained_types = next(sepolicy.info(sepolicy.ATTRIBUTE, "mcs_constrained_type"))
    return mcs_constrained_types