Beispiel #1
0
    def vulscan(self):
        self.reset()

        distro, distro_release = lib.detect_distribution()

        yum = common.check_programs_installed("yum")
        apt = common.check_programs_installed("apt-get")

        if yum:
            self.redhat_get_installed_packages()

            if "centos" in distro.lower():
                self.redhat_centos_checkupdate()
                self.redhat_centos_vulscan()
            else:
                self.redhat_common_checkupdate()
                self.redhat_common_vulscan()

        if apt:
            self.debian_update_packages()
            self.debian_check_dependencies()
            self.debian_get_installed_packages()
            self.debian_scan_cveid_from_changelog()

        vuls = Kdatabase().get_obj("vuls")
        vuls["items"] = self.vuls
Beispiel #2
0
def kernel_available_version(response):
    available_kernel = ""

    if common.check_programs_installed("yum"):
        data, success, retcode = common.exec_command(
            ["yum", "list", "updates", "kernel"])

        if success:
            lines = data.split("\n")
            begin_pattern = re.compile(r"^Available Upgrades")
            begin_pattern2 = re.compile(r"^Updated Packages")
            begin_pattern3 = re.compile(r"^Upgraded Packages")
            is_begin = False

            for line in lines:
                if not is_begin:
                    if begin_pattern.match(line) or begin_pattern2.match(
                            line) or begin_pattern3.match(line):
                        is_begin = True
                        continue
                else:
                    result = line.split()

                    if len(result) == 3:
                        available_kernel = result[1]
                        break

    elif common.check_programs_installed("apt-cache"):
        data, success, retcode = common.exec_command(
            ["apt-cache", "search", "linux-image"])

        if success:
            lines = data.split("\n")
            pattern = re.compile(r"^linux-image-([\d\.]+)-(\d*)-")
            kernel_versions = []

            for line in lines:
                match = pattern.match(line.strip())

                if match and len(match.groups()) == 2:
                    kernel_versions.append(match.groups())

            kernel_versions.sort(key=lambda v: "".join(
                x.zfill(5) for x in v[0].split(".") + [v[1]]),
                                 reverse=True)

            if len(kernel_versions):
                available_kernel = "-".join(kernel_versions[0])

    response["kernel"].append({
        "name": Klanguage().to_ts(1129),
        "value": platform.release()
    })

    if available_kernel:
        response["kernel"].append({
            "name": Klanguage().to_ts(1130),
            "value": available_kernel
        })
Beispiel #3
0
    def do(action_useful):
        # Checking allows auto-hide to work for non-APT systems
        if not common.check_programs_installed('yum'):
            raise StopIteration

        yield command.Function(None, functions.yum_clean,
                               'yum clean all').execute()
Beispiel #4
0
    def debian_check_dependencies(self):
        aptitude = common.check_programs_installed("aptitude")

        if aptitude:
            self.changelogtool = "aptitude"
            return

        self.changelogtool = "apt-get"
Beispiel #5
0
    def ssh_detect(self):
        lines = []
        logfile = None

        if os.path.exists(macro.AUTH_LOG):
            logfile = macro.AUTH_LOG
        elif os.path.exists(macro.SECURE_LOG):
            logfile = macro.SECURE_LOG

        if logfile:
            lines = file_op.cat_lines(logfile, "r")
        else:
            if common.check_programs_installed("journalctl"):
                data, success, retcode = common.exec_command(
                    ['journalctl', '_COMM=sshd', '-n', '50'])

                if success:
                    lines = data.split("\n")
                else:
                    data, success, retcode = common.exec_command(
                        ['journalctl', '_COMM=ssh', '-n', '50'])

                    if success:
                        lines = data.split("\n")

        for line in lines:
            #Feb 1 16:07:41 iZj6cd9xxma2xamt72ui3qZ sshd[19864]: Failed password for root from 182.100.67.252 port 57888 ssh2
            #Feb 1 16:07:41 iZj6cd9xxma2xamt72ui3qZ sshd[19864]: Accepted password for root from 100.129.58.124 port 61745 ssh2
            s = re.search(
                "(^.*\d+:\d+:\d+).*sshd.*Accepted password for (.*) from (.*) port.*$",
                line, re.I | re.M)
            f = re.search(
                "(^.*\d+:\d+:\d+).*sshd.*Failed password for (.*) from (.*) port.*$",
                line, re.I | re.M)
            b = re.search("(^.*\d+:\d+:\d+).*sshguard.*Blocking (.*) for.*$",
                          line, re.I | re.M)

            if s:
                dt = datetime.strptime(s.group(1), '%b %d %X')
                new_dt = datetime(datetime.now().year, dt.month, dt.day,
                                  dt.hour, dt.minute, dt.second)
                ts = time_op.to_timestamp(new_dt)

                if ts > self.ssh_lasttime_scan and not net_op.is_private_ip(
                        s.group(3)):
                    self.ssh_login_success(s.group(2), s.group(3), ts)

            if f:
                dt = datetime.strptime(f.group(1), '%b %d %X')
                new_dt = datetime(datetime.now().year, dt.month, dt.day,
                                  dt.hour, dt.minute, dt.second)
                ts = time_op.to_timestamp(new_dt)

                if ts > self.ssh_lasttime_scan and not net_op.is_private_ip(
                        f.group(3)):
                    self.ssh_login_failed(f.group(2), f.group(3), ts)
Beispiel #6
0
    def candidate_size(self, package_name, candidate):
        apt = common.check_programs_installed("apt-get")
        size = 0

        if apt:
            data, success, retcode = common.exec_command(
                ["apt-cache", "show", package_name])

            if success:
                lines = data.split("\n")
                pattern_size = re.compile(r'^Size: (\d+)')

                for line in lines:
                    match = pattern_size.match(line)

                    if match:
                        size = int(match.groups()[0])
                        break

        yum = common.check_programs_installed("yum")

        #Available Packages
        #Name        : systemd
        #Arch        : x86_64
        #Version     : 219
        #Release     : 42.el7_4.4
        #Size        : 5.2 M
        if yum:
            data, success, retcode = common.exec_command(
                ["yum", "info", "available", package_name])

            if success:
                lines = data.split("\n")
                pattern = re.compile(r"^Size\s*:\s(.+)")  #need to upgrade

                for line in lines:
                    match = pattern.match(line)

                    if match:
                        size = common.sizestring2int(match.groups()[0])
                        break

        return size
Beispiel #7
0
    def repair(self, package):
        yum = common.check_programs_installed("yum")
        apt = common.check_programs_installed("apt-get")

        if not any([yum, apt]):
            return "Vulnerability repair not support on this OS"

        if yum:
            data, success, retcode = common.exec_command(
                ['yum', 'update', '-y', package])

            if not success:
                return "yum error : {} code : {}".format(data, retcode)
        elif apt:
            data, success, retcode = common.exec_command(
                ['apt-get', 'install', '-y', '--only-upgrade', package])

            if not success:
                return "apt-get error : {} code : {}".format(data, retcode)

        self.update_record(package)

        return None
Beispiel #8
0
def get_boot_time():
    if common.check_programs_installed("systemd-analyze"):
        data, success, retcode = common.exec_command(
            ['systemd-analyze', 'time'])

        if success:
            pattern = re.compile(
                r"^Startup finished in (.+s) \(kernel\) \+ (.+s) \(initrd\) \+ (.+s) \(userspace\) \= (.+s)"
            )
            match = pattern.match(data)

            if match:
                groups = list(match.groups())

                if len(groups) == 4:
                    for i in range(len(groups)):
                        index = groups[i].find(".")
                        if index >= 0 and len(
                                groups[i][index + 1:index + 4]) == 3:
                            groups[i] = groups[i][:index +
                                                  2] + groups[i][index + 4:]

                    return tuple(groups)

            pattern = re.compile(
                r"^Startup finished in (.+s) \(kernel\) \+ (.+s) \(userspace\) \= (.+s)"
            )
            match = pattern.match(data)

            if match:
                groups = list(match.groups())

                if len(groups) == 3:
                    for i in range(len(groups)):
                        index = groups[i].find(".")
                        if index >= 0 and len(
                                groups[i][index + 1:index + 4]) == 3:
                            groups[i] = groups[i][:index +
                                                  2] + groups[i][index + 4:]
                    return tuple(groups)

    return None
def op_service(name, op, response):
	if common.is_linux():
		if common.check_programs_installed("systemctl"):
			#data, success, retcode = common.exec_command(['systemctl', 'is-enabled', name])

			if op == 0:
				data, success, retcode = common.exec_command(['systemctl', 'enable', name, "--no-ask-password"])

				if success:
					response["status"] = "enabled"
				else:
					response["error"] = "{} code : {}".format(data, retcode)

			else:
				data, success, retcode = common.exec_command(['systemctl', 'disable', name, "--no-ask-password"])

				if success:
					response["status"] = "disabled"
				else:
					response["error"] = "{} code : {}".format(data, retcode)
		else:
			response["error"] = Klanguage().to_ts(4003)
Beispiel #10
0
 def do(action_useful):
     if common.check_programs_installed('journalctl'):
         yield command.Function(None, functions.journald_clean,
                                'journalctl --vacuum-time=1').execute()
Beispiel #11
0
 def do(action_useful):
     # Checking executable allows auto-hide to work for non-APT systems
     if common.check_programs_installed('apt-get'):
         yield command.Function(None, functions.apt_clean,
                                'apt-get clean').execute()
Beispiel #12
0
def get_boot_services(response):
    global runlevel

    if common.check_programs_installed("systemctl"):
        values = []
        blame = {}

        #service time
        data, success, retcode = common.exec_command(
            ['systemd-analyze', 'blame'])

        if success:
            lines = data.split("\n")

            for line in lines:
                result = line.split()

                if len(result) == 2:
                    index = result[0].find(".")
                    if index >= 0 and len(result[0][index + 1:index + 4]) == 3:
                        result[0] = result[0][:index + 2] + result[0][index +
                                                                      4:]
                    blame[result[1]] = result[0]

        data, success, retcode = common.exec_command(
            ['systemctl', 'list-unit-files', '--type=service'])

        if success:
            lines = data.split("\n")

            for line in lines:
                result = line.split()

                if len(result) == 2 and (result[1] == "enabled"
                                         or result[1] == "disabled"):
                    values.append([
                        result[0],
                        blame[result[0]] if result[0] in blame else "",
                        lib.get_description_by_name(result[0], 0), result[1]
                    ])

        response["boot_services"] = {"value": len(values), "values": values}
    else:
        values = []

        if runlevel:
            init_rcd = "/etc/rc{}.d".format(runlevel)
            systemv_script_pattern = re.compile(r"S\d{2}(\S+)")

            for file in os.listdir(init_rcd):
                match = systemv_script_pattern.match(file)

                if match and len(match.groups()):
                    values.append([
                        match.groups()[0], "",
                        lib.get_description_by_name(match.groups()[0], 2),
                        "enabled"
                    ])

            response["boot_services"] = {
                "value": len(values),
                "values": values
            }
    '''
	elif lib.check_programs_installed("initctl"):
		values = [["Upstart Script", "Start On", "Stop On"]]
		upstart_config = []
		data, success, retcode = common.exec_command(['initctl', 'list'])

		if success:
			lines = data.split("\n")
			for line in lines:
				if line:
					upstart_config.append(line.split()[0])

		starton_pattern = re.compile(r"\s*start on\s(.*)")
		stopon_pattern = re.compile(r"\s*stop on\s(.*)")

		for config in upstart_config:
			data, success, retcode = common.exec_command(['initctl', 'show-config', config])

			if success:
				lines = data.split("\n")
				starton = ""
				stopon = ""

				for line in lines:
					match = starton_pattern.match(line)

					if match:
						starton = match.groups()[0]

					match = stopon_pattern.match(line)

					if match:
						stopon = match.groups()[0]

				values.append([
					config,
					starton,
					stopon])

		response["boot_services"].append({
			"name" : "Boot Services",
			"value" : len(values) - 1,
			"values" : values
		})
	'''
    '''