Beispiel #1
0
def enable(svcname=None):

    if svcname == None:
        return None

    #
    # Solaris Operating System (svcadm)
    #
    if info.is_solaris() == True:
        if not os.path.isfile('/usr/sbin/svcadm'):
            return None

        cmd = '/usr/sbin/svcadm enable -r %s' % svcname
        output = tcs_utils.tcs_run_cmd(cmd, True)
        msg = 'Solaris: %s' % output[2]
        if output[0] != 0:
            logger.debug(MODULE_NAME, msg)
            return False
        else:
            msg = """Solaris: 'svcadm enable -r %s' was successful""" % svcname
            logger.debug(MODULE_NAME, msg)
            return True

    #
    # Linux Operating System (chkconfig)
    #
    pattern = re.compile('insserv: Service .* has to be enabled')
    cmd = "/sbin/chkconfig %s on" % svcname
    output = tcs_utils.tcs_run_cmd(cmd, True)
    if output[0] != 0:
        msg = """Linux: %s """ % output[2]
        logger.debug(MODULE_NAME, msg)
        if info.is_LikeSUSE() != True:
            return False

        if not pattern.search(output[2]):
            return False

        msg = "Error detected, trying alternative insserv(8) utility with force option (-f)..."
        logger.debug(MODULE_NAME, msg)

        cmd = "/sbin/insserv -f -d %s " % svcname
        output = tcs_utils.tcs_run_cmd(cmd, True)
        if output[0] != 0:
            msg = """Linux: %s """ % output[2]
            logger.debug(MODULE_NAME, msg)
            return False
        else:
            msg = """Linux: 'insserv -f -d %s' was successful""" % svcname
            logger.debug(MODULE_NAME, msg)
            return True

    else:
        msg = """Linux: 'chkconfig %s on' was successful""" % svcname
        logger.debug(MODULE_NAME, msg)
        return True

    return False
Beispiel #2
0
    def apply(self, option=None):

        result, reason, messages = self.scan()
        if result == True:
            return False, '', {}

        action_record = []

        zonename = sb_utils.os.solaris.zonename()
        if zonename != 'global':
            msg = "Non-global Solaris zone (%s): Unable to use the pmadm command" % (
                zonename)
            self.logger.notice(self.module_name, 'Scan: ' + msg)
            raise tcs_utils.ZoneNotApplicable('%s %s' %
                                              (self.module_name, msg))

        if not os.path.isfile('/usr/sbin/pmadm'):
            msg = "Unable to find /usr/sbin/pmadm command"
            self.logger.error(self.module_name, 'Apply Error: ' + msg)
            raise tcs_utils.ActionError('%s %s' % (self.module_name, msg))

        failure_flag = False
        cmd = "/usr/sbin/pmadm -L -p zsmon"
        results = tcs_utils.tcs_run_cmd(cmd, True)
        if results[0] != 0:
            msg = "Unable to execute: %s (%s)" % (cmd, results[2])
            self.logger.notice(self.module_name, 'Apply Failed: ' + msg)
            return False, '', {}

        for line in results[1].split('\n'):
            fields = line.split(':')
            if len(fields) == 1:
                continue

            if len(fields) < 4:
                msg = "Ignoring malformed line: %s" % line
                self.logger.debug(self.module_name, msg)
                continue

            test = fields[3].find('x')
            if test < 0:
                cmd = "/usr/sbin/pmadm -d -p zsmon -s %s" % str(fields[2])
                results = tcs_utils.tcs_run_cmd(cmd, True)
                if results[0] != 0:
                    msg = "Unable to disable %s: %s" % (
                        fields[2], str(results[2]).rstrip())
                    self.logger.notice(self.module_name,
                                       "Apply Failed: " + msg)
                else:
                    msg = "Disabled %s" % (fields[2])
                    self.logger.notice(self.module_name,
                                       "Apply Performed: " + msg)
                    action_record.append(fields[2])

        return True, ' '.join(action_record), {}
    def undo(self, change_record):
        """
        Reset password aging on user accounts
        """

        if not change_record:
            msg = "Unable to perform undo operation without change record."
            self.logger.error(self.module_name, 'Undo Error: ' + msg)
            raise tcs_utils.ActionError('%s %s' % (self.module_name, msg))

        cmd1 = '/usr/bin/passwd -r files -x -1'
        cmd2 = '/usr/sbin/usermod -f 0'
        cmd3 = '/usr/sbin/rolemod -f 0'

        undo_fail_flag = False

        for user in change_record.split('\n'):
            if not user:
                continue

            try:
                test = pwd.getpwnam(user)
            except Exception:
                msg = "User account '%s' does not exist" % user
                self.logger.warn(self.module_name, 'Undo: ' + msg)
                continue

            cmd = "%s %s" % (cmd1, user)
            results = tcs_utils.tcs_run_cmd(cmd, True)
            if results[0] != 0:
                msg = "Failed to execute '%s' (%s)" % (cmd, results[2])
                self.logger.error(self.module_name, 'Undo Failed: ' + msg)
                undo_fail_flag = True
            else:
                msg = "Undo Performed: Password aging removed: %s" % cmd
                self.logger.notice(self.module_name, msg)

            if user in self.__usersWithRoles:
                cmd = "%s %s" % (cmd3, user)
            else:
                cmd = "%s %s" % (cmd2, user)

            results = tcs_utils.tcs_run_cmd(cmd, True)
            if results[0] != 0:
                msg = "Failed to execute '%s' (%s)" % (cmd, results[2])
                self.logger.error(self.module_name, 'Undo Failed: ' + msg)
                undo_fail_flag = True
            else:
                msg = "Undo Performed: Inactivity field cleared: %s" % cmd
                self.logger.notice(self.module_name, msg)

        if undo_fail_flag == True:
            return 0
        else:
            return 1
Beispiel #4
0
def listAllFilesForPackage(pkgname=None):
    """Return a list of files that were installed by the package"""
    pkgList = []

    try:
        logger = TCSLogger.TCSLogger.getInstance(6)
    except TCSLogger.SingletonException:
        logger = TCSLogger.TCSLogger.getInstance()

    if not is_installed(pkgname):
        return pkgList
    if info.is_solaris() == True:
        cmd = "/usr/sbin/pkgchk -l %s | grep 'Pathname:'" % pkgname
        if not os.path.isfile('/usr/sbin/pkginfo'):
            return None

        output = tcs_utils.tcs_run_cmd(cmd, True)
        if output[0] == 0:
            pkgList = [
                thisfile[10:] for thisfile in output[1].splitlines()
                if thisfile.startswith('Pathname: ')
            ]

        del output

    else:
        try:
            import rpm
        except ImportError:
            return None

        try:
            transet = rpm.TransactionSet()
        except Exception, err:
            logger.error(MODULE_NAME, err)
            return None

        ## First try, the Python RPM API....
        pkglist = transet.dbMatch('name', pkgname)
        if type(pkglist).__name__ == 'mi':
            for hdr in pkglist:
                if hdr['name'] == pkgname:
                    pkgList = hdr['filenames']
                    break
        ## Okay, now try the old-fashioned method of using rpm(8) command
        else:
            msg = "Unable to determine if '%s' is installed using "\
                  "Python-RPM API, trying the rpm(8) utility" % pkgname
            logger.info(MODULE_NAME, msg)
            cmd = "/bin/rpm -q --list %s " % pkgname
            output = tcs_utils.tcs_run_cmd(cmd, True)
            if output[0] == 0:
                pkgList = output[1].split()
Beispiel #5
0
    def undo(self, change_record=None):
        """Undo the previous action."""

        result, reason = self.scan()
        if result == 'Fail':
            return 0

        if change_record == None:
            msg = "Skipping Undo: No change record in state file."
            self.logger.notice(self.module_name, msg)
            return 0

        if change_record != 'yes':
            msg = "Skipping Undo: Unknown change record in state file: '%s'" % change_record
            self.logger.error(self.module_name, 'Skipping undo: ' + msg)
            return 0

        # Set property
        cmd = "/usr/sbin/svccfg -s system-log setprop config/log_from_remote = true"
        results = tcs_utils.tcs_run_cmd(cmd, True)
        if results[0] != 0:
            msg = 'failed to execute %s: %s' % (cmd, results[2])
            self.logger.error(self.module_name, 'Undo Error: ' + msg)
            raise tcs_utils.ActionError('%s %s' % (self.module_name, msg))
        else:
            msg = 'Executed %s' % (cmd)
            self.logger.info(self.module_name, 'Undo Performed: ' + msg)

        # Re-read configuration
        cmd = "/usr/sbin/svcadm refresh system-log"
        results = tcs_utils.tcs_run_cmd(cmd, True)
        if results[0] != 0:
            msg = 'failed to execute %s: %s' % (cmd, results[2])
            self.logger.error(self.module_name, 'Apply Error: ' + msg)
            raise tcs_utils.ActionError('%s %s' % (self.module_name, msg))
        else:
            msg = 'Executed %s' % (cmd)
            self.logger.info(self.module_name, 'Apply Performed: ' + msg)

        # Restart Service
        cmd = "/usr/sbin/svcadm restart system-log"
        results = tcs_utils.tcs_run_cmd(cmd, True)
        if results[0] != 0:
            msg = 'failed to execute %s: %s' % (cmd, results[2])
            self.logger.error(self.module_name, 'Apply Error: ' + msg)
            raise tcs_utils.ActionError('%s %s' % (self.module_name, msg))
        else:
            msg = 'Executed %s' % (cmd)
            self.logger.info(self.module_name, 'Apply Performed: ' + msg)

        msg = 'Allowing remote syslog messages'
        self.logger.notice(self.module_name, 'Undo Performed: ' + msg)
        return 1
Beispiel #6
0
    def apply(self, option=None):

        messages = {}
        messages['messages'] = []

        action_record = []
        for param in ['ipv4-forwarding', 'ipv6-forwarding']:
            cmd = '/usr/sbin/routeadm -p %s' % param
            results = tcs_utils.tcs_run_cmd(cmd, True)
            if results[0] != 0:
                msg = 'failed to execute %s: %s' % (cmd, results[2])
                self.logger.error(self.module_name, 'Apply Error: ' + msg)
                raise tcs_utils.ActionError('%s %s' % (self.module_name, msg))

            try:
                param_key = results[1].split(' ')[0].split('=')[0]
                param_val = results[1].split(' ')[0].split('=')[1]
            except IndexError:
                msg = 'Can not determine status of %s' % param
                self.logger.error(self.module_name, 'Apply Error: ' + msg)
                raise tcs_utils.ActionError('%s %s' % (self.module_name, msg))

            if param_val == 'enabled':
                cmd = '/usr/sbin/routeadm -d %s' % param
                results = tcs_utils.tcs_run_cmd(cmd, True)
                if results[0] != 0:
                    msg = 'failed to execute %s: %s' % (cmd, results[2])
                    self.logger.error(self.module_name, 'Apply Error: ' + msg)
                    raise tcs_utils.ActionError('%s %s' %
                                                (self.module_name, msg))
                else:
                    action_record.append('/usr/sbin/routeadm -e %s\n' % param)
                    msg = 'Apply Performed: IP forwarding disabled: %s' % (cmd)
                    self.logger.notice(self.module_name, msg)
                    msg = "Disabled by executing /usr/sbin/routeadm -d %s" % param
                    messages['messages'].append(msg)

        if not os.path.isfile('/etc/notrouter'):
            try:
                out_obj = open('/etc/notrouter', 'w')
                out_obj.write('')
                out_obj.close()
                msg = 'Created /etc/notrouter file'
                messages['messages'].append(msg)
                self.logger.notice(self.module_name, 'Apply Performed: ' + msg)
                action_record.append('/bin/rm -f /etc/notrouter\n')
            except IOError, err:
                msg = "Unable to create /etc/notrouter: %s" % err
                messages['messages'].append("Error: %s" % msg)
                self.logger.error(self.module_name, 'Apply Error: ' + msg)
Beispiel #7
0
def ndd_set(param=None, paramValue=None, driver=None):
    """
    Get ndd parameter
    """
    logger = TCSLogger.TCSLogger.getInstance()

    if param == None or driver == None or paramValue == None:
        return False

    if paramValue == "":
        msg = "Ndd does not allow 'unsetting' of a value - reboot to pick up the default (if any) in /etc/default/ndd"
        logger.log_notice('sb_utils.os.solaris.ndd_set', msg)
        return True
        
    logger = TCSLogger.TCSLogger.getInstance()
 
    cmd = '/usr/sbin/ndd -set /dev/%s %s %s' % (driver, param, paramValue)
    output = tcs_utils.tcs_run_cmd(cmd, True)
    if output[0] != 0:
        msg = "Execution of '%s' failed: %s" % (cmd, output[2])
        logger.log_err('sb_utils.os.solaris', msg)
        del logger
        return False
    else:
        msg = "Execution of '%s' succeeded: %s" % (cmd, output[1])
        logger.log_debug('sb_utils.os.solaris', msg)
        del logger
        return True
Beispiel #8
0
    def do_metastat(self):

        cmd = "/usr/sbin/metastat"
        if not os.path.isfile(cmd):
            return

        results = tcs_utils.tcs_run_cmd(cmd, True)
        if results[0] == 0:
            barline = ""
            for ix in range(0, 50):
                barline += '#'
            self.logger.warn(self.module_name, barline)

            msg = "/usr/sbin/metastat reports that there are metadevice " \
                  "state database(s) present. Disable Solaris Volume Manager "\
                  "services with caution."
            self.logger.warn(self.module_name, msg)
            self.logger.warn(self.module_name, barline)

        else:
            msg = "/usr/sbin/metastat reports no metadevice " \
                  "state database(s) present. "
            self.logger.debug(self.module_name, msg)

        del msg
        del results

        return
Beispiel #9
0
def status(svcname=None):
    """Status of  service: return True if successful or False if failed"""

    if svcname == None:
        return None

    if info.is_solaris() == True:
        return None

    if not os.path.isfile('/sbin/service'):
        msg = "Could not find the /sbin/service command."
        logger.error(MODULE_NAME, msg)
        return False

    cmd = '/sbin/service %s status' % (svcname)
    output = tcs_utils.tcs_run_cmd(cmd, True)
    if output[0] != 0:
        msg = "Status of service '%s': (Return Code=%s) %s" % (
            svcname, output[0], output[2].rstrip())
        logger.notice(MODULE_NAME, msg)
        return False
    else:
        msg = "Status of service '%s': (Return Code=%s) %s" % (
            svcname, output[0], output[1].rstrip())
        logger.notice(MODULE_NAME, msg)
        return True
Beispiel #10
0
def get(paramKey=None):

    if paramKey == None or sb_utils.os.info.is_solaris() == True:
        return None

    if CONFIG_SOURCE == "":
        msg = "Unable to locate gconf.xml.mandatory file to get value from"
        logger.log_err(MODULE_NAME, msg)
        return None

    cmdString = "%s --direct --config-source %s --get %s" % \
         (GCONF_COMMAND, CONFIG_SOURCE, str(paramKey))

    output = tcs_utils.tcs_run_cmd(cmdString, True)
    keyValue = None
    if output[0] != 0:
        msg = "Unable get GDM '%s' key from %s (%s)" % (
            paramKey, CONFIG_SOURCE, output[2])
        logger.log_err(MODULE_NAME, msg)
    else:
        if output[2].strip().startswith('No value set for '):
            msg = "GDM '%s' key is not set" % paramKey
        else:
            msg = "GDM '%s' key is set" % paramKey
            keyValue = output[1].strip()
        logger.log_info(MODULE_NAME, msg)

    return keyValue
Beispiel #11
0
def getXttr(filepath):

    if testFile(filepath) == False:
        return ''

    if sb_utils.os.info.is_solaris() == True:
        msg = "Extended File Attributes - Not applicable in Solaris"
        logger.log_info(MODULE_NAME, msg)
        return ''

    results = sb_utils.os.software.is_installed(pkgname='e2fsprogs')
    if results == False:
        msg = "'e2fsprogs' package is not installed"
        logger.log_err(MODULE_NAME, msg)
        return ''

    if not os.path.exists('/usr/bin/lsattr'):
        msg = "'/usr/bin/lsattr' does not exist"
        logger.log_err(MODULE_NAME, msg)
        return ''

    cmd = "/usr/bin/lsattr %s" % filepath
    out = tcs_utils.tcs_run_cmd(cmd, True)

    if out[0] != 0 or not out[1]:
        msg = "Unable to get file attributes: %s" % str(out[2])
        logger.log_err(MODULE_NAME, msg)
        return ''

    return out[1].split()[0].strip()
Beispiel #12
0
    def undo(self, change_record=None):
        """Undo the previous action."""

        result, reason = self.scan()
        if result == 'Fail':
            return 0

        force_flag = ""
        if sb_utils.os.info.is_solaris() == False:
            force_flag = "-f"

        if not change_record:
            msg = "Skipping Undo: No change record in state file."
            self.logger.notice(self.module_name, 'Skipping undo: ' + msg)
            return 0

        for user in change_record.split('\n'):
            if not user:
                break
            cmd = '/usr/bin/passwd %s -u %s' % (force_flag, user)
            output_tuple = tcs_utils.tcs_run_cmd(cmd)
            if output_tuple[0] != 0:
                msg = "Unexpected return value (%s)" % output_tuple[0]
                self.logger.error(self.module_name, 'Undo Error: ' + msg)
                raise tcs_utils.ActionError('%s %s' % (self.module_name, msg))
            else:
                msg = "Successfully executed: %s" % cmd
                self.logger.debug(self.module_name, 'Undo Performed: ' + msg)

                msg = "User (%s) unlocked" % user
                self.logger.notice(self.module_name, 'Undo Performed: ' + msg)

        msg = 'User accounts with empty passwords have been unlocked.'
        self.logger.notice(self.module_name, 'Undo Performed: ' + msg)
        return 1
Beispiel #13
0
def cracklib_set(option=None, optValue=None):

    if option == None or optValue == None:
        return False

    if os.path.exists('/usr/sbin/pam-config'):
        pam_config = '/usr/sbin/pam-config'
        cmd_string = "%s -a --cracklib-%s=%s" % (pam_config, str(option),
                                                 str(optValue))
        results = tcs_utils.tcs_run_cmd(cmd_string, True)
        if results[0] != 0:
            logger.log_err(MODULE_NAME, results[2])
            return False
        msg = "SET Value: cracklib '%s' option now set to '%s' " % (option,
                                                                    optValue)
        logger.debug(MODULE_NAME, msg)
        return True

    try:
        in_obj = open('/etc/pam.d/common-password-pc', 'r')
        lines = in_obj.readlines()
        in_obj.close()
        out_obj = open('/etc/pam.d/common-password-pc', 'w')
    except IOError, err:
        logger.err(MODULE_NAME, str(err))
        return False
Beispiel #14
0
def setXttr(filepath, immutable=False):

    if testFile(filepath) == False:
        return False

    if sb_utils.os.info.is_solaris() == True:
        msg = "Extended File Attributes - Not applicable in Solaris"
        logger.log_info(MODULE_NAME, msg)
        return False

    results = sb_utils.os.software.is_installed(pkgname='e2fsprogs')
    if results == False:
        msg = "'e2fsprogs' package is not installed"
        logger.log_err(MODULE_NAME, msg)
        return False

    if not os.path.exists('/usr/bin/lsattr'):
        msg = "'/usr/bin/lsattr' does not exist"
        logger.log_err(MODULE_NAME, msg)
        return False

    if immutable == True:
        cmd = "/usr/bin/chattr +i %s" % filepath
    else:
        cmd = "/usr/bin/chattr -i %s" % filepath

    out = tcs_utils.tcs_run_cmd(cmd, True)
    if out[0] != 0:
        msg = "Unable to set file attributes: %s" % str(out[2])
        logger.log_err(MODULE_NAME, msg)
        return False

    return True
Beispiel #15
0
def version(pkgname=None):
    """
    Determine version and release of software package
    Return a tuple: [version, release]
    """

    try:
        logger = TCSLogger.TCSLogger.getInstance(6)
    except TCSLogger.SingletonException:
        logger = TCSLogger.TCSLogger.getInstance()

    if pkgname == None:
        return None

    if info.is_solaris() == True:
        if not os.path.isfile('/usr/bin/pkgparam'):
            return None
        cmd = '/usr/bin/pkgparam %s VERSION' % pkgname
    else:
        if not os.path.isfile('/bin/rpm'):
            return None
        cmd = """/bin/rpm -q %s --queryformat "%%{VERSION},%%{RELEASE}" """ % pkgname

    results = tcs_utils.tcs_run_cmd(cmd, True)
    if results[0] != 0:
        msg = """Unable to get version of %s: %s""" % (pkgname, results[2])
        logger.error(MODULE_NAME, msg)
        return None

    msg = """Package '%s' is installed""" % pkgname
    logger.debug(MODULE_NAME, msg)
    return results[1].rstrip('\n').split(',')
Beispiel #16
0
def zonelist():
    """
    Return a list of zone names
    """
    logger = TCSLogger.TCSLogger.getInstance()
    myzonelist = []

    cmd = '/usr/sbin/zoneadm list'

    if not os.path.isfile('/usr/sbin/zoneadm'):
        msg = "%s command not available" % cmd
        logger.log_notice('sb_utils.os.solaris', msg)
        return None

    output = tcs_utils.tcs_run_cmd(cmd, True)

    if output[0] != 0:
        msg = "Execution of '%s' failed: %s" % (cmd, output[2])
        logger.log_err('sb_utils.os.solaris', msg)
        del logger
        return None

    msg = "Execution of '%s' succeeded: %s" % (cmd, output[1])
    logger.log_debug('sb_utils.os.solaris', msg)

    for zone in output[1].split('\n'):
        if not zone: 
            continue
        else:
            myzonelist.append(zone)
         
    return myzonelist
Beispiel #17
0
def zonepath(zonename=None):
    """
    Get Zone's filesystem path
    """

    if zonename == None:
        return None

    if zonename == 'global':
        return None

    try:
        logger = TCSLogger.TCSLogger.getInstance(6)
    except TCSLogger.SingletonException:
        logger = TCSLogger.TCSLogger.getInstance()

    cmd = "/usr/sbin/zonecfg -z %s info zonepath" % zonename
    output = tcs_utils.tcs_run_cmd(cmd, True)

    if output[0] != 0:
        msg = "Execution of '%s' failed: %s" % (cmd, output[2])
        logger.log_err('sb_utils.os.solaris', msg)
        del logger
        return None
    else:
        msg = "Execution of '%s' succeeded: %s" % (cmd, output[1])
        logger.log_debug('sb_utils.os.solaris', msg)
        del logger
        line = output[1].rstrip('\n')
        try:
            line = line.split(':')[1].lstrip(' ')
        except IndexError:
            return None
        return line
Beispiel #18
0
    def apply(self, option=None):
        """
        Lock user accounts with UID 0 which are not ROOT
        """
        if option != None:
            option = None

        action_record = ''
        lockstatus = self.lock_status()
        # look for duplicates including any external account sources
        for user in pwd.getpwall():
            if user.pw_name != 'root' and user.pw_uid == 0:
                if lockstatus[user.pw_name] == 'unlocked':
                    cmd = "/usr/bin/passwd -l %s" % user.pw_name
                    output = tcs_utils.tcs_run_cmd(cmd, True)
                    if output[0] != 0:
                        msg = "Unable to lock %s: %s" % (user.pw_name, output[2])
                        self.logger.error(self.module_name, 'Scan Failed: ' + msg)
                        continue

                    action_record += user.pw_name + ':'
                    msg = 'User ' + user.pw_name + ' locked'
                    self.logger.notice(self.module_name, 
                                           'Apply Performed: ' + msg)
                else:
                    msg = 'User ' + user.pw_name + ' already locked'
                    self.logger.notice(self.module_name, 
                                           'Apply Performed: ' + msg)


        if action_record == '':
            return 0, ''
        else:
            return 1, action_record
Beispiel #19
0
def setprop(svcname=None, property=None, propval=None):
    """
    Set a Solaris service property, return the following:
        None  - if it couldn't do anything (missing params or commands) 
        True  - Successful
        False - Unsuccessful
    """

    if svcname == None or property == None or propval == None:
        return None

    if info.is_solaris() == False:
        return None

    if not os.path.isfile('/usr/sbin/svccfg'):
        return None

    # Example format of command:
    # svccfg -s service_fmri setprop property = value

    cmd = """/usr/sbin/svccfg -s %s setprop %s = "%s" """ % \
               (svcname, property, propval)

    output = tcs_utils.tcs_run_cmd(cmd, True)

    if output[0] != 0:
        msg = "Solaris: '%s' failed: %s" % (cmd, output[2])
        logger.debug(MODULE_NAME, msg)
        return False
    else:
        msg = "Solaris: '%s' succeeded: %s" % (cmd, output[1])
        logger.debug(MODULE_NAME, msg)
        return True
Beispiel #20
0
def restart(svcname=None):
    """Restart a service: return True if successful or False if failed"""

    if svcname == None:
        return False

    if info.is_solaris() == True:
        disable(svcname=svcname)
        return enable(svcname=svcname)

    if not os.path.isfile('/sbin/service'):
        msg = "Could not find the /sbin/service command."
        logger.error(MODULE_NAME, msg)
        return False

    cmd = '/sbin/service %s restart' % (svcname)
    output = tcs_utils.tcs_run_cmd(cmd, True)
    if output[0] != 0:
        msg = "Unable to stop '%s': %s" % (svcname, output[2])
        logger.error(MODULE_NAME, msg)
        return False
    else:
        msg = "Successfully restarted service '%s': %s" % (svcname,
                                                           output[1].rstrip())
        logger.notice(MODULE_NAME, msg)
        return True
Beispiel #21
0
    def apply(self, optionDict=None):

        messages = {'messages': []}

        result, reason, msg = self.scan(optionDict)
        if result == True:
            return False, 'none', {}

        option = optionDict['gnomeSaverActivate']
        old_state = {}
        for line in self.__settings:
            optkey, optval, opttype = line.split(',')
            getconf = "%s %s --get %s 2>&1" % (self.__cmd, self.__cfg_src,
                                               optkey)

            msg = "Executing: %s" % getconf
            self.logger.info(self.module_name, msg)

            pipe = os.popen(getconf)
            curval = pipe.readlines()

            for retval in curval:
                retval = retval.rstrip('\n')
                if retval.startswith('Resolved address'):
                    continue

                if retval.startswith('No value'):
                    msg = "gconftool-2 reports: %s" % retval
                    self.logger.info(self.module_name, msg)
                    old_state[optkey.split('/')[-1]] = ''
                else:
                    old_state[optkey.split('/')[-1]] = retval

            pipe.close()

        change_record = old_state

        setlist = (self.CMD1, self.CMD2, self.CMD3, self.CMD4)
        for cmd in setlist:
            if cmd == self.CMD4:
                cmd = str(self.CMD4 + str(option))

            cmd = "%s %s" % (self.__cmd, cmd)
            results = tcs_utils.tcs_run_cmd(cmd, True)
            if results[0] != 0:
                msg = "Failed to execute: %s (%s)" % (cmd, results[2])
                self.logger.error(self.module_name, msg)
                raise tcs_utils.ActionError('%s %s' % (self.module_name, msg))
            else:
                msg = "Executed: %s" % (cmd)
                messages['messages'].append(msg)
                self.logger.notice(self.module_name, 'Apply Performed: ' + msg)

        msg = 'Mandatory Screen locking security settings now configured.'
        self.logger.notice(self.module_name, 'Apply performed: ' + msg)
        return True, str(change_record), messages
Beispiel #22
0
    def apply(self, option=None):
        """Apply changes."""

        action_record = ''
        result, reason = self.scan()
        if result == 'Pass':
            return 0, action_record

        # Set Property
        cmd = "/usr/sbin/svccfg -s system-log setprop config/log_from_remote = false"
        results = tcs_utils.tcs_run_cmd(cmd, True)
        if results[0] != 0:
            msg = 'failed to execute %s: %s' % (cmd, results[2])
            self.logger.error(self.module_name, 'Apply Error: ' + msg)
            raise tcs_utils.ActionError('%s %s' % (self.module_name, msg))
        else:
            msg = 'Executed %s' % (cmd)
            self.logger.info(self.module_name, 'Apply Performed: ' + msg)

        # Re-read/refresh configuration
        cmd = "/usr/sbin/svcadm refresh system-log"
        results = tcs_utils.tcs_run_cmd(cmd, True)
        if results[0] != 0:
            msg = 'failed to execute %s: %s' % (cmd, results[2])
            self.logger.error(self.module_name, 'Apply Error: ' + msg)
            raise tcs_utils.ActionError('%s %s' % (self.module_name, msg))
        else:
            msg = 'Executed %s' % (cmd)
            self.logger.info(self.module_name, 'Apply Performed: ' + msg)

        # Restart Service
        cmd = "/usr/sbin/svcadm restart system-log"
        results = tcs_utils.tcs_run_cmd(cmd, True)
        if results[0] != 0:
            msg = 'failed to execute %s: %s' % (cmd, results[2])
            self.logger.error(self.module_name, 'Apply Error: ' + msg)
            raise tcs_utils.ActionError('%s %s' % (self.module_name, msg))
        else:
            msg = 'Executed %s' % (cmd)
            self.logger.info(self.module_name, 'Apply Performed: ' + msg)

        msg = 'Disallowing remote syslog messages'
        return 1, 'yes'
Beispiel #23
0
    def undo(self, change_record):

        if not change_record:
            return 0, 'No change record provided'

        fieldArgs = ['spaceholder', 'M', 'm', 'W', 'I']

        # Note - legacy RedHat/Fedora change records used a space as the record delimiter, and also had
        # the fields in slightly altered order.  So we need to detect if we have such a record and
        # reorder it before proceeding.  Both change records will have 5 fields, with either ' ' or '|' as
        # the field delimiter.
        # The legacy RH/Fedora order is 'user sp_min sp_max sp_warn sp_inact', and current ordering
        # is                            'user sp_max sp_min sp_warn sp_inact'
        # The change record will record 'empty' fields if the setting in the shadow file for the account
        # in question was strict enough and did not require changing.

        changelist = change_record.split('\n')
        for record in changelist:
            # if we have a space, assume legacy Redhat/Fedora style and fix
            if not record:
                continue
            if '|' in record:
                fields = record.split('|')
            else:
                fieldsRH = record.split(' ')
                fields = [fieldsRH[elem] for elem in [0, 2, 1, 3, 4]]

            if len(fields) != 5:
                msg = "Element of change record has incorect number of fields, skipping '%s'" % record
                self.logger.error(self.module_name, "Undo Error: " + msg)
                continue

            try:
                pwd.getpwnam(fields[0])
            except Exception, err:
                msg = "Unable to get information on account '%s' " % fields[0]
                self.logger.error(self.module_name, 'Undo Error: ' + msg)
                continue

            cmdArgs = []
            for i in range(1, len(fields)):
                if fields[i]:
                    cmdArgs.append("-%s %s" % (fieldArgs[i], fields[i]))
            cmd = "/usr/bin/chage %s %s" % (' '.join(cmdArgs), fields[0])

            output = tcs_utils.tcs_run_cmd(cmd, True)
            if output[0] != 0:
                msg = "Unable to undo password aging on '%s': %s" % (fields[0],
                                                                     output[2])
                self.logger.error(self.module_name, 'Undo Failed: ' + msg)
                continue
            else:
                msg = "Password aging reset on '%s'" % (fields[0])
                self.logger.notice(self.module_name, 'Undo Performed: ' + msg)
Beispiel #24
0
    def serviceExists(self, svcname):
        """
        See if the service even exists, needed because the hplip software has migrated
        away from a service (which we could disable) to simply a package that should be removed
        So process the chkconfig --list hplip command looking for any error string (field 2)
        """

        cmd = "/sbin/chkconfig --list %s" % svcname
        results = tcs_utils.tcs_run_cmd(cmd, True)
        if results[2] != '':
            return False
        else: return True
Beispiel #25
0
    def setparam(self, paramname=None, paramval=None):
        if paramname == None or paramval == None:
            return False

        cmd = "/sbin/sysctl -w %s=%s" % (str(paramname), str(paramval))
        results = tcs_utils.tcs_run_cmd(cmd, True)
        if results[0] != 0:
            self.logger.log_err(MODULE_NAME, results[2])
            return False

        del results
        return True
Beispiel #26
0
    def scan(self, option=None):

        zonename = sb_utils.os.solaris.zonename()
        if zonename != 'global':
            msg = "Non-global Solaris zone (%s): Unable to use pmadm command" % (
                zonename)
            self.logger.notice(self.module_name, 'Scan: ' + msg)
            raise tcs_utils.ZoneNotApplicable('%s %s' %
                                              (self.module_name, msg))

        if not os.path.isfile('/usr/sbin/pmadm'):
            msg = "Unable to find /usr/sbin/pmadm command"
            self.logger.error(self.module_name, 'Scan Error: ' + msg)
            raise tcs_utils.ScanError('%s %s' % (self.module_name, msg))

        failure_flag = False
        cmd = "/usr/sbin/pmadm -L -p zsmon"
        results = tcs_utils.tcs_run_cmd(cmd, True)
        if results[0] != 0:
            msg = "Unable to execute: %s (%s)" % (cmd, results[2])
            self.logger.notice(self.module_name, 'Scan Failed: ' + msg)
            return False, '', {'messages': [msg]}

        for line in results[1].split('\n'):
            fields = line.split(':')
            if len(fields) == 1:
                continue

            if len(fields) < 4:
                msg = "Ignoring malformed line: %s" % line
                self.logger.debug(self.module_name, msg)
                continue

            test = fields[3].find('x')
            if test < 0:
                msg = "%s is NOT disabled through port monitor %s" % (
                    fields[2], fields[0])
                self.logger.notice(self.module_name, "Scan Failed: " + msg)
                failure_flag = True
            else:
                msg = "%s is disabled through port monitor %s" % (fields[2],
                                                                  fields[0])
                self.logger.info(self.module_name, msg)

        if failure_flag == True:
            return False, 'Some services are not disabled through the zsmon port monitor', {
                'messages': [msg]
            }
        else:
            return True, '', {}
Beispiel #27
0
    def scan(self, option=None):

        messages = {}
        messages['messages'] = []

        msg = "Using routeadm to test ipv4-forwarding and ipv6-forwarding"
        messages['messages'].append(msg)
        self.logger.debug(self.module_name, msg)

        failure_flag = False
        for param in ['ipv4-forwarding', 'ipv6-forwarding']:
            cmd = '/usr/sbin/routeadm -p %s' % param
            results = tcs_utils.tcs_run_cmd(cmd, True)
            if results[0] != 0:
                msg = 'failed to execute %s: %s' % (cmd, results[2])
                self.logger.error(self.module_name, 'Scan Error: ' + msg)
                raise tcs_utils.ScanError('%s %s' % (self.module_name, msg))

            try:
                param_key = results[1].split(' ')[0].split('=')[0]
                param_val = results[1].split(' ')[0].split('=')[1]
            except IndexError:
                msg = 'Can not determine status of %s' % param
                self.logger.error(self.module_name, 'Scan Error: ' + msg)
                raise tcs_utils.ScanError('%s %s' % (self.module_name, msg))

            if param_val == 'enabled':
                msg = '%s %s is enabled' % (param, param_key)
                messages['messages'].append("Fail: %s" % msg)
                self.logger.notice(self.module_name, 'Scan Failed: ' + msg)
                failure_flag = True
            else:
                msg = '%s %s is disabled' % (param, param_key)
                messages['messages'].append("Okay: %s" % msg)
                self.logger.info(self.module_name, msg)

        if not os.path.isfile('/etc/notrouter'):
            msg = '/etc/notrouter file is missing'
            messages['messages'].append("Fail: %s" % msg)
            self.logger.notice(self.module_name, 'Scan Failed: ' + msg)
            failure_flag = True
        else:
            msg = '/etc/notrouter file is present'
            messages['messages'].append("Okay: %s" % msg)
            self.logger.debug(self.module_name, msg)

        if failure_flag == True:
            return False, 'IP Forwarding is enabled.', messages
        else:
            return True, '', messages
Beispiel #28
0
    def undo(self, change_record=None):
        """Undo the previous action."""

        if not change_record or change_record != 'disabled':
            msg = 'unable to undo without valid change record'
            self.logger.error(self.module_name, 'Undo Error: ' + msg)
            return 0

        cmd = '/bin/grep "release 5" /etc/redhat-release'
        output = tcs_utils.tcs_run_cmd(cmd, True)

        # RHEL 4 PCMCIA
        # NOTE: This requires testing on RHEL4
        if output[0] != 0:
            cmd = "/bin/rpm -q pcmcia-cs"
            output = tcs_utils.tcs_run_cmd(cmd, True)
            if output[0] == 0:
                cmd = "/sbin/chkconfig pcmcia on"
                output = tcs_utils.tcs_run_cmd(cmd, True)
                if output[0] != 0:
                    msg = 'Failed to enable pcmcia'
                    self.logger.error(self.module_name, 'Apply Error: ' + msg)
                    raise tcs_utils.ActionError('%s %s' %
                                                (self.module_name, msg))

        cmd = "/sbin/grubby --update-kernel=`/sbin/grubby --default-kernel` "
        cmd += "--remove-args 'nopcmcia=1 nousb nousbstorage'"
        output = tcs_utils.tcs_run_cmd(cmd, True)
        sb_utils.SELinux.restoreSecurityContext(self.__target_file)
        if output[0] != 0:
            msg = 'Failed to remove disable USB/PCMCIA kernel arguments'
            self.logger.error(self.module_name, 'Apply Error: ' + msg)
            return 0

        msg = 'USB/PCMCIA service enabled'
        self.logger.notice(self.module_name, 'Undo Performed: ' + msg)
        return 1
Beispiel #29
0
    def scan(self, option=None):

        cmd = '/usr/bin/svcprop -p config/log_from_remote system-log'
        results = tcs_utils.tcs_run_cmd(cmd, True)
        if results[0] != 0:
            msg = 'failed to execute %s: %s' % (cmd, results[2])
            self.logger.error(self.module_name, 'Scan Error: ' + msg)
            raise tcs_utils.ScanError('%s %s' % (self.module_name, msg))

        if results[1].rstrip('\n') == 'true':
            msg = "system-log 'config/log_from_remote' property is set to true"
            self.logger.notice(self.module_name, 'Scan Failed: ' + msg)
            return 'Fail', msg

        return 'Pass', ''
Beispiel #30
0
    def apply(self, optionDict=None):
        """
        Update grub.conf with correct parameters
        """

        result, reason = self.scan(optionDict)
        if result == 'Pass':
            return 0, ''
        option = optionDict['usbDevices']

        # Note: Not that this case can even exist, but keeping it for
        #       standard's sake

        cmd = '/bin/grep "release 5" /etc/redhat-release'
        output = tcs_utils.tcs_run_cmd(cmd, True)

        # RHEL 4 PCMCIA
        # NOTE: This requires testing on RHEL4
        if output[0] != 0:
            cmd = "/bin/rpm -q pcmcia-cs"
            output = tcs_utils.tcs_run_cmd(cmd, True)
            if output[0] == 0:
                cmd = "/sbin/chkconfig pcmcia off"
                output = tcs_utils.tcs_run_cmd(cmd, True)
                if output[0] != 0:
                    msg = 'Failed to disable pcmcia'
                    self.logger.error(self.module_name, 'Apply Error: ' + msg)
                    raise tcs_utils.ActionError('%s %s' %
                                                (self.module_name, msg))

        # Checking if USB is disabled in default kernel
        cmd = "/sbin/grubby --info=`/sbin/grubby --default-kernel` "
        cmd += "| /bin/grep nousb"
        output = tcs_utils.tcs_run_cmd(cmd, True)
        if output[0] != 0:
            opt = str(option)
            if opt == '1':
                cmd = "/sbin/grubby --update-kernel=`/sbin/grubby --default-kernel` "
                cmd += "--args='nousb nopcmcia=1'"
                output = tcs_utils.tcs_run_cmd(cmd, True)
            elif opt == '2':
                cmd = "/sbin/grubby --update-kernel=`/sbin/grubby --default-kernel` "
                cmd += "--args='nousbstorage nopcmcia=1'"
                output = tcs_utils.tcs_run_cmd(cmd, True)
            else:
                msg = 'You must supply either a 1 or 2 as the option for %s' \
                % self.module_name
                raise tcs_utils.ActionError(msg)
            if output[0] != 0:
                msg = 'Failed to disable usb'
                self.logger.error(self.module_name, 'Apply Error: ' + msg)
                raise tcs_utils.ActionError('%s %s' % (self.module_name, msg))
        sb_utils.SELinux.restoreSecurityContext(self.__target_file)
        msg = 'USB & PCMCIA disabled'
        self.logger.notice(self.module_name, 'Apply Performed: ' + msg)
        return 1, 'disabled'