Commit eeb0b9ee by Alexander Popov

Big rework of the report modes

Let's fold the alternative options --debug and --json into --mode parameter:
  -m {verbose,json}, --mode {verbose,json}
  			choose the report mode

That also allows to get rid of 'debug_mode' and 'json_mode' globals.

This work is a prerequisite of solving the issue #45.
parent 21d9db90
......@@ -54,28 +54,28 @@ jobs:
coverage run -a --branch bin/kconfig-hardened-check
coverage run -a --branch bin/kconfig-hardened-check -p X86_64
coverage run -a --branch bin/kconfig-hardened-check -p X86_64 --debug
coverage run -a --branch bin/kconfig-hardened-check -p X86_64 --json
coverage run -a --branch bin/kconfig-hardened-check -p X86_64 -m verbose
coverage run -a --branch bin/kconfig-hardened-check -p X86_64 -m json
coverage run -a --branch bin/kconfig-hardened-check -p X86_32
coverage run -a --branch bin/kconfig-hardened-check -p X86_32 --debug
coverage run -a --branch bin/kconfig-hardened-check -p X86_32 --json
coverage run -a --branch bin/kconfig-hardened-check -p X86_32 -m verbose
coverage run -a --branch bin/kconfig-hardened-check -p X86_32 -m json
coverage run -a --branch bin/kconfig-hardened-check -p ARM64
coverage run -a --branch bin/kconfig-hardened-check -p ARM64 --debug
coverage run -a --branch bin/kconfig-hardened-check -p ARM64 --json
coverage run -a --branch bin/kconfig-hardened-check -p ARM64 -m verbose
coverage run -a --branch bin/kconfig-hardened-check -p ARM64 -m json
coverage run -a --branch bin/kconfig-hardened-check -p ARM
coverage run -a --branch bin/kconfig-hardened-check -p ARM --debug
coverage run -a --branch bin/kconfig-hardened-check -p ARM --json
coverage run -a --branch bin/kconfig-hardened-check -p ARM -m verbose
coverage run -a --branch bin/kconfig-hardened-check -p ARM -m json
CONFIG_DIR=`find /opt/hostedtoolcache/Python/ -name config_files`
CONFIGS=`find $CONFIG_DIR -type f|grep "\.config"`
for C in $CONFIGS
do
coverage run -a --branch bin/kconfig-hardened-check -c $C
coverage run -a --branch bin/kconfig-hardened-check -c $C --debug
coverage run -a --branch bin/kconfig-hardened-check -c $C --json
coverage run -a --branch bin/kconfig-hardened-check -c $C -m verbose
coverage run -a --branch bin/kconfig-hardened-check -c $C -m json
done
coverage xml -i -o coverage.xml
......
......@@ -43,47 +43,44 @@ or simply run `./bin/kconfig-hardened-check` from the cloned repository.
## Usage
```
usage: kconfig-hardened-check [-h] [-p {X86_64,X86_32,ARM64,ARM}] [-c CONFIG]
[--debug] [--json] [--version]
usage: kconfig-hardened-check [-h] [--version] [-p {X86_64,X86_32,ARM64,ARM}]
[-c CONFIG] [-m {verbose,json}]
Checks the hardening options in the Linux kernel config
optional arguments:
-h, --help show this help message and exit
--version show program's version number and exit
-p {X86_64,X86_32,ARM64,ARM}, --print {X86_64,X86_32,ARM64,ARM}
print hardening preferences for selected architecture
-c CONFIG, --config CONFIG
check the config_file against these preferences
--debug enable verbose debug mode
--json print results in JSON format
--version show program's version number and exit
-m {verbose,json}, --mode {verbose,json}
choose the report mode
```
## Output for `Ubuntu 20.04 LTS (Focal Fossa)` kernel config
```
$ ./bin/kconfig-hardened-check -c kconfig_hardened_check/config_files/distros/ubuntu-focal.config
[+] Trying to detect architecture in "kconfig_hardened_check/config_files/distros/ubuntu-focal.config"...
[+] Config file to check: kconfig_hardened_check/config_files/distros/ubuntu-focal.config
[+] Detected architecture: X86_64
[+] Trying to detect kernel version in "kconfig_hardened_check/config_files/distros/ubuntu-focal.config"...
[+] Found version line: "# Linux/x86 5.4.0-29-generic Kernel Configuration"
[+] Detected kernel version: 5.4
[+] Checking "kconfig_hardened_check/config_files/distros/ubuntu-focal.config" against X86_64 hardening preferences...
=========================================================================================================================
option name | desired val | decision | reason | check result
=========================================================================================================================
CONFIG_BUG | y |defconfig | self_protection | OK
CONFIG_STRICT_KERNEL_RWX | y |defconfig | self_protection | OK
CONFIG_STACKPROTECTOR_STRONG | y |defconfig | self_protection | OK
CONFIG_SLUB_DEBUG | y |defconfig | self_protection | OK
CONFIG_STRICT_MODULE_RWX | y |defconfig | self_protection | OK
CONFIG_GCC_PLUGINS | y |defconfig | self_protection | FAIL: not found
CONFIG_STACKPROTECTOR_STRONG | y |defconfig | self_protection | OK
CONFIG_STRICT_KERNEL_RWX | y |defconfig | self_protection | OK
CONFIG_STRICT_MODULE_RWX | y |defconfig | self_protection | OK
CONFIG_REFCOUNT_FULL | y |defconfig | self_protection | FAIL: "is not set"
CONFIG_IOMMU_SUPPORT | y |defconfig | self_protection | OK
CONFIG_MICROCODE | y |defconfig | self_protection | OK
CONFIG_RETPOLINE | y |defconfig | self_protection | OK
CONFIG_X86_SMAP | y |defconfig | self_protection | OK
CONFIG_X86_UMIP | y |defconfig | self_protection | OK: CONFIG_X86_INTEL_UMIP "y"
CONFIG_SYN_COOKIES | y |defconfig | self_protection | OK
CONFIG_X86_UMIP | y |defconfig | self_protection | OK: CONFIG_X86_INTEL_UMIP "y"
CONFIG_PAGE_TABLE_ISOLATION | y |defconfig | self_protection | OK
CONFIG_RANDOMIZE_MEMORY | y |defconfig | self_protection | OK
CONFIG_INTEL_IOMMU | y |defconfig | self_protection | OK
......@@ -98,12 +95,13 @@ CONFIG_SLAB_FREELIST_HARDENED | y | kspp | self_pr
CONFIG_SLAB_FREELIST_RANDOM | y | kspp | self_protection | OK
CONFIG_SHUFFLE_PAGE_ALLOCATOR | y | kspp | self_protection | OK
CONFIG_FORTIFY_SOURCE | y | kspp | self_protection | OK
CONFIG_GCC_PLUGIN_RANDSTRUCT | y | kspp | self_protection | FAIL: not found
CONFIG_GCC_PLUGIN_LATENT_ENTROPY | y | kspp | self_protection | FAIL: not found
CONFIG_DEBUG_LIST | y | kspp | self_protection | FAIL: "is not set"
CONFIG_DEBUG_SG | y | kspp | self_protection | FAIL: "is not set"
CONFIG_DEBUG_CREDENTIALS | y | kspp | self_protection | FAIL: "is not set"
CONFIG_DEBUG_NOTIFIERS | y | kspp | self_protection | FAIL: "is not set"
CONFIG_INIT_ON_ALLOC_DEFAULT_ON | y | kspp | self_protection | OK
CONFIG_GCC_PLUGIN_LATENT_ENTROPY | y | kspp | self_protection | FAIL: not found
CONFIG_GCC_PLUGIN_RANDSTRUCT | y | kspp | self_protection | FAIL: not found
CONFIG_HARDENED_USERCOPY | y | kspp | self_protection | OK
CONFIG_HARDENED_USERCOPY_FALLBACK | is not set | kspp | self_protection | FAIL: "y"
CONFIG_MODULE_SIG | y | kspp | self_protection | OK
......@@ -111,19 +109,18 @@ CONFIG_MODULE_SIG_ALL | y | kspp | self_pr
CONFIG_MODULE_SIG_SHA512 | y | kspp | self_protection | OK
CONFIG_MODULE_SIG_FORCE | y | kspp | self_protection | FAIL: "is not set"
CONFIG_INIT_STACK_ALL | y | kspp | self_protection | FAIL: not found
CONFIG_INIT_ON_ALLOC_DEFAULT_ON | y | kspp | self_protection | OK
CONFIG_INIT_ON_FREE_DEFAULT_ON | y | kspp | self_protection | OK: CONFIG_PAGE_POISONING "y"
CONFIG_GCC_PLUGIN_STACKLEAK | y | kspp | self_protection | FAIL: not found
CONFIG_STACKLEAK_METRICS | is not set | clipos | self_protection | FAIL: CONFIG_GCC_PLUGIN_STACKLEAK is needed
CONFIG_STACKLEAK_RUNTIME_DISABLE | is not set | clipos | self_protection | FAIL: CONFIG_GCC_PLUGIN_STACKLEAK is needed
CONFIG_DEFAULT_MMAP_MIN_ADDR | 65536 | kspp | self_protection | OK
CONFIG_SECURITY_DMESG_RESTRICT | y | clipos | self_protection | FAIL: "is not set"
CONFIG_DEBUG_VIRTUAL | y | clipos | self_protection | FAIL: "is not set"
CONFIG_STATIC_USERMODEHELPER | y | clipos | self_protection | FAIL: "is not set"
CONFIG_SLAB_MERGE_DEFAULT | is not set | clipos | self_protection | FAIL: "y"
CONFIG_GCC_PLUGIN_RANDSTRUCT_PERFORMANCE | is not set | clipos | self_protection | FAIL: CONFIG_GCC_PLUGIN_RANDSTRUCT is needed
CONFIG_RANDOM_TRUST_BOOTLOADER | is not set | clipos | self_protection | FAIL: "y"
CONFIG_RANDOM_TRUST_CPU | is not set | clipos | self_protection | FAIL: "y"
CONFIG_GCC_PLUGIN_RANDSTRUCT_PERFORMANCE | is not set | clipos | self_protection | FAIL: CONFIG_GCC_PLUGIN_RANDSTRUCT is needed
CONFIG_STACKLEAK_METRICS | is not set | clipos | self_protection | FAIL: CONFIG_GCC_PLUGIN_STACKLEAK is needed
CONFIG_STACKLEAK_RUNTIME_DISABLE | is not set | clipos | self_protection | FAIL: CONFIG_GCC_PLUGIN_STACKLEAK is needed
CONFIG_INTEL_IOMMU_SVM | y | clipos | self_protection | OK
CONFIG_INTEL_IOMMU_DEFAULT_ON | y | clipos | self_protection | FAIL: "is not set"
CONFIG_SLUB_DEBUG_ON | y | my | self_protection | FAIL: "is not set"
......@@ -135,16 +132,12 @@ CONFIG_SECURITY_WRITABLE_HOOKS | is not set | my | securit
CONFIG_SECURITY_LOCKDOWN_LSM | y | clipos | security_policy | OK
CONFIG_SECURITY_LOCKDOWN_LSM_EARLY | y | clipos | security_policy | OK
CONFIG_LOCK_DOWN_KERNEL_FORCE_CONFIDENTIALITY| y | clipos | security_policy | FAIL: "is not set"
CONFIG_SECURITY_SAFESETID | y | my | security_policy | OK
CONFIG_SECURITY_LOADPIN | y | my | security_policy | FAIL: "is not set"
CONFIG_SECURITY_LOADPIN_ENFORCE | y | my | security_policy | FAIL: CONFIG_SECURITY_LOADPIN is needed
CONFIG_SECURITY_SAFESETID | y | my | security_policy | OK
CONFIG_SECCOMP | y |defconfig | cut_attack_surface | OK
CONFIG_SECCOMP_FILTER | y |defconfig | cut_attack_surface | OK
CONFIG_STRICT_DEVMEM | y |defconfig | cut_attack_surface | OK
CONFIG_MODULES | is not set | kspp | cut_attack_surface | FAIL: "y"
CONFIG_DEVMEM | is not set | kspp | cut_attack_surface | FAIL: "y"
CONFIG_IO_STRICT_DEVMEM | y | kspp | cut_attack_surface | FAIL: "is not set"
CONFIG_LEGACY_VSYSCALL_NONE | y | kspp | cut_attack_surface | FAIL: "is not set"
CONFIG_ACPI_CUSTOM_METHOD | is not set | kspp | cut_attack_surface | OK
CONFIG_COMPAT_BRK | is not set | kspp | cut_attack_surface | OK
CONFIG_DEVKMEM | is not set | kspp | cut_attack_surface | OK
......@@ -159,6 +152,10 @@ CONFIG_IA32_EMULATION | is not set | kspp | cut_atta
CONFIG_X86_X32 | is not set | kspp | cut_attack_surface | FAIL: "y"
CONFIG_MODIFY_LDT_SYSCALL | is not set | kspp | cut_attack_surface | FAIL: "y"
CONFIG_OABI_COMPAT | is not set | kspp | cut_attack_surface | OK: not found
CONFIG_MODULES | is not set | kspp | cut_attack_surface | FAIL: "y"
CONFIG_DEVMEM | is not set | kspp | cut_attack_surface | FAIL: "y"
CONFIG_IO_STRICT_DEVMEM | y | kspp | cut_attack_surface | FAIL: "is not set"
CONFIG_LEGACY_VSYSCALL_NONE | y | kspp | cut_attack_surface | FAIL: "is not set"
CONFIG_X86_PTDUMP | is not set |grsecurity| cut_attack_surface | OK
CONFIG_ZSMALLOC_STAT | is not set |grsecurity| cut_attack_surface | OK
CONFIG_PAGE_OWNER | is not set |grsecurity| cut_attack_surface | OK
......@@ -185,7 +182,6 @@ CONFIG_X86_IOPL_IOPERM | is not set | lockdown | cut_atta
CONFIG_EFI_TEST | is not set | lockdown | cut_attack_surface | FAIL: "m"
CONFIG_BPF_SYSCALL | is not set | lockdown | cut_attack_surface | FAIL: "y"
CONFIG_MMIOTRACE_TEST | is not set | lockdown | cut_attack_surface | OK
CONFIG_X86_INTEL_TSX_MODE_OFF | y | clipos | cut_attack_surface | OK
CONFIG_STAGING | is not set | clipos | cut_attack_surface | FAIL: "y"
CONFIG_KSM | is not set | clipos | cut_attack_surface | FAIL: "y"
CONFIG_KALLSYMS | is not set | clipos | cut_attack_surface | FAIL: "y"
......@@ -196,6 +192,7 @@ CONFIG_USER_NS | is not set | clipos | cut_atta
CONFIG_X86_MSR | is not set | clipos | cut_attack_surface | FAIL: "m"
CONFIG_X86_CPUID | is not set | clipos | cut_attack_surface | FAIL: "m"
CONFIG_LDISC_AUTOLOAD | is not set | clipos | cut_attack_surface | FAIL: "y"
CONFIG_X86_INTEL_TSX_MODE_OFF | y | clipos | cut_attack_surface | OK
CONFIG_AIO | is not set |grapheneos| cut_attack_surface | FAIL: "y"
CONFIG_MMIOTRACE | is not set | my | cut_attack_surface | FAIL: "y"
CONFIG_LIVEPATCH | is not set | my | cut_attack_surface | FAIL: "y"
......@@ -208,7 +205,7 @@ CONFIG_INPUT_EVBUG | is not set | my | cut_atta
CONFIG_INTEGRITY | y |defconfig |userspace_hardening | OK
CONFIG_ARCH_MMAP_RND_BITS | 32 | clipos |userspace_hardening | FAIL: "28"
[+] config check is finished: 'OK' - 57 / 'FAIL' - 79
[+] Config check is finished: 'OK' - 57 / 'FAIL' - 79
```
## kconfig-hardened-check versioning
......
......@@ -64,13 +64,12 @@ from .__about__ import __version__
# pylint: disable=line-too-long,bad-whitespace,too-many-branches
# pylint: disable=too-many-statements,global-statement
# debug_mode enables:
# - reporting about unknown kernel options in the config,
# - verbose printing of ComplexOptChecks (OR, AND).
debug_mode = False
# json_mode is for printing results in JSON format
json_mode = False
# Report modes:
# * verbose mode for
# - reporting about unknown kernel options in the config
# - verbose printing of ComplexOptCheck items
# * json mode for printing the results in JSON format
report_modes = ['verbose', 'json']
supported_archs = ['X86_64', 'X86_32', 'ARM64', 'ARM']
......@@ -101,7 +100,7 @@ class OptCheck:
return True
return False
def table_print(self, with_results):
def table_print(self, mode, with_results):
print('CONFIG_{:<38}|{:^13}|{:^10}|{:^20}'.format(self.name, self.expected, self.decision, self.reason), end='')
if with_results:
print('| {}'.format(self.result), end='')
......@@ -125,7 +124,7 @@ class VerCheck:
self.result = 'FAIL: version < ' + str(self.ver_expected[0]) + '.' + str(self.ver_expected[1])
return False
def table_print(self, with_results):
def table_print(self, mode, with_results):
ver_req = 'kernel version >= ' + str(self.ver_expected[0]) + '.' + str(self.ver_expected[1])
print('{:<91}'.format(ver_req), end='')
if with_results:
......@@ -145,7 +144,7 @@ class PresenceCheck:
self.result = 'OK: is present'
return True
def table_print(self, with_results):
def table_print(self, mode, with_results):
print('CONFIG_{:<84}'.format(self.name + ' is present'), end='')
if with_results:
print('| {}'.format(self.result), end='')
......@@ -172,17 +171,17 @@ class ComplexOptCheck:
def reason(self):
return self.opts[0].reason
def table_print(self, with_results):
if debug_mode:
def table_print(self, mode, with_results):
if mode == 'verbose':
print(' {:87}'.format('<<< ' + self.__class__.__name__ + ' >>>'), end='')
if with_results:
print('| {}'.format(self.result), end='')
for o in self.opts:
print()
o.table_print(with_results)
o.table_print(mode, with_results)
else:
o = self.opts[0]
o.table_print(False)
o.table_print(mode, False)
if with_results:
print('| {}'.format(self.result), end='')
......@@ -234,8 +233,6 @@ def detect_arch(fname):
with open(fname, 'r') as f:
arch_pattern = re.compile("CONFIG_[a-zA-Z0-9_]*=y")
arch = None
if not json_mode:
print('[+] Trying to detect architecture in "{}"...'.format(fname))
for line in f.readlines():
if arch_pattern.match(line):
option, _ = line[7:].split('=', 1)
......@@ -252,13 +249,9 @@ def detect_arch(fname):
def detect_version(fname):
with open(fname, 'r') as f:
ver_pattern = re.compile("# Linux/.* Kernel Configuration")
if not json_mode:
print('[+] Trying to detect kernel version in "{}"...'.format(fname))
for line in f.readlines():
if ver_pattern.match(line):
line = line.strip()
if not json_mode:
print('[+] Found version line: "{}"'.format(line))
parts = line.split()
ver_str = parts[2]
ver_numbers = ver_str.split('.')
......@@ -518,8 +511,22 @@ def construct_checklist(l, arch):
# l += [OptCheck('feature_test', 'my', 'LKDTM', 'm')] # only for debugging!
def print_checklist(checklist, with_results):
if json_mode:
def print_unknown_options(checklist, parsed_options):
known_options = []
for opt in checklist:
if hasattr(opt, 'opts'):
for o in opt.opts:
if hasattr(o, 'name'):
known_options.append(o.name)
else:
known_options.append(opt.name)
for option, value in parsed_options.items():
if option not in known_options:
print('[?] No rule for option {} ({})'.format(option, value))
def print_checklist(mode, checklist, with_results):
if mode == 'json':
opts = []
for o in checklist:
opt = ['CONFIG_'+o.name, o.expected, o.decision, o.reason]
......@@ -542,12 +549,19 @@ def print_checklist(checklist, with_results):
# table contents
for opt in checklist:
opt.table_print(with_results)
opt.table_print(mode, with_results)
print()
if debug_mode:
if mode == 'verbose':
print('-' * sep_line_len)
print()
# final score
if with_results:
error_count = len(list(filter(lambda opt: opt.result.startswith('FAIL'), checklist)))
ok_count = len(list(filter(lambda opt: opt.result.startswith('OK'), checklist)))
if mode != 'json':
print('[+] Config check is finished: \'OK\' - {} / \'FAIL\' - {}'.format(ok_count, error_count))
def perform_checks(checklist, parsed_options):
for opt in checklist:
......@@ -564,14 +578,11 @@ def perform_checks(checklist, parsed_options):
opt.check()
def check_config_file(checklist, fname, arch):
def parse_config_file(parsed_options, fname):
with open(fname, 'r') as f:
parsed_options = OrderedDict()
opt_is_on = re.compile("CONFIG_[a-zA-Z0-9_]*=[a-zA-Z0-9_\"]*")
opt_is_off = re.compile("# CONFIG_[a-zA-Z0-9_]* is not set")
if not json_mode:
print('[+] Checking "{}" against {} hardening preferences...'.format(fname, arch))
for line in f.readlines():
line = line.strip()
option = None
......@@ -587,81 +598,67 @@ def check_config_file(checklist, fname, arch):
if option in parsed_options:
sys.exit('[!] ERROR: config option "{}" exists multiple times'.format(line))
if option is not None:
if option:
parsed_options[option] = value
perform_checks(checklist, parsed_options)
if debug_mode:
known_options = []
for opt in checklist:
if hasattr(opt, 'opts'):
for o in opt.opts:
if hasattr(o, 'name'):
known_options.append(o.name)
else:
known_options.append(opt.name)
for option, value in parsed_options.items():
if option not in known_options:
print('DEBUG: dunno about option {} ({})'.format(option, value))
return parsed_options
print_checklist(checklist, True)
def main():
global debug_mode
global json_mode
global kernel_version
mode = None
config_checklist = []
parsed_options = OrderedDict()
parser = ArgumentParser(prog='kconfig-hardened-check',
description='Checks the hardening options in the Linux kernel config')
parser.add_argument('--version', action='version', version='%(prog)s ' + __version__)
parser.add_argument('-p', '--print', choices=supported_archs,
help='print hardening preferences for selected architecture')
parser.add_argument('-c', '--config',
help='check the config_file against these preferences')
parser.add_argument('--debug', action='store_true',
help='enable verbose debug mode')
parser.add_argument('--json', action='store_true',
help='print results in JSON format')
parser.add_argument('--version', action='version', version='%(prog)s ' + __version__)
parser.add_argument('-m', '--mode', choices=report_modes,
help='choose the report mode')
args = parser.parse_args()
if args.debug:
debug_mode = True
print('[!] WARNING: debug mode is enabled')
if args.json:
json_mode = True
if debug_mode and json_mode:
sys.exit('[!] ERROR: options --debug and --json cannot be used simultaneously')
if args.mode:
mode = args.mode
if mode != 'json':
print("[+] Special report mode: {}".format(mode))
if args.config:
if mode != 'json':
print('[+] Config file to check: {}'.format(args.config))
arch, msg = detect_arch(args.config)
if not arch:
sys.exit('[!] ERROR: {}'.format(msg))
elif not json_mode:
if mode != 'json':
print('[+] Detected architecture: {}'.format(arch))
kernel_version, msg = detect_version(args.config)
if not kernel_version:
sys.exit('[!] ERROR: {}'.format(msg))
elif not json_mode:
if mode != 'json':
print('[+] Detected kernel version: {}.{}'.format(kernel_version[0], kernel_version[1]))
construct_checklist(config_checklist, arch)
check_config_file(config_checklist, args.config, arch)
error_count = len(list(filter(lambda opt: opt.result.startswith('FAIL'), config_checklist)))
ok_count = len(list(filter(lambda opt: opt.result.startswith('OK'), config_checklist)))
if not debug_mode and not json_mode:
print('[+] config check is finished: \'OK\' - {} / \'FAIL\' - {}'.format(ok_count, error_count))
parse_config_file(parsed_options, args.config)
perform_checks(config_checklist, parsed_options)
if mode == 'verbose':
print_unknown_options(config_checklist, parsed_options)
print_checklist(mode, config_checklist, True)
sys.exit(0)
if args.print:
arch = args.print
construct_checklist(config_checklist, arch)
if not json_mode:
if mode != 'json':
print('[+] Printing kernel hardening preferences for {}...'.format(arch))
print_checklist(config_checklist, False)
print_checklist(mode, config_checklist, False)
sys.exit(0)
parser.print_help()
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment