Debian Codegraph @

utils/autotailor

raw symbols SCIP
1 #!/usr/bin/env python3
2
3 # Copyright (C) 2020 Matěj Týč <[email protected]om>
4 #
5 # This library is free software; you can redistribute it and/or
6 # modify it under the terms of the GNU Lesser General Public
7 # License as published by the Free Software Foundation; either
8 # version 2 of the License, or (at your option) any later version.
9 #
10 # This library is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 # Lesser General Public License for more details.
14 #
15 # You should have received a copy of the GNU Lesser General Public
16 # License along with this library; if not, write to the
17 # Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
18 # Boston, MA 02110-1301 USA
19
20 import argparse
21 import collections
22 import datetime
23 import re
24 import sys
25 import pathlib
26 import xml.etree.ElementTree as ET
27 import xml.dom.minidom
28 import json
29
30
31 NS = "http://checklists.nist.gov/xccdf/1.2"
32 NS_PREFIX = "xccdf-1.2"
33 DEFAULT_PROFILE_SUFFIX = "_customized"
34 DEFAULT_REVERSE_DNS = "org.ssgproject.content"
35 ROLES = ["full", "unscored", "unchecked"]
36 SEVERITIES = ["unknown", "info", "low", "medium", "high"]
37 ATTRIBUTES = ["role", "severity"]
38
39
40 def quote(string):
41 return "\"" + string + "\""
42
43
44 def assignment_to_tuple(assignment):
45 varname, value = assignment.split("=", 1)
46 return varname, value
47
48
49 def is_valid_xccdf_id(string):
50 return re.match(
51 r"^xccdf_[a-zA-Z0-9.-]+_(benchmark|profile|rule|group|value|"
52 r"testresult|tailoring)_.+",
53 string) is not None
54
55
56 class Profile:
57 def __init__(self):
58 self.reverse_dns = DEFAULT_REVERSE_DNS
59 self._profile_id = None
60 self.extends = ""
61 self.profile_title = ""
62
63 self.value_changes = set()
64 self.rules_to_select = set()
65 self.rules_to_unselect = set()
66 self.groups_to_select = set()
67 self.groups_to_unselect = set()
68 self._rule_refinements = collections.defaultdict(dict)
69 self._value_refinements = collections.defaultdict(dict)
70
71 @property
72 def profile_id(self):
73 if self._profile_id is not None:
74 return self._profile_id
75 else:
76 return self.extends + DEFAULT_PROFILE_SUFFIX
77
78 @profile_id.setter
79 def profile_id(self, new_profile_id):
80 self._profile_id = new_profile_id
81
82 def rule_refinements(self, rule_id, attribute):
83 return self._rule_refinements[rule_id][attribute]
84
85 @staticmethod
86 def _find_rule_enumeration(attribute):
87 if attribute == "role":
88 enumeration = ROLES
89 elif attribute == "severity":
90 enumeration = SEVERITIES
91 else:
92 msg = f"Unsupported refine-rule attribute {attribute}"
93 raise ValueError(msg)
94 return enumeration
95
96 @staticmethod
97 def _validate_rule_refinement_params(rule_id, attribute, value):
98 if not is_valid_xccdf_id(rule_id):
99 msg = f"Rule id '{rule_id}' is invalid!"
100 raise ValueError(msg)
101 enumeration = Profile._find_rule_enumeration(attribute)
102 if value in enumeration:
103 return
104 allowed = ", ".join(map(quote, enumeration))
105 msg = (f"Can't refine {attribute} of rule '{rule_id}' to '{value}'. "
106 f"Allowed {attribute} values are: {allowed}.")
107 raise ValueError(msg)
108
109 @staticmethod
110 def _validate_value_refinement_params(value_id, attribute, value):
111 if not is_valid_xccdf_id(value_id):
112 msg = f"Value id '{value_id}' is invalid!"
113 raise ValueError(msg)
114 if attribute == 'selector':
115 return
116 msg = (f"Can't refine {attribute} of value '{value_id}' to '{value}'. "
117 f"Unsupported refine-rule attribute {attribute}.")
118 raise ValueError(msg)
119
120 def _prevent_duplicate_rule_refinement(self, attribute, rule_id, value):
121 refinements = self._rule_refinements[rule_id]
122 if attribute not in refinements:
123 return
124 current = refinements[attribute]
125 msg = (f"Can't refine {attribute} of rule '{rule_id}' to '{value}'. "
126 f"This rule {attribute} is already refined to '{current}'.")
127 raise ValueError(msg)
128
129 def _prevent_duplicate_value_refinement(self, attribute, value_id, value):
130 refinements = self._value_refinements[value_id]
131 if attribute not in refinements:
132 return
133 current = refinements[attribute]
134 msg = (f"Can't refine {attribute} of value '{value_id}' to '{value}'. "
135 f"This value {attribute} is already refined to '{current}'.")
136 raise ValueError(msg)
137
138 def refine_rule(self, rule_id, attribute, value):
139 Profile._validate_rule_refinement_params(rule_id, attribute, value)
140 self._prevent_duplicate_rule_refinement(attribute, rule_id, value)
141 self._rule_refinements[rule_id][attribute] = value
142
143 def refine_value(self, value_id, attribute, value):
144 Profile._validate_value_refinement_params(value_id, attribute, value)
145 self._prevent_duplicate_value_refinement(attribute, value_id, value)
146 self._value_refinements[value_id][attribute] = value
147
148 def add_value_change(self, varname, value):
149 self.value_changes.add((varname, value))
150
151 def change_rule_attribute(self, rule_id, attribute, value):
152 full_rule_id = self._full_rule_id(rule_id)
153 self.refine_rule(full_rule_id, attribute, value)
154
155 def change_value_attribute(self, var_id, attribute, value):
156 full_value_id = self._full_var_id(var_id)
157 self.refine_value(full_value_id, attribute, value)
158
159 def change_rules_attributes(self, assignments, attribute):
160 for change in assignments:
161 rule_id, value = assignment_to_tuple(change)
162 self.change_rule_attribute(rule_id, attribute, value)
163
164 def change_roles(self, assignments):
165 self.change_rules_attributes(assignments, "role")
166
167 def change_severities(self, assignments):
168 self.change_rules_attributes(assignments, "severity")
169
170 def change_values(self, assignments):
171 for change in assignments:
172 varname, value = assignment_to_tuple(change)
173 self.add_value_change(varname, value)
174
175 def change_selectors(self, assignments):
176 for change in assignments:
177 varname, selector = assignment_to_tuple(change)
178 self.change_value_attribute(varname, "selector", selector)
179
180 def _full_id(self, string, el_type):
181 if is_valid_xccdf_id(string):
182 return string
183 return f"xccdf_{self.reverse_dns}_{el_type}_{string}"
184
185 def _full_profile_id(self, string):
186 return self._full_id(string, "profile")
187
188 def _full_var_id(self, string):
189 return self._full_id(string, "value")
190
191 def _full_rule_id(self, string):
192 return self._full_id(string, "rule")
193
194 def _full_group_id(self, string):
195 return self._full_id(string, "group")
196
197 def _add_group_select_operations_to_xml(self, container_element):
198 for group_id in sorted(self.groups_to_select):
199 change = ET.SubElement(container_element, "{%s}select" % NS)
200 change.set("idref", self._full_group_id(group_id))
201 change.set("selected", "true")
202
203 for group_id in sorted(self.groups_to_unselect):
204 change = ET.SubElement(container_element, "{%s}select" % NS)
205 change.set("idref", self._full_group_id(group_id))
206 change.set("selected", "false")
207
208 def _add_rule_select_operations_to_xml(self, container_element):
209 for rule_id in sorted(self.rules_to_select):
210 change = ET.SubElement(container_element, "{%s}select" % NS)
211 change.set("idref", self._full_rule_id(rule_id))
212 change.set("selected", "true")
213
214 for rule_id in sorted(self.rules_to_unselect):
215 change = ET.SubElement(container_element, "{%s}select" % NS)
216 change.set("idref", self._full_rule_id(rule_id))
217 change.set("selected", "false")
218
219 def _add_value_overrides_to_xml(self, container_element):
220 for varname, value in sorted(self.value_changes):
221 change = ET.SubElement(container_element, "{%s}set-value" % NS)
222 change.set("idref", self._full_var_id(varname))
223 change.text = str(value)
224
225 def rule_refinements_to_xml(self, profile_el):
226 for rule_id, refinements in self._rule_refinements.items():
227 ref_rule_el = ET.SubElement(profile_el, "{%s}refine-rule" % NS)
228 ref_rule_el.set("idref", rule_id)
229 for attr, val in refinements.items():
230 ref_rule_el.set(attr, val)
231
232 def value_refinements_to_xml(self, profile_el):
233 for value_id, refinements in self._value_refinements.items():
234 ref_value_el = ET.SubElement(profile_el, "{%s}refine-value" % NS)
235 ref_value_el.set("idref", value_id)
236 for attr, val in refinements.items():
237 ref_value_el.set(attr, val)
238
239 def _import_groups_from_tailoring(self, tailoring):
240 if "groups" in tailoring:
241 for group_id, props in tailoring["groups"].items():
242 if "evaluate" in props:
243 if props["evaluate"]:
244 self.groups_to_select.add(group_id)
245 else:
246 self.groups_to_unselect.add(group_id)
247
248 def _import_variables_from_tailoring(self, tailoring):
249 if "variables" in tailoring:
250 for variable_id, props in tailoring["variables"].items():
251 if "value" in props:
252 self.add_value_change(variable_id, props["value"])
253 if "option_id" in props:
254 self.change_value_attribute(variable_id, "selector", props["option_id"])
255
256 def _import_rules_from_tailoring(self, tailoring):
257 if "rules" in tailoring:
258 for rule_id, props in tailoring["rules"].items():
259 if "evaluate" in props:
260 if props["evaluate"]:
261 self.rules_to_select.add(rule_id)
262 else:
263 self.rules_to_unselect.add(rule_id)
264 for attr in ATTRIBUTES:
265 if attr in props:
266 self.change_rule_attribute(rule_id, attr, props[attr])
267
268 def to_xml(self, root):
269 profile = ET.SubElement(root, "{%s}Profile" % NS)
270 profile.set("id", self._full_profile_id(self.profile_id))
271 if self.extends:
272 profile.set("extends", self._full_profile_id(self.extends))
273
274 # Title has to be there due to the schema definition.
275 title = ET.SubElement(profile, "{%s}title" % NS)
276 if self.profile_title:
277 title.set("override", "true")
278 else:
279 title.set("override", "false")
280 title.text = self.profile_title
281
282 self._add_group_select_operations_to_xml(profile)
283 self._add_rule_select_operations_to_xml(profile)
284 self._add_value_overrides_to_xml(profile)
285 self.rule_refinements_to_xml(profile)
286 self.value_refinements_to_xml(profile)
287
288 def import_json_tailoring_profile(self, profile_dict):
289 if not profile_dict.get("base_profile_id") and not profile_dict.get("id"):
290 raise ValueError("You must define a base_profile_id or an id")
291 self.extends = profile_dict.get("base_profile_id")
292 self.profile_id = profile_dict.get("id")
293 self.profile_title = profile_dict.get("title", self.profile_title)
294
295 self._import_groups_from_tailoring(profile_dict)
296 self._import_rules_from_tailoring(profile_dict)
297 self._import_variables_from_tailoring(profile_dict)
298
299
300 class Tailoring:
301 def __init__(self):
302 self.reverse_dns = DEFAULT_REVERSE_DNS
303 self.id = "xccdf_auto_tailoring_default"
304 self.version = 1
305 self.original_ds_filename = ""
306
307 self.profiles = []
308
309 def get_or_create_tailored_profile_with_id(self, profile_id):
310 if profile_id is not None:
311 for profile in self.profiles:
312 if profile.profile_id == profile_id:
313 return profile
314 profile = Profile()
315 if profile_id is not None:
316 profile.profile_id = profile_id
317 profile.reverse_dns = self.reverse_dns
318 self.profiles.append(profile)
319 return profile
320
321 def to_xml(self, root):
322 root.set("id", self.id)
323
324 benchmark = ET.SubElement(root, "{%s}benchmark" % NS)
325 datastream_uri = pathlib.Path(
326 self.original_ds_filename).absolute().as_uri()
327 benchmark.set("href", datastream_uri)
328
329 version = ET.SubElement(root, "{%s}version" % NS)
330 version.set("time", datetime.datetime.now().isoformat())
331 version.text = str(self.version)
332
333 for profile in self.profiles:
334 profile.to_xml(root)
335
336 def as_xml_string(self, location=None):
337 root = ET.Element("{%s}Tailoring" % NS)
338 self.to_xml(root)
339 root_str = ET.tostring(root)
340 pretty_xml = xml.dom.minidom.parseString(root_str).toprettyxml()
341 with open(location, "w") if location != "-" else sys.stdout as f:
342 f.write(pretty_xml)
343
344 def import_json_tailoring(self, json_tailoring):
345 with open(json_tailoring, "r") as jf:
346 tailoring_dict = json.load(jf)
347
348 if 'profiles' in tailoring_dict and tailoring_dict['profiles']:
349 for profile_dict in tailoring_dict['profiles']:
350 profile = Profile()
351 profile.reverse_dns = self.reverse_dns
352 profile.import_json_tailoring_profile(profile_dict)
353 self.profiles.append(profile)
354 else:
355 raise ValueError("JSON Tailoring does not define any profiles.")
356
357
358 def get_parser():
359 parser = argparse.ArgumentParser(
360 description="This script produces XCCDF 1.2 tailoring files "
361 "to be used by SCAP scanners and SCAP data streams.")
362 parser.add_argument(
363 "datastream", metavar="DS_FILENAME",
364 help="The tailored data stream filename.")
365 parser.add_argument(
366 "profile", metavar="BASE_PROFILE_ID", nargs='?', default="",
367 help="Specify ID of the base profile. ID of the profile can be "
368 "either its full ID, or the suffix, in which case the "
369 "'xccdf_<id-namespace>_profile' prefix will be prepended internally.")
370 parser.add_argument(
371 "-j", "--json-tailoring", metavar="JSON_TAILORING_FILENAME", default="",
372 help="Provide a JSON Tailoring (https://github.com/ComplianceAsCode/schemas/blob/main/tailoring/schema.json) "
373 "file to use as the base for XCCDF tailoring generation. JSON tailoring can be accompanied with "
374 "additional command-line options to either override contents of an existing profile "
375 "(along with --tailored-profile-id identifier) or to create an extra profile (BASE_PROFILE_ID is "
376 "a mandatory argument in this case and --tailored-profile-id is optional) in the resulting "
377 "XCCDF tailoring file.")
378 parser.add_argument(
379 "--title", default="",
380 help="Title of the new profile.")
381 parser.add_argument(
382 "--id-namespace", default=DEFAULT_REVERSE_DNS,
383 help="The reverse-DNS style string that is part of entities IDs in "
384 "the corresponding data stream. If left out, the default value "
385 "'{reverse_dns}' is used.".format(reverse_dns=DEFAULT_REVERSE_DNS))
386 parser.add_argument(
387 "-v", "--var-value", metavar="VAR=VALUE", action="append", default=[],
388 help="Specify modification of the XCCDF value in form "
389 "<varname>=<value>. Name of the variable can be either its full name, "
390 "or the suffix, in which case the 'xccdf_<id-namespace>_value' prefix "
391 "will be prepended internally. Specify the argument multiple times "
392 "if needed.")
393 parser.add_argument(
394 "-V", "--var-select", metavar="VAR=SELECTOR", action="append", default=[],
395 help="Specify refinement of the XCCDF value in form "
396 "<varname>=<selector>. Name of the variable can be either its full name, "
397 "or the suffix, in which case the 'xccdf_<id-namespace>_value' prefix "
398 "will be prepended internally. Specify the argument multiple times "
399 "if needed.")
400 parser.add_argument(
401 "-r", "--rule-role", metavar="RULE=ROLE", action="append", default=[],
402 help="Specify refinement of the XCCDF rule role in form "
403 "<rule_id>=<role>. Name of the rule can be either its full name, or "
404 "the suffix, in which case the 'xccdf_<id-namespace>_rule_' prefix "
405 "will be prepended internally. The value of <role> can be one of "
406 "{options}. Specify the argument multiple times if "
407 "needed.".format(options=", ".join(ROLES)))
408 parser.add_argument(
409 "-e", "--rule-severity", metavar="RULE=SEVERITY", action="append",
410 default=[],
411 help="Specify refinement of the XCCDF rule severity in form "
412 "<rule_id>=<severity>. Name of the rule can be either its full name, "
413 "or the suffix, in which case the 'xccdf_<id-namespace>_rule_' "
414 "prefix will be prepended internally. The value of <severity> can be "
415 "one of {options}. Specify the argument multiple times if "
416 "needed.".format(options=", ".join(SEVERITIES)))
417 parser.add_argument(
418 "-s", "--select", metavar="RULE_ID", action="append", default=[],
419 help="Specify what rules to select. "
420 "The rule ID can be either full, or just the suffix, in which case "
421 "the 'xccdf_<id-namespace>_rule' prefix will be prepended internally. "
422 "Specify the argument multiple times if needed.")
423 parser.add_argument(
424 "-u", "--unselect", metavar="RULE_ID", action="append", default=[],
425 help="Specify what rules to unselect. "
426 "The argument works the same way as the --select argument.")
427 parser.add_argument(
428 "-p", "--tailored-profile-id", "--new-profile-id",
429 help="Specify the ID of the tailored profile. "
430 "The ID of the new profile can be either its full ID, or the suffix, "
431 "in which case the 'xccdf_<id-namespace>_profile_' prefix will be "
432 "prepended internally. If left out, the new ID will be obtained "
433 "by appending '{suffix}' to the tailored profile ID."
434 .format(suffix=DEFAULT_PROFILE_SUFFIX))
435 parser.add_argument(
436 "-o", "--output", default="-",
437 help="Where to save the tailoring file. If not supplied, write to "
438 "standard output.")
439 return parser
440
441
442 if __name__ == "__main__":
443 parser = get_parser()
444 args = parser.parse_args()
445
446 ET.register_namespace(NS_PREFIX, NS)
447
448 if not args.profile and not args.json_tailoring:
449 parser.error("one of the following arguments has to be provided: "
450 "BASE_PROFILE_ID or --json-tailoring JSON_TAILORING_FILENAME")
451
452 t = Tailoring()
453 t.original_ds_filename = args.datastream
454 t.reverse_dns = args.id_namespace
455
456 if args.json_tailoring:
457 t.import_json_tailoring(args.json_tailoring)
458
459 if args.profile or (args.json_tailoring and args.tailored_profile_id):
460 p = t.get_or_create_tailored_profile_with_id(args.tailored_profile_id)
461 p.extends = args.profile
462 if args.title:
463 p.profile_title = args.title
464
465 p.rules_to_select.update(args.select)
466 p.rules_to_unselect.update(args.unselect)
467 p.rules_to_select.difference_update(p.rules_to_unselect)
468
469 p.change_values(args.var_value)
470 p.change_selectors(args.var_select)
471 p.change_roles(args.rule_role)
472 p.change_severities(args.rule_severity)
473
474 t.as_xml_string(args.output)