Beispiel #1
0
def selinux_status():
    """
    Returns a dict as similar to:
        {'enabled': False, 'mode': 'enforcing'}
    """
    selinux_enabled = False
    selinux_mode = None

    try:
        import selinux
    except ImportError:
        # If Python bindings for SELinux are not installed (if we're
        # running on Jessie where we can't build python3-selinux package)
        # we resort to calling sestatus executable.
        try:
            from sh import sestatus
        except ImportError:
            return {'enabled': False}

        # Manually parse out the output for SELinux status
        for line in sestatus().stdout.split(b'\n'):
            row = line.split(b':')

            if row[0].startswith(b'SELinux status'):
                selinux_enabled = row[1].strip() == b'enabled'

            if row[0].startswith(b'Current mode'):
                selinux_mode = row[1].strip()
    else:
        if selinux.is_selinux_enabled() == 1:
            selinux_enabled = True
            selinux_mode = {-1: None, 0: 'permissive', 1: 'enforcing'}[selinux.security_getenforce()]
    return {'enabled': selinux_enabled, 'mode': selinux_mode}
def get_selinux_status():
    ''' Get SELinux status information '''

    try:
        import selinux
    except ImportError:
        api.report_error(
            "SELinux Import Error",
            details="libselinux-python package must be installed.")
        return

    outdata = dict({'enabled': selinux.is_selinux_enabled() == 1})
    outdata['mls_enabled'] = selinux.is_selinux_mls_enabled() == 1

    try:
        outdata['runtime_mode'] = "enforcing" if selinux.security_getenforce(
        ) == 1 else "permissive"
        # FIXME: check selinux_getenforcemode[0] (that should be return value of a underneath function)
        enforce_mode = selinux.selinux_getenforcemode()[1]
        if enforce_mode >= 0:
            outdata[
                'static_mode'] = "enforcing" if enforce_mode == 1 else "permissive"
        else:
            outdata['static_mode'] = "disabled"
        outdata['policy'] = selinux.selinux_getpolicytype()[1]
    except OSError:
        # This happens when SELinux is disabled
        # [Errno 2] No such file or directory
        outdata['runtime_mode'] = 'permissive'
        outdata['static_mode'] = 'disabled'
        outdata['policy'] = 'targeted'

    return SELinuxFacts(**outdata)
def run(options={}):
    """main loop for this plugin"""

    _success = 1
    _message = 'toggle unsuccessful, selinux setting unchanged'

    if 'dryrun' in options:
        if options['dryrun'] == True:
            _success = 0
            _message = 'I would have toggled selinux enforcing setting'
            return _success, _message

    # First, is SELinux available on this system?
    if selinux.is_selinux_enabled():
        try:
            is_enforce = selinux.security_getenforce()
        except OSError:
            _success, _message = 1, 'SELinux is not available on this host'
            return _success, _message
    else:
        print 'selinux disabled, will not be able to toggle setting'
        sys.exit(1)

    _success, _message = toggle_selinux(is_enforce)
    return _success, _message
Beispiel #4
0
def is_selinux_enforcing():

    #try if we can import selinux python bindings (preferred way of checking)
    try:
        import selinux
        return bool(selinux.is_selinux_enabled()) and bool(
            selinux.security_getenforce())
    except Exception as e:
        logger.error(e)

    if os.getenv("FLATPAK_ID") is not None:
        commands = []
        commands.append("flatpak-spawn")
        commands.append("--host")
        commands.append("sestatus")

        try:
            out = subprocess.run(commands, stdout=subprocess.PIPE)
            out = out.stdout.decode('utf-8')
            logger.debug(out)
            if ("enabled" in out) and ("enforcing" in out):
                return True
        except:
            return False

    return False
Beispiel #5
0
 def get_current_mode(self):
     if selinux.is_selinux_enabled():
         if selinux.security_getenforce() > 0:
             return ENFORCING
         else:
             return PERMISSIVE
     else:
         return DISABLED
 def get_current_mode(self):
     if selinux.is_selinux_enabled():
         if selinux.security_getenforce() > 0:
             return ENFORCING
         else:
             return PERMISSIVE
     else:
         return DISABLED
Beispiel #7
0
def log_selinux_state():
    """Log the current state of selinux"""
    if selinux.is_selinux_enabled():
        if selinux.security_getenforce():
            logger.info("selinux is enabled and in Enforcing mode")
        else:
            logger.info("selinux is enabled and in Permissive mode")
    else:
        logger.info("selinux is Disabled")
Beispiel #8
0
def is_selinux_running():
    """
    @return True if selinux is available on system and enabled
    """
    try:
        import selinux
        if selinux.security_getenforce() < 0:
            return False
    except (ImportError, OSError):
        return False
    return True
Beispiel #9
0
def setexec(ctx="\n"):
    ctx = _native_string(ctx, encoding=_encodings['content'], errors='strict')
    rc = 0
    try:
        rc = selinux.setexeccon(ctx)
    except OSError:
        msg = _("Failed to set new SELinux execution context. " + \
         "Is your current SELinux context allowed to run Portage?")
        if selinux.security_getenforce() == 1:
            raise OSError(msg)
        else:
            portage.writemsg("!!! %s\n" % msg, noiselevel=-1)

    if rc < 0:
        if selinux.security_getenforce() == 1:
            raise OSError(_("Failed setting exec() context \"%s\".") % ctx)
        else:
            portage.writemsg("!!! " + \
             _("Failed setting exec() context \"%s\".") % ctx, \
             noiselevel=-1)
Beispiel #10
0
def is_selinux_running():
    """
    @return True if selinux is available on system and enabled
    """
    try:
        import selinux
        if selinux.security_getenforce() < 0:
            return False
    except (ImportError, OSError):
        return False
    return True
def setexec(ctx="\n"):
	ctx = _unicode_encode(ctx, encoding=_encodings['content'], errors='strict')
	if selinux.setexeccon(ctx) < 0:
		ctx = _unicode_decode(ctx, encoding=_encodings['content'],
			errors='replace')
		if selinux.security_getenforce() == 1:
			raise OSError(_("Failed setting exec() context \"%s\".") % ctx)
		else:
			portage.writemsg("!!! " + \
				_("Failed setting exec() context \"%s\".") % ctx, \
				noiselevel=-1)
Beispiel #12
0
def setexec(ctx="\n"):
    ctx = _unicode_encode(ctx, encoding=_encodings['content'], errors='strict')
    if selinux.setexeccon(ctx) < 0:
        ctx = _unicode_decode(ctx,
                              encoding=_encodings['content'],
                              errors='replace')
        if selinux.security_getenforce() == 1:
            raise OSError(_("Failed setting exec() context \"%s\".") % ctx)
        else:
            portage.writemsg("!!! " + \
             _("Failed setting exec() context \"%s\".") % ctx, \
             noiselevel=-1)
Beispiel #13
0
def selinux_is_enforcing():
    """
    Return True if selinux is currently in enforcing mode.

    :raise ValueError: If there was an error from libselinux
    :rtype: bool
    """
    mode = selinux.security_getenforce()
    if mode not in [selinux.ENFORCING, selinux.PERMISSIVE]:
        raise ValueError("Unexpected value from"
                         " security_getenforce(): %s" % mode)
    return mode == selinux.ENFORCING
def selinux_is_enforcing():
    """
    Return True if selinux is currently in enforcing mode.

    :raise ValueError: If there was an error from libselinux
    :rtype: bool
    """
    mode = selinux.security_getenforce()
    if mode not in [selinux.ENFORCING, selinux.PERMISSIVE]:
        raise ValueError("Unexpected value from"
                         " security_getenforce(): %s" % mode)
    return mode == selinux.ENFORCING
    def collect(self, module=None, collected_facts=None):
        facts_dict = {}
        selinux_facts = {}

        # If selinux library is missing, only set the status and selinux_python_present since
        # there is no way to tell if SELinux is enabled or disabled on the system
        # without the library.
        if not HAVE_SELINUX:
            selinux_facts['status'] = 'Missing selinux Python library'
            facts_dict['selinux'] = selinux_facts
            facts_dict['selinux_python_present'] = False
            return facts_dict

        # Set a boolean for testing whether the Python library is present
        facts_dict['selinux_python_present'] = True

        if not selinux.is_selinux_enabled():
            selinux_facts['status'] = 'disabled'
        else:
            selinux_facts['status'] = 'enabled'

            try:
                selinux_facts['policyvers'] = selinux.security_policyvers()
            except (AttributeError, OSError):
                selinux_facts['policyvers'] = 'unknown'

            try:
                (rc, configmode) = selinux.selinux_getenforcemode()
                if rc == 0:
                    selinux_facts['config_mode'] = SELINUX_MODE_DICT.get(
                        configmode, 'unknown')
                else:
                    selinux_facts['config_mode'] = 'unknown'
            except (AttributeError, OSError):
                selinux_facts['config_mode'] = 'unknown'

            try:
                mode = selinux.security_getenforce()
                selinux_facts['mode'] = SELINUX_MODE_DICT.get(mode, 'unknown')
            except (AttributeError, OSError):
                selinux_facts['mode'] = 'unknown'

            try:
                (rc, policytype) = selinux.selinux_getpolicytype()
                if rc == 0:
                    selinux_facts['type'] = policytype
                else:
                    selinux_facts['type'] = 'unknown'
            except (AttributeError, OSError):
                selinux_facts['type'] = 'unknown'

        facts_dict['selinux'] = selinux_facts
        return facts_dict
Beispiel #16
0
    def collect(self, module=None, collected_facts=None):
        facts_dict = {}
        selinux_facts = {}

        # If selinux library is missing, only set the status and selinux_python_present since
        # there is no way to tell if SELinux is enabled or disabled on the system
        # without the library.
        if not HAVE_SELINUX:
            selinux_facts['status'] = 'Missing selinux Python library'
            facts_dict['selinux'] = selinux_facts
            facts_dict['selinux_python_present'] = False
            return facts_dict

        # Set a boolean for testing whether the Python library is present
        facts_dict['selinux_python_present'] = True

        if not selinux.is_selinux_enabled():
            selinux_facts['status'] = 'disabled'
        else:
            selinux_facts['status'] = 'enabled'

            try:
                selinux_facts['policyvers'] = selinux.security_policyvers()
            except (AttributeError, OSError):
                selinux_facts['policyvers'] = 'unknown'

            try:
                (rc, configmode) = selinux.selinux_getenforcemode()
                if rc == 0:
                    selinux_facts['config_mode'] = SELINUX_MODE_DICT.get(configmode, 'unknown')
                else:
                    selinux_facts['config_mode'] = 'unknown'
            except (AttributeError, OSError):
                selinux_facts['config_mode'] = 'unknown'

            try:
                mode = selinux.security_getenforce()
                selinux_facts['mode'] = SELINUX_MODE_DICT.get(mode, 'unknown')
            except (AttributeError, OSError):
                selinux_facts['mode'] = 'unknown'

            try:
                (rc, policytype) = selinux.selinux_getpolicytype()
                if rc == 0:
                    selinux_facts['type'] = policytype
                else:
                    selinux_facts['type'] = 'unknown'
            except (AttributeError, OSError):
                selinux_facts['type'] = 'unknown'

        facts_dict['selinux'] = selinux_facts
        return facts_dict
Beispiel #17
0
    def collect(self, module=None, collected_facts=None):
        facts_dict = {}
        selinux_facts = {}

        # This is weird. The value of the facts 'selinux' key can be False or a dict
        if not HAVE_SELINUX:
            facts_dict['selinux'] = False
            facts_dict['selinux_python_present'] = False
            return facts_dict

        facts_dict['selinux_python_present'] = True

        if not selinux.is_selinux_enabled():
            selinux_facts['status'] = 'disabled'
        # NOTE: this could just return in the above clause and the rest of this is up an indent -akl
        else:
            selinux_facts['status'] = 'enabled'

            try:
                selinux_facts['policyvers'] = selinux.security_policyvers()
            except (AttributeError, OSError):
                selinux_facts['policyvers'] = 'unknown'

            try:
                (rc, configmode) = selinux.selinux_getenforcemode()
                if rc == 0:
                    selinux_facts['config_mode'] = SELINUX_MODE_DICT.get(
                        configmode, 'unknown')
                else:
                    selinux_facts['config_mode'] = 'unknown'
            except (AttributeError, OSError):
                selinux_facts['config_mode'] = 'unknown'

            try:
                mode = selinux.security_getenforce()
                selinux_facts['mode'] = SELINUX_MODE_DICT.get(mode, 'unknown')
            except (AttributeError, OSError):
                selinux_facts['mode'] = 'unknown'

            try:
                (rc, policytype) = selinux.selinux_getpolicytype()
                if rc == 0:
                    selinux_facts['type'] = policytype
                else:
                    selinux_facts['type'] = 'unknown'
            except (AttributeError, OSError):
                selinux_facts['type'] = 'unknown'

        facts_dict['selinux'] = selinux_facts
        return facts_dict
Beispiel #18
0
    def collect(self, module=None, collected_facts=None):
        facts_dict = {}
        selinux_facts = {}

        # This is weird. The value of the facts 'selinux' key can be False or a dict
        if not HAVE_SELINUX:
            facts_dict['selinux'] = False
            facts_dict['selinux_python_present'] = False
            return facts_dict

        facts_dict['selinux_python_present'] = True

        if not selinux.is_selinux_enabled():
            selinux_facts['status'] = 'disabled'
        # NOTE: this could just return in the above clause and the rest of this is up an indent -akl
        else:
            selinux_facts['status'] = 'enabled'

            try:
                selinux_facts['policyvers'] = selinux.security_policyvers()
            except (AttributeError, OSError):
                selinux_facts['policyvers'] = 'unknown'

            try:
                (rc, configmode) = selinux.selinux_getenforcemode()
                if rc == 0:
                    selinux_facts['config_mode'] = SELINUX_MODE_DICT.get(configmode, 'unknown')
                else:
                    selinux_facts['config_mode'] = 'unknown'
            except (AttributeError, OSError):
                selinux_facts['config_mode'] = 'unknown'

            try:
                mode = selinux.security_getenforce()
                selinux_facts['mode'] = SELINUX_MODE_DICT.get(mode, 'unknown')
            except (AttributeError, OSError):
                selinux_facts['mode'] = 'unknown'

            try:
                (rc, policytype) = selinux.selinux_getpolicytype()
                if rc == 0:
                    selinux_facts['type'] = policytype
                else:
                    selinux_facts['type'] = 'unknown'
            except (AttributeError, OSError):
                selinux_facts['type'] = 'unknown'

        facts_dict['selinux'] = selinux_facts
        return facts_dict
Beispiel #19
0
    def selinux(self):
        try:
            if selinux.security_getenforce():
                state = self.state_enforcing
                color = self.py3.COLOR_GOOD
            else:
                state = self.state_permissive
                color = self.py3.COLOR_DEGRADED
        except AttributeError:
            state = self.state_disabled
            color = self.py3.COLOR_BAD

        return {
            'cached_until': self.py3.time_in(self.cache_timeout),
            'full_text': self.py3.safe_format(self.format, {'state': state}),
            'color': color
        }
Beispiel #20
0
    def selinux(self):
        try:
            if selinux.security_getenforce():
                state = self.state_enforcing
                color = self.py3.COLOR_GOOD
            else:
                state = self.state_permissive
                color = self.py3.COLOR_DEGRADED
        except AttributeError:
            state = self.state_disabled
            color = self.py3.COLOR_BAD

        return {
            "cached_until": self.py3.time_in(self.cache_timeout),
            "full_text": self.py3.safe_format(self.format, {"state": state}),
            "color": color,
        }
Beispiel #21
0
    def __init__(self):
        """
        The facts class is meant to determine different facts about the server being
        backed up, like what the storage layout is, what are the mount points, selinux,
        etc. The variables are used through out the application for various stuff.
        """
        self.lvm = dict()

        # Some of these need to be called in order.
        self.recovery_mode = environ.get('RECOVERY_MODE', False)
        self.hostname = uname().nodename
        self.distro = distro.name()
        self.distro_pretty = distro.name(pretty=True)
        self.uname = uname().release
        self.udev_ctx = Context()
        self.mnts = get_mnts(self.udev_ctx)
        self.disks = get_part_layout(self.udev_ctx)
        self.lvm_installed = rpmq("lvm2")

        if not self.recovery_mode:
            self.modules = get_modules()
            self.uefi = exists("/sys/firmware/efi")
            self.arch = machine()

            from selinux import is_selinux_enabled, security_getenforce
            if is_selinux_enabled():
                self.selinux_enabled = 1
                self.selinux_enforcing = security_getenforce()
            else:
                self.selinux_enabled = 0
                self.selinux_enforcing = 0

            if rpmq("mokutil") and "enabled" in run_cmd(
                ['mokutil', '--sb-state'], ret=True).stdout.decode():
                self.secure_boot = 1
            else:
                self.secure_boot = 0

        # Confirm the lvm2 pkg is installed before querying lvm.
        if self.lvm_installed:
            self.lvm = get_lvm_report(self.udev_ctx)

        self.md_info = get_md_info(self.udev_ctx)
        self.luks = get_luks_devs(self.udev_ctx)
Beispiel #22
0
    def selinux_status(self):
        try:
            if selinux.security_getenforce():
                selinuxstring = 'enforcing'
                color = self.py3.COLOR_GOOD
            else:
                selinuxstring = 'permissive'
                color = self.py3.COLOR_BAD
        except OSError:
            selinuxstring = 'disabled'
            color = self.py3.COLOR_BAD

        response = {
            'cached_until': self.py3.time_in(self.cache_timeout),
            'full_text': self.py3.safe_format(self.format, {'state': selinuxstring}),
            'color': color,
        }

        return response
Beispiel #23
0
    def selinux_status(self, i3s_output_list, i3s_config):
        try:
            if selinux.security_getenforce():
                selinuxstring = 'enforcing'
                color = 'color_good'
            else:
                selinuxstring = 'permissive'
                color = 'color_bad'
        except OSError:
            selinuxstring = 'disabled'
            color = 'color_bad'

        response = {
            'cached_until': time() + self.cache_timeout,
            'full_text': self.format.format(state=selinuxstring),
            'color': i3s_config[color]
        }

        return response
Beispiel #24
0
    def selinux(self):
        if not self.py3.check_commands(['getenforce']):
            return {'cache_until': self.py3.CACHE_FOREVER,
                    'color': self.py3.COLOR_BAD,
                    'full_text': STRING_UNAVAILABLE}
        try:
            if selinux.security_getenforce():
                state = self.state_enforcing
                color = self.py3.COLOR_GOOD
            else:
                state = self.state_permissive
                color = self.py3.COLOR_BAD
        except:
            state = self.state_disabled
            color = self.py3.COLOR_BAD

        return {'cached_until': self.py3.time_in(self.cache_timeout),
                'full_text': self.py3.safe_format(self.format, {'state': state}),
                'color': color}
Beispiel #25
0
    def selinux_status(self):
        try:
            if selinux.security_getenforce():
                selinuxstring = 'enforcing'
                color = self.py3.COLOR_GOOD
            else:
                selinuxstring = 'permissive'
                color = self.py3.COLOR_BAD
        except OSError:
            selinuxstring = 'disabled'
            color = self.py3.COLOR_BAD

        response = {
            'cached_until': self.py3.time_in(self.cache_timeout),
            'full_text': self.format.format(state=selinuxstring),
            'color': color,
        }

        return response
Beispiel #26
0
    def update(self):
        import platform
        import selinux
        # security_getenforce is the same as the getenforce command.
        # selinux_getenforcemode tells you what is set in /etc/selinux/config

        self.platform, self.kernel = get_os_environment()
        self.policy_type = selinux.selinux_getpolicytype()[1]
        self.policy_rpm = get_rpm_nvr_by_name("selinux-policy")
        self.policyvers = str(selinux.security_policyvers())
        enforce = selinux.security_getenforce()
        if enforce == 0:
            self.enforce = "Permissive"
        else:
            self.enforce = "Enforcing"

        self.selinux_enabled = bool(selinux.is_selinux_enabled())
        self.selinux_mls_enabled = bool(selinux.is_selinux_mls_enabled())
        self.hostname = platform.node()
        self.uname = " ".join(platform.uname())
    def update(self):
        import platform
        import selinux
        # security_getenforce is the same as the getenforce command.
        # selinux_getenforcemode tells you what is set in /etc/selinux/config

        self.platform, self.kernel = get_os_environment()
        self.policy_type = selinux.selinux_getpolicytype()[1]
        self.policy_rpm = get_rpm_nvr_by_name("selinux-policy")
        self.policyvers = str(selinux.security_policyvers())
        enforce = selinux.security_getenforce()
        if enforce == 0:
            self.enforce = "Permissive"
        else:
            self.enforce = "Enforcing"

        self.selinux_enabled = bool(selinux.is_selinux_enabled())
        self.selinux_mls_enabled = bool(selinux.is_selinux_mls_enabled())
        self.hostname = platform.node()
        self.uname = " ".join(platform.uname())
Beispiel #28
0
    def __init__(self):
        super(_NGUtilSELinux, self).__init__()

        # Check if SELinux is available
        try:
            import selinux
            self._selinux = selinux
            
            # Enforcing / status
            self.enforcing = True if selinux.security_getenforce() == 1 else False
            self.enabled   = True if selinux.is_selinux_enabled() == 1 else False 
            
            # If SELinux found and enabled
            if self.enabled:
                self.feedback.info('SELinux found on current system: enforcing={0}'.format(repr(self.enforcing)))
            
            # SELinux disabled
            else:
                self.feedback.info('SELinux disabled on current system...')
            
        # SELinux not available
        except:
            self.feedback.info('SELinux not available on current system')
            self.enabled = False
Beispiel #29
0
def main():
    module = AnsibleModule(
        argument_spec=dict(
            policy=dict(required=False),
            state=dict(choices=['enforcing', 'permissive', 'disabled'], required=True),
            configfile=dict(aliases=['conf', 'file'], default='/etc/selinux/config')
        ),
        supports_check_mode=True
    )

    if not HAS_SELINUX:
        module.fail_json(msg='libselinux-python required for this module')

    # global vars
    changed = False
    msgs = []
    configfile = module.params['configfile']
    policy = module.params['policy']
    state = module.params['state']
    runtime_enabled = selinux.is_selinux_enabled()
    runtime_policy = selinux.selinux_getpolicytype()[1]
    runtime_state = 'disabled'

    if runtime_enabled:
        # enabled means 'enforcing' or 'permissive'
        if selinux.security_getenforce():
            runtime_state = 'enforcing'
        else:
            runtime_state = 'permissive'

    if not os.path.isfile(configfile):
        module.fail_json(msg="Unable to find file {0}".format(configfile),
                         details="Please install SELinux-policy package, "
                                 "if this package is not installed previously.")

    config_policy = get_config_policy(configfile)
    config_state = get_config_state(configfile)

    # check to see if policy is set if state is not 'disabled'
    if state != 'disabled':
        if not policy:
            module.fail_json(msg='policy is required if state is not \'disabled\'')
    else:
        if not policy:
            policy = config_policy

    # check changed values and run changes
    if policy != runtime_policy:
        if module.check_mode:
            module.exit_json(changed=True)
        # cannot change runtime policy
        msgs.append('reboot to change the loaded policy')
        changed = True

    if policy != config_policy:
        if module.check_mode:
            module.exit_json(changed=True)
        msgs.append('config policy changed from \'%s\' to \'%s\'' % (config_policy, policy))
        set_config_policy(policy, configfile)
        changed = True

    if state != runtime_state:
        if module.check_mode:
            module.exit_json(changed=True)
        if runtime_enabled:
            if state == 'disabled':
                if runtime_state != 'permissive':
                    # Temporarily set state to permissive
                    set_state(module, 'permissive')
                    msgs.append('runtime state temporarily changed from \'%s\' to \'permissive\', state change will take effect next reboot' % (runtime_state))
                else:
                    msgs.append('state change will take effect next reboot')
            else:
                set_state(module, state)
                msgs.append('runtime state changed from \'%s\' to \'%s\'' % (runtime_state, state))
        else:
            msgs.append('state change will take effect next reboot')
        changed = True

    if state != config_state:
        if module.check_mode:
            module.exit_json(changed=True)
        msgs.append('config state changed from \'%s\' to \'%s\'' % (config_state, state))
        set_config_state(state, configfile)
        changed = True

    module.exit_json(changed=changed, msg=', '.join(msgs), configfile=configfile, policy=policy, state=state)
Beispiel #30
0
    group = parser.add_mutually_exclusive_group(required=True)
    group.add_argument('-a', "--all", dest="all", default=False,
                       action="store_true",
                       help=("Run all semanage unit tests"))
    group.add_argument('-l', "--list", dest="list", default=False,
                       action="store_true",
                       help=("List all semanage unit tests"))
    group.add_argument('-t', "--test", dest="test", default=[],
                       action=CheckTest, nargs="*",
                       help=("Run selected semanage unit test(s)"))
    group.set_defaults(func=semanage_args)

if __name__ == "__main__":
    import selinux
    semanage_test_list = filter(lambda x: x.startswith("test_"), dir(SemanageTests))
    if selinux.security_getenforce() == 1:
        parser = argparse.ArgumentParser(description='Semanage unit test script')
        gen_semanage_test_args(parser)
        try:
            args = parser.parse_args()
            args.func(args)
            sys.exit(0)
        except ValueError as e:
            sys.stderr.write("%s: %s\n" % (e.__class__.__name__, str(e)))
            sys.exit(1)
        except IOError as e:
            sys.stderr.write("%s: %s\n" % (e.__class__.__name__, str(e)))
            sys.exit(1)
        except KeyboardInterrupt:
            sys.exit(0)
    else:
Beispiel #31
0
    def run(self, dbo, product, version, release, variant="", bugurl="",
            isfinal=False, workdir=None, outputdir=None, buildarch=None, volid=None,
            domacboot=True, doupgrade=True, remove_temp=False,
            installpkgs=None, excludepkgs=None,
            size=2,
            add_templates=None,
            add_template_vars=None,
            add_arch_templates=None,
            add_arch_template_vars=None,
            verify=True):

        assert self._configured

        installpkgs = installpkgs or []
        excludepkgs = excludepkgs or []

        if domacboot:
            try:
                runcmd(["rpm", "-q", "hfsplus-tools"])
            except CalledProcessError:
                logger.critical("you need to install hfsplus-tools to create mac images")
                sys.exit(1)

        # set up work directory
        self.workdir = workdir or tempfile.mkdtemp(prefix="pylorax.work.")
        if not os.path.isdir(self.workdir):
            os.makedirs(self.workdir)

        # set up log directory
        logdir = self.conf.get("lorax", "logdir")
        if not os.path.isdir(logdir):
            os.makedirs(logdir)

        self.init_stream_logging()
        self.init_file_logging(logdir)

        logger.debug("version is %s", vernum)
        logger.debug("using work directory %s", self.workdir)
        logger.debug("using log directory %s", logdir)

        # set up output directory
        self.outputdir = outputdir or tempfile.mkdtemp(prefix="pylorax.out.")
        if not os.path.isdir(self.outputdir):
            os.makedirs(self.outputdir)
        logger.debug("using output directory %s", self.outputdir)

        # do we have root privileges?
        logger.info("checking for root privileges")
        if not os.geteuid() == 0:
            logger.critical("no root privileges")
            sys.exit(1)

        # is selinux disabled?
        # With selinux in enforcing mode the rpcbind package required for
        # dracut nfs module, which is in turn required by anaconda module,
        # will not get installed, because it's preinstall scriptlet fails,
        # resulting in an incomplete initial ramdisk image.
        # The reason is that the scriptlet runs tools from the shadow-utils
        # package in chroot, particularly groupadd and useradd to add the
        # required rpc group and rpc user. This operation fails, because
        # the selinux context on files in the chroot, that the shadow-utils
        # tools need to access (/etc/group, /etc/passwd, /etc/shadow etc.),
        # is wrong and selinux therefore disallows access to these files.
        logger.info("checking the selinux mode")
        if selinux.is_selinux_enabled() and selinux.security_getenforce():
            logger.critical("selinux must be disabled or in Permissive mode")
            sys.exit(1)

        # do we have a proper dnf base object?
        logger.info("checking dnf base object")
        if not isinstance(dbo, dnf.Base):
            logger.critical("no dnf base object")
            sys.exit(1)
        self.inroot = dbo.conf.installroot
        logger.debug("using install root: %s", self.inroot)

        if not buildarch:
            buildarch = get_buildarch(dbo)

        logger.info("setting up build architecture")
        self.arch = ArchData(buildarch)
        for attr in ('buildarch', 'basearch', 'libdir'):
            logger.debug("self.arch.%s = %s", attr, getattr(self.arch,attr))

        logger.info("setting up build parameters")
        self.product = DataHolder(name=product, version=version, release=release,
                                 variant=variant, bugurl=bugurl, isfinal=isfinal)
        logger.debug("product data: %s", self.product)

        # NOTE: if you change isolabel, you need to change pungi to match, or
        # the pungi images won't boot.
        isolabel = volid or "%s-%s-%s" % (self.product.name, self.product.version, self.arch.basearch)

        if len(isolabel) > 32:
            logger.fatal("the volume id cannot be longer than 32 characters")
            sys.exit(1)

        # NOTE: rb.root = dbo.conf.installroot (== self.inroot)
        rb = RuntimeBuilder(product=self.product, arch=self.arch,
                            dbo=dbo, templatedir=self.templatedir,
                            installpkgs=installpkgs,
                            excludepkgs=excludepkgs,
                            add_templates=add_templates,
                            add_template_vars=add_template_vars)

        logger.info("installing runtime packages")
        rb.install()

        # write .buildstamp
        buildstamp = BuildStamp(self.product.name, self.product.version,
                                self.product.bugurl, self.product.isfinal, self.arch.buildarch)

        buildstamp.write(joinpaths(self.inroot, ".buildstamp"))

        if self.debug:
            rb.writepkglists(joinpaths(logdir, "pkglists"))
            rb.writepkgsizes(joinpaths(logdir, "original-pkgsizes.txt"))

        logger.info("doing post-install configuration")
        rb.postinstall()

        # write .discinfo
        discinfo = DiscInfo(self.product.release, self.arch.basearch)
        discinfo.write(joinpaths(self.outputdir, ".discinfo"))

        logger.info("backing up installroot")
        installroot = joinpaths(self.workdir, "installroot")
        linktree(self.inroot, installroot)

        logger.info("generating kernel module metadata")
        rb.generate_module_data()

        logger.info("cleaning unneeded files")
        rb.cleanup()

        if verify:
            logger.info("verifying the installroot")
            if not rb.verify():
                sys.exit(1)
        else:
            logger.info("Skipping verify")

        if self.debug:
            rb.writepkgsizes(joinpaths(logdir, "final-pkgsizes.txt"))

        logger.info("creating the runtime image")
        runtime = "images/install.img"
        compression = self.conf.get("compression", "type")
        compressargs = self.conf.get("compression", "args").split()     # pylint: disable=no-member
        if self.conf.getboolean("compression", "bcj"):
            if self.arch.bcj:
                compressargs += ["-Xbcj", self.arch.bcj]
            else:
                logger.info("no BCJ filter for arch %s", self.arch.basearch)
        rb.create_runtime(joinpaths(installroot,runtime),
                          compression=compression, compressargs=compressargs,
                          size=size)
        rb.finished()

        logger.info("preparing to build output tree and boot images")
        treebuilder = TreeBuilder(product=self.product, arch=self.arch,
                                  inroot=installroot, outroot=self.outputdir,
                                  runtime=runtime, isolabel=isolabel,
                                  domacboot=domacboot, doupgrade=doupgrade,
                                  templatedir=self.templatedir,
                                  add_templates=add_arch_templates,
                                  add_template_vars=add_arch_template_vars,
                                  workdir=self.workdir)

        logger.info("rebuilding initramfs images")
        dracut_args = ["--xz", "--install", "/.buildstamp", "--no-early-microcode", "--add", "fips"]
        anaconda_args = dracut_args + ["--add", "anaconda pollcdrom qemu qemu-net"]

        # ppc64 cannot boot an initrd > 32MiB so remove some drivers
        if self.arch.basearch in ("ppc64", "ppc64le"):
            dracut_args.extend(["--omit-drivers", REMOVE_PPC64_DRIVERS])

            # Only omit dracut modules from the initrd so that they're kept for
            # upgrade.img
            anaconda_args.extend(["--omit", REMOVE_PPC64_MODULES])

        treebuilder.rebuild_initrds(add_args=anaconda_args)

        logger.info("populating output tree and building boot images")
        treebuilder.build()

        # write .treeinfo file and we're done
        treeinfo = TreeInfo(self.product.name, self.product.version,
                            self.product.variant, self.arch.basearch)
        for section, data in treebuilder.treeinfo_data.items():
            treeinfo.add_section(section, data)
        treeinfo.write(joinpaths(self.outputdir, ".treeinfo"))

        # cleanup
        if remove_temp:
            remove(self.workdir)
Beispiel #32
0
    def exit_spoke(self, hubName="INSTALLATION SUMMARY", node=None):
        """Leave a spoke by clicking the Done button in the upper left corner,
           then verify we have returned to the proper hub.  Since most spokes
           are off the summary hub, that's the default.  If we are not back
           on the hub, the current test case will be failed.
        """
        button = self.find("_Done", "push button", node=node)
        self.assertIsNotNone(button, msg="Done button not found")
        button.click()
        doDelay(5)
        self.check_window_displayed(hubName)


@unittest.skipIf(os.geteuid() != 0, "GUI tests must be run as root")
@unittest.skipIf(os.environ.get("DISPLAY", "") == "", "DISPLAY must be defined")
@unittest.skipIf(selinux.is_selinux_enabled() and selinux.security_getenforce() == 1, "SELinux must be disabled or in Permissive mode, see rhbz#1276376")
@unittest.skipIf(not isA11yEnabled(), "Assistive Technologies are disabled")
class DogtailTestCase(unittest.TestCase):
    """A subclass that defines all the parameters for starting a local
       copy of anaconda, inspecting results, and managing temporary data!

       Most subclasses will only need to define the following four attributes:

       drives       -- A list of tuples describing disk images to create.  Each
                       tuple is the name of the drive and its size as a blivet.Size.
       environ      -- A dictionary of environment variables that should be added
                       to the environment the test suite will run under.
       name         -- A unique string that names the test.  This name will
                       be used in creating the results directory (and perhaps
                       other places in the future) so make sure it doesn't
                       conflict with another object.
Beispiel #33
0
    def __init__(self, hostInfo):
        cpuInfo = read_cpuinfo()
        memory = read_memory()
        self.UUID = getUUID()
        self.os = Gate().process('distro', software.read_os(), WITHHELD_MAGIC_STRING)
        self.defaultRunlevel = Gate().process('run_level', software.read_runlevel(), -1)
        self.bogomips = Gate().process('cpu', cpuInfo['bogomips'], 0)
        self.cpuVendor = Gate().process('cpu', cpuInfo['type'], WITHHELD_MAGIC_STRING)
        self.cpuModel = Gate().process('cpu', cpuInfo['model'], WITHHELD_MAGIC_STRING)
        self.cpu_stepping = Gate().process('cpu', cpuInfo['cpu_stepping'], 0)
        self.cpu_family = Gate().process('cpu', cpuInfo['cpu_family'], 0)
        self.cpu_model_num = Gate().process('cpu', cpuInfo['cpu_model_num'], 0)
        self.numCpus = Gate().process('cpu', cpuInfo['count'], 0)
        self.cpuSpeed = Gate().process('cpu', cpuInfo['speed'], 0)
        self.systemMemory = Gate().process('ram_size', memory['ram'], 0)
        self.systemSwap = Gate().process('swap_size', memory['swap'], 0)
        self.kernelVersion = Gate().process('kernel', os.uname()[2], WITHHELD_MAGIC_STRING)
        if Gate().grants('language'):
            try:
                self.language = os.environ['LANG']
            except KeyError:
                self.language = 'Unknown'
        else:
            self.language = WITHHELD_MAGIC_STRING

        try:
            tempform = hostInfo['system.kernel.machine']
        except KeyError:
            tempform = 'Unknown'
        self.platform = Gate().process('arch', tempform, WITHHELD_MAGIC_STRING)

        if Gate().grants('vendor'):
            self.systemVendor = hostInfo.get('system.vendor')
            if not self.systemVendor:
                self.systemVendor = hostInfo.get('system.hardware.vendor')
            if not self.systemVendor:
                self.systemVendor = 'Unknown'
        else:
            self.systemVendor = WITHHELD_MAGIC_STRING

        if Gate().grants('model'):
            self.systemModel = hostInfo.get('system.product')
            if not self.systemModel:
                self.systemModel = hostInfo.get('system.hardware.product')
                if hostInfo.get('system.hardware.version'):
                    self.systemModel += ' ' + hostInfo.get('system.hardware.version')
            if not self.systemModel:
                self.systemModel = 'Unknown'
        else:
            self.systemModel = WITHHELD_MAGIC_STRING

        if Gate().grants('form_factor'):
            try:
                self.formfactor = hostInfo['system.formfactor']
            except:
                self.formfactor = 'Unknown'
        else:
            self.formfactor = WITHHELD_MAGIC_STRING

        if tempform == 'ppc64':
            if hostInfo.get('openfirmware.model'):
                if hostInfo['openfirmware.model'][:3] == 'IBM':
                    self.systemVendor = 'IBM'
                model = hostInfo['openfirmware.model'][4:8]

                model_map = {
                    '8842':'JS20',
                    '6779':'JS21',
                    '6778':'JS21',
                    '7988':'JS21',
                    '8844':'JS21',
                    '0200':'QS20',
                    '0792':'QS21',
                }
                try:
                    model_name = model_map[model]
                    self.systemModel = Gate().process('model', model_name)
                    self.formfactor = Gate().process('form_factor', 'Blade')
                except KeyError:
                    pass

        if Gate().grants('selinux'):
            try:
                import selinux
                try:
                    if selinux.is_selinux_enabled() == 1:
                        self.selinux_enabled = SELINUX_ENABLED
                    else:
                        self.selinux_enabled = SELINUX_DISABLED
                except:
                    self.selinux_enabled = SELINUX_DISABLED
                try:
                    self.selinux_policy = selinux.selinux_getpolicytype()[1]
                except:
                    self.selinux_policy = "Unknown"
                try:
                    enforce = selinux.security_getenforce()
                    if enforce == 0:
                        self.selinux_enforce = "Permissive"
                    elif enforce == 1:
                        self.selinux_enforce = "Enforcing"
                    elif enforce == -1:
                        self.selinux_enforce = "Disabled"
                    else:
                        self.selinux_enforce = "FUBARD"
                except:
                    self.selinux_enforce = "Unknown"
            except ImportError:
                self.selinux_enabled = SELINUX_DISABLED
                self.selinux_policy = "Not Installed"
                self.selinux_enforce = "Not Installed"
        else:
            self.selinux_enabled = SELINUX_WITHHELD
            self.selinux_policy = WITHHELD_MAGIC_STRING
            self.selinux_enforce = WITHHELD_MAGIC_STRING
Beispiel #34
0
    def __init__(self, gate, uuid):
        cpuInfo = read_cpuinfo()
        memory = read_memory()
        self.UUID = uuid
        self.os = gate.process('distro', software.read_os(),
                               WITHHELD_MAGIC_STRING)
        self.defaultRunlevel = gate.process('run_level',
                                            software.read_runlevel(), -1)

        self.bogomips = gate.process('cpu', cpuInfo.get('bogomips', 0), 0)
        self.cpuVendor = gate.process('cpu', cpuInfo.get('type', ''),
                                      WITHHELD_MAGIC_STRING)
        self.cpuModel = gate.process('cpu', cpuInfo.get('model', ''),
                                     WITHHELD_MAGIC_STRING)
        self.cpu_stepping = gate.process('cpu', cpuInfo.get('cpu_stepping', 0),
                                         0)
        self.cpu_family = gate.process('cpu', cpuInfo.get('cpu_family', ''),
                                       '')
        self.cpu_model_num = gate.process('cpu',
                                          cpuInfo.get('cpu_model_num', 0), 0)
        self.numCpus = gate.process('cpu', cpuInfo.get('count', 0), 0)
        self.cpuSpeed = gate.process('cpu', cpuInfo.get('speed', 0), 0)

        self.systemMemory = gate.process('ram_size', memory['ram'], 0)
        self.systemSwap = gate.process('swap_size', memory['swap'], 0)
        self.kernelVersion = gate.process('kernel',
                                          os.uname()[2], WITHHELD_MAGIC_STRING)
        if gate.grants('language'):
            try:
                self.language = os.environ['LANG']
            except KeyError:
                try:
                    status, lang = commands.getstatusoutput(
                        "grep LANG /etc/sysconfig/i18n")
                    if status == 0:
                        self.language = lang.split('"')[1]
                    else:
                        self.language = 'Unknown'
                except:
                    self.language = 'Unknown'
        else:
            self.language = WITHHELD_MAGIC_STRING

        tempform = platform.machine()
        self.platform = gate.process('arch', tempform, WITHHELD_MAGIC_STRING)

        if gate.grants('vendor'):
            #self.systemVendor = hostInfo.get('system.vendor'
            try:
                self.systemVendor = cat(
                    '/sys/devices/virtual/dmi/id/sys_vendor')[0].strip()
            except:
                self.systemVendor = 'Unknown'
        else:
            self.systemVendor = WITHHELD_MAGIC_STRING

        if gate.grants('model'):
            try:
                self.systemModel = cat(
                    '/sys/devices/virtual/dmi/id/product_name'
                )[0].strip() + ' ' + cat(
                    '/sys/devices/virtual/dmi/id/product_version')[0].strip()
            except:
                self.systemModel = 'Unknown'
            #hostInfo was removed with the hal restructure
            #if not self.systemModel:
            #self.systemModel = hostInfo.get('system.hardware.product')
            #if hostInfo.get('system.hardware.version'):
            #self.systemModel += ' ' + hostInfo.get('system.hardware.version')
            #if not self.systemModel:
            #self.systemModel = 'Unknown'
        else:
            self.systemModel = WITHHELD_MAGIC_STRING

        if gate.grants('form_factor'):
            try:
                formfactor_id = int(
                    cat('/sys/devices/virtual/dmi/id/chassis_type')[0].strip())
                self.formfactor = FORMFACTOR_LIST[formfactor_id]
            except:
                self.formfactor = 'Unknown'
        else:
            self.formfactor = WITHHELD_MAGIC_STRING

        if tempform == 'ppc64':
            if hostInfo.get('openfirmware.model'):
                if hostInfo['openfirmware.model'][:3] == 'IBM':
                    self.systemVendor = 'IBM'
                model = hostInfo['openfirmware.model'][4:8]

                model_map = {
                    '8842': 'JS20',
                    '6779': 'JS21',
                    '6778': 'JS21',
                    '7988': 'JS21',
                    '8844': 'JS21',
                    '0200': 'QS20',
                    '0792': 'QS21',
                }
                try:
                    model_name = model_map[model]
                    self.systemModel = gate.process('model', model_name)
                    self.formfactor = gate.process('form_factor', 'Blade')
                except KeyError:
                    pass

        if gate.grants('selinux'):
            try:
                import selinux
                try:
                    if selinux.is_selinux_enabled() == 1:
                        self.selinux_enabled = SELINUX_ENABLED
                    else:
                        self.selinux_enabled = SELINUX_DISABLED
                except:
                    self.selinux_enabled = SELINUX_DISABLED
                try:
                    self.selinux_policy = selinux.selinux_getpolicytype()[1]
                except:
                    self.selinux_policy = "Unknown"
                try:
                    enforce = selinux.security_getenforce()
                    if enforce == 0:
                        self.selinux_enforce = "Permissive"
                    elif enforce == 1:
                        self.selinux_enforce = "Enforcing"
                    elif enforce == -1:
                        self.selinux_enforce = "Disabled"
                    else:
                        self.selinux_enforce = "FUBARD"
                except:
                    self.selinux_enforce = "Unknown"
            except ImportError:
                self.selinux_enabled = SELINUX_DISABLED
                self.selinux_policy = "Not Installed"
                self.selinux_enforce = "Not Installed"
        else:
            self.selinux_enabled = SELINUX_WITHHELD
            self.selinux_policy = WITHHELD_MAGIC_STRING
            self.selinux_enforce = WITHHELD_MAGIC_STRING
Beispiel #35
0
    def run(self,
            dbo,
            product,
            version,
            release,
            variant="",
            bugurl="",
            isfinal=False,
            workdir=None,
            outputdir=None,
            buildarch=None,
            volid=None,
            domacboot=True,
            doupgrade=True,
            remove_temp=False,
            installpkgs=None,
            excludepkgs=None,
            size=2,
            add_templates=None,
            add_template_vars=None,
            add_arch_templates=None,
            add_arch_template_vars=None,
            verify=True):

        assert self._configured

        installpkgs = installpkgs or []
        excludepkgs = excludepkgs or []

        if domacboot:
            try:
                runcmd(["rpm", "-q", "hfsplus-tools"])
            except CalledProcessError:
                logger.critical(
                    "you need to install hfsplus-tools to create mac images")
                sys.exit(1)

        # set up work directory
        self.workdir = workdir or tempfile.mkdtemp(prefix="pylorax.work.")
        if not os.path.isdir(self.workdir):
            os.makedirs(self.workdir)

        # set up log directory
        logdir = self.conf.get("lorax", "logdir")
        if not os.path.isdir(logdir):
            os.makedirs(logdir)

        self.init_stream_logging()
        self.init_file_logging(logdir)

        logger.debug("version is %s", vernum)
        logger.debug("using work directory %s", self.workdir)
        logger.debug("using log directory %s", logdir)

        # set up output directory
        self.outputdir = outputdir or tempfile.mkdtemp(prefix="pylorax.out.")
        if not os.path.isdir(self.outputdir):
            os.makedirs(self.outputdir)
        logger.debug("using output directory %s", self.outputdir)

        # do we have root privileges?
        logger.info("checking for root privileges")
        if not os.geteuid() == 0:
            logger.critical("no root privileges")
            sys.exit(1)

        # is selinux disabled?
        # With selinux in enforcing mode the rpcbind package required for
        # dracut nfs module, which is in turn required by anaconda module,
        # will not get installed, because it's preinstall scriptlet fails,
        # resulting in an incomplete initial ramdisk image.
        # The reason is that the scriptlet runs tools from the shadow-utils
        # package in chroot, particularly groupadd and useradd to add the
        # required rpc group and rpc user. This operation fails, because
        # the selinux context on files in the chroot, that the shadow-utils
        # tools need to access (/etc/group, /etc/passwd, /etc/shadow etc.),
        # is wrong and selinux therefore disallows access to these files.
        logger.info("checking the selinux mode")
        if selinux.is_selinux_enabled() and selinux.security_getenforce():
            logger.critical("selinux must be disabled or in Permissive mode")
            sys.exit(1)

        # do we have a proper dnf base object?
        logger.info("checking dnf base object")
        if not isinstance(dbo, dnf.Base):
            logger.critical("no dnf base object")
            sys.exit(1)
        self.inroot = dbo.conf.installroot
        logger.debug("using install root: %s", self.inroot)

        if not buildarch:
            buildarch = get_buildarch(dbo)

        logger.info("setting up build architecture")
        self.arch = ArchData(buildarch)
        for attr in ('buildarch', 'basearch', 'libdir'):
            logger.debug("self.arch.%s = %s", attr, getattr(self.arch, attr))

        logger.info("setting up build parameters")
        self.product = DataHolder(name=product,
                                  version=version,
                                  release=release,
                                  variant=variant,
                                  bugurl=bugurl,
                                  isfinal=isfinal)
        logger.debug("product data: %s", self.product)

        # NOTE: if you change isolabel, you need to change pungi to match, or
        # the pungi images won't boot.
        isolabel = volid or "%s-%s-%s" % (
            self.product.name, self.product.version, self.arch.basearch)

        if len(isolabel) > 32:
            logger.fatal("the volume id cannot be longer than 32 characters")
            sys.exit(1)

        # NOTE: rb.root = dbo.conf.installroot (== self.inroot)
        rb = RuntimeBuilder(product=self.product,
                            arch=self.arch,
                            dbo=dbo,
                            templatedir=self.templatedir,
                            installpkgs=installpkgs,
                            excludepkgs=excludepkgs,
                            add_templates=add_templates,
                            add_template_vars=add_template_vars)

        logger.info("installing runtime packages")
        rb.install()

        # write .buildstamp
        buildstamp = BuildStamp(self.product.name, self.product.version,
                                self.product.bugurl, self.product.isfinal,
                                self.arch.buildarch, self.product.variant)

        buildstamp.write(joinpaths(self.inroot, ".buildstamp"))

        if self.debug:
            rb.writepkglists(joinpaths(logdir, "pkglists"))
            rb.writepkgsizes(joinpaths(logdir, "original-pkgsizes.txt"))

        logger.info("doing post-install configuration")
        rb.postinstall()

        # write .discinfo
        discinfo = DiscInfo(self.product.release, self.arch.basearch)
        discinfo.write(joinpaths(self.outputdir, ".discinfo"))

        logger.info("backing up installroot")
        installroot = joinpaths(self.workdir, "installroot")
        linktree(self.inroot, installroot)

        logger.info("generating kernel module metadata")
        rb.generate_module_data()

        logger.info("cleaning unneeded files")
        rb.cleanup()

        if verify:
            logger.info("verifying the installroot")
            if not rb.verify():
                sys.exit(1)
        else:
            logger.info("Skipping verify")

        if self.debug:
            rb.writepkgsizes(joinpaths(logdir, "final-pkgsizes.txt"))

        logger.info("creating the runtime image")
        runtime = "images/install.img"
        compression = self.conf.get("compression", "type")
        compressargs = self.conf.get("compression", "args").split()  # pylint: disable=no-member
        if self.conf.getboolean("compression", "bcj"):
            if self.arch.bcj:
                compressargs += ["-Xbcj", self.arch.bcj]
            else:
                logger.info("no BCJ filter for arch %s", self.arch.basearch)
        rb.create_runtime(joinpaths(installroot, runtime),
                          compression=compression,
                          compressargs=compressargs,
                          size=size)
        rb.finished()

        logger.info("preparing to build output tree and boot images")
        treebuilder = TreeBuilder(product=self.product,
                                  arch=self.arch,
                                  inroot=installroot,
                                  outroot=self.outputdir,
                                  runtime=runtime,
                                  isolabel=isolabel,
                                  domacboot=domacboot,
                                  doupgrade=doupgrade,
                                  templatedir=self.templatedir,
                                  add_templates=add_arch_templates,
                                  add_template_vars=add_arch_template_vars,
                                  workdir=self.workdir)

        logger.info("rebuilding initramfs images")
        dracut_args = [
            "--xz", "--install", "/.buildstamp", "--no-early-microcode",
            "--add", "fips"
        ]
        anaconda_args = dracut_args + [
            "--add", "anaconda pollcdrom qemu qemu-net"
        ]

        # ppc64 cannot boot an initrd > 32MiB so remove some drivers
        if self.arch.basearch in ("ppc64", "ppc64le"):
            dracut_args.extend(["--omit-drivers", REMOVE_PPC64_DRIVERS])

            # Only omit dracut modules from the initrd so that they're kept for
            # upgrade.img
            anaconda_args.extend(["--omit", REMOVE_PPC64_MODULES])

        treebuilder.rebuild_initrds(add_args=anaconda_args)

        logger.info("populating output tree and building boot images")
        treebuilder.build()

        # write .treeinfo file and we're done
        treeinfo = TreeInfo(self.product.name, self.product.version,
                            self.product.variant, self.arch.basearch)
        for section, data in treebuilder.treeinfo_data.items():
            treeinfo.add_section(section, data)
        treeinfo.write(joinpaths(self.outputdir, ".treeinfo"))

        # cleanup
        if remove_temp:
            remove(self.workdir)
Beispiel #36
0
    def run(self, ybo, product, version, release, variant="", bugurl="",
            isfinal=False, workdir=None, outputdir=None, buildarch=None, volid=None,
            domacboot=False, doupgrade=True, remove_temp=False):

        assert self._configured

        # get lorax version
        try:
            import pylorax.version
        except ImportError:
            vernum = "devel"
        else:
            vernum = pylorax.version.num

        if domacboot:
            try:
                runcmd(["rpm", "-q", "hfsplus-tools"])
            except CalledProcessError:
                logger.critical("you need to install hfsplus-tools to create mac images")
                sys.exit(1)

        # set up work directory
        self.workdir = workdir or tempfile.mkdtemp(prefix="pylorax.work.")
        if not os.path.isdir(self.workdir):
            os.makedirs(self.workdir)

        # set up log directory
        logdir = '/var/log/lorax'
        if not os.path.isdir(logdir):
            os.makedirs(logdir)

        self.init_stream_logging()
        self.init_file_logging(logdir)

        logger.debug("version is {0}".format(vernum))
        logger.debug("using work directory {0.workdir}".format(self))
        logger.debug("using log directory {0}".format(logdir))

        # set up output directory
        self.outputdir = outputdir or tempfile.mkdtemp(prefix="pylorax.out.")
        if not os.path.isdir(self.outputdir):
            os.makedirs(self.outputdir)
        logger.debug("using output directory {0.outputdir}".format(self))

        # do we have root privileges?
        logger.info("checking for root privileges")
        if not os.geteuid() == 0:
            logger.critical("no root privileges")
            sys.exit(1)

        # is selinux disabled?
        # With selinux in enforcing mode the rpcbind package required for
        # dracut nfs module, which is in turn required by anaconda module,
        # will not get installed, because it's preinstall scriptlet fails,
        # resulting in an incomplete initial ramdisk image.
        # The reason is that the scriptlet runs tools from the shadow-utils
        # package in chroot, particularly groupadd and useradd to add the
        # required rpc group and rpc user. This operation fails, because
        # the selinux context on files in the chroot, that the shadow-utils
        # tools need to access (/etc/group, /etc/passwd, /etc/shadow etc.),
        # is wrong and selinux therefore disallows access to these files.
        logger.info("checking the selinux mode")
        if selinux.is_selinux_enabled() and selinux.security_getenforce():
            logger.critical("selinux must be disabled or in Permissive mode")
            sys.exit(1)

        # do we have a proper yum base object?
        logger.info("checking yum base object")
        if not isinstance(ybo, yum.YumBase):
            logger.critical("no yum base object")
            sys.exit(1)
        self.inroot = ybo.conf.installroot
        logger.debug("using install root: {0}".format(self.inroot))

        if not buildarch:
            buildarch = get_buildarch(ybo)

        logger.info("setting up build architecture")
        self.arch = ArchData(buildarch)
        for attr in ('buildarch', 'basearch', 'libdir'):
            logger.debug("self.arch.%s = %s", attr, getattr(self.arch,attr))

        logger.info("setting up build parameters")
        product = DataHolder(name=product, version=version, release=release,
                             variant=variant, bugurl=bugurl, isfinal=isfinal)
        self.product = product
        logger.debug("product data: %s" % product)

        # NOTE: if you change isolabel, you need to change pungi to match, or
        # the pungi images won't boot.
        isolabel = volid or "{0.name} {0.version} {1.basearch}".format(self.product,
                                                                       self.arch)

        if len(isolabel) > 32:
            logger.fatal("the volume id cannot be longer than 32 characters")
            sys.exit(1)

        templatedir = self.conf.get("lorax", "sharedir")
        # NOTE: rb.root = ybo.conf.installroot (== self.inroot)
        rb = RuntimeBuilder(product=self.product, arch=self.arch,
                            yum=ybo, templatedir=templatedir)

        logger.info("installing runtime packages")
        rb.yum.conf.skip_broken = self.conf.getboolean("yum", "skipbroken")
        rb.install()

        # write .buildstamp
        buildstamp = BuildStamp(self.product.name, self.product.version,
                                self.product.bugurl, self.product.isfinal, self.arch.buildarch)

        buildstamp.write(joinpaths(self.inroot, ".buildstamp"))

        if self.debug:
            rb.writepkglists(joinpaths(logdir, "pkglists"))
            rb.writepkgsizes(joinpaths(logdir, "original-pkgsizes.txt"))

        logger.info("doing post-install configuration")
        rb.postinstall()

        # write .discinfo
        discinfo = DiscInfo(self.product.release, self.arch.basearch)
        discinfo.write(joinpaths(self.outputdir, ".discinfo"))

        logger.info("backing up installroot")
        installroot = joinpaths(self.workdir, "installroot")
        linktree(self.inroot, installroot)

        logger.info("generating kernel module metadata")
        rb.generate_module_data()

        logger.info("cleaning unneeded files")
        rb.cleanup()

        if self.debug:
            rb.writepkgsizes(joinpaths(logdir, "final-pkgsizes.txt"))

        logger.info("creating the runtime image")
        runtime = "images/install.img"
        compression = self.conf.get("compression", "type")
        compressargs = self.conf.get("compression", "args").split()
        if self.conf.getboolean("compression", "bcj"):
            if self.arch.bcj:
                compressargs += ["-Xbcj", self.arch.bcj]
            else:
                logger.info("no BCJ filter for arch %s", self.arch.basearch)
        rb.create_runtime(joinpaths(installroot,runtime),
                          compression=compression, compressargs=compressargs)

        logger.info("preparing to build output tree and boot images")
        treebuilder = TreeBuilder(product=self.product, arch=self.arch,
                                  inroot=installroot, outroot=self.outputdir,
                                  runtime=runtime, isolabel=isolabel,
                                  domacboot=domacboot, doupgrade=doupgrade,
                                  templatedir=templatedir)

        logger.info("rebuilding initramfs images")
        dracut_args = ["--xz", "--install", "/.buildstamp"]
        anaconda_args = dracut_args + ["--add", "anaconda pollcdrom"]

        # ppc64 cannot boot an initrd > 32MiB so remove some drivers
        if self.arch.basearch in ("ppc64", "ppc64le"):
            dracut_args.extend(["--omit-drivers", REMOVE_PPC64_DRIVERS])

            # Only omit dracut modules from the initrd so that they're kept for
            # upgrade.img
            anaconda_args.extend(["--omit", REMOVE_PPC64_MODULES])

        treebuilder.rebuild_initrds(add_args=anaconda_args)

        if doupgrade:
            # Build upgrade.img. It'd be nice if these could coexist in the same
            # image, but that would increase the size of the anaconda initramfs,
            # which worries some people (esp. PPC tftpboot). So they're separate.
            try:
                # If possible, use the 'redhat-upgrade-tool' plymouth theme
                themes = runcmd_output(['plymouth-set-default-theme', '--list'],
                                       root=installroot)
                if 'redhat-upgrade-tool' in themes.splitlines():
                    os.environ['PLYMOUTH_THEME_NAME'] = 'redhat-upgrade-tool'
            except RuntimeError:
                pass
            upgrade_args = dracut_args + ["--add", "system-upgrade convertfs"]
            treebuilder.rebuild_initrds(add_args=upgrade_args, prefix="upgrade")

        logger.info("populating output tree and building boot images")
        treebuilder.build()

        # write .treeinfo file and we're done
        treeinfo = TreeInfo(self.product.name, self.product.version,
                            self.product.variant, self.arch.basearch)
        for section, data in treebuilder.treeinfo_data.items():
            treeinfo.add_section(section, data)
        treeinfo.write(joinpaths(self.outputdir, ".treeinfo"))

        # cleanup
        if remove_temp:
            remove(self.workdir)
Beispiel #37
0
    def run(self, ybo, product, version, release, variant="", bugurl="",
            isfinal=False, workdir=None, outputdir=None, buildarch=None, volid=None,
            domacboot=False, doupgrade=True, remove_temp=False,
            installpkgs=None,
            ssss=None,
            size=2,
            add_templates=None,
            add_template_vars=None,
            add_arch_templates=None,
            add_arch_template_vars=None,
            template_tempdir=None):

        assert self._configured

        installpkgs = installpkgs or []

        # get lorax version
        try:
            import pylorax.version
        except ImportError:
            vernum = "devel"
        else:
            vernum = pylorax.version.num

        if domacboot:
            try:
                runcmd(["rpm", "-q", "hfsplus-tools"])
            except CalledProcessError:
                logger.critical("you need to install hfsplus-tools to create mac images")
                sys.exit(1)

        # set up work directory
        self.workdir = workdir or tempfile.mkdtemp(prefix="pylorax.work.")
        if not os.path.isdir(self.workdir):
            os.makedirs(self.workdir)

        # set up log directory
        logdir = '/var/log/lorax'
        if not os.path.isdir(logdir):
            os.makedirs(logdir)

        self.init_stream_logging()
        self.init_file_logging(logdir)

        logger.debug("version is {0}".format(vernum))
        logger.debug("using work directory {0.workdir}".format(self))
        logger.debug("using log directory {0}".format(logdir))

        # set up output directory
        self.outputdir = outputdir or tempfile.mkdtemp(prefix="pylorax.out.")
        if not os.path.isdir(self.outputdir):
            os.makedirs(self.outputdir)
        logger.debug("using output directory {0.outputdir}".format(self))

        # do we have root privileges?
        logger.info("checking for root privileges")
        if not os.geteuid() == 0:
            logger.critical("no root privileges")
            sys.exit(1)

        # is selinux disabled?
        # With selinux in enforcing mode the rpcbind package required for
        # dracut nfs module, which is in turn required by anaconda module,
        # will not get installed, because it's preinstall scriptlet fails,
        # resulting in an incomplete initial ramdisk image.
        # The reason is that the scriptlet runs tools from the shadow-utils
        # package in chroot, particularly groupadd and useradd to add the
        # required rpc group and rpc user. This operation fails, because
        # the selinux context on files in the chroot, that the shadow-utils
        # tools need to access (/etc/group, /etc/passwd, /etc/shadow etc.),
        # is wrong and selinux therefore disallows access to these files.
        logger.info("checking the selinux mode")
        if selinux.is_selinux_enabled() and selinux.security_getenforce():
            logger.critical("selinux must be disabled or in Permissive mode")
            sys.exit(1)

        # do we have a proper yum base object?
        logger.info("checking yum base object")
        if not isinstance(ybo, yum.YumBase):
            logger.critical("no yum base object")
            sys.exit(1)
        self.inroot = ybo.conf.installroot
        logger.debug("using install root: {0}".format(self.inroot))

        if not buildarch:
            buildarch = get_buildarch(ybo)

        logger.info("setting up build architecture")
        self.arch = ArchData(buildarch)
        for attr in ('buildarch', 'basearch', 'libdir'):
            logger.debug("self.arch.%s = %s", attr, getattr(self.arch,attr))

        logger.info("setting up build parameters")
        product = DataHolder(name=product, version=version, release=release,
                             variant=variant, bugurl=bugurl, isfinal=isfinal)
        self.product = product
        logger.debug("product data: %s" % product)

        # NOTE: if you change isolabel, you need to change pungi to match, or
        # the pungi images won't boot.
        isolabel = volid or "{0.name} {0.version} {1.basearch}".format(self.product,
                                                                       self.arch)

        if len(isolabel) > 32:
            logger.fatal("the volume id cannot be longer than 32 characters")
            sys.exit(1)

        templatedir = self.conf.get("lorax", "sharedir")
        # NOTE: rb.root = ybo.conf.installroot (== self.inroot)
        rb = RuntimeBuilder(product=self.product, arch=self.arch,
                            yum=ybo, templatedir=templatedir,
                            installpkgs=installpkgs,
                            add_templates=add_templates,
                            add_template_vars=add_template_vars)

        logger.info("installing runtime packages")
        rb.yum.conf.skip_broken = self.conf.getboolean("yum", "skipbroken")
        rb.install()

        # write .buildstamp
        buildstamp = BuildStamp(self.product.name, self.product.version,
                                self.product.bugurl, self.product.isfinal, self.arch.buildarch)

        buildstamp.write(joinpaths(self.inroot, ".buildstamp"))

        if self.debug:
            rb.writepkglists(joinpaths(logdir, "pkglists"))
            rb.writepkgsizes(joinpaths(logdir, "original-pkgsizes.txt"))

        logger.info("doing post-install configuration")
        rb.postinstall()

        # write .discinfo
        discinfo = DiscInfo(self.product.release, self.arch.basearch)
        discinfo.write(joinpaths(self.outputdir, ".discinfo"))

        logger.info("backing up installroot")
        installroot = joinpaths(self.workdir, "installroot")
        linktree(self.inroot, installroot)

        logger.info("generating kernel module metadata")
        rb.generate_module_data()

        logger.info("cleaning unneeded files")
        rb.cleanup()

        if self.debug:
            rb.writepkgsizes(joinpaths(logdir, "final-pkgsizes.txt"))

        logger.info("creating the runtime image")
        runtime = "images/install.img"
        compression = self.conf.get("compression", "type")
        compressargs = self.conf.get("compression", "args").split()
        if self.conf.getboolean("compression", "bcj"):
            if self.arch.bcj:
                compressargs += ["-Xbcj", self.arch.bcj]
            else:
                logger.info("no BCJ filter for arch %s", self.arch.basearch)
        rb.create_runtime(joinpaths(installroot,runtime),
                          compression=compression, compressargs=compressargs)

        logger.info("preparing to build output tree and boot images")
        treebuilder = TreeBuilder(product=self.product, arch=self.arch,
                                  inroot=installroot, outroot=self.outputdir, ssss=ssss,
                                  runtime=runtime, isolabel=isolabel,
                                  domacboot=domacboot, doupgrade=doupgrade,
                                  templatedir=templatedir,
                                  add_templates=add_arch_templates,
                                  add_template_vars=add_arch_template_vars,
                                  workdir=self.workdir)

        logger.info("rebuilding initramfs images")
        dracut_args = ["--xz", "--install", "/.buildstamp", "--no-early-microcode"]
        anaconda_args = dracut_args + ["--add", "anaconda pollcdrom"]

        # ppc64 cannot boot an initrd > 32MiB so remove some drivers
        if self.arch.basearch in ("ppc64", "ppc64le"):
            dracut_args.extend(["--omit-drivers", REMOVE_PPC64_DRIVERS])

            # Only omit dracut modules from the initrd so that they're kept for
            # upgrade.img
            anaconda_args.extend(["--omit", REMOVE_PPC64_MODULES])

        treebuilder.rebuild_initrds(add_args=anaconda_args)

        if doupgrade:
            # Build upgrade.img. It'd be nice if these could coexist in the same
            # image, but that would increase the size of the anaconda initramfs,
            # which worries some people (esp. PPC tftpboot). So they're separate.
            try:
                # If possible, use the 'redhat-upgrade-tool' plymouth theme
                themes = runcmd_output(['plymouth-set-default-theme', '--list'],
                                       root=installroot)
                if 'redhat-upgrade-tool' in themes.splitlines():
                    os.environ['PLYMOUTH_THEME_NAME'] = 'redhat-upgrade-tool'
            except RuntimeError:
                pass
            upgrade_args = dracut_args + ["--add", "system-upgrade convertfs"]
            treebuilder.rebuild_initrds(add_args=upgrade_args, prefix="upgrade")

        logger.info("populating output tree and building boot images")
        treebuilder.build()

        # write .treeinfo file and we're done
        treeinfo = TreeInfo(self.product.name, self.product.version,
                            self.product.variant, self.arch.basearch)
        for section, data in treebuilder.treeinfo_data.items():
            treeinfo.add_section(section, data)
        treeinfo.write(joinpaths(self.outputdir, ".treeinfo"))

        # cleanup
        if remove_temp:
            remove(self.workdir)
Beispiel #38
0
    group = parser.add_mutually_exclusive_group(required=True)
    group.add_argument('-a', "--all", dest="all", default=False,
                        action="store_true",
                        help=("Run all semanage unit tests"))
    group.add_argument('-l', "--list", dest="list", default=False,
                        action="store_true",
                        help=("List all semanage unit tests"))
    group.add_argument('-t', "--test", dest="test", default=[],
                        action=CheckTest, nargs="*",
                        help=("Run selected semanage unit test(s)"))
    group.set_defaults(func=semanage_args)

if __name__ == "__main__":
    import selinux
    semanage_test_list=filter(lambda x: x.startswith("test_"), dir(SemanageTests))
    if selinux.security_getenforce() == 1:
        parser = argparse.ArgumentParser(description='Semanage unit test script')
        gen_semanage_test_args(parser)
        try:
            args = parser.parse_args()
            args.func(args)
            sys.exit(0)
        except ValueError,e:
            sys.stderr.write("%s: %s\n" % (e.__class__.__name__, str(e)))
            sys.exit(1)
        except IOError,e:
            sys.stderr.write("%s: %s\n" % (e.__class__.__name__, str(e)))
            sys.exit(1)
        except KeyboardInterrupt:
            sys.exit(0)
    else:
Beispiel #39
0
def main():
    module = AnsibleModule(
        argument_spec=dict(
            policy=dict(type='str'),
            state=dict(type='str',
                       required='True',
                       choices=['enforcing', 'permissive', 'disabled']),
            configfile=dict(type='str',
                            default='/etc/selinux/config',
                            aliases=['conf', 'file']),
        ),
        supports_check_mode=True,
    )

    if not HAS_SELINUX:
        module.fail_json(msg=missing_required_lib('libselinux-python'),
                         exception=SELINUX_IMP_ERR)

    # global vars
    changed = False
    msgs = []
    configfile = module.params['configfile']
    policy = module.params['policy']
    state = module.params['state']
    runtime_enabled = selinux.is_selinux_enabled()
    runtime_policy = selinux.selinux_getpolicytype()[1]
    runtime_state = 'disabled'
    reboot_required = False

    if runtime_enabled:
        # enabled means 'enforcing' or 'permissive'
        if selinux.security_getenforce():
            runtime_state = 'enforcing'
        else:
            runtime_state = 'permissive'

    if not os.path.isfile(configfile):
        module.fail_json(msg="Unable to find file {0}".format(configfile),
                         details="Please install SELinux-policy package, "
                         "if this package is not installed previously.")

    config_policy = get_config_policy(configfile)
    config_state = get_config_state(configfile)

    # check to see if policy is set if state is not 'disabled'
    if state != 'disabled':
        if not policy:
            module.fail_json(
                msg="Policy is required if state is not 'disabled'")
    else:
        if not policy:
            policy = config_policy

    # check changed values and run changes
    if policy != runtime_policy:
        if module.check_mode:
            module.exit_json(changed=True)
        # cannot change runtime policy
        msgs.append("Running SELinux policy changed from '%s' to '%s'" %
                    (runtime_policy, policy))
        changed = True

    if policy != config_policy:
        if module.check_mode:
            module.exit_json(changed=True)
        set_config_policy(module, policy, configfile)
        msgs.append(
            "SELinux policy configuration in '%s' changed from '%s' to '%s'" %
            (configfile, config_policy, policy))
        changed = True

    if state != runtime_state:
        if runtime_enabled:
            if state == 'disabled':
                if runtime_state != 'permissive':
                    # Temporarily set state to permissive
                    if not module.check_mode:
                        set_state(module, 'permissive')
                    module.warn(
                        "SELinux state temporarily changed from '%s' to 'permissive'. State change will take effect next reboot."
                        % (runtime_state))
                    changed = True
                else:
                    module.warn(
                        'SELinux state change will take effect next reboot')
                reboot_required = True
            else:
                if not module.check_mode:
                    set_state(module, state)
                msgs.append("SELinux state changed from '%s' to '%s'" %
                            (runtime_state, state))

                # Only report changes if the file is changed.
                # This prevents the task from reporting changes every time the task is run.
                changed = True
        else:
            module.warn("Reboot is required to set SELinux state to '%s'" %
                        state)
            reboot_required = True

    if state != config_state:
        if not module.check_mode:
            set_config_state(module, state, configfile)
        msgs.append("Config SELinux state changed from '%s' to '%s'" %
                    (config_state, state))
        changed = True

    module.exit_json(changed=changed,
                     msg=', '.join(msgs),
                     configfile=configfile,
                     policy=policy,
                     state=state,
                     reboot_required=reboot_required)
def main():

    module = AnsibleModule(argument_spec=dict(
        policy=dict(required=False),
        state=dict(choices=['enforcing', 'permissive', 'disabled'],
                   required=True),
        configfile=dict(aliases=['conf', 'file'],
                        default='/etc/selinux/config')),
                           supports_check_mode=True)

    # global vars
    changed = False
    msgs = []
    configfile = module.params['configfile']
    policy = module.params['policy']
    state = module.params['state']
    runtime_enabled = selinux.is_selinux_enabled()
    runtime_policy = selinux.selinux_getpolicytype()[1]
    runtime_state = 'disabled'
    if (runtime_enabled):
        # enabled means 'enforcing' or 'permissive'
        if (selinux.security_getenforce()):
            runtime_state = 'enforcing'
        else:
            runtime_state = 'permissive'
    config_policy = get_config_policy(configfile)
    config_state = get_config_state(configfile)

    # check to see if policy is set if state is not 'disabled'
    if (state != 'disabled'):
        if not policy:
            module.fail_json(
                msg='policy is required if state is not \'disabled\'')
    else:
        if not policy:
            policy = config_policy

    # check changed values and run changes
    if (policy != runtime_policy):
        if module.check_mode:
            module.exit_json(changed=True)
        # cannot change runtime policy
        msgs.append('reboot to change the loaded policy')
        changed = True

    if (policy != config_policy):
        if module.check_mode:
            module.exit_json(changed=True)
        msgs.append('config policy changed from \'%s\' to \'%s\'' %
                    (config_policy, policy))
        set_config_policy(policy, configfile)
        changed = True

    if (state != runtime_state):
        if module.check_mode:
            module.exit_json(changed=True)
        if (state == 'disabled'):
            msgs.append('state change will take effect next reboot')
        else:
            if (runtime_enabled):
                set_state(state)
                msgs.append('runtime state changed from \'%s\' to \'%s\'' %
                            (runtime_state, state))
            else:
                msgs.append('state change will take effect next reboot')
        changed = True

    if (state != config_state):
        if module.check_mode:
            module.exit_json(changed=True)
        msgs.append('config state changed from \'%s\' to \'%s\'' %
                    (config_state, state))
        set_config_state(state, configfile)
        changed = True

    module.exit_json(changed=changed,
                     msg=', '.join(msgs),
                     configfile=configfile,
                     policy=policy,
                     state=state)
Beispiel #41
0
def main():
    module = AnsibleModule(
        argument_spec=dict(
            policy=dict(required=False),
            state=dict(choices=['enforcing', 'permissive', 'disabled'], required=True),
            configfile=dict(aliases=['conf', 'file'], default='/etc/selinux/config')
        ),
        supports_check_mode=True
    )

    if not HAS_SELINUX:
        module.fail_json(msg='libselinux-python required for this module')

    # global vars
    changed = False
    msgs = []
    configfile = module.params['configfile']
    policy = module.params['policy']
    state = module.params['state']
    runtime_enabled = selinux.is_selinux_enabled()
    runtime_policy = selinux.selinux_getpolicytype()[1]
    runtime_state = 'disabled'
    reboot_required = False

    if runtime_enabled:
        # enabled means 'enforcing' or 'permissive'
        if selinux.security_getenforce():
            runtime_state = 'enforcing'
        else:
            runtime_state = 'permissive'

    if not os.path.isfile(configfile):
        module.fail_json(msg="Unable to find file {0}".format(configfile),
                         details="Please install SELinux-policy package, "
                                 "if this package is not installed previously.")

    config_policy = get_config_policy(configfile)
    config_state = get_config_state(configfile)

    # check to see if policy is set if state is not 'disabled'
    if state != 'disabled':
        if not policy:
            module.fail_json(msg='Policy is required if state is not \'disabled\'')
    else:
        if not policy:
            policy = config_policy

    # check changed values and run changes
    if policy != runtime_policy:
        if module.check_mode:
            module.exit_json(changed=True)
        # cannot change runtime policy
        msgs.append('Running SELinux policy changed from \'%s\' to \'%s\'' % (runtime_policy, policy))
        changed = True

    if policy != config_policy:
        if module.check_mode:
            module.exit_json(changed=True)
        set_config_policy(module, policy, configfile)
        msgs.append('SELinux policy configuration in \'%s\' changed from \'%s\' to \'%s\'' % (configfile, config_policy, policy))
        changed = True

    if state != runtime_state:
        if module.check_mode:
            module.exit_json(changed=True)
        if runtime_enabled:
            if state == 'disabled':
                if runtime_state != 'permissive':
                    # Temporarily set state to permissive
                    set_state(module, 'permissive')
                    module.warn('SELinux state temporarily changed from \'%s\' to \'permissive\'. State change will take effect next reboot.' % (runtime_state))
                else:
                    module.warn('SELinux state change will take effect next reboot')
                reboot_required = True
            else:
                set_state(module, state)
                msgs.append('SELinux state changed from \'%s\' to \'%s\'' % (runtime_state, state))

                # Only report changes if the file is changed.
                # This prevents the task from reporting changes every time the task is run.
                changed = True
        else:
            module.warn("Reboot is required to set SELinux state to %s" % state)
            reboot_required = True

    if state != config_state:
        if module.check_mode:
            module.exit_json(changed=True)
        msgs.append('Config SELinux state changed from \'%s\' to \'%s\'' % (config_state, state))
        set_config_state(module, state, configfile)
        changed = True

    module.exit_json(changed=changed, msg=', '.join(msgs), configfile=configfile, policy=policy, state=state, reboot_required=reboot_required)
Beispiel #42
0
def main():

    module = AnsibleModule(
        argument_spec=dict(
            policy=dict(required=False),
            state=dict(choices=["enforcing", "permissive", "disabled"], required=True),
            configfile=dict(aliases=["conf", "file"], default="/etc/selinux/config"),
        ),
        supports_check_mode=True,
    )

    # global vars
    changed = False
    msgs = []
    configfile = module.params["configfile"]
    policy = module.params["policy"]
    state = module.params["state"]
    runtime_enabled = selinux.is_selinux_enabled()
    runtime_policy = selinux.selinux_getpolicytype()[1]
    runtime_state = "disabled"
    if runtime_enabled:
        # enabled means 'enforcing' or 'permissive'
        if selinux.security_getenforce():
            runtime_state = "enforcing"
        else:
            runtime_state = "permissive"
    config_policy = get_config_policy(configfile)
    config_state = get_config_state(configfile)

    # check to see if policy is set if state is not 'disabled'
    if state != "disabled":
        if not policy:
            module.fail_json(msg="policy is required if state is not 'disabled'")
    else:
        if not policy:
            policy = config_policy

    # check changed values and run changes
    if policy != runtime_policy:
        if module.check_mode:
            module.exit_json(changed=True)
        # cannot change runtime policy
        msgs.append("reboot to change the loaded policy")
        changed = True

    if policy != config_policy:
        if module.check_mode:
            module.exit_json(changed=True)
        msgs.append("config policy changed from '%s' to '%s'" % (config_policy, policy))
        set_config_policy(policy, configfile)
        changed = True

    if state != runtime_state:
        if module.check_mode:
            module.exit_json(changed=True)
        if runtime_enabled:
            if state == "disabled":
                if runtime_state != "permissive":
                    # Temporarily set state to permissive
                    set_state("permissive")
                    msgs.append(
                        "runtime state temporarily changed from '%s' to 'permissive', state change will take effect next reboot"
                        % (runtime_state)
                    )
                else:
                    msgs.append("state change will take effect next reboot")
            else:
                set_state(state)
                msgs.append("runtime state changed from '%s' to '%s'" % (runtime_state, state))
        else:
            msgs.append("state change will take effect next reboot")
        changed = True

    if state != config_state:
        if module.check_mode:
            module.exit_json(changed=True)
        msgs.append("config state changed from '%s' to '%s'" % (config_state, state))
        set_config_state(state, configfile)
        changed = True

    module.exit_json(changed=changed, msg=", ".join(msgs), configfile=configfile, policy=policy, state=state)
    def test_interface_l(self):
        "Verify sepolicy interface -l works"
        p = Popen(['sepolicy', 'interface', '-l'], stdout=PIPE)
        out, err = p.communicate()
        self.assertSuccess(p.returncode, err)

    def test_interface_a(self):
        "Verify sepolicy interface -a works"
        p = Popen(['sepolicy', 'interface', '-a'], stdout=PIPE)
        out, err = p.communicate()
        self.assertSuccess(p.returncode, err)

    def test_interface_p(self):
        "Verify sepolicy interface -u works"
        p = Popen(['sepolicy', 'interface', '-u'], stdout=PIPE)
        out, err = p.communicate()
        self.assertSuccess(p.returncode, err)

    def test_interface_ci(self):
        "Verify sepolicy interface -c -i works"
        p = Popen(['sepolicy', 'interface', '-c', '-i', 'apache_admin'], stdout=PIPE)
        out, err = p.communicate()
        self.assertSuccess(p.returncode, err)

if __name__ == "__main__":
    import selinux
    if selinux.is_selinux_enabled() and selinux.security_getenforce() == 1:
        unittest.main()
    else:
        print("SELinux must be in enforcing mode for this test")
Beispiel #44
0
def main():

    module = AnsibleModule(
        argument_spec=dict(
            policy=dict(required=False),
            state=dict(
                choices=['enforcing', 'permissive', 'disabled'],
                required=True),
            configfile=dict(
                aliases=['conf', 'file'], default='/etc/selinux/config')),
        supports_check_mode=True)

    # global vars
    changed = False
    msgs = []
    configfile = module.params['configfile']
    policy = module.params['policy']
    state = module.params['state']
    runtime_enabled = selinux.is_selinux_enabled()
    runtime_policy = selinux.selinux_getpolicytype()[1]
    runtime_state = 'disabled'
    if (runtime_enabled):
        # enabled means 'enforcing' or 'permissive'
        if (selinux.security_getenforce()):
            runtime_state = 'enforcing'
        else:
            runtime_state = 'permissive'
    config_policy = get_config_policy(configfile)
    config_state = get_config_state(configfile)

    # check to see if policy is set if state is not 'disabled'
    if (state != 'disabled'):
        if not policy:
            module.fail_json(
                msg='policy is required if state is not \'disabled\'')
    else:
        if not policy:
            policy = config_policy

    # check changed values and run changes
    if (policy != runtime_policy):
        if module.check_mode:
            module.exit_json(changed=True)
        # cannot change runtime policy
        msgs.append('reboot to change the loaded policy')
        changed = True

    if (policy != config_policy):
        if module.check_mode:
            module.exit_json(changed=True)
        msgs.append('config policy changed from \'%s\' to \'%s\'' %
                    (config_policy, policy))
        set_config_policy(policy, configfile)
        changed = True

    if (state != runtime_state):
        if module.check_mode:
            module.exit_json(changed=True)
        if (state == 'disabled'):
            msgs.append('state change will take effect next reboot')
        else:
            if (runtime_enabled):
                set_state(state)
                msgs.append('runtime state changed from \'%s\' to \'%s\'' %
                            (runtime_state, state))
            else:
                msgs.append('state change will take effect next reboot')
        changed = True

    if (state != config_state):
        if module.check_mode:
            module.exit_json(changed=True)
        msgs.append('config state changed from \'%s\' to \'%s\'' %
                    (config_state, state))
        set_config_state(state, configfile)
        changed = True

    module.exit_json(
        changed=changed,
        msg=', '.join(msgs),
        configfile=configfile,
        policy=policy,
        state=state)
Beispiel #45
0
def _getSecStatus():
    try:
        value = selinux.security_getenforce()
    except:
        value = -1
    return value
Beispiel #46
0
    def __init__(self, gate, uuid):
        cpuInfo = read_cpuinfo()
        memory = read_memory()
        self.UUID = uuid
        self.os = gate.process('distro', software.read_os(), WITHHELD_MAGIC_STRING)
        self.defaultRunlevel = gate.process('run_level', software.read_runlevel(), -1)

        self.bogomips = gate.process('cpu', cpuInfo.get('bogomips', 0), 0)
        self.cpuVendor = gate.process('cpu', cpuInfo.get('type', ''), WITHHELD_MAGIC_STRING)
        self.cpuModel = gate.process('cpu', cpuInfo.get('model', ''), WITHHELD_MAGIC_STRING)
        self.cpu_stepping = gate.process('cpu', cpuInfo.get('cpu_stepping', 0), 0)
        self.cpu_family = gate.process('cpu', cpuInfo.get('cpu_family', ''), '')
        self.cpu_model_num = gate.process('cpu', cpuInfo.get('cpu_model_num', 0), 0)
        self.numCpus = gate.process('cpu', cpuInfo.get('count', 0), 0)
        self.cpuSpeed = gate.process('cpu', cpuInfo.get('speed', 0), 0)

        self.systemMemory = gate.process('ram_size', memory['ram'], 0)
        self.systemSwap = gate.process('swap_size', memory['swap'], 0)
        self.kernelVersion = gate.process('kernel', os.uname()[2], WITHHELD_MAGIC_STRING)
        if gate.grants('language'):
            try:
                self.language = os.environ['LANG']
            except KeyError:
                try:
                    status, lang = commands.getstatusoutput("grep LANG /etc/sysconfig/i18n")
                    if status == 0:
                        self.language = lang.split('"')[1]
                    else:
                        self.language = 'Unknown'
                except:
                    self.language = 'Unknown'
        else:
            self.language = WITHHELD_MAGIC_STRING

        tempform = platform.machine()
        self.platform = gate.process('arch', tempform, WITHHELD_MAGIC_STRING)

        if gate.grants('vendor'):
            #self.systemVendor = hostInfo.get('system.vendor'
            try:
                self.systemVendor = cat('/sys/devices/virtual/dmi/id/sys_vendor')[0].strip()
            except:
                self.systemVendor = 'Unknown'
        else:
            self.systemVendor = WITHHELD_MAGIC_STRING

        if gate.grants('model'):
            try:
                self.systemModel = cat('/sys/devices/virtual/dmi/id/product_name')[0].strip() + ' ' + cat('/sys/devices/virtual/dmi/id/product_version')[0].strip()
            except:
                self.systemModel = 'Unknown'
            #hostInfo was removed with the hal restructure
            #if not self.systemModel:
                #self.systemModel = hostInfo.get('system.hardware.product')
                #if hostInfo.get('system.hardware.version'):
                    #self.systemModel += ' ' + hostInfo.get('system.hardware.version')
            #if not self.systemModel:
                #self.systemModel = 'Unknown'
        else:
            self.systemModel = WITHHELD_MAGIC_STRING

        if gate.grants('form_factor'):
            try:
                formfactor_id = int(cat('/sys/devices/virtual/dmi/id/chassis_type')[0].strip())
                self.formfactor = FORMFACTOR_LIST[formfactor_id]
            except:
                self.formfactor = 'Unknown'
        else:
            self.formfactor = WITHHELD_MAGIC_STRING

        if tempform == 'ppc64':
            if hostInfo.get('openfirmware.model'):
                if hostInfo['openfirmware.model'][:3] == 'IBM':
                    self.systemVendor = 'IBM'
                model = hostInfo['openfirmware.model'][4:8]

                model_map = {
                    '8842':'JS20',
                    '6779':'JS21',
                    '6778':'JS21',
                    '7988':'JS21',
                    '8844':'JS21',
                    '0200':'QS20',
                    '0792':'QS21',
                }
                try:
                    model_name = model_map[model]
                    self.systemModel = gate.process('model', model_name)
                    self.formfactor = gate.process('form_factor', 'Blade')
                except KeyError:
                    pass

        if gate.grants('selinux'):
            try:
                import selinux
                try:
                    if selinux.is_selinux_enabled() == 1:
                        self.selinux_enabled = SELINUX_ENABLED
                    else:
                        self.selinux_enabled = SELINUX_DISABLED
                except:
                    self.selinux_enabled = SELINUX_DISABLED
                try:
                    self.selinux_policy = selinux.selinux_getpolicytype()[1]
                except:
                    self.selinux_policy = "Unknown"
                try:
                    enforce = selinux.security_getenforce()
                    if enforce == 0:
                        self.selinux_enforce = "Permissive"
                    elif enforce == 1:
                        self.selinux_enforce = "Enforcing"
                    elif enforce == -1:
                        self.selinux_enforce = "Disabled"
                    else:
                        self.selinux_enforce = "FUBARD"
                except:
                    self.selinux_enforce = "Unknown"
            except ImportError:
                self.selinux_enabled = SELINUX_DISABLED
                self.selinux_policy = "Not Installed"
                self.selinux_enforce = "Not Installed"
        else:
            self.selinux_enabled = SELINUX_WITHHELD
            self.selinux_policy = WITHHELD_MAGIC_STRING
            self.selinux_enforce = WITHHELD_MAGIC_STRING