Ejemplo n.º 1
0
    def testMountingXFS(self):
        an_fs = fs.XFS(device=self.loopDevices[0], label="test")
        self.assertIsNone(an_fs.create())

        blivet.flags.installer_mode = False
        mountpoint = tempfile.mkdtemp("test.selinux")
        an_fs.mount(mountpoint=mountpoint)

        root_selinux_context = selinux.getfilecon(mountpoint)

        lost_and_found = os.path.join(mountpoint, "lost+found")
        self.assertFalse(os.path.exists(lost_and_found))

        an_fs.unmount()
        os.rmdir(mountpoint)

        self.assertEqual(root_selinux_context[1], 'system_u:object_r:unlabeled_t:s0')

        blivet.flags.installer_mode = True
        mountpoint = tempfile.mkdtemp("test.selinux")
        an_fs.mount(mountpoint=mountpoint)

        root_selinux_context = selinux.getfilecon(mountpoint)

        lost_and_found = os.path.join(mountpoint, "lost+found")
        self.assertFalse(os.path.exists(lost_and_found))

        an_fs.unmount()
        os.rmdir(mountpoint)

        self.assertEqual(root_selinux_context[1], 'system_u:object_r:file_t:s0')
Ejemplo n.º 2
0
def get_init_transtype(path):
    entrypoint = selinux.getfilecon(path)[1].split(":")[2]
    try:
        entrypoints = list(filter(lambda x: x['target'] == entrypoint, search([TRANSITION], {'source': "init_t", 'class': 'process'})))
        return entrypoints[0]["transtype"]
    except (TypeError, AttributeError, IndexError):
        pass
    return None
Ejemplo n.º 3
0
def get_file_level(file_name):
    try:
        context = selinux.getfilecon(file_name)
        context_array = context[1].split(":")
        range = context_array[3]
        range_array = range.split("-")
        level = range_array[0]
    except Exception, ex:
        return "Cancel - getting file level for %s exception: %s" % (file_name, ex)
Ejemplo n.º 4
0
def overwrite_safely(path, content, preserve_mode=True, preserve_context=True):
    """Safely overwrite a file by creating a temporary file in the same
    directory, writing it, moving it over the original file, eventually
    preserving file mode and SELinux context."""

    path = os.path.realpath(path)
    dir_ = os.path.dirname(path)
    base = os.path.basename(path)

    fd = None
    f = None
    tmpname = None

    exists = os.path.exists(path)

    if preserve_context and selinux.is_selinux_enabled() <= 0:
        preserve_context = False

    try:
        fd, tmpname = tempfile.mkstemp(prefix=base + os.path.extsep,
                                       dir=dir_)

        if exists and preserve_mode:
            shutil.copymode(path, tmpname)

        if exists and preserve_context:
            ret, ctx = selinux.getfilecon(path)
            if ret < 0:
                raise RuntimeError("getfilecon(%r) failed" % path)

        f = os.fdopen(fd, "w")
        fd = None

        f.write(content)

        f.close()
        f = None

        os.rename(tmpname, path)

        if preserve_context:
            if exists:
                selinux.setfilecon(path, ctx)
            else:
                selinux.restorecon(path)

    finally:
        if f:
            f.close()
        elif fd:
            os.close(fd)
        if tmpname and os.path.isfile(tmpname):
            try:
                os.unlink(tmpname)
            except:
                pass
Ejemplo n.º 5
0
def get_selinux_context(path):
    """
    When selinux is enabled, return the context of ``path``
    :param path: Full or relative path to a file or directory
    :return: SELinux context as a string
    :raises IOError: As per usual.  Documented here as it's
    a behavior difference from ``set_selinux_context()``.
    """
    # First list item is null-terminated string length
    return selinux.getfilecon(path)[1]
Ejemplo n.º 6
0
def get_init_transtype(path):
    entrypoint = selinux.getfilecon(path)[1].split(":")[2]
    try:
        entrypoints = [x for x in search([TRANSITION],{'source':"init_t", 'class':'process'}) if x['target'] == entrypoint]
        if len(entrypoints) == 0:
            return None
        return entrypoints[0]["transtype"]
    except TypeError:
        pass
    return None
Ejemplo n.º 7
0
    def testMountingExt2FS(self):
        _LOOP_DEV0 = self._loopMap[self._LOOP_DEVICES[0]]

        an_fs = fs.Ext2FS(device=_LOOP_DEV0, label="test")
        self.assertIsNone(an_fs.create())

        blivet.flags.installer_mode = False
        mountpoint = tempfile.mkdtemp("test.selinux")
        an_fs.mount(mountpoint=mountpoint)

        root_selinux_context = selinux.getfilecon(mountpoint)

        lost_and_found = os.path.join(mountpoint, "lost+found")
        self.assertTrue(os.path.exists(lost_and_found))

        lost_and_found_selinux_context = selinux.getfilecon(lost_and_found)

        an_fs.unmount()
        os.rmdir(mountpoint)

        self.assertEqual(root_selinux_context[1], 'system_u:object_r:file_t:s0')

        self.assertEqual(lost_and_found_selinux_context[1],
           'system_u:object_r:file_t:s0')

        blivet.flags.installer_mode = True
        mountpoint = tempfile.mkdtemp("test.selinux")
        an_fs.mount(mountpoint=mountpoint)

        root_selinux_context = selinux.getfilecon(mountpoint)

        lost_and_found = os.path.join(mountpoint, "lost+found")
        self.assertTrue(os.path.exists(lost_and_found))

        lost_and_found_selinux_context = selinux.getfilecon(lost_and_found)

        an_fs.unmount()
        os.rmdir(mountpoint)

        self.assertEqual(root_selinux_context[1], 'system_u:object_r:file_t:s0')

        self.assertEqual(lost_and_found_selinux_context[1],
           'system_u:object_r:lost_found_t:s0')
Ejemplo n.º 8
0
    def _gather_data(self, path):
        """ Get data on the existing state of <path> -- e.g., whether
        or not it exists, owner, group, permissions, etc. """
        try:
            ondisk = os.stat(path)
        except OSError:
            self.logger.debug("POSIX: %s does not exist" % path)
            return (False, None, None, None, None, None)

        try:
            owner = str(ondisk[stat.ST_UID])
        except OSError:
            err = sys.exc_info()[1]
            self.logger.debug("POSIX: Could not get current owner of %s: %s" %
                              (path, err))
            owner = None
        except KeyError:
            self.logger.error('POSIX: User resolution failed for %s' % path)
            owner = None

        try:
            group = str(ondisk[stat.ST_GID])
        except (OSError, KeyError):
            err = sys.exc_info()[1]
            self.logger.debug("POSIX: Could not get current group of %s: %s" %
                              (path, err))
            group = None
        except KeyError:
            self.logger.error('POSIX: Group resolution failed for %s' % path)
            group = None

        try:
            mode = oct_mode(ondisk[stat.ST_MODE])[-4:]
        except (OSError, KeyError, TypeError):
            err = sys.exc_info()[1]
            self.logger.debug("POSIX: Could not get current permissions of "
                              "%s: %s" % (path, err))
            mode = None

        if HAS_SELINUX:
            try:
                secontext = selinux.getfilecon(path)[1].split(":")[2]
            except (OSError, KeyError):
                err = sys.exc_info()[1]
                self.logger.debug("POSIX: Could not get current SELinux "
                                  "context of %s: %s" % (path, err))
                secontext = None
        else:
            secontext = None

        if HAS_ACLS:
            acls = self._list_file_acls(path)
        else:
            acls = None
        return (ondisk, owner, group, mode, secontext, acls)
Ejemplo n.º 9
0
Archivo: base.py Proyecto: ab/bcfg2
    def _gather_data(self, path):
        try:
            ondisk = os.stat(path)
        except OSError:
            self.logger.debug("POSIX: %s does not exist" % path)
            return (False, None, None, None, None, None)

        try:
            owner = str(ondisk[stat.ST_UID])
        except OSError:
            err = sys.exc_info()[1]
            self.logger.debug("POSIX: Could not get current owner of %s: %s" %
                              (path, err))
            owner = None
        except KeyError:
            self.logger.error('POSIX: User resolution failed for %s' % path)
            owner = None

        try:
            group = str(ondisk[stat.ST_GID])
        except (OSError, KeyError):
            err = sys.exc_info()[1]
            self.logger.debug("POSIX: Could not get current group of %s: %s" %
                              (path, err))
            group = None
        except KeyError:
            self.logger.error('POSIX: Group resolution failed for %s' % path)
            group = None

        try:
            perms = oct(ondisk[stat.ST_MODE])[-4:]
        except (OSError, KeyError, TypeError):
            err = sys.exc_info()[1]
            self.logger.debug("POSIX: Could not get current permissions of %s: "
                              "%s" % (path, err))
            perms = None

        if has_selinux:
            try:
                secontext = selinux.getfilecon(path)[1].split(":")[2]
            except (OSError, KeyError):
                err = sys.exc_info()[1]
                self.logger.debug("POSIX: Could not get current SELinux "
                                  "context of %s: %s" % (path, err))
                secontext = None
        else:
            secontext = None

        if has_acls:
            acls = self._list_file_acls(path)
        else:
            acls = None
        return (ondisk, owner, group, perms, secontext, acls)
Ejemplo n.º 10
0
    def test_mounting_ext2fs(self):
        """ Test that lost+found directory gets assigned correct SELinux
            context if selinux_set_fcon is True, and retains some random old
            context if selinux_set_fcon is False.
        """
        LOST_AND_FOUND_CONTEXT = "system_u:object_r:lost_found_t:s0"
        an_fs = fs.Ext2FS(device=self.loop_devices[0], label="test")

        if not an_fs.formattable or not an_fs.mountable:
            self.skipTest("can not create or mount filesystem %s" % an_fs.name)

        self.assertIsNone(an_fs.create())

        blivet.flags.selinux_reset_fcon = False
        mountpoint = tempfile.mkdtemp("test.selinux")
        an_fs.mount(mountpoint=mountpoint)

        lost_and_found = os.path.join(mountpoint, "lost+found")
        self.assertTrue(os.path.exists(lost_and_found))

        lost_and_found_selinux_context = selinux.getfilecon(lost_and_found)

        an_fs.unmount()
        os.rmdir(mountpoint)

        self.assertNotEqual(lost_and_found_selinux_context[1], LOST_AND_FOUND_CONTEXT)

        blivet.flags.selinux_reset_fcon = True
        mountpoint = tempfile.mkdtemp("test.selinux")
        an_fs.mount(mountpoint=mountpoint)

        lost_and_found = os.path.join(mountpoint, "lost+found")
        self.assertTrue(os.path.exists(lost_and_found))

        lost_and_found_selinux_context = selinux.getfilecon(lost_and_found)

        an_fs.unmount()
        os.rmdir(mountpoint)

        self.assertEqual(lost_and_found_selinux_context[1], LOST_AND_FOUND_CONTEXT)
Ejemplo n.º 11
0
def make_polydir_name(dir_name, context):
    (rc, dircon) = selinux.getfilecon(dir_name)
    if rc < 0:
        raise Exception("Error in getting directory context: %s " % (dir_name))
    context_array = dircon.split(":")
    # Only generate polyinstantiated name based on the level not the range
    context_array[3] = get_level(context)
    newcontext = ':'.join(context_array)
    (rc, full_dir) = selinux.selinux_trans_to_raw_context(newcontext)
    if rc < 0:
        raise Exception("Error translating context: %s " % (newcontext))
    m = md5.new()
    m.update(full_dir)
    return dir_name + ".inst/" + m.hexdigest()
Ejemplo n.º 12
0
def mkdir(target, refdir):
    target = _native_string(target, encoding=_encodings['fs'], errors='strict')
    refdir = _native_string(refdir, encoding=_encodings['fs'], errors='strict')
    (rc, ctx) = selinux.getfilecon(refdir)
    if rc < 0:
        raise OSError(
         _("mkdir: Failed getting context of reference directory \"%s\".") \
         % refdir)

    setfscreate(ctx)
    try:
        os.mkdir(target)
    finally:
        setfscreate()
Ejemplo n.º 13
0
def get_init_transtype(path):
    entrypoint = selinux.getfilecon(path)[1].split(":")[2]
    try:
        entrypoints = list(
            filter(
                lambda x: x['target'] == entrypoint,
                search([TRANSITION], {
                    'source': "init_t",
                    'class': 'process'
                })))
        return entrypoints[0]["transtype"]
    except (TypeError, AttributeError, IndexError):
        pass
    return None
Ejemplo n.º 14
0
def make_polydir_name(dir_name, context):
    (rc, dircon) = selinux.getfilecon(dir_name)
    if rc < 0:
        raise Exception("Error in getting directory context: %s " % (dir_name))
    context_array = dircon.split(":")
    # Only generate polyinstantiated name based on the level not the range
    context_array[3] = get_level(context)
    newcontext = ':'.join(context_array)
    (rc, full_dir) = selinux.selinux_trans_to_raw_context(newcontext)
    if rc < 0:
        raise Exception("Error translating context: %s " % (newcontext))
    m = md5.new()
    m.update(full_dir)
    return dir_name + ".inst/" + m.hexdigest()
Ejemplo n.º 15
0
def get_init_transtype(path):
    entrypoint = selinux.getfilecon(path)[1].split(":")[2]
    try:
        entrypoints = filter(
            lambda x: x['target'] == entrypoint,
            search([TRANSITION], {
                'source': "init_t",
                'class': 'process'
            }))
        if len(entrypoints) == 0:
            return None
        return entrypoints[0]["transtype"]
    except TypeError:
        pass
    return None
Ejemplo n.º 16
0
    def analyze(self, avc):
        if not avc.query_environment: return None

        if avc.spath is None: return None
        if avc.spath[0] != '/': return None
        try:
            mcon = selinux.matchpathcon(avc.spath.strip('"'), S_IFREG)[1]
            mcon_type = mcon.split(":")[2]
            gcon = selinux.getfilecon(avc.spath.strip('"'))[1]
            gcon_type = gcon.split(":")[2]
            if mcon_type != gcon_type:
                return self.report((0, mcon_type))
        except OSError:
            pass

        return None
    def analyze(self, avc):
        if not avc.query_environment: return None

        if avc.spath is None: return None
        if avc.spath[0] != '/': return None
        try:
            mcon = selinux.matchpathcon(avc.spath.strip('"'), S_IFREG)[1]
            mcon_type=mcon.split(":")[2]
            gcon = selinux.getfilecon(avc.spath.strip('"'))[1]
            gcon_type = gcon.split(":")[2]
            if mcon_type != gcon_type:
                return self.report((0, mcon_type))
        except OSError:
            pass

        return None
Ejemplo n.º 18
0
def mkdir(target, refdir):
	target = _unicode_encode(target, encoding=_encodings['fs'], errors='strict')
	refdir = _unicode_encode(refdir, encoding=_encodings['fs'], errors='strict')
	(rc, ctx) = selinux.getfilecon(refdir)
	if rc < 0:
		refdir = _unicode_decode(refdir, encoding=_encodings['fs'],
			errors='replace')
		raise OSError(
			_("mkdir: Failed getting context of reference directory \"%s\".") \
			% refdir)

	setfscreate(ctx)
	try:
		os.mkdir(target)
	finally:
		setfscreate()
Ejemplo n.º 19
0
    def _copyfile(selinux_hnd, src, dest, try_hardlink=False):

        if selinux_hnd is not None:
            mode = 0o755
            try:
                mode = os.stat(src).st_mode
            except OSError:
                pass

            ctx = selinux.selabel_lookup_raw(selinux_hnd, str(dest), mode)
            selinux.setfscreatecon_raw(ctx[1])

        if os.path.isdir(src):
            # add the directory only if it is empty, so we don't delete directories that
            # weren't added by us.  Anyway a non empty directory would be created by
            # its children.
            if len(os.listdir(src)) == 0:
                os.mkdir(dest)
                return True
        elif os.path.islink(src):
            linkto = os.readlink(src)
            os.symlink(linkto, dest)
            return True
        else:
            file_copied = False
            # newer version of Skopeo/SELinux use the same SELinux context for system containers
            # files as the host files at the same location i.e. /exports/hostfs/foo -> /foo.
            if try_hardlink and selinux_hnd is not None:
                src_label = selinux.getfilecon(src)
                # Files have the same label, we can use a hard link.
                if src_label[1] == ctx[1]:
                    try:
                        os.link(src, dest)
                        file_copied = True
                    except:  # pylint: disable=bare-except
                        pass

            # fallback to file copy.
            if not file_copied:
                # we cannot use shutil.copy2() or shutil.copystat() here as it would override the
                # security.selinux xattr.
                shutil.copy(src, dest)
                shutil.copymode(src, dest)
            return True
        return False
Ejemplo n.º 20
0
def check_permission(path):
    #check selinux context_t
    if selinux.is_selinux_enabled():
        context_t = selinux.getfilecon(path)[1].split(":")[2]
        #openstack-selinux already supports /var/run folder with var_run_t context.
        #for other folder, we expect virt_cache_t context.
        if not (((path == '/var/run' or path.startswith('/var/run/'))
                 and context_t == 'var_run_t') or context_t == 'virt_cache_t'):
            msg = "selinux context is not properly configured on %s" % (path)
            return False, msg

    #check rx permission for qemu-kvm-user
    ##user that the (libvirt managed) QEMU VM(process)s are run as: that utimately requires permission on vhost sockets.
    ##The default user is "qemu" for RHEL7.5 (the comment in /etc/libvirt/qemu.conf seems wrong, which says default is root)
    ##ps -ef shows |grep qemu, confirms the user.
    ##We are checking "libvirt capabilities" to find out the user.
    qemu_kvm_user = get_qemu_process_user()
    if qemu_kvm_user is None:
        msg = "qemu_kvm_user couldnot be found."
        return False, msg
    uid_qemu_kvm_user = pwd.getpwnam(qemu_kvm_user).pw_uid
    gid_groups_qemu_kvm_user = [
        g.gr_gid for g in grp.getgrall() if qemu_kvm_user in g.gr_mem
    ]

    stat_obj = os.stat(path)
    uid_path = stat_obj.st_uid
    gid_path = stat_obj.st_gid
    chmod_path = oct(stat_obj.st_mode)[-3:]  #e.g. '755'

    #user falls in user/group/other
    if uid_path == uid_qemu_kvm_user:
        index = 0
    elif gid_path in gid_groups_qemu_kvm_user:
        index = 1
    else:
        index = 2
    #check rx permission
    if chmod_path[index] in ['5', '7']:
        return True, ''
    else:
        msg = "%s does not have read/execute permission set on %s" % (
            qemu_kvm_user, path)
        return False, msg
Ejemplo n.º 21
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
Ejemplo n.º 22
0
def set_password(user, password):
    """Set the password for a particular user"""
    for filename in PASSWD_FILES:
        if not os.path.exists(filename):
            continue

        # Get the selinux file context before we do anything with the file
        if SELINUX:
            selinux_context = selinux.getfilecon(filename)

        tmpfile = _create_temp_password_file(user, password, filename)
        bakfile = '{0}.bak.{1}'.format(filename, os.getpid())

        os.rename(filename, bakfile)
        os.rename(tmpfile, filename)
        os.remove(bakfile)

        # Update selinux context after the file replace
        if SELINUX:
            selinux.setfilecon(filename, selinux_context[1])

        return

    raise PasswordError((500, "No password file found"))
Ejemplo n.º 23
0
 def get_selinux_label(path: str) -> str:
     """Get file's SELinux label."""
     return selinux.getfilecon(path)[-1]
Ejemplo n.º 24
0
def default_ro_container_context():
    if selinux.is_selinux_enabled() != 0:
        return selinux.getfilecon("/usr")[1]
    return ""
Ejemplo n.º 25
0
 def getcon(self, abspath):
     """ Return context of file, symlink or dir """
     try:
         return selinux.getfilecon(abspath)[1]
     except OSError:
         self._logger.warning('Cannot get selinux context: "%s"', abspath)
Ejemplo n.º 26
0
def upgradeMountFilesystems(anaconda):
    # mount everything and turn on swap

    try:
        mountExistingSystem(anaconda, anaconda.id.upgradeRoot[0], allowDirty=0)
    except ValueError as e:
        log.error("Error mounting filesystem: %s" % e)
        anaconda.intf.messageWindow(
            _("Mount failed"),
            _("The following error occurred when mounting the file "
              "systems listed in /etc/fstab.  Please fix this problem "
              "and try to upgrade again.\n%s" % e))
        sys.exit(0)
    except IndexError as e:
        # The upgrade root is search earlier but we give the message here.
        log.debug("No upgrade root was found.")
        if anaconda.isKickstart and anaconda.id.ksdata.upgrade.upgrade:
            anaconda.intf.messageWindow(
                _("Upgrade root not found"),
                _("The root for the previously installed system was not "
                  "found."),
                type="custom",
                custom_icon="info",
                custom_buttons=[_("Exit installer")])
            sys.exit(0)
        else:
            rc = anaconda.intf.messageWindow(
                _("Upgrade root not found"),
                _("The root for the previously installed system was not "
                  "found.  You can exit installer or backtrack to choose "
                  "installation instead of upgrade."),
                type="custom",
                custom_buttons=[_("_Back"), _("_Exit installer")],
                custom_icon="question")
            if rc == 0:
                return DISPATCH_BACK
            elif rc == 1:
                sys.exit(0)

    checkLinks = ('/etc', '/var', '/var/lib', '/var/lib/rpm', '/boot', '/tmp',
                  '/var/tmp', '/root', '/bin/sh', '/usr/tmp')
    badLinks = []
    for n in checkLinks:
        if not os.path.islink(anaconda.rootPath + n): continue
        l = os.readlink(anaconda.rootPath + n)
        if l[0] == '/':
            badLinks.append(n)

    if badLinks:
        message = _("The following files are absolute symbolic "
                    "links, which we do not support during an "
                    "upgrade. Please change them to relative "
                    "symbolic links and restart the upgrade.\n\n")
        for n in badLinks:
            message = message + '\t' + n + '\n'
        anaconda.intf.messageWindow(_("Absolute Symlinks"), message)
        sys.exit(0)

    # fix for 80446
    badLinks = []
    mustBeLinks = ('/usr/tmp', )
    for n in mustBeLinks:
        if not os.path.islink(anaconda.rootPath + n):
            badLinks.append(n)

    if badLinks:
        message = _("The following are directories which should instead "
                    "be symbolic links, which will cause problems with the "
                    "upgrade.  Please return them to their original state "
                    "as symbolic links and restart the upgrade.\n\n")
        for n in badLinks:
            message = message + '\t' + n + '\n'
        anaconda.intf.messageWindow(_("Invalid Directories"), message)
        sys.exit(0)

    anaconda.id.storage.turnOnSwap(upgrading=True)
    anaconda.id.storage.mkDevRoot()

    # Move /etc/rpm/platform out of the way.
    if os.path.exists(anaconda.rootPath + "/etc/rpm/platform"):
        shutil.move(anaconda.rootPath + "/etc/rpm/platform",
                    anaconda.rootPath + "/etc/rpm/platform.rpmsave")

    # if they've been booting with selinux disabled, then we should
    # disable it during the install as well (#242510)
    try:
        if os.path.exists(anaconda.rootPath + "/.autorelabel"):
            ctx = selinux.getfilecon(anaconda.rootPath + "/.autorelabel")[1]
            if not ctx or ctx == "unlabeled":
                flags.selinux = False
                log.info("Disabled SELinux for upgrade based on /.autorelabel")
    except Exception, e:
        log.warning("error checking selinux state: %s" % (e, ))
Ejemplo n.º 27
0
 def getcon(self, abspath):
     """ Return context of file, symlink or dir """
     try:
         return selinux.getfilecon(abspath.encode("utf-8"))[1]
     except OSError:
         self._logger.warning('Cannot get selinux context: "%s"', abspath)
Ejemplo n.º 28
0
def selinux_getfilecon(path):
    if have_selinux():
        return selinux.getfilecon(path)[1]
    return None
Ejemplo n.º 29
0
def default_ro_container_context():
    if selinux.is_selinux_enabled() != 0:
        return selinux.getfilecon("/usr")[1]
    return ""
Ejemplo n.º 30
0
def validateEnv(env: Env) -> None:
    """Sanity check and warn user about missing setting"""
    def warn(msg: str) -> None:
        print(f"\033[93m{msg}\033[m")

    # Check if SELinux will block socket access
    if env.capabilities.get("selinux"):
        for cap in ("x11", "tun", "pulseaudio"):
            if env.capabilities.get(cap):
                warn(
                    f"SELinux is disabled because capability '{cap}' need "
                    "extra type enforcement that are not currently supported.")
                selinuxCap(False, env.ctx, env)
                env.capabilities["selinux"] = False

    # Check for uid permissions
    if not env.capabilities.get("root") and not env.capabilities.get("uidmap"):
        for cap in ("x11", "pulseaudio", "ssh", "gpg"):
            if env.capabilities.get(cap):
                warn(f"UIDMap is required because '{cap}' need "
                     "DAC access to the host file")
                uidmapCap(True, env.ctx, env)
                break

    # Check for system capabilities
    if env.capabilities.get("tun") and "NET_ADMIN" not in env.ctx.syscaps:
        warn(f"NET_ADMIN capability is needed by the tun device")
        env.ctx.syscaps.append("NET_ADMIN")

    # Check mount points labels
    if env.capabilities.get("selinux") and HAS_SELINUX:
        label = "container_file_t"
        for hostPath in env.ctx.mounts.values():
            hostPath = hostPath.expanduser().resolve()
            if hostPath.exists() and \
               selinux.getfilecon(str(hostPath))[1].split(':')[2] != label:
                warn(f"SELinux is disabled because {hostPath} doesn't have "
                     f"the {label} label. To set the label run: "
                     f"chcon -Rt {label} {hostPath}")
                selinuxCap(False, env.ctx, env)

    # Check mount points permissions
    for hostPath in env.ctx.mounts.values():
        hostPath = hostPath.expanduser().resolve()
        if hostPath.exists() and not os.access(str(hostPath), os.R_OK):
            warn(f"{hostPath} is not readable by the current user.")

    # Check for home mount point
    if env.overlays and not env.ctx.mounts.get(env.ctx.home):
        warn(f"overlay needs a home mount point, "
             "mountRun capability is enabled.")
        mountRunCap(True, env.ctx, env)

    if env.capabilities.get(
            "mount-home") and not env.capabilities.get("uidmap"):
        warn("UIDMap is required for mount-home")
        uidmapCap(True, env.ctx, env)

    # Check for image management
    if not env.manageImage:
        if env.packages:
            warn("manage-image capability is required for packages")
            manageImageCap(True, env.ctx, env)
        if env.imageCustomizations or env.imageTasks:
            warn("manage-image capability is required for image tasks")
            manageImageCap(True, env.ctx, env)
        if env.branchImage:
            warn("branch-image capability is incompatible with manage-image")
Ejemplo n.º 31
0
def upgradeMountFilesystems(anaconda):
    # mount everything and turn on swap

    try:
        mountExistingSystem(anaconda, anaconda.upgradeRoot[0], allowDirty = 0)
    except ValueError as e:
        log.error("Error mounting filesystem: %s" % e)
        anaconda.intf.messageWindow(_("Mount failed"),
            _("The following error occurred when mounting the file "
              "systems listed in /etc/fstab.  Please fix this problem "
              "and try to upgrade again.\n%s" % e))
        sys.exit(0)
    except IndexError as e:
        # The upgrade root is search earlier but we give the message here.
        log.debug("No upgrade root was found.")
        if anaconda.ksdata and anaconda.ksdata.upgrade.upgrade:
            anaconda.intf.messageWindow(_("Upgrade root not found"),
                _("The root for the previously installed system was not "
                  "found."), type="custom",
                custom_icon="info",
                custom_buttons=[_("Exit installer")])
            sys.exit(0)
        else:
            rc = anaconda.intf.messageWindow(_("Upgrade root not found"),
                    _("The root for the previously installed system was not "
                      "found.  You can exit installer or backtrack to choose "
                      "installation instead of upgrade."),
                type="custom",
                custom_buttons = [ _("_Back"),
                                   _("_Exit installer") ],
                custom_icon="question")
            if rc == 0:
                return DISPATCH_BACK
            elif rc == 1:
                sys.exit(0)

    checkLinks = ( '/etc', '/var', '/var/lib', '/var/lib/rpm',
                   '/boot', '/tmp', '/var/tmp', '/root',
                   '/bin/sh', '/usr/tmp')
    badLinks = []
    for n in checkLinks:
        if not os.path.islink(anaconda.rootPath + n): continue
        l = os.readlink(anaconda.rootPath + n)
        if l[0] == '/':
            badLinks.append(n)

    if badLinks:
        message = _("The following files are absolute symbolic " 
                    "links, which we do not support during an " 
                    "upgrade. Please change them to relative "
                    "symbolic links and restart the upgrade.\n\n")
        for n in badLinks:
            message = message + '\t' + n + '\n'
        anaconda.intf.messageWindow(_("Absolute Symlinks"), message)
        sys.exit(0)

    # fix for 80446
    badLinks = []
    mustBeLinks = ( '/usr/tmp', )
    for n in mustBeLinks:
        if not os.path.islink(anaconda.rootPath + n):
            badLinks.append(n)

    if badLinks: 
        message = _("The following are directories which should instead "
                    "be symbolic links, which will cause problems with the "
                    "upgrade.  Please return them to their original state "
                    "as symbolic links and restart the upgrade.\n\n")
        for n in badLinks:
            message = message + '\t' + n + '\n'
        anaconda.intf.messageWindow(_("Invalid Directories"), message)
        sys.exit(0)

    anaconda.storage.turnOnSwap(upgrading=True)
    anaconda.storage.mkDevRoot()

    # Move /etc/rpm/platform out of the way.
    if os.path.exists(anaconda.rootPath + "/etc/rpm/platform"):
        shutil.move(anaconda.rootPath + "/etc/rpm/platform",
                    anaconda.rootPath + "/etc/rpm/platform.rpmsave")

    # if they've been booting with selinux disabled, then we should
    # disable it during the install as well (#242510)
    try:
        if os.path.exists(anaconda.rootPath + "/.autorelabel"):
            ctx = selinux.getfilecon(anaconda.rootPath + "/.autorelabel")[1]
            if not ctx or ctx == "unlabeled":
                flags.selinux = False
                log.info("Disabled SELinux for upgrade based on /.autorelabel")
    except Exception, e:
        log.warning("error checking selinux state: %s" %(e,))
Ejemplo n.º 32
0
 def get_selinux_context(self, path):
     try:
         (rc, c) = selinux.getfilecon(path)
         return c
     except Exception:
         return None
def selinux_getfilecon(path):
    if have_selinux():
        return selinux.getfilecon(path)[1]
    return None
Ejemplo n.º 34
0
 def get_selinux_context(self, path):
     try:
         (rc, c) = selinux.getfilecon(path)
         return c
     except:
         return None
Ejemplo n.º 35
0
            raise AutoUpdateError(msg)

    # Ok, we need to try and fix the SELinux context of the relevant files.  We'll
    # copy the existing context of known libraries, since we know we can
    # call them from the current context already.
    # If any call here fails, silently skip the rest and keep running.

    if selinuxIsEnabled:

        try:
            # not sure at this point if we're updating Security Blanket or OS Lockdown, so
            # do a quick check...
            # If upgrading Security Blanket start with *that* contexts, otherwise use OS Lockdown context.
            if os.path.isfile(
                    '/usr/share/security-blanket/sb_utils/auth/Affirm.pyo'):
                startingContext = selinux.getfilecon(
                    "/usr/share/security-blanket")[1]
            else:
                startingContext = selinux.getfilecon(
                    "/usr/share/oslockdown")[1]

            selinux.setfilecon(candidate1,
                               startingContext.replace("_rw_t", "_py_t"))
            selinux.setfilecon(candidate2,
                               startingContext.replace("_rw_t", "_licso_t"))

            os.chmod(candidate1, 0700)
            os.chmod(candidate2, 0700)
        except (NameError, AttributeError), e:
            logging.getLogger('AutoUpdate').error(e)

    sys.path.append(candidatedir)