Make the static typing work for Python v3.8
[kconfig-hardened-check.git] / kernel_hardening_checker / engine.py
index 268a142387b87940d1803adbb2fe72b6d6c71a24..f6282fe540382895fa30f28f2c62dfa9c868475f 100644 (file)
@@ -11,12 +11,18 @@ This module is the engine of checks.
 # pylint: disable=missing-class-docstring,missing-function-docstring
 # pylint: disable=line-too-long,invalid-name,too-many-branches
 
+import sys
+
+from typing import Optional, Dict, Tuple
+StrOrNone = Optional[str]
+TupleOrNone = Optional[Tuple]
+
 GREEN_COLOR = '\x1b[32m'
 RED_COLOR = '\x1b[31m'
 COLOR_END = '\x1b[0m'
 
 def colorize_result(input_text):
-    if input_text is None:
+    if input_text is None or not sys.stdout.isatty():
         return input_text
     if input_text.startswith('OK'):
         color = GREEN_COLOR
@@ -27,7 +33,7 @@ def colorize_result(input_text):
 
 
 class OptCheck:
-    def __init__(self, reason, decision, name, expected):
+    def __init__(self, reason: str, decision: str, name: str, expected: str):
         assert(name and name == name.strip() and len(name.split()) == 1), \
                f'invalid name "{name}" for {self.__class__.__name__}'
         self.name = name
@@ -58,7 +64,7 @@ class OptCheck:
         self.result = None
 
     @property
-    def type(self):
+    def opt_type(self):
         return None
 
     def set_state(self, data):
@@ -98,15 +104,23 @@ class OptCheck:
         else:
             self.result = f'FAIL: "{self.state}"'
 
-    def table_print(self, _mode, with_results):
-        print(f'{self.name:<40}|{self.type:^7}|{self.expected:^12}|{self.decision:^10}|{self.reason:^18}', end='')
+    def table_print(self, _mode, with_results: bool):
+        print(f'{self.name:<40}|{self.opt_type:^7}|{self.expected:^12}|{self.decision:^10}|{self.reason:^18}', end='')
         if with_results:
             print(f'| {colorize_result(self.result)}', end='')
 
-    def json_dump(self, with_results):
-        dump = [self.name, self.type, self.expected, self.decision, self.reason]
+    def json_dump(self, with_results: bool) -> Dict:
+        dump = {
+            "option_name": self.name,
+            "type": self.opt_type,
+            "desired_val": self.expected,
+            "decision": self.decision,
+            "reason": self.reason,
+        }
         if with_results:
-            dump.append(self.result)
+            assert self.result, f'unexpected empty result in {self.name}'
+            dump["check_result"] = self.result
+            dump["check_result_bool"] = self.result.startswith('OK')
         return dump
 
 
@@ -116,24 +130,24 @@ class KconfigCheck(OptCheck):
         self.name = f'CONFIG_{self.name}'
 
     @property
-    def type(self):
+    def opt_type(self):
         return 'kconfig'
 
 
 class CmdlineCheck(OptCheck):
     @property
-    def type(self):
+    def opt_type(self):
         return 'cmdline'
 
 
 class SysctlCheck(OptCheck):
     @property
-    def type(self):
+    def opt_type(self):
         return 'sysctl'
 
 
 class VersionCheck:
-    def __init__(self, ver_expected):
+    def __init__(self, ver_expected: Tuple):
         assert(ver_expected and isinstance(ver_expected, tuple) and len(ver_expected) == 3), \
                f'invalid expected version "{ver_expected}" for VersionCheck (1)'
         assert(all(map(lambda x: isinstance(x, int), ver_expected))), \
@@ -143,10 +157,10 @@ class VersionCheck:
         self.result = None
 
     @property
-    def type(self):
+    def opt_type(self):
         return 'version'
 
-    def set_state(self, data):
+    def set_state(self, data: Tuple):
         assert(data and isinstance(data, tuple) and len(data) >= 3), \
                f'invalid version "{data}" for VersionCheck'
         self.ver = data[:3]
@@ -171,7 +185,7 @@ class VersionCheck:
             return
         self.result = f'FAIL: version < {self.ver_expected}'
 
-    def table_print(self, _mode, with_results):
+    def table_print(self, _mode, with_results: bool):
         ver_req = f'kernel version >= {self.ver_expected}'
         print(f'{ver_req:<91}', end='')
         if with_results:
@@ -190,7 +204,7 @@ class ComplexOptCheck:
         self.result = None
 
     @property
-    def type(self):
+    def opt_type(self):
         return 'complex'
 
     @property
@@ -201,7 +215,7 @@ class ComplexOptCheck:
     def expected(self):
         return self.opts[0].expected
 
-    def table_print(self, mode, with_results):
+    def table_print(self, mode: str, with_results: bool):
         if mode == 'verbose':
             class_name = f'<<< {self.__class__.__name__} >>>'
             print(f'    {class_name:87}', end='')
@@ -216,10 +230,13 @@ class ComplexOptCheck:
             if with_results:
                 print(f'| {colorize_result(self.result)}', end='')
 
-    def json_dump(self, with_results):
+    def json_dump(self, with_results: bool) -> Dict:
         dump = self.opts[0].json_dump(False)
         if with_results:
-            dump.append(self.result)
+            # Add the 'check_result' and 'check_result_bool' keys to the dictionary
+            assert self.result, f'unexpected empty result in {self.name}'
+            dump["check_result"] = self.result
+            dump["check_result_bool"] = self.result.startswith('OK')
         return dump
 
 
@@ -286,34 +303,34 @@ class AND(ComplexOptCheck):
 SIMPLE_OPTION_TYPES = ('kconfig', 'cmdline', 'sysctl', 'version')
 
 
-def populate_simple_opt_with_data(opt, data, data_type):
-    assert(opt.type != 'complex'), \
+def populate_simple_opt_with_data(opt, data, data_type: str):
+    assert(opt.opt_type != 'complex'), \
            f'unexpected ComplexOptCheck "{opt.name}"'
-    assert(opt.type in SIMPLE_OPTION_TYPES), \
-           f'invalid opt type "{opt.type}"'
+    assert(opt.opt_type in SIMPLE_OPTION_TYPES), \
+           f'invalid opt_type "{opt.opt_type}"'
     assert(data_type in SIMPLE_OPTION_TYPES), \
-           f'invalid data type "{data_type}"'
+           f'invalid data_type "{data_type}"'
     assert(data), \
            'empty data'
 
-    if data_type != opt.type:
+    if data_type != opt.opt_type:
         return
 
     if data_type in ('kconfig', 'cmdline', 'sysctl'):
         opt.set_state(data.get(opt.name, None))
     else:
         assert(data_type == 'version'), \
-               f'unexpected data type "{data_type}"'
+               f'unexpected data_type "{data_type}"'
         opt.set_state(data)
 
 
 def populate_opt_with_data(opt, data, data_type):
-    assert(opt.type != 'version'), 'a single VersionCheck is useless'
-    if opt.type != 'complex':
+    assert(opt.opt_type != 'version'), 'a single VersionCheck is useless'
+    if opt.opt_type != 'complex':
         populate_simple_opt_with_data(opt, data, data_type)
     else:
         for o in opt.opts:
-            if o.type != 'complex':
+            if o.opt_type != 'complex':
                 populate_simple_opt_with_data(o, data, data_type)
             else:
                 # Recursion for nested ComplexOptCheck objects
@@ -328,8 +345,8 @@ def populate_with_data(checklist, data, data_type):
 def override_expected_value(checklist, name, new_val):
     for opt in checklist:
         if opt.name == name:
-            assert(opt.type in ('kconfig', 'cmdline', 'sysctl')), \
-                   f'overriding an expected value for "{opt.type}" checks is not supported yet'
+            assert(opt.opt_type in ('kconfig', 'cmdline', 'sysctl')), \
+                   f'overriding an expected value for "{opt.opt_type}" checks is not supported yet'
             opt.expected = new_val