Exploit database

GH-79eaa866baf7dd38942437ed09636fed

f5devcentral/cve-2020-5902-ioc-bigip-checker

GitHubNot listedPoC
Download repository ZIP

Sources for CVE-2020-5902

59 sources

Preferred order: Exploit-DB, Metasploit, then GitHub repositories by stars. Open preferred source

Repository files2
f5devcentral/cve-2020-5902-ioc-bigip-checkerRevision 6171b3fa947d

Files from this repository share one source choice. Supporting files may cover other vulnerabilities.

CVE-2020-5902_bigip_ioc_checker.py

Python · 38,690 bytes
#!/usr/bin/python
"""This script is intended to search the BIG-IP for potential
Indicators of Compromise (IoCs) relating to CVE-2020-5902"""

# Copyright 2019 F5 Networks, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#       http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# Author:
#   Sr ENE Bean Wu,
#   Sp Support Engineer Kidd Wang,
#   Sr Security Engineer David Wang,
#   Sr Security Engineer Aaron Brailsford

# Version: CVE-2020-5902_bigip_ioc_checker.py v1.5

import sys
import os
import re
import gzip
import getopt
import base64

try:
    from hashlib import md5
except ImportError:
    from md5 import md5

try:
    all
except NameError:
    def all(iterable):
        for element in iterable:
            if not element:
                return False
        return True
try:
    any
except NameError:
    def any(s):
        for v in s:
            if v:
                return True
        return False


class Util(object):
    """Small utility class to make printing to screen easier, handles
    selective colourization of messages (for output to a terminal vs.
    redirected output to a file) and header lines"""
    def __init__(self, disable_color_print):
        self.output = ""
        self.disable_color_print = disable_color_print

    def exec_cmd(self, cmd):
        # need to compatible with python 2.4 no finally
        try:
            self.output = os.popen(cmd).read()
            return self.output
        except Exception:
            t, e = sys.exc_info()[:2]
            print("CMD Error: %s %s" % (e, cmd))
            return self.output

    def print_msg(self, message, key_words=None):
        """Prints a colourized message out to stdout, used to highlight important
        messages"""
        if not self.disable_color_print:
            color_begin = '\033[1;31m'
            color_end = '\033[0m'
            if key_words:
                message = message.replace(key_words, color_begin + key_words + color_end)
        print(message)

    @staticmethod
    def head_line(message):
        """Prints the 'headline' message, i.e. used to indicate sections of checks"""
        n = int((80 - len(message)) / 2)
        title = r"%s %s %s" % ('=' * n, message, '=' * n)
        return title


class Checker(object):
    """This is essentially the main program logic; we take input of which checks to skip
    and which to run, then run through them one-at-a-time to check the system for
    the defined potential IoCs"""
    def __init__(self, checks_to_skip):
        self.checks_to_skip = checks_to_skip
        self.blacklist = ['.php', '.jsp', 'fsockopen', 'bash -i', 'nc -e', 'use Socket',
                          'socket.socket', 'curl ', 'wget ', 'base64', 'nmap ', 'passthru',
                          'shell_exec', 'phpinfo', 'base64_decode', 'fopen', 'fclose',
                          'readfile', 'php_uname', 'eval']
        self.fixed_version = {'16': 0, '15': 104,
                              '14': 126, '13': 134, '12': 152, '11': 652}
        self.bug_id = '895525'
        self.sys_eicheck_hash = ['68f669cc7e164ad70b87a1f08b6094f5',
                                 '77280f2ba2ae018c63ccb2fac65bc32e',
                                 '9a7b875ae839d4690d27e18ad02ac3fb']
        self.upgrade_time = ''
        self.is_recent_upgrade = False
        self.backdoor_flag = False
        self.patched_flag = False
        self.attacked_flag = False
        self.base64_commnd_count = 0
        self.attack_msg_header = '!! IoC pattern'
        self.result = {
            'version': '',
            'hf': '',
        }
        self.tmp_normal_file = [
            '/tmp/._f5_Debug_Control.mmap',
            '/tmp/hosts_script',
            '/tmp/pci_ethmap',
            '/tmp/new-license',
            '/tmp/pci_order_ethmap',
            '/tmp/bwc-tmm.mp.bwcdist',
            '/tmp/old-license',
            '/tmp/sshd_login.sh',
            '/tmp/.rnd',
            '/tmp/BigDB.dat.orig',
            '/tmp/localdbmgr_tmp.out',
            '/tmp/dhclient.sh',
            '/tmp/.s.PGSQL.5432.lock',
            '/tmp/httpd_reconfig.pl',
            '/tmp/mgmt_dhclient.sh',
            '/tmp/systemauth.pl.null'
        ]

    def __get_version(self):
        # read system os version, build and enghf ID
        util = Util(self.checks_to_skip['disable_color_print'])
        version_output = util.exec_cmd('tmsh show sys version')
        version = '0'
        hf = '0'
        if version_output:
            for line in version_output.split('\n'):
                if '  Version' in line:
                    version = line.strip().split(' ')[-1]
                elif '  Build' in line:
                    hf = line.strip().split(' ')[-1]
            self.result['version'] = version
            self.result['hf'] = hf
        return version_output

    def __check_version(self, version_output):
        # check if current version fixed CVE-2020-5902
        if self.result['version']:
            main = self.result['version'].split('.')[0]
            miner = ''.join(self.result['version'].split('.')[1:])
            if len(miner) == 2:
                miner += '0'
            if int(miner) < self.fixed_version[main] and self.bug_id not in version_output:
                return False
            return True
        return False

    def __check_version_info(self):
        util = Util(self.checks_to_skip['disable_color_print'])
        version_output = self.__get_version()
        is_patched = self.__check_version(version_output)
        self.patched_flag = is_patched
        util.print_msg(
            '[+] Version %s Build %s CVE-2020-5902 Fixed: %s'
            % (self.result['version'], self.result['hf'], is_patched)
        )
        if is_patched:
            util.print_msg(
                '[+] Running non-vulnerable version, '
                'double check if any attack happened before upgrading',
                'Running non-vulnerable version,'
                ' double check if any attack happened before upgrading')
            
    def __home_check(self):
        util = Util(self.checks_to_skip['disable_color_print'])
        content = util.exec_cmd("ls -al /home/ 2>/dev/null |grep -e systems -e bigipuser ")
        if content:
            title = util.head_line(' /home/ checking ')
            message = "%s malicious user created in /home/:\n%s" \
                      % (self.attack_msg_header, content)
            util.print_msg("\n[+] %s" % title)          
            util.print_msg(message, content)
            
    def __check_each_audit(self, log_file):
        util = Util(self.checks_to_skip['disable_color_print'])
        # Get log file content
        if log_file.endswith('.gz'):
            f = gzip.open(log_file, 'rb')
            content = f.read()
            f.close()
        else:
            f = open(log_file, 'rb')
            content = f.read()
            f.close()
        result = {}

        admin_auditlog_pattern = re.compile(r'list\s+/?\s*auth\s+user\s+admin')
        for line in content.split('\n'):
            regex_result = admin_auditlog_pattern.search(str(line), re.I)
            if regex_result and 'user=admin' in line:
                result['list_admin_auditlog'] = [log_file]
                self.attacked_flag = True
                break

        # attacker can only change tmsh modify, create, list and delete to alias bash!
        alias_pattern = re.compile(r'create\s+/?\s*cli\s+alias')
        cmd_bash_pattern = re.compile(r'command\s+bash')
        cli_alias_bash_pattern = re.compile(r'cli_shared_alias_command\s+"bash"')
        for line in content.split('\n'):
            line = line.lower()
            is_curd = 'list ' in line or 'delete ' in line or 'modify ' in line or 'create ' in line
            is_cli_alias = alias_pattern.search(line, re.I)
            is_cmd_bash = cmd_bash_pattern.search(line, re.I)
            is_cli_alias_bash = cli_alias_bash_pattern.search(line, re.I)
            if (is_cli_alias and is_curd and is_cmd_bash) or is_cli_alias_bash:
                self.attacked_flag = True
                result['create_alias_auditlog'] = [log_file]
                break

        # check if run util bash command contains blacklisted word.
        cmd_check_pattern = re.compile(r"run\s+/?\s*util\s+bash.*")
        if not self.checks_to_skip['bigiq_cmd_check']:
            for line in content.split('\n'):
                if 'base64 ' in line:
                    self.base64_commnd_count += 1
                cmd = cmd_check_pattern.search(str(line), re.I)
                if cmd and any(word in line for word in self.blacklist):
                    self.attacked_flag = True
                    if 'run_bash_command' not in result.keys():
                        result['run_bash_command'] = [cmd.group(0)]
                    if not cmd.group(0) in result['run_bash_command']:
                        result['run_bash_command'].append(cmd.group(0))
        else:
            try:
                bigiq_blacklist = []
                for word in self.blacklist:
                    if word != 'base64':
                        bigiq_blacklist.append(word)
                util_bash_pattern = re.compile(r'run\s+/?\s*util\s+bash.*')
                base64_pattern = re.compile(r'run\s+/?\s*util\s+bash.*base64\s+-{1,2}d')
                for line in content.split('\n'):
                    regex_bash = util_bash_pattern.search(str(line), re.I)
                    # highlight_part = 'malicious bash command found'
                    if regex_bash and any(word in line for word in bigiq_blacklist):
                        self.attacked_flag = True
                        if 'run_bash_command' not in result.keys():
                            result['run_bash_command'] = [regex_bash.group(0)]
                        if not regex_bash.group(0) in result['run_bash_command']:
                            result['run_bash_command'].append(regex_bash.group(0))
                    elif regex_bash and 'base64' in line:
                        regex_base64 = base64_pattern.search(line, re.I)
                        match = regex_base64.group(0)
                        tmp = match.replace('|', '').replace('"', '').replace("'", '')
                        tmp = re.sub(r'\s+', ' ', tmp)
                        base64_str = tmp.split(' ')[-3]
                        data = base64.b64decode(base64_str)
                        if any(word in data for word in self.blacklist):
                            self.attacked_flag = True
                            if 'run_bash_command' not in result.keys():
                                result['run_bash_command'] = [match]
                            if not match in result['run_bash_command']:
                                result['run_bash_command'].append(match)
            except Exception:
                t, e = sys.exc_info()[:2]
                util.print_msg("Base64 Error: %s %s" % (e, match))

        # check if user systems was created in audit log
        regex_bigip = re.search(r'auth\s+user\s+systems', content, re.I)
        regex_mcpd = re.search(r'user_role_partition_user\s+"systems"', content, re.I)
        if regex_bigip or regex_mcpd:
            self.attacked_flag = True
            result['create_user_systems_auditlog'] = {
                'systems': []
            }
            result['create_user_systems_auditlog']['systems'].append(log_file)

        # check if user bigipuserX was created in audit log
        regex_bigip = re.findall(r'auth\s+user\s+(bigipuser\w+)', content, re.I)
        regex_mcpd = re.findall(r'user_role_partition_user\s+"(bigipuser\w+)', content, re.I)
        if regex_bigip and regex_mcpd:
            regex_bigip = list(set(regex_bigip))
            regex_mcpd = list(set(regex_mcpd))
            if len(regex_bigip) > len(regex_mcpd):
                regex_result = regex_bigip
            else:
                regex_result = regex_mcpd
        elif regex_bigip:
            regex_result = list(set(regex_bigip))
        elif regex_mcpd:
            regex_result = list(set(regex_mcpd))
        else:
            regex_result = None

        if regex_result:
            self.attacked_flag = True
            if 'create_user_systems_auditlog' not in result.keys():
                result['create_user_systems_auditlog'] = {}
            for user in regex_result:
                if not user in result['create_user_systems_auditlog'].keys():
                    result['create_user_systems_auditlog'][user] = [log_file]
                else:
                    result['create_user_systems_auditlog'][user].append(log_file)

        # check if command "run /util bash /tmp/<filename>" was run in tmsh
        regex_result = re.search(r'run\s+/?\s*util\s+bash\s+/tmp', content, re.I)
        if regex_result:
            self.attacked_flag = True
            result['run_bash_auditlog'] = [log_file]

        if 'user "%tmui"' in content:
            self.attacked_flag = True
            result['user_tmui'] = [log_file]
        return result

    def __audit_check(self):
        # find all of audit logs
        util = Util(self.checks_to_skip['disable_color_print'])
        cmd_output = util.exec_cmd(
            'find /var/log/ -name "audit*" -type f 2>/dev/null')
        audit_logs = cmd_output.strip().split('\n')
        check_result = {}
        if audit_logs:
            for audit_log in audit_logs:
                if 'audit' in audit_log:
                    single_result = self.__check_each_audit(audit_log)

                if not check_result:
                    check_result = single_result
                else:
                    for single_key, single_value in single_result.items():
                        if single_key not in check_result.keys():
                            check_result[single_key] = single_value
                        else:
                            if isinstance(single_value, dict):
                                for sec_key, sec_value in single_value.items():
                                    if sec_key not in check_result[single_key].keys():
                                        check_result[single_key][sec_key] = sec_value
                                    else:
                                        check_result[single_key][sec_key].extend(sec_value)
                            else:
                                check_result[single_key].extend(single_value)
        title = util.head_line('log and config checking')
        util.print_msg("\n[+] %s" % title)
        if 'list_admin_auditlog' in check_result.keys():
            message = r'%s "list auth user admin" found in files %s' % \
                      (self.attack_msg_header, str(check_result['list_admin_auditlog']))
            util.print_msg(message, 'list auth user admin')
        if 'create_user_systems_auditlog' in check_result.keys():
            for name in check_result['create_user_systems_auditlog'].keys():
                log_files = str(check_result['create_user_systems_auditlog'][name])
                message = r'%s user "%s" created in files %s' % \
                          (self.attack_msg_header, name, log_files)
                util.print_msg(message, name)
        if 'create_alias_auditlog' in check_result.keys():
            log_files = str(check_result['create_alias_auditlog'])
            message = r'%s cli alias found in files %s' % (self.attack_msg_header, log_files)
            util.print_msg(message, 'cli alias')
        if 'run_bash_auditlog' in check_result.keys():
            log_files = str(check_result['run_bash_auditlog'])
            message = r'%s "run /util bash /tmp" found in files %s' % \
                      (self.attack_msg_header, log_files)
            util.print_msg(message, "run /util bash /tmp")
        if 'user_tmui' in check_result.keys():
            log_files = str(check_result['user_tmui'])
            message = r'%s user %%tmui error found in files %s' % \
                      (self.attack_msg_header, log_files)
            util.print_msg(message, 'user %tmui')
        if 'run_bash_command' in check_result.keys():
            commands = str(check_result['run_bash_command'])
            message = r'%s malicious bash command found: %s' % (self.attack_msg_header, commands)
            util.print_msg(message, 'malicious bash command found')
            if self.base64_commnd_count > 10:
                msg = "!!  %s duplicated bash commands are detected as malicious"\
                " because of the base64 encoding script! Those could be false positives"\
                " on a BIG-IP system managed by BIG-IQ. You can use option -q"\
                " to ignore some legitimate base64 encoding scripts sent from BIG-IQ."\
                %self.base64_commnd_count
                util.print_msg(msg, msg)

    def __journal_check(self):
        # checking if journal log contains '..;', '/hsqldb;' and '/hsqldb%0a'
        journal_check_result = {'hsqldb': False, 'semicolon': False}
        if os.path.exists('/bin/journalctl'):
            util = Util(self.checks_to_skip['disable_color_print'])
            content = util.exec_cmd(
                "journalctl /bin/logger | grep -e ';' -e 'hsqldb'")
            for line in content.split('\n'):
                is_hsqldb = 'hsqldb;' in line or "hsqldb\\n" in line
                is_not_404 = ' 404 ' not in line
                is_ssl_acc = '[ssl_acc]' in line
                is_semicolon = '..;' in line
                if not journal_check_result['hsqldb']:
                    if is_hsqldb and is_not_404 and is_ssl_acc:
                        self.attacked_flag = True
                        message = r"%s request to /hsqldb found in journal log, Run command " \
                                  r"'/bin/journalctl /bin/logger|grep hsqldb' " \
                                  % self.attack_msg_header
                        if self.patched_flag:
                            message = r"""%s -- Could be false positive if the system has been patched,
                            need to check log time and patching time!
                            """ % message
                        util.print_msg(message, '/hsqldb')
                        journal_check_result['hsqldb'] = True
                if not journal_check_result['semicolon']:
                    if is_semicolon and is_not_404 and is_ssl_acc:
                        self.attacked_flag = True
                        message = r"""%s '..;' found in journal log, Run command '/bin/journalctl /bin/logger|grep "\\.\\.;"'
                        """ % self.attack_msg_header
                        if self.patched_flag:
                            message = r"""%s -- Could be false positive if the system has been patched,
                            need to check log time and patching time!
                            """ % message
                        util.print_msg(message, r"'..;'")
                        journal_check_result['semicolon'] = True

    def __systems_check(self):
        if os.path.exists('/config/bigip_user.conf'):
            f = open('/config/bigip_user.conf')
            content = f.read()
            f.close()

            util = Util(self.checks_to_skip['disable_color_print'])
            # check if user systems has been created in /config/bigip_user.conf
            regex_result = re.search(r"user\s+systems", content, re.I)
            if regex_result:
                self.attacked_flag = True
                message = '%s user "systems" created in bigip_user.conf, need to confirm with operator' % self.attack_msg_header
                util.print_msg(message, r"systems")

            # check if user bigipuserX has been created in /config/bigip_user.conf
            regex_result = re.findall(r"user\s+(bigipuser\w+)", content, re.I)
            if regex_result:
                self.attacked_flag = True
                for name in regex_result:
                    message = '%s user "%s" created in bigip_user.conf, need to confirm with operator' % (self.attack_msg_header, name)
                    util.print_msg(message, name)

    def __alias_check(self):
        # attacker can only change tmsh modify, create, list and delete to alias bash!
        util = Util(self.checks_to_skip['disable_color_print'])
        content = util.exec_cmd("awk '/^cli.alias/,/^}/' /config/bigip_*.conf 2>/dev/null")
        is_tmsh_curd = re.search(r"list|modify|create|delete\s+{", content, re.I)
        is_cmd_bash = re.search(r"command\s+bash", content, re.I)
        if is_tmsh_curd and is_cmd_bash:
            self.attacked_flag = True
            content = content.replace('\n', ' ')
            message = "%s cli alias found in config file as below:\n %s" \
                      % (self.attack_msg_header, content)
            util.print_msg(message, content)

    def __catalina_check(self):
        # When fileSave.jsp and fileRead.jsp could not read or
        # save file due to permission or file not found error, Catalina will log it.
        util = Util(self.checks_to_skip['disable_color_print'])
        output = util.exec_cmd(
            "zgrep -e 'workspace.fileSave_jsp] in context with path' -e "
            "'workspace.fileRead_jsp] in context with path' -A 1 /var/log/tomcat/catalina.out* "
            "2>/dev/null|grep FileNotFoundException "
        )
        catalina_check_result = {}
        if len(output) > 5:
            for line in output.split('\n'):
                if 'FileNotFoundException' in line and '/' in ''.join(line.split(':')[1:]):
                    self.attacked_flag = True
                    file = line.split(' ')[1]
                    log = line.split(' ')[0].split(':')[0]
                    if not log in catalina_check_result:
                        catalina_check_result[log] = []
                    if not file in catalina_check_result[log]:
                        catalina_check_result[log].append(file)
            if catalina_check_result:
                for log in catalina_check_result:
                    message = "%s %s access denied in file %s" % (self.attack_msg_header, catalina_check_result[log], log)
                    util.print_msg(message, str(catalina_check_result[log]))

    def __bigipstartup_check(self):
        # check if /config/startup contains blacklisted words
        bigipstartup_check_result = []
        util = Util(self.checks_to_skip['disable_color_print'])
        if os.path.exists('/config/startup'):
            f = open('/config/startup')
            content = f.read()
            f.close()
            for line in content.split('\n'):
                if not line.startswith('#') and \
                        any(i in line for i in self.blacklist) and \
                        line.strip() not in bigipstartup_check_result:
                    self.attacked_flag = True
                    bigipstartup_check_result.append(line.strip())
                    highlight_part = line.strip()
                    message = r"%s Possible backdoor %s in file /config/startup" \
                            % (self.attack_msg_header, highlight_part)
                    util.print_msg(message, highlight_part)

    def __get_liveinstalltime(self):
        util = Util(self.checks_to_skip['disable_color_print'])
        if os.path.exists('/var/log/liveinstall.log'):
            cmd_output = util.exec_cmd(
                r"grep 'install start at' "
                r"/var/log/liveinstall.log|grep -Po '\d+/\d+/\d+'")
            self.upgradetime = cmd_output.strip()
            if '/' in self.upgradetime:
                year = self.upgradetime.split('/')[0]
                month = self.upgradetime.split('/')[1]
                date = self.upgradetime.split('/')[2]
                if year == '2020':
                    if month == '06' and int(date) > 29:
                        self.is_recent_upgrade = True
                    elif int(month) > 6:
                        self.is_recent_upgrade = True
                    else:
                        self.is_recent_upgrade = False
                else:
                    self.is_recent_upgrade = False

    def __webshell_check(self):
        # check Files created after 2020 Jun 29 in /usr/local/www/. Could be webshell
        util = Util(self.checks_to_skip['disable_color_print'])
        util.exec_cmd('/bin/touch -t 202006290100 /tmp/kbtime')
        web_shell_self_result = util.exec_cmd(
            'find /usr/local/www/ -type f -newer /tmp/kbtime -ls|grep -v /usr/local/www/xui/framework/scripts/variables.js')
        if web_shell_self_result:
            self.backdoor_flag = True
            title = util.head_line(' webshell checking ')
            util.print_msg('\n[+]' + title)
            util.print_msg(
                '!! Files created in /usr/local/www/ after 2020 Jun 29, '
                'need to check if those are webshell or information leakage')
            print(web_shell_self_result)
            if self.is_recent_upgrade:
                msg = "!! System OS installed on %s, false positive possible." % self.upgradetime
                highlight_part = "System OS installed on %s, " \
                                 "false positive possible" % self.upgradetime
                util.print_msg(msg, highlight_part)
            if len(web_shell_self_result.split('\n')) > 20:
                msg = "!! Too many files detected, You can use option -w to skip webshell check if those are false positive"
                util.print_msg(msg, msg)

    def __autostart_check(self):
        # check Files created after 2020 Jun 29 in /etc/. Could be autostart script
        util = Util(self.checks_to_skip['disable_color_print'])
        util.exec_cmd('/bin/touch -t 202006290100 /tmp/kbtime')
        auto_self_result = util.exec_cmd(
            "(find /etc/ -type f -newer /tmp/kbtime -ls; "
            "find /var/spool/cron -type f -newer /tmp/kbtime -ls) "
            "|grep -e 'init.d' -e 'modules' -e cron -e 'rc.local'"
            "|grep -v /etc/selinux/targeted")
        if auto_self_result:
            self.backdoor_flag = True
            title = util.head_line(' auto start script checking ')
            util.print_msg('\n[+]' + title)
            util.print_msg(
                '!! Files created in /etc/ after 2020 Jun 29, need '
                'to check if those are malicious daemon startup script')
            if self.is_recent_upgrade:
                self.attacked_flag = True
                msg = "!! System OS installed on %s, false positive possible" % self.upgradetime
                highlight_part = "System OS installed on %s, " \
                                 "false positive possible" % self.upgradetime
                util.print_msg(msg, highlight_part)
            util.print_msg(auto_self_result)

    def __tmp_check(self):
        util = Util(self.checks_to_skip['disable_color_print'])
        # check files content contains blacklist words
        auto_self_result = util.exec_cmd(
            "find /tmp/ -type f -ls|grep -v 'sess_' |grep -v hsperfdata")
        lines = []
        for line in auto_self_result.split('\n'):
            if not line.split(' ')[-1].strip() in self.tmp_normal_file:
                lines.append(line)
        auto_self_result = '\n'.join(lines)
        malicious_files = []
        if auto_self_result:
            for i in auto_self_result.split('\n'):
                i = re.sub(r'\s+', ' ', i)
                file = i.strip().split(' ')[-1]
                if '/tmp/' in file:
                    f_name = open(file)
                    content = f_name.read()
                    f_name.close()
                    # files contain blacklisted words could be malicious
                    if any(kword in content for kword in self.blacklist):
                        malicious_files.append(file)
                        # highlight_part = file
        # check Files created after 2020 Jun 29 in /tmp. Could be malicious script
        util.exec_cmd('/bin/touch -t 202006290100 /tmp/kbtime')
        auto_self_result = util.exec_cmd(
            "find /tmp/ -type f -newer /tmp/kbtime -ls|grep -v 'sess_' |grep -v hsperfdata")
        lines = []
        for line in auto_self_result.split('\n'):
            if not line.split(' ')[-1].strip() in self.tmp_normal_file:
                lines.append(line)
        auto_self_result = '\n'.join(lines)
        if auto_self_result or malicious_files:
            self.backdoor_flag = True
            title = util.head_line(' /tmp/ checking ')
            util.print_msg('\n[+]' + title)
            for filename in malicious_files:
                message = '!! File %s could be a malicous script' % filename
                highlight_part = filename
                util.print_msg(message, highlight_part)
            util.print_msg(
                '!! Files created in /tmp/ after 2020 Jun 29, '
                'need to check if those are malicious scripts')
            if self.is_recent_upgrade:
                message = "!! System OS installed on %s, false positive possible" % self.upgradetime
                highlight_part = "System OS installed on %s, " \
                                 "false positive possible" % self.upgradetime
                util.print_msg(message, highlight_part)
            util.print_msg(auto_self_result)

    def __sys_eicheck(self):
        util = Util(self.checks_to_skip['disable_color_print'])
        if self.result['version']:
            version_number = ''.join(self.result['version'].split('.')[:2])
            if int(version_number) >= 131 and not os.path.exists("/usr/libexec/sys-eicheck.py"):
                highlight_part = 'Critical: /usr/libexec/sys-eicheck.py is missing'
                message = r"!! %s" % highlight_part
                util.print_msg(message, highlight_part)
        if os.path.exists("/usr/libexec/sys-eicheck.py"):
            a = open('/usr/libexec/sys-eicheck.py')
            b = a.read()
            a.close()
            py_sys_eicheck_hash = md5(b).hexdigest()
            bash_sys_eicheck_hash = util.exec_cmd(
                'md5sum /usr/libexec/sys-eicheck.py').strip().split(' ')[0]
            if py_sys_eicheck_hash == bash_sys_eicheck_hash and \
                    py_sys_eicheck_hash in self.sys_eicheck_hash:
                util.print_msg('[+] sys-eicheck.py hash check: PASS')
                util.print_msg(
                    '[+] BIG-IP Integrity check in progress. This may take several minutes.\n[+] '
                    'You can use -i or --skip_sys-eicheck argument to skip it.\n')
                output = util.exec_cmd("/usr/libexec/sys-eicheck.py")
                if 'Integrity Test Result: [ PASS ]' in output:
                    util.print_msg('[+] BIG-IP Integrity check result: PASS')
                else:
                    util.print_msg(
                        '[+] BIG-IP Integrity check result: FAIL', 'FAIL')
                    util.print_msg(output, 'FAIL')
            else:
                util.print_msg('[+] sys-eicheck.py hash check: FAIL, '
                               'sys-eicheck.py may have been altered.',
                               'sys-eicheck.py hash check: FAIL, '
                               'sys-eicheck.py may have been altered.')

    def checker(self):
        """Main logic block for this class; calls each IoC check in turn"""
        util = Util(self.checks_to_skip['disable_color_print'])
        util.print_msg(
            'CVE-2020-5902 Indicators of Compromise checker. False positive reports '
            'are possible and all results should be manually verified.')

        self.__check_version_info()

        self.__get_liveinstalltime()
        
        self.__home_check()
        
        if not self.checks_to_skip['sys_eicheck']:
            self.__sys_eicheck()

        if not self.checks_to_skip['audit_check']:
            self.__audit_check()

        if not self.checks_to_skip['journal_check']:
            self.__journal_check()

        if not self.checks_to_skip['systems_check']:
            self.__systems_check()

        if not self.checks_to_skip['alias_check']:
            self.__alias_check()

        if not self.checks_to_skip['catalina_check']:
            self.__catalina_check()

        if not self.checks_to_skip['bigipstartup_check']:
            self.__bigipstartup_check()

        if not self.checks_to_skip['autostart_check']:
            self.__autostart_check()

        if not self.checks_to_skip['tmp_check']:
            self.__tmp_check()

        if not self.checks_to_skip['webshell_check']:
            self.__webshell_check()

        if not self.attacked_flag and not self.backdoor_flag:
            util.print_msg('No indications of compromise known to this script found.')


if __name__ == '__main__':
    checks_to_skip = {
        'sys_eicheck': False,
        'audit_check': False,
        'journal_check': False,
        'systems_check': False,
        'alias_check': False,
        'catalina_check': False,
        'bigipstartup_check': False,
        'webshell_check': False,
        'autostart_check': False,
        'tmp_check': False,
        'bigiq_cmd_check': False,
        'disable_color_print': False
    }
    try:
        opts, args = getopt.getopt(
            sys.argv[1:], 'hiajylcbwutqp',
            ['help', 'skip_sys-eicheck', 'skip_audit_check', 'skip_journal_check',
             'skip_systems_check', 'skip_alias_check', 'skip_catalina_check',
             'skip_catalina_check', 'skip_bigipstartup_check',
             'skip_webshell_check', 'skip_autostart_check', 'skip_tmp_check', 'bigiq_cmd_check', 'disable_color_print'])
    except getopt.GetoptError:
        t, e = sys.exc_info()[:2]
        print(e)
        sys.exit()

    for opt_name, opt_value in opts:
        if opt_name in ('-h', '--help'):
            print("USAGE: python " + sys.argv[0])
            print("\nYou can use the following options <-iajylcbwut> to skip some checks:\n")
            print("Option: -i or --skip_sys-eicheck\n[+] Skip using the sys_eicheck utility "
                  "to scan the BIG-IP system for any unexpected changes to the system software.\n"
                  "[+] Please refer to https://support.f5.com/csp/article/K00029945"
                  "for more details about the sys-eicheck utility.\n"
                  "[+] The sys-eicheck utility may take several minutes to finish.\n")
            print("Option: -a or --skip_audit_check        "
                  "[+] Skip scanning the audit log for malicious activities.")
            print("Option: -j or --skip_journal_check      "
                  "[+] Skip scanning the journal log for malicious activities.")
            print("Option: -y or --skip_systems_check      "
                  "[+] Skip scanning /config/bigip_user.conf to look for malicious users.")
            print("Option: -l or --skip_alias_check        "
                  "[+] Skip scanning /config/bigip_*.conf for malicious alias definition.")
            print("Option: -c or --skip_catalina_check     "
                  "[+] Skip scanning the tomcat catalina.out log for malicious activities.")
            print("Option: -b or --skip_bigipstartup_check "
                  "[+] Skip checking if /config/startup contains blacklisted words.")
            print("Option: -w or --skip_webshell_check     "
                  "[+] Skip checking Files created after 2020 Jun 29 "
                  "in the /usr/local/www/ to look for possible webshell files.")
            print("Option: -u or --skip_autostart_check    "
                  "[+] Skip checking Files created after 2020 Jun 29 "
                  "in /etc/ to look for the possible autostart script.")
            print("Option: -t or --skip_tmp_check          "
                  "[+] Skip checking Files created after 2020 Jun 29 in /tmp")
            print("Option: -p or --disable_color_print     "
                  "[+] Disable color print, better for saving result")
            print("Option: -q or --bigiq_cmd_check         "
                  "[+] Run BIG-IQ compatible malicious command check\n")
            print("Option: -h or --help                    [+] Print usage")

            sys.exit()
        if opt_name in ('-i', '--skip_sys-eicheck'):
            checks_to_skip['sys_eicheck'] = True
            print(">>>> Skip sys-eicheck check")
        if opt_name in ('-a', '--skip_audit_check'):
            checks_to_skip['audit_check'] = True
            print(">>>> Skip audit log check")
        if opt_name in ('-j', '--skip_journal_check'):
            checks_to_skip['journal_check'] = True
            print(">>>> Skip journal log check")
        if opt_name in ('-y', '--skip_systems_check'):
            checks_to_skip['systems_check'] = True
            print(">>>> Skip systems user check")
        if opt_name in ('-l', '--skip_alias_check'):
            checks_to_skip['alias_check'] = True
            print(">>>> Skip alias command check")
        if opt_name in ('-c', '--skip_catalina_check'):
            checks_to_skip['catalina_check'] = True
            print(">>>> Skip tomcat catalina log check")
        if opt_name in ('-b', '--skip_bigipstartup_check'):
            checks_to_skip['bigipstartup_check'] = True
            print(">>>> Skip bigip startup check")
        if opt_name in ('-w', '--skip_webshell_check'):
            checks_to_skip['webshell_check'] = True
            print(">>>> Skip webshell check")
        if opt_name in ('-u', '--skip_autostart_check'):
            checks_to_skip['autostart_check'] = True
            print(">>>> Skip autostart check")
        if opt_name in ('-t', '--skip_tmp_check'):
            checks_to_skip['tmp_check'] = True
            print(">>>> Skip tmp directory check")
        if opt_name in ('-p', '--disable_color_print'):
            print(">>>> Disable color print")
            checks_to_skip['disable_color_print'] = True
        if opt_name in ('-q', '--bigiq_cmd_check'):
            checks_to_skip['bigiq_cmd_check'] = True
            print(">>>> Run BIG-IQ compatible malicious command check")
    checker_obj = Checker(checks_to_skip)
    checker_obj.checker()