Test Failed
Pull Request — master (#7876)
by Matthew
02:14
created

ssg.controls.Control.__hash__()   A

Complexity

Conditions 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 1
CRAP Score 1.125

Importance

Changes 0
Metric Value
cc 1
eloc 2
nop 1
dl 0
loc 4
ccs 1
cts 2
cp 0.5
crap 1.125
rs 10
c 0
b 0
f 0
1 2
import collections
2 2
import logging
3 2
import os
4 2
import copy
5 2
from glob import glob
6
7 2
import ssg.build_yaml
8 2
import ssg.yaml
9 2
import ssg.utils
10
11
12 2
class InvalidStatus(Exception):
13 2
    pass
14
15 2
class Status():
16 2
    PENDING = "pending"
17 2
    PLANNED = "planned"
18 2
    NOT_APPLICABLE = "not applicable"
19 2
    INHERENTLY_MET = "inherently met"
20 2
    DOCUMENTATION = "documentation"
21 2
    PARTIAL = "partial"
22 2
    SUPPORTED = "supported"
23 2
    AUTOMATED = "automated"
24
25 2
    def __init__(self, status):
26
        self.status = status
27
28 2
    @classmethod
29
    def from_control_info(cls, ctrl, status):
30
        if status is None:
31
            return cls.PENDING
32
33
        valid_statuses = [
34
            cls.PENDING,
35
            cls.PLANNED,
36
            cls.NOT_APPLICABLE,
37
            cls.INHERENTLY_MET,
38
            cls.DOCUMENTATION,
39
            cls.PARTIAL,
40
            cls.SUPPORTED,
41
            cls.AUTOMATED,
42
        ]
43
44
        if status not in valid_statuses:
45
            raise InvalidStatus(
46
                    "The given status '{given}' in the control '{control}' "
47
                    "was invalid. Please use one of "
48
                    "the following: {valid}".format(given=status,
49
                                                    control=ctrl,
50
                                                    valid=valid_statuses))
51
        return status
52
53 2
    def __str__(self):
54
        return self.status
55
56 2
    def __eq__(self, other):
57
        if isinstance(other, Status):
58
            return self.status == other.status
59
        elif isinstance(other, str):
60
            return self.status == other
61
        return False
62
63
64 2
class Control(ssg.build_yaml.SelectionHandler):
65 2
    def __init__(self):
66
        super(Control, self).__init__()
67
        self.id = None
68
        self.levels = []
69
        self.notes = ""
70
        self.title = ""
71
        self.description = ""
72
        self.automated = ""
73
        self.status = None
74
75 2
    def __hash__(self):
76
        """ Controls are meant to be unique, so using the
77
        ID should suffice"""
78
        return hash(self.id)
79
80 2
    @classmethod
81 2
    def from_control_dict(cls, control_dict, env_yaml=None, default_level=["default"]):
82
        control = cls()
83
        control.id = ssg.utils.required_key(control_dict, "id")
84
        control.title = control_dict.get("title")
85
        control.description = control_dict.get("description")
86
        control.status = Status.from_control_info(control.id, control_dict.get("status", None))
87
        control.automated = control_dict.get("automated", "no")
88
        if control.status == "automated":
89
            control.automated = "yes"
90
        if control.automated not in ["yes", "no", "partially"]:
91
            msg = (
92
                "Invalid value '%s' of automated key in control "
93
                "%s '%s'. Can be only 'yes', 'no', 'partially'."
94
                % (control.automated,  control.id, control.title))
95
            raise ValueError(msg)
96
        control.levels = control_dict.get("levels", default_level)
97
        control.notes = control_dict.get("notes", "")
98
        selections = control_dict.get("rules", {})
99
100
        product = None
101
        product_dir = None
102
        benchmark_root = None
103
        if env_yaml:
104
            product = env_yaml.get('product', None)
105
            product_dir = env_yaml.get('product_dir', None)
106
            benchmark_root = env_yaml.get('benchmark_root', None)
107
            content_dir = os.path.join(product_dir, benchmark_root)
108
109
        control.selections = selections
110
111
        control.related_rules = control_dict.get("related_rules", [])
112
        control.note = control_dict.get("note")
113
        return control
114
115
116 2
class Level():
117 2
    def __init__(self):
118
        self.id = None
119
        self.inherits_from = None
120
121 2
    @classmethod
122
    def from_level_dict(cls, level_dict):
123
        level = cls()
124
        level.id = ssg.utils.required_key(level_dict, "id")
125
        level.inherits_from = level_dict.get("inherits_from")
126
        return level
127
128 2
class Policy():
129 2
    def __init__(self, filepath, env_yaml=None):
130
        self.id = None
131
        self.env_yaml = env_yaml
132
        self.filepath = filepath
133
        self.controls_dir = os.path.splitext(filepath)[0]
134
        self.controls = []
135
        self.controls_by_id = dict()
136
        self.levels = []
137
        self.levels_by_id = dict()
138
        self.title = ""
139
        self.source = ""
140
141 2
    def _parse_controls_tree(self, tree):
142
        default_level = ["default"]
143
        if self.levels:
144
            default_level = [self.levels[0].id]
145
146
        for node in tree:
147
            try:
148
                control = Control.from_control_dict(
149
                    node, self.env_yaml, default_level=default_level)
150
            except Exception as exc:
151
                msg = (
152
                    "Unable to parse controls from {filename}: {error}"
153
                    .format(filename=self.filepath, error=str(exc)))
154
                raise RuntimeError(msg)
155
            if "controls" in node:
156
                for sc in self._parse_controls_tree(node["controls"]):
157
                    yield sc
158
                    control.update_with(sc)
159
            yield control
160
161 2
    def load(self):
162
        yaml_contents = ssg.yaml.open_and_expand(self.filepath, self.env_yaml)
163
        self.id = ssg.utils.required_key(yaml_contents, "id")
164
        self.title = ssg.utils.required_key(yaml_contents, "title")
165
        self.source = yaml_contents.get("source", "")
166
167
        level_list = yaml_contents.get("levels", [])
168
        for lv in level_list:
169
            level = Level.from_level_dict(lv)
170
            self.levels.append(level)
171
            self.levels_by_id[level.id] = level
172
173
        controls_tree = ssg.utils.required_key(yaml_contents, "controls")
174
        if os.path.exists(self.controls_dir) and os.path.isdir(self.controls_dir):
175
            files = os.listdir(self.controls_dir)
176
            for file in files:
177
                if file.endswith('.yml'):
178
                    full_path = os.path.join(self.controls_dir, file)
179
                    yaml_contents = ssg.yaml.open_and_expand(full_path, self.env_yaml)
180
                    for control in yaml_contents['controls']:
181
                        controls_tree.append(control)
182
                elif file.startswith('.'):
183
                    continue
184
                else:
185
                    raise RuntimeError("Found non yaml file in %s" % self.controls_dir)
186
        for c in self._parse_controls_tree(controls_tree):
187
            self.controls.append(c)
188
            self.controls_by_id[c.id] = c
189
190 2
    def get_control(self, control_id):
191
        try:
192
            c = self.controls_by_id[control_id]
193
            return c
194
        except KeyError:
195
            msg = "%s not found in policy %s" % (
196
                control_id, self.id
197
            )
198
            raise ValueError(msg)
199
200 2
    def get_level(self, level_id):
201
        try:
202
            lv = self.levels_by_id[level_id]
203
            return lv
204
        except KeyError:
205
            msg = "Level %s not found in policy %s" % (
206
                level_id, self.id
207
            )
208
            raise ValueError(msg)
209
210 2
    def get_level_with_ancestors_sequence(self, level_id):
211
        # use OrderedDict for Python2 compatibility instead of ordered set
212
        levels = collections.OrderedDict()
213
        level = self.get_level(level_id)
214
        levels[level] = ""
215
        if level.inherits_from:
216
            for lv in level.inherits_from:
217
                eligible_levels = [l for l in self.get_level_with_ancestors_sequence(lv) if l not in levels.keys()]
218
                for l in eligible_levels:
219
                    levels[l] = ""
220
        return list(levels.keys())
221
222
223 2
class ControlsManager():
224 2
    def __init__(self, controls_dir, env_yaml=None):
225
        self.controls_dir = os.path.abspath(controls_dir)
226
        self.env_yaml = env_yaml
227
        self.policies = {}
228
229 2
    def load(self):
230
        if not os.path.exists(self.controls_dir):
231
            return
232
        for filename in sorted(glob(os.path.join(self.controls_dir, "*.yml"))):
233
            logging.info("Found file %s" % (filename))
234
            filepath = os.path.join(self.controls_dir, filename)
235
            policy = Policy(filepath, self.env_yaml)
236
            policy.load()
237
            self.policies[policy.id] = policy
238
239 2
    def get_control(self, policy_id, control_id):
240
        try:
241
            policy = self.policies[policy_id]
242
        except KeyError:
243
            msg = "policy '%s' doesn't exist" % (policy_id)
244
            raise ValueError(msg)
245
        control = policy.get_control(control_id)
246
        return control
247
248 2
    def _get_policy(self, policy_id):
249
        try:
250
            policy = self.policies[policy_id]
251
        except KeyError:
252
            msg = "policy '%s' doesn't exist" % (policy_id)
253
            raise ValueError(msg)
254
        return policy
255
256 2
    def get_all_controls_of_level(self, policy_id, level_id):
257
        policy = self._get_policy(policy_id)
258
        levels = policy.get_level_with_ancestors_sequence(level_id)
259
        all_policy_controls = self.get_all_controls(policy_id)
260
        eligible_controls = []
261
        already_defined_variables = set()
262
        # we will go level by level, from top to bottom
263
        # this is done to enable overriding of variables by higher levels
264
        for lv in levels:
265
            for control in all_policy_controls:
266
                if lv.id not in control.levels:
267
                    continue
268
269
                variables = set(control.variables.keys())
270
271
                variables_to_remove = variables.intersection(already_defined_variables)
272
                already_defined_variables.update(variables)
273
274
                new_c = self._get_control_without_variables(variables_to_remove, control)
275
                eligible_controls.append(new_c)
276
277
        return eligible_controls
278
279 2
    @staticmethod
280
    def _get_control_without_variables(variables_to_remove, control):
281
        if not variables_to_remove:
282
            return control
283
284
        new_c = copy.deepcopy(control)
285
        for var in variables_to_remove:
286
            del new_c.variables[var]
287
        return new_c
288
289 2
    def get_all_controls(self, policy_id):
290
        policy = self._get_policy(policy_id)
291
        return policy.controls_by_id.values()
292