Ejemplo n.º 1
0
    def is_installed_oscap_ok():
        """Check whether expected openscap rpms are installed."""
        class GetCmdStdout():
            def __init__(self):
                self.stdout_lines = []

            def __call__(self, line):
                if line.strip():
                    self.stdout_lines.append(line.strip())

        if not os.path.exists(settings.openscap_binary):
            log_message("Oscap with SCE enabled is not installed")
            return False
        if not os.access(settings.openscap_binary, os.X_OK):
            log_message("Oscap with SCE %s is not executable"
                        % settings.openscap_binary)
            return False
        # that's generic problem that could be on various rpm-based systems
        url = "https://access.redhat.com/documentation/en-us/red_hat_enterprise_linux/6/html-single/6.10_release_notes/index#BZ1804691"
        for pkg in settings.openscap_rpms:
            cmd = ["rpm", "-q", pkg, "--qf", "%{ARCH}\n"]
            cmdout = GetCmdStdout()
            ProcessHelper.run_subprocess(cmd, function=cmdout)
            if SystemIdentification.get_arch() not in cmdout.stdout_lines:
                log_message("The %s rpm is not installed for the"
                            " %s architecture. This usually ends in a broken"
                            " state in which all the Preupgrade Assistant modules"
                            " are skipped (notchecked state). Please, install"
                            " packages related for your architecture. See %s"
                            " for more info."
                            % (pkg, SystemIdentification.get_arch(), url))
                return False
        return True
Ejemplo n.º 2
0
 def common_results(self):
     """run common scripts"""
     log_message("Gathering logs used by the Preupgrade Assistant:")
     self.switch_dir()
     try:
         max_length = max(
             max([len(x.split("=", 4)[3]) for x in self.lines]),
             len(settings.assessment_text))
         # Log files which will not be updated
         # when RPM database is not changed
         for counter, line in enumerate(self.lines):
             line = line.strip()
             if line.startswith("#"):
                 continue
             cmd, log_file, dummy_bash_value, name, values = line.split(
                 "=", 4)
             log_message(
                 "%s : %.2d/%d ...running" %
                 (name.ljust(max_length), counter + 1, len(self.lines)),
                 new_line=False)
             start_time = datetime.datetime.now()
             common_file_path = self.common_logfiles(log_file)
             ProcessHelper.run_subprocess(cmd,
                                          output=common_file_path,
                                          shell=True)
             end_time = datetime.datetime.now()
             diff = end_time - start_time
             log_message(" %sfinished (time %.2d:%.2ds)" %
                         ('\b' * 8, diff.seconds / 60, diff.seconds % 60))
             # os.chmod(common_file_path, 0640)
         self.switch_back_dir()
     except IOError:
         return 0
     else:
         return 1
 def common_results(self):
     """run common scripts"""
     log_message("Gathering logs used by the Preupgrade Assistant:")
     self.switch_dir()
     try:
         max_length = max(max([len(x.split("=", 4)[3]) for x in self.lines]), len(settings.assessment_text))
         # Log files which will not be updated
         # when RPM database is not changed
         for counter, line in enumerate(self.lines):
             line = line.strip()
             if line.startswith("#"):
                 continue
             cmd, log_file, dummy_bash_value, name, values = line.split("=", 4)
             log_message("%s : %.2d/%d ...running" % (name.ljust(max_length),
                                                      counter+1,
                                                      len(self.lines)),
                         new_line=False)
             start_time = datetime.datetime.now()
             common_file_path = self.common_logfiles(log_file)
             ProcessHelper.run_subprocess(cmd, output=common_file_path, shell=True)
             end_time = datetime.datetime.now()
             diff = end_time - start_time
             log_message(" %sfinished (time %.2d:%.2ds)" % ('\b' * 8,
                                                            diff.seconds / 60,
                                                            diff.seconds % 60))
             # os.chmod(common_file_path, 0640)
         self.switch_back_dir()
     except IOError:
         return 0
     else:
         return 1
Ejemplo n.º 4
0
def check_rpm_to(check_rpm="", check_bin=""):
    """
    Function checks if relevant package is installed and if relevant binary exists on the system.

    Function is needed from module point of view.

    :param check_rpm: list of RPMs separated by comma
    :param check_bin: list of binaries separated by comma
    :return:
    """
    not_applicable = 0

    if check_rpm != "":
        rpms = check_rpm.split(',')
        lines = FileHelper.get_file_content(VALUE_RPM_QA, "rb", True)
        for rpm in rpms:
            lst = [x for x in lines if rpm == x.split('\t')[0]]
            if not lst:
                log_high_risk("Package %s is not installed." % rpm)
                not_applicable = 1

    if check_bin != "":
        binaries = check_bin.split(',')
        lines = FileHelper.get_file_content(VALUE_EXECUTABLES, "rb", True)
        for binary in binaries:
            cmd = "which %s" % binary
            if ProcessHelper.run_subprocess(cmd, print_output=False, shell=True) != 0:
                log_high_risk("Binary %s is not installed." % binary)
                not_applicable = 1

    if not_applicable:
        log_high_risk("Please, install all required packages (and binaries)"
                      " and run preupg again to process check properly.")
        exit_fail()
    return not_applicable
def check_rpm_to(check_rpm="", check_bin=""):
    """
    Function checks if relevant package is installed and if relevant binary exists on the system.

    Function is needed from module point of view.

    :param check_rpm: list of RPMs separated by comma
    :param check_bin: list of binaries separated by comma
    :return:
    """
    not_applicable = 0

    if check_rpm != "":
        rpms = check_rpm.split(',')
        lines = FileHelper.get_file_content(VALUE_RPM_QA, "rb", True)
        for rpm in rpms:
            lst = [x for x in lines if rpm == x.split('\t')[0]]
            if not lst:
                log_high_risk("Package %s is not installed." % rpm)
                not_applicable = 1

    if check_bin != "":
        binaries = check_bin.split(',')
        for binary in binaries:
            cmd = "which %s" % binary
            if ProcessHelper.run_subprocess(
                    cmd, print_output=False, shell=True) != 0:
                log_high_risk("Binary %s is not installed." % binary)
                not_applicable = 1

    if not_applicable:
        log_high_risk("Please, install all required packages (and binaries)"
                      " and run preupg again to process check properly.")
        exit_fail()
    return not_applicable
Ejemplo n.º 6
0
 def kickstart_scripts():
     ks_scripts_file = os.path.join(settings.data_dir, "preassessment",
                                    settings.KS_SCRIPTS)
     try:
         lines = FileHelper.get_file_content(ks_scripts_file, "rb", True)
         for line in lines:
             line = line.strip()
             if line.startswith("#"):
                 continue
             if 'is not installed' in line:
                 continue
             cmd, name = line.split("=", 2)
             kickstart_file = os.path.join(settings.KS_DIR, name)
             ProcessHelper.run_subprocess(cmd, output=kickstart_file, shell=True)
     except IOError:
         pass
 def run_scan(self, function=None):
     """
     The function is used for either scanning system or
     for applying changes on the target system
     """
     cmd = self.openscap_helper.build_command()
     logger_debug.debug('running_command: %s', cmd)
     return ProcessHelper.run_subprocess(cmd, print_output=False, function=function)
Ejemplo n.º 8
0
 def run_scan(self, function=None):
     """
     The function is used for either scanning system or
     for applying changes on the target system
     """
     cmd = self.openscap_helper.build_command()
     logger_debug.debug('running_command: %s', cmd)
     return ProcessHelper.run_subprocess(cmd, print_output=False, function=function)
Ejemplo n.º 9
0
 def kickstart_scripts():
     ks_scripts_file = os.path.join(settings.data_dir, "preassessment",
                                    settings.KS_SCRIPTS)
     try:
         lines = FileHelper.get_file_content(ks_scripts_file, "rb", True)
         for line in lines:
             line = line.strip()
             if line.startswith("#"):
                 continue
             if 'is not installed' in line:
                 continue
             cmd, name = line.split("=", 2)
             kickstart_file = os.path.join(settings.KS_DIR, name)
             ProcessHelper.run_subprocess(cmd,
                                          output=kickstart_file,
                                          shell=True)
     except IOError:
         pass
Ejemplo n.º 10
0
    def prepare_xml_for_html(self):
        """The function prepares a XML file for HTML creation"""
        # Reload XML file
        self.report_parser.reload_xml(self.openscap_helper.get_default_xml_result_path())
        # Replace fail in case of slight and medium risks with needs_inspection
        self.report_parser.replace_inplace_risk(scanning_results=self.scanning_progress)
        if not self.conf.debug:
            self.report_parser.remove_debug_info()
        self.report_parser.reload_xml(self.openscap_helper.get_default_xml_result_path())
        self.report_parser.update_check_description()
        self.prepare_for_generation()

        if not self.conf.verbose:
            self.xml_mgr.remove_html_information()
        # This function finalize XML operations
        self.finalize_xml_files()
        if self.conf.text:
            ProcessHelper.run_subprocess(self.get_cmd_convertor(), print_output=False, shell=True)
Ejemplo n.º 11
0
    def prepare_xml_for_html(self):
        """The function prepares a XML file for HTML creation"""
        # Reload XML file
        self.report_parser.reload_xml(
            self.openscap_helper.get_default_xml_result_path())
        # Replace fail in case of slight and medium risks with needs_inspection
        self.report_parser.replace_inplace_risk(
            scanning_results=self.scanning_progress)
        if not self.conf.debug:
            self.report_parser.remove_debug_info()
        self.report_parser.reload_xml(
            self.openscap_helper.get_default_xml_result_path())
        self.report_parser.update_check_description()
        self.prepare_for_generation()

        if not self.conf.verbose:
            self.xml_mgr.remove_html_information()
        # This function finalize XML operations
        self.finalize_xml_files()
        if self.conf.text:
            ProcessHelper.run_subprocess(self.get_cmd_convertor(),
                                         print_output=False,
                                         shell=True)
Ejemplo n.º 12
0
def generate_html():
    if not os.path.exists(diff_report_name_xml):
        sys.exit("Error: HTML generation failed: source {0} not found."
                 .format(diff_report_name_xml))
    cmd = OpenSCAPHelper.build_generate_command(diff_report_name_xml,
                                                diff_report_name_html,
                                                parsed_opts.simple_html)
    log = "html.log"  # log for text printed during html generation
    ret_val = ProcessHelper.run_subprocess(cmd, print_output=True,
                                           output=log)
    if ret_val != 0:
        sys.exit("Error: HTML generation failed. See {0} for details."
                 .format(log))
    else:  # no error when generating html - safe to remove the log
        os.remove(log)
Ejemplo n.º 13
0
 def generate_html_or_text(self):
     self.generate_html()
     if self.conf.text:
         ProcessHelper.run_subprocess(self.get_cmd_convertor(),
                                      print_output=False,
                                      shell=True)
 def generate_html_or_text(self):
     self.generate_html()
     if self.conf.text:
         ProcessHelper.run_subprocess(self.get_cmd_convertor(), print_output=False, shell=True)