Пример #1
0
def load_policy(opts):
    PWD = getcwd()
    chdir(TEMPLATES_STORE)

    if opts["LoadModules"]:
        handle = semanage.semanage_handle_create()
        semanage.semanage_connect(handle)

        for template in templates_to_load:
            semanage.semanage_module_install_file(handle, template + ".cil")

        chdir(PWD)

        semanage.semanage_module_install_file(handle,
                                              opts["ContainerName"] + ".cil")

        semanage.semanage_commit(handle)
    else:
        templates = list_templates_to_string(templates_to_load)
        if len(templates_to_load) > 1:
            print("\nPlease load these modules using: \n# semodule -i " +
                  opts["ContainerName"] + ".cil " + TEMPLATES_STORE + "/{" +
                  templates + "}")
        else:
            print("\nPlease load these modules using: \n# semodule -i " +
                  opts["ContainerName"] + ".cil " + TEMPLATES_STORE + "/" +
                  templates + "")

        chdir(PWD)
Пример #2
0
def load_policy(opts):
    PWD = getcwd()
    chdir(TEMPLATES_STORE)

    if opts['LoadModules']:
        handle = semanage.semanage_handle_create()
        semanage.semanage_connect(handle)

        for template in templates_to_load:
            semanage.semanage_module_install_file(handle, template + '.cil')

        chdir(PWD)

        semanage.semanage_module_install_file(handle,
                                              opts['ContainerName'] + '.cil')

        semanage.semanage_commit(handle)
    else:
        templates = list_templates_to_string(templates_to_load)
        if len(templates_to_load) > 1:
            print('\nPlease load these modules using: \n# semodule -i ' +
                  opts['ContainerName'] + '.cil ' + TEMPLATES_STORE + "/{" +
                  templates + '}')
        else:
            print('\nPlease load these modules using: \n# semodule -i ' +
                  opts['ContainerName'] + '.cil ' + TEMPLATES_STORE + "/" +
                  templates + '')

        chdir(PWD)
Пример #3
0
def list_contexts(directory):
    directory_len = (len(directory))

    handle = semanage.semanage_handle_create()
    semanage.semanage_connect(handle)

    (rc, fclist) = semanage.semanage_fcontext_list(handle)
    (rc, fclocal) = semanage.semanage_fcontext_list_local(handle)
    (rc, fchome) = semanage.semanage_fcontext_list_homedirs(handle)

    contexts = []
    for fcontext in fclist + fclocal + fchome:
        expression = semanage.semanage_fcontext_get_expr(fcontext)
        if expression[0:directory_len] == directory:
            context = semanage.semanage_fcontext_get_con(fcontext)
            if context:
                contexts.append(semanage.semanage_context_get_type(context))

    selabel = selinux.selabel_open(selinux.SELABEL_CTX_FILE, None, 0)
    (rc, context) = selinux.selabel_lookup(selabel, directory, 0)
    if context == None:
        if exists(directory) == False:
            exit(3)
        context = selinux.getfilecon(directory)[1]
    contexts.append(context.split(':')[2])
    return contexts
def semanage_boolean_value(module, name, state):
    rc = 0
    value = 0
    if state:
        value = 1
    handle = semanage.semanage_handle_create()
    if handle is None:
        module.fail_json(msg="Failed to create semanage library handle")
    try:
        managed = semanage.semanage_is_managed(handle)
        if managed < 0:
            module.fail_json(
                msg="Failed to determine whether policy is manage")
        if managed == 0:
            if os.getuid() == 0:
                module.fail_json(
                    msg="Cannot set persistent booleans without managed policy"
                )
            else:
                module.fail_json(
                    msg="Cannot set persistent booleans; please try as root")
        if semanage.semanage_connect(handle) < 0:
            module.fail_json(msg="Failed to connect to semanage")

        if semanage.semanage_begin_transaction(handle) < 0:
            module.fail_json(msg="Failed to begin semanage transaction")

        rc, sebool = semanage.semanage_bool_create(handle)
        if rc < 0:
            module.fail_json(msg="Failed to create seboolean with semanage")
        if semanage.semanage_bool_set_name(handle, sebool, name) < 0:
            module.fail_json(msg="Failed to set seboolean name with semanage")
        semanage.semanage_bool_set_value(sebool, value)

        rc, boolkey = semanage.semanage_bool_key_extract(handle, sebool)
        if rc < 0:
            module.fail_json(msg="Failed to extract boolean key with semanage")

        if semanage.semanage_bool_modify_local(handle, boolkey, sebool) < 0:
            module.fail_json(msg="Failed to modify boolean key with semanage")

        if semanage.semanage_bool_set_active(handle, boolkey, sebool) < 0:
            module.fail_json(
                msg="Failed to set boolean key active with semanage")

        semanage.semanage_bool_key_free(boolkey)
        semanage.semanage_bool_free(sebool)

        semanage.semanage_set_reload(handle, 0)
        if semanage.semanage_commit(handle) < 0:
            module.fail_json(msg="Failed to commit changes to semanage")

        semanage.semanage_disconnect(handle)
        semanage.semanage_handle_destroy(handle)
    except Exception:
        e = get_exception()
        module.fail_json(msg="Failed to manage policy for boolean %s: %s" %
                         (name, str(e)))
    return True
Пример #5
0
def semanage_boolean_value(module, name, state):
    rc = 0
    value = 0
    if state:
        value = 1
    handle = semanage.semanage_handle_create()
    if handle is None:
        module.fail_json(msg="Failed to create semanage library handle")
    try:
        managed = semanage.semanage_is_managed(handle)
        if managed < 0:
            module.fail_json(msg="Failed to determine whether policy is manage")
        if managed == 0:
            if os.getuid() == 0:
                module.fail_json(msg="Cannot set persistent booleans without managed policy")
            else:
                module.fail_json(msg="Cannot set persistent booleans; please try as root")
        if semanage.semanage_connect(handle) < 0:
            module.fail_json(msg="Failed to connect to semanage")

        if semanage.semanage_begin_transaction(handle) < 0:
            module.fail_json(msg="Failed to begin semanage transaction")

        rc, sebool = semanage.semanage_bool_create(handle)
        if rc < 0:
            module.fail_json(msg="Failed to create seboolean with semanage")
        if semanage.semanage_bool_set_name(handle, sebool, name) < 0:
            module.fail_json(msg="Failed to set seboolean name with semanage")
        semanage.semanage_bool_set_value(sebool, value)

        rc, boolkey = semanage.semanage_bool_key_extract(handle, sebool)
        if rc < 0:
            module.fail_json(msg="Failed to extract boolean key with semanage")

        if semanage.semanage_bool_modify_local(handle, boolkey, sebool) < 0:
            module.fail_json(msg="Failed to modify boolean key with semanage")

        if semanage.semanage_bool_set_active(handle, boolkey, sebool) < 0:
            module.fail_json(msg="Failed to set boolean key active with semanage")

        semanage.semanage_bool_key_free(boolkey)
        semanage.semanage_bool_free(sebool)

        semanage.semanage_set_reload(handle, 0)
        if semanage.semanage_commit(handle) < 0:
            module.fail_json(msg="Failed to commit changes to semanage")

        semanage.semanage_disconnect(handle)
        semanage.semanage_handle_destroy(handle)
    except Exception:
        e = get_exception()
        module.fail_json(msg="Failed to manage policy for boolean %s: %s" % (name, str(e)))
    return True
Пример #6
0
def list_ports(port_number):

    handle = semanage.semanage_handle_create()
    semanage.semanage_connect(handle)

    (rc, plist) = semanage.semanage_port_list(handle)
    (rc, plocal) = semanage.semanage_port_list_local(handle)

    for port in plist + plocal:
        con = semanage.semanage_port_get_con(port)
        ctype = semanage.semanage_context_get_type(con)
        low = semanage.semanage_port_get_low(port)
        if low == port_number:
            return ctype
Пример #7
0
def list_ports(port_number, port_proto):

    handle = semanage.semanage_handle_create()
    semanage.semanage_connect(handle)

    (rc, plist) = semanage.semanage_port_list(handle)
    (rc, plocal) = semanage.semanage_port_list_local(handle)

    for port in plocal + plist:
        con = semanage.semanage_port_get_con(port)
        ctype = semanage.semanage_context_get_type(con)
        proto = semanage.semanage_port_get_proto(port)
        proto_str = semanage.semanage_port_get_proto_str(proto)
        low = semanage.semanage_port_get_low(port)
        high = semanage.semanage_port_get_high(port)
        if low <= port_number <= high and port_proto == proto_str:
            return ctype
Пример #8
0
def semanage_get_handle(module):
    handle = semanage.semanage_handle_create()
    if not handle:
        module.fail_json(msg="Failed to create semanage library handle")

    managed = semanage.semanage_is_managed(handle)
    if managed <= 0:
        semanage.semanage_handle_destroy(handle)
    if managed < 0:
        module.fail_json(msg="Failed to determine whether policy is manage")
    if managed == 0:
        if os.getuid() == 0:
            module.fail_json(msg="Cannot set persistent booleans without managed policy")
        else:
            module.fail_json(msg="Cannot set persistent booleans; please try as root")

    if semanage.semanage_connect(handle) < 0:
        semanage.semanage_handle_destroy(handle)
        module.fail_json(msg="Failed to connect to semanage")

    return handle
Пример #9
0
def list_contexts(directory):
    directory_len = len(directory)

    handle = semanage.semanage_handle_create()
    semanage.semanage_connect(handle)

    (rc, fclist) = semanage.semanage_fcontext_list(handle)
    (rc, fclocal) = semanage.semanage_fcontext_list_local(handle)
    (rc, fchome) = semanage.semanage_fcontext_list_homedirs(handle)

    contexts = []
    for fcontext in fclist + fclocal + fchome:
        expression = semanage.semanage_fcontext_get_expr(fcontext)
        if expression[0:directory_len] == directory:
            context = semanage.semanage_fcontext_get_con(fcontext)
            if context:
                contexts.append(semanage.semanage_context_get_type(context))

    selabel = selinux.selabel_open(selinux.SELABEL_CTX_FILE, None, 0)
    try:
        (rc, context) = selinux.selabel_lookup(selabel, directory, 0)
    except FileNotFoundError:
        # File context definition containing "<<none>>" triggers exception
        context = None
    if context:
        contexts.append(context.split(":")[2])

    # Get the real label (ls -lZ) - may differ from what selabel_lookup returns
    try:
        context = selinux.getfilecon(directory)[1]
    except FileNotFoundError:
        context = None

    if context:
        contexts.append(context.split(":")[2])

    return contexts
Пример #10
0
def main(argv=None):
	if argv is None:
		argv = sys.argv
	try:
        	try:
			opts, args = getopt.getopt(argv[1:], "hvmuspfibcUSPFIBCanN", ["help", "verbose", "modules", "users", "seusers", "ports", "file contexts", "network interfaces", "booleans", "active booleans", "network nodes", "writeuser", "writeseuser", "writeport", "writefcontext", "writeinterface", "writeboolean", "writeaboolean", "writenode", "all"])
			tests = Tests()
			for o, a in opts:
        			if o == "-v":
            				tests.verbose = True
					print "Verbose output selected."
        			if o == "-a":
            				tests.all = True
        			if o == "-u":
            				tests.users = True
        			if o == "-U":
            				tests.writeuser = True
        			if o == "-s":
            				tests.seusers = True
        			if o == "-S":
            				tests.writeseuser = True
				if o == "-p":
					tests.ports = True
				if o == "-P":
					tests.writeport = True
				if o == "-f":
					tests.fcontexts = True
				if o == "-F":
					tests.writefcontext = True
				if o == "-i":
					tests.interfaces = True
				if o == "-I":
					tests.writeinterface = True
				if o == "-b":
					tests.booleans = True
				if o == "-B":
					tests.writeboolean = True
				if o == "-c":
					tests.abooleans = True
				if o == "-C":
					tests.writeaboolean = True
				if o == "-n":
					tests.nodes = True
				if o == "-N":
					tests.writenode = True
        			if o == "-m":
            				tests.modules = True
        			if o == "-h":
					raise Usage(usage)

			if not tests.selected():
				raise Usage("Please select a valid test.")

        	except getopt.error, msg:
             		raise Usage(msg)

		sh=semanage.semanage_handle_create()
		
		if (semanage.semanage_is_managed(sh) != 1):
			raise Status("Unmanaged!")
		
		status = semanage.semanage_connect(sh)
		if status < 0:
			raise Error("Could not establish semanage connection")

		tests.run(sh)

		status = semanage.semanage_disconnect(sh)
		if status < 0:
			raise Error("Could not disconnect")

		semanage.semanage_handle_destroy(sh)
Пример #11
0
def main(argv=None):
    if argv is None:
        argv = sys.argv
    try:
        try:
            opts, args = getopt.getopt(argv[1:], "hvmuspfibcUSPFIBCanN", [
                "help",
                "verbose",
                "modules",
                "users",
                "seusers",
                "ports",
                "file contexts",
                "network interfaces",
                "booleans",
                "active booleans",
                "network nodes",
                "writeuser",
                "writeseuser",
                "writeport",
                "writefcontext",
                "writeinterface",
                "writeboolean",
                "writeaboolean",
                "writenode",
                "all",
            ])
            tests = Tests()
            for o, a in opts:
                if o == "-v":
                    tests.verbose = True
                    print("Verbose output selected.")
                if o == "-a":
                    tests.all = True
                if o == "-u":
                    tests.users = True
                if o == "-U":
                    tests.writeuser = True
                if o == "-s":
                    tests.seusers = True
                if o == "-S":
                    tests.writeseuser = True
                if o == "-p":
                    tests.ports = True
                if o == "-P":
                    tests.writeport = True
                if o == "-f":
                    tests.fcontexts = True
                if o == "-F":
                    tests.writefcontext = True
                if o == "-i":
                    tests.interfaces = True
                if o == "-I":
                    tests.writeinterface = True
                if o == "-b":
                    tests.booleans = True
                if o == "-B":
                    tests.writeboolean = True
                if o == "-c":
                    tests.abooleans = True
                if o == "-C":
                    tests.writeaboolean = True
                if o == "-n":
                    tests.nodes = True
                if o == "-N":
                    tests.writenode = True
                if o == "-m":
                    tests.modules = True
                if o == "-h":
                    raise Usage(usage)

            if not tests.selected():
                raise Usage("Please select a valid test.")

        except getopt.error as msg:
            raise Usage(msg)

        sh = semanage.semanage_handle_create()

        if semanage.semanage_is_managed(sh) != 1:
            raise Status("Unmanaged!")

        status = semanage.semanage_connect(sh)
        if status < 0:
            raise Error("Could not establish semanage connection")

        tests.run(sh)

        status = semanage.semanage_disconnect(sh)
        if status < 0:
            raise Error("Could not disconnect")

        semanage.semanage_handle_destroy(sh)

    except Usage as err:
        print(err.msg, file=sys.stderr)
    except Status as err:
        print(err.msg, file=sys.stderr)
    except Error as err:
        print(err.msg, file=sys.stderr)

    return 2
Пример #12
0
# it is *much* faster than semanage port -l

# will work with python 2.6+
from __future__ import print_function
from sys import exit
try:
  import semanage
except ImportError:
  # The semanage python library does not exist, so let's assume SELinux is disabled...
  # In this case, the correct response is to return no ports when puppet does a
  # prefetch, to avoid an error. We depend on the semanage binary anyway, which
  # is uses the library
  exit(0)


handle = semanage.semanage_handle_create()

if semanage.semanage_is_managed(handle) < 0:
    exit(1)
if semanage.semanage_connect(handle) < 0:
    exit(1)

def print_port(kind, port):
    con = semanage.semanage_port_get_con(port)
    con_str = semanage.semanage_context_to_string(handle, con)
    high = semanage.semanage_port_get_high(port)
    low = semanage.semanage_port_get_low(port)
    proto = semanage.semanage_port_get_proto(port)
    proto_str = semanage.semanage_port_get_proto_str(proto)
    print(kind, con_str[1], high, low, proto_str)
Пример #13
0
# This script uses libsemanage directly to access the ports list
# it is *much* faster than semanage port -l

# will work with python 2.6+
from __future__ import print_function
from sys import exit
try:
    import semanage
except ImportError:
    # The semanage python library does not exist, so let's assume SELinux is disabled...
    # In this case, the correct response is to return no ports when puppet does a
    # prefetch, to avoid an error. We depend on the semanage binary anyway, which
    # is uses the library
    exit(0)

handle = semanage.semanage_handle_create()

if semanage.semanage_is_managed(handle) < 0:
    exit(1)
if semanage.semanage_connect(handle) < 0:
    exit(1)


def print_port(kind, port):
    con = semanage.semanage_port_get_con(port)
    con_str = semanage.semanage_context_to_string(handle, con)
    high = semanage.semanage_port_get_high(port)
    low = semanage.semanage_port_get_low(port)
    proto = semanage.semanage_port_get_proto(port)
    proto_str = semanage.semanage_port_get_proto_str(proto)
    print(kind, con_str[1], high, low, proto_str)