-
Notifications
You must be signed in to change notification settings - Fork 817
Expand file tree
/
Copy pathbuild_yaml.py
More file actions
3613 lines (2972 loc) · 143 KB
/
Copy pathbuild_yaml.py
File metadata and controls
3613 lines (2972 loc) · 143 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Common functions for building YAML in SSG.
Also contains definitions of basic classes like Rule, Group, Value and Platform.
"""
from __future__ import absolute_import
from copy import deepcopy
import datetime
import time
import json
import os
import os.path
import re
import sys
import glob
import ssg.build_remediations
import ssg.components
from .build_cpe import CPEALLogicalTest, CPEALCheckFactRef, ProductCPEs
from .constants import (XCCDF12_NS,
OSCAP_BENCHMARK,
OSCAP_GROUP,
OSCAP_RULE,
OSCAP_VALUE,
SCE_SYSTEM,
cce_uri,
dc_namespace,
ocil_cs,
ocil_namespace,
oval_namespace,
xhtml_namespace,
xsi_namespace,
timestamp,
timestamp_yyyy_mm_dd,
SSG_BENCHMARK_LATEST_URI,
SSG_PROJECT_NAME,
SSG_REF_URIS,
SSG_IDENT_URIS,
PREFIX_TO_NS,
FIX_TYPE_TO_SYSTEM
)
from .rules import get_rule_dir_yaml, is_rule_dir
from .cce import is_cce_format_valid, is_cce_value_valid
from .yaml import DocumentationNotComplete, open_and_expand
from .utils import required_key, mkdir_p, safe_evaluate_boolean_filter
from .xml import ElementTree as ET, register_namespaces, parse_file
import ssg.build_stig
from .entities.common import add_sub_element, make_items_product_specific, \
XCCDFEntity, Templatable
from .entities.profile import Profile, ProfileWithInlinePolicies
def _get_cpe_platforms_of_sub_groups(group, rule_ids_list):
"""
Retrieves the set of CPE platforms used by the sub-groups of a given group.
Args:
group (Group): The group object containing sub-groups.
rule_ids_list (list): A list of rule IDs to filter the CPE platforms.
Returns:
set: A set of CPE platforms used by the sub-groups.
"""
cpe_platforms = set()
for sub_group in group.groups.values():
cpe_platforms_of_sub_group = sub_group.get_used_cpe_platforms(rule_ids_list)
cpe_platforms.update(cpe_platforms_of_sub_group)
return cpe_platforms
def reorder_according_to_ordering(unordered, ordering, regex=None):
"""
Reorders a list of items according to a specified ordering.
Args:
unordered (list): The list of unordered items.
ordering (list): The list of items specifying the desired order.
regex (str, optional): A regex pattern to filter items to be ordered.
If None, a pattern is created from the ordering list.
Returns:
list: A list of items ordered according to the ordering list, followed by any remaining
items sorted alphabetically.
"""
ordered = []
if regex is None:
regex = "|".join(["({0})".format(item) for item in ordering])
regex = re.compile(regex)
items_to_order = list(filter(regex.match, unordered))
unordered = set(unordered)
for priority_type in ordering:
for item in items_to_order:
if priority_type in item and item in unordered:
ordered.append(item)
unordered.remove(item)
ordered.extend(sorted(unordered))
return ordered
def add_warning_elements(element, warnings):
"""
Adds warning elements to the given XML element.
This function iterates over a list of warning dictionaries and adds each warning as a
sub-element to the provided XML element. Each dictionary in the warnings list should contain
a single key-value pair, where the key represents the warning category and the value
represents the warning text.
Args:
element (xml.etree.ElementTree.Element): The XML element to which the warning elements
will be added.
warnings (list of dict): A list of dictionaries, each containing a single key-value pair
representing the warning category and text.
Returns:
None
"""
# The use of [{dict}, {dict}] in warnings is to handle the following
# scenario where multiple warnings have the same category which is
# valid in SCAP and our content:
#
# warnings:
# - general: Some general warning
# - general: Some other general warning
# - general: |-
# Some really long multiline general warning
#
# Each of the {dict} should have only one key/value pair.
for warning_dict in warnings:
warning = add_sub_element(
element, "warning", XCCDF12_NS, list(warning_dict.values())[0])
warning.set("category", list(warning_dict.keys())[0])
def add_nondata_subelements(element, subelement, attribute, attr_data):
"""
Add multiple iterations of a subelement that contains an attribute but no data.
This function creates subelements under a given XML element. Each subelement will have a
specified attribute set to a value from the provided list of attribute data.
Args:
element (xml.etree.ElementTree.Element): The parent XML element to which subelements will
be added.
subelement (str): The tag name of the subelements to be created.
attribute (str): The name of the attribute to be set on each subelement.
attr_data (list): A list of values to be assigned to the specified attribute of each
subelement.
"""
for data in attr_data:
req = ET.SubElement(element, "{%s}%s" % (XCCDF12_NS, subelement))
req.set(attribute, data)
def check_warnings(xccdf_structure):
"""
Checks the warnings in the given xccdf_structure.
This function iterates through the warnings in the xccdf_structure and ensures that each
warning dictionary contains exactly one key/value pair. If a warning dictionary contains more
than one key/value pair, a ValueError is raised with an appropriate message.
Args:
xccdf_structure (object): An object that contains a list of warning dictionaries under the
attribute 'warnings'.
Returns:
None
Raises:
ValueError: If any warning dictionary contains more than one key/value pair.
"""
for warning_list in xccdf_structure.warnings:
if len(warning_list) != 1:
msg = "Only one key/value pair should exist for each warnings dictionary"
raise ValueError(msg)
def add_reference_elements(element, references, ref_uri_dict):
"""
Adds reference elements to an XML element based on provided references and their
corresponding URIs.
Args:
element (xml.etree.ElementTree.Element): The XML element to which reference elements will
be added.
references (dict): A dictionary where keys are reference types (e.g., 'srg') and values
are lists of reference values.
ref_uri_dict (dict): A dictionary mapping reference types to their corresponding URIs.
Returns:
None
Raises:
ValueError: If an SRG reference does not have a defined URI or if an unknown reference
type is encountered.
"""
for ref_type, ref_vals in references.items():
for ref_val in ref_vals:
# This assumes that a single srg key may have items from multiple SRG types
if ref_type == 'srg':
if ref_val.startswith('SRG-OS-'):
ref_href = ref_uri_dict['os-srg']
elif re.match(r'SRG-APP-\d{5,}-CTR-\d{5,}', ref_val):
# The more specific case needs to come first, otherwise the generic SRG-APP
# will catch everything
ref_href = ref_uri_dict['app-srg-ctr']
elif ref_val.startswith('SRG-APP-'):
ref_href = ref_uri_dict['app-srg']
else:
raise ValueError("SRG {0} doesn't have a URI defined.".format(ref_val))
else:
if ref_type not in ref_uri_dict.keys():
msg = (
"Error processing reference {0}: {1}. A reference type "
"has been added that the project doesn't know about."
.format(ref_type, ref_vals))
raise ValueError(msg)
ref_href = ref_uri_dict[ref_type]
ref = ET.SubElement(element, '{%s}reference' % XCCDF12_NS)
ref.set("href", ref_href)
ref.text = ref_val
def add_reference_title_elements(benchmark_el, env_yaml):
"""
Adds reference title elements to the given benchmark element.
This function creates and appends reference elements to the provided benchmark element.
The references are sourced from the `env_yaml` if provided, otherwise from the default
`SSG_REF_URIS`.
Args:
benchmark_el (xml.etree.ElementTree.Element): The benchmark element to which reference
elements will be added.
env_yaml (dict): A dictionary containing reference URIs. If None, the default
`SSG_REF_URIS` will be used.
Returns:
None
"""
if env_yaml:
ref_uri_dict = env_yaml['reference_uris']
else:
ref_uri_dict = SSG_REF_URIS
for title, uri in ref_uri_dict.items():
reference = ET.SubElement(benchmark_el, "{%s}reference" % XCCDF12_NS)
reference.set("href", uri)
reference.text = title
def add_benchmark_metadata(element, include_contributors):
"""
Adds benchmark metadata to an XML element.
This function appends metadata information to the provided XML element, including publisher,
creator, contributors, and source information.
Args:
element (xml.etree.ElementTree.Element): The XML element to which the metadata will be added.
include_contributors (bool): A flag indicating whether to include
contributors in the metadata.
Returns:
None
"""
metadata = ET.SubElement(element, "{%s}metadata" % XCCDF12_NS)
publisher = ET.SubElement(metadata, "{%s}publisher" % dc_namespace)
publisher.text = SSG_PROJECT_NAME
creator = ET.SubElement(metadata, "{%s}creator" % dc_namespace)
creator.text = SSG_PROJECT_NAME
if include_contributors:
contributors_file = os.path.join(os.path.dirname(__file__), "../Contributors.xml")
contrib_tree = parse_file(contributors_file)
for c in contrib_tree.iter('contributor'):
contributor = ET.SubElement(metadata, "{%s}contributor" % dc_namespace)
contributor.text = c.text
source = ET.SubElement(metadata, "{%s}source" % dc_namespace)
source.text = SSG_BENCHMARK_LATEST_URI
class Value(XCCDFEntity):
"""
Represents an XCCDF Value entity.
Attributes:
KEYS (dict): A dictionary of default values for various attributes.
MANDATORY_KEYS (set): A set of keys that are mandatory for the Value entity.
"""
KEYS = dict(
description=lambda: "",
type=lambda: "",
operator=lambda: "equals",
interactive=lambda: False,
options=lambda: dict(),
warnings=lambda: list(),
** XCCDFEntity.KEYS
)
MANDATORY_KEYS = {
"title",
"description",
"type",
}
@classmethod
def process_input_dict(cls, input_contents, env_yaml, product_cpes=None):
"""
Processes the input dictionary for a given environment YAML and optional product CPEs.
Args:
input_contents (dict): The input dictionary containing various parameters.
env_yaml (dict): The environment YAML configuration.
product_cpes (optional): Product CPEs, if any.
Returns:
dict: Processed data dictionary with validated and possibly modified contents.
Raises:
ValueError: If the operator in the input data is not one of the expected possible operators.
"""
if "interactive" in input_contents and isinstance(input_contents["interactive"], str):
input_contents["interactive"] = (
input_contents.get("interactive", "false").lower() == "true")
data = super(Value, cls).process_input_dict(input_contents, env_yaml)
possible_operators = ["equals", "not equal", "greater than",
"less than", "greater than or equal",
"less than or equal", "pattern match"]
if data["operator"] not in possible_operators:
raise ValueError(
"Found an invalid operator value '%s'. "
"Expected one of: %s"
% (data["operator"], ", ".join(possible_operators))
)
return data
@classmethod
def from_yaml(cls, yaml_file, env_yaml=None, product_cpes=None):
"""
Create an instance of the class from a YAML file.
Args:
yaml_file (str): Path to the YAML file.
env_yaml (str, optional): Path to an environment YAML file. Defaults to None.
product_cpes (str, optional): Product CPEs information. Defaults to None.
Returns:
Value: An instance of the class created from the YAML file.
"""
value = super(Value, cls).from_yaml(yaml_file, env_yaml)
check_warnings(value)
return value
def to_xml_element(self):
"""
Converts the current object to an XML element.
This method creates an XML element representing the current object using the XCCDF 1.2
namespace. It sets attributes and child elements based on the object's properties.
Returns:
xml.etree.ElementTree.Element: The XML element representing the object.
"""
value = ET.Element('{%s}Value' % XCCDF12_NS)
value.set('id', OSCAP_VALUE + self.id_)
value.set('type', self.type)
if self.operator != "equals": # equals is the default
value.set('operator', self.operator)
if self.interactive: # False is the default
value.set('interactive', 'true')
title = ET.SubElement(value, '{%s}title' % XCCDF12_NS)
title.text = self.title
add_sub_element(value, 'description', XCCDF12_NS, self.description)
add_warning_elements(value, self.warnings)
for selector, option in self.options.items():
# do not confuse Value with big V with value with small v
# value is child element of Value
value_small = ET.SubElement(value, '{%s}value' % XCCDF12_NS)
# by XCCDF spec, default value is value without selector
if selector != "default":
value_small.set('selector', str(selector))
value_small.text = str(option)
return value
class Benchmark(XCCDFEntity):
"""
Represents an XCCDF Benchmark entity with various attributes and methods to manipulate and
represent the benchmark data.
Attributes:
KEYS (dict): Dictionary of keys with default values.
MANDATORY_KEYS (set): Set of mandatory keys for the benchmark.
GENERIC_FILENAME (str): Default filename for the benchmark.
"""
KEYS = dict(
status=lambda: "",
description=lambda: "",
notice_id=lambda: "",
notice_description=lambda: "",
front_matter=lambda: "",
rear_matter=lambda: "",
cpes=lambda: list(),
version=lambda: "",
profiles=lambda: list(),
values=lambda: dict(),
groups=lambda: dict(),
rules=lambda: dict(),
platforms=lambda: dict(),
product_cpe_names=lambda: list(),
** XCCDFEntity.KEYS
)
MANDATORY_KEYS = {
"title",
"status",
"description",
"front_matter",
"rear_matter",
}
GENERIC_FILENAME = "benchmark.yml"
def load_entities(self, rules_by_id, values_by_id, groups_by_id):
"""
Load entities into the current object from provided dictionaries if they are not already set.
Args:
rules_by_id (dict): A dictionary containing rule entities indexed by their IDs.
values_by_id (dict): A dictionary containing value entities indexed by their IDs.
groups_by_id (dict): A dictionary containing group entities indexed by their IDs.
This method updates the `rules`, `values`, and `groups` attributes of the current object.
If an entity in these attributes is not already set (i.e., its value is falsy), it will be
loaded from the corresponding provided dictionary.
"""
for rid, val in self.rules.items():
if not val:
self.rules[rid] = rules_by_id[rid]
for vid, val in self.values.items():
if not val:
self.values[vid] = values_by_id[vid]
for gid, val in self.groups.items():
if not val:
self.groups[gid] = groups_by_id[gid]
@classmethod
def process_input_dict(cls, input_contents, env_yaml, product_cpes):
"""
Processes the input dictionary by transforming specific keys and extracting required data.
Args:
cls (type): The class that calls this method.
input_contents (dict): The dictionary containing the input data to be processed.
env_yaml (dict): The environment YAML data.
product_cpes (list): The list of product CPEs.
Returns:
dict: The processed data dictionary with transformed and extracted information.
Raises:
KeyError: If any required key is missing in the input dictionaries.
"""
input_contents["front_matter"] = input_contents["front-matter"]
del input_contents["front-matter"]
input_contents["rear_matter"] = input_contents["rear-matter"]
del input_contents["rear-matter"]
data = super(Benchmark, cls).process_input_dict(input_contents, env_yaml, product_cpes)
notice_contents = required_key(input_contents, "notice")
del input_contents["notice"]
data["notice_id"] = required_key(notice_contents, "id")
del notice_contents["id"]
data["notice_description"] = required_key(notice_contents, "description")
del notice_contents["description"]
return data
def represent_as_dict(self):
"""
Converts the instance attributes to a dictionary representation, modifying specific keys
for compatibility.
Returns:
dict: A dictionary representation of the instance with modified keys.
"""
data = super(Benchmark, self).represent_as_dict()
data["rear-matter"] = data["rear_matter"]
del data["rear_matter"]
data["front-matter"] = data["front_matter"]
del data["front_matter"]
return data
@classmethod
def from_yaml(cls, yaml_file, env_yaml=None, product_cpes=None):
"""
Creates a Benchmark instance from a YAML file.
Args:
yaml_file (str): Path to the YAML file.
env_yaml (dict, optional): Environment-specific YAML data. Defaults to None.
product_cpes (ProductCPEs, optional): Product CPEs instance. Defaults to None.
Returns:
Benchmark: An instance of the Benchmark class populated with data from the YAML file.
"""
benchmark = super(Benchmark, cls).from_yaml(yaml_file, env_yaml)
if env_yaml:
benchmark.product_cpe_names = product_cpes.get_product_cpe_names()
benchmark.product_cpes = product_cpes
benchmark.id_ = env_yaml["benchmark_id"]
benchmark.version = env_yaml["ssg_version_str"]
else:
benchmark.id_ = "product-name"
benchmark.version = "0.0"
return benchmark
def add_profiles_from_dir(self, dir_, env_yaml, product_cpes):
"""
Adds profiles from the specified directory to the current instance.
This method scans the given directory for files with the '.profile' extension, attempts to
create ProfileWithInlinePolicies objects from them, and appends them to the instance's
profiles list.
Args:
dir_ (str): The directory to scan for profile files.
env_yaml (dict): The environment YAML data used for profile creation.
product_cpes (list): The list of product CPEs used for profile creation.
Returns:
None
Raises:
RuntimeError: If there is an error building a profile from a file.
Notes:
- Files that do not have the '.profile' extension are skipped.
- If a profile file is incomplete or an error occurs during its creation, it is skipped.
"""
for dir_item in sorted(os.listdir(dir_)):
dir_item_path = os.path.join(dir_, dir_item)
if not os.path.isfile(dir_item_path):
continue
_, ext = os.path.splitext(os.path.basename(dir_item_path))
if ext != '.profile':
sys.stderr.write(
"Encountered file '%s' while looking for profiles, "
"extension '%s' is unknown. Skipping..\n"
% (dir_item, ext)
)
continue
try:
new_profile = ProfileWithInlinePolicies.from_compiled_json(
dir_item_path, env_yaml, product_cpes)
except DocumentationNotComplete:
continue
except Exception as exc:
msg = ("Error building profile from '{fname}': '{error}'"
.format(fname=dir_item_path, error=str(exc)))
raise RuntimeError(msg) from exc
if new_profile is None:
continue
self.profiles.append(new_profile)
def unselect_empty_groups(self):
"""
Unselects empty groups from each profile in the profiles list.
This method iterates through each profile in the `profiles` list and calls the
`unselect_empty_groups` method on each profile, passing the current instance as an
argument.
Returns:
None
"""
for p in self.profiles:
p.unselect_empty_groups(self)
def drop_rules_not_included_in_a_profile(self):
"""
Removes rules from groups that are not included in any profile.
This method retrieves the set of rules that are selected in all profiles and removes any
rules from each group that are not listed in this set.
Returns:
None
"""
selected_rules = self.get_rules_selected_in_all_profiles()
for g in self.groups.values():
g.remove_rules_with_ids_not_listed(selected_rules)
def get_components_not_included_in_a_profiles(self, profiles, rules_and_variables_dict):
"""
Identify and return the sets of rules, groups, and variables that are not included in any
of the given profiles.
Args:
profiles (list): A list of profiles to check against.
rules_and_variables_dict (dict): A dictionary containing rules and their associated
variables.
Returns:
tuple: A tuple containing three sets:
- rules (set): A set of rules not included in any of the profiles.
- groups (set): A set of groups not included in any of the profiles.
- variables (set): A set of variables not included in any of the profiles.
"""
selected_rules = self.get_rules_selected_in_all_profiles(profiles)
selected_variables = self.get_variables_of_rules(
profiles, selected_rules, rules_and_variables_dict
)
rules = set()
groups = set()
variables = set()
out_sets = dict(rules_set=rules, groups_set=groups, variables_set=variables)
for sub_group in self.groups.values():
self._update_not_included_components(
sub_group, selected_rules, selected_variables, out_sets
)
return rules, groups, variables
def get_used_cpe_platforms(self, profiles):
"""
Retrieves the CPE platforms used by the selected rules in the given profiles.
Args:
profiles (list): A list of profiles to check for selected rules.
Returns:
list: A list of CPE platforms associated with the selected rules.
"""
selected_rules = self.get_rules_selected_in_all_profiles(profiles)
cpe_platforms = _get_cpe_platforms_of_sub_groups(self, selected_rules)
return cpe_platforms
def get_not_used_cpe_platforms(self, profiles):
"""
Get the CPE platforms that are not used in the given profiles.
Args:
profiles (list): A list of profiles to check for used CPE platforms.
Returns:
set: A set of CPE platforms that are not used in the given profiles.
"""
used_cpe_platforms = self.get_used_cpe_platforms(profiles)
out = set()
for cpe_platform in self.product_cpes.platforms.keys():
if cpe_platform not in used_cpe_platforms:
out.add(cpe_platform)
return out
@staticmethod
def get_variables_of_rules(profiles, rule_ids, rules_and_variables_dict):
"""
Collects and returns a set of variables associated with the given rules and profiles.
Args:
profiles (list): A list of profile objects, each containing a dictionary of variables.
rule_ids (list): A list of rule identifiers.
rules_and_variables_dict (dict): A dictionary mapping rule identifiers to sets of variables.
Returns:
set: A set of variables associated with the specified rules and profiles.
"""
selected_variables = set()
for rule in rule_ids:
selected_variables.update(rules_and_variables_dict.get(rule))
for profile in profiles:
selected_variables.update(profile.variables.keys())
return selected_variables
def get_rules_selected_in_all_profiles(self, profiles=None):
"""
Get the set of rules that are selected in all given profiles.
Args:
profiles (list, optional): A list of profile objects. If None, the method will use the
instance's profiles attribute.
Returns:
set: A set of rules that are selected in all provided profiles.
"""
selected_rules = set()
if profiles is None:
profiles = self.profiles
for p in profiles:
selected_rules.update(p.selected)
return selected_rules
def _create_benchmark_xml_skeleton(self, env_yaml):
"""
Creates the skeleton of a benchmark XML document.
This method initializes the root element of the XML document with the necessary attributes
and sub-elements based on the provided environment YAML configuration.
Args:
env_yaml (dict): A dictionary containing environment configuration parameters.
Returns:
xml.etree.ElementTree.Element: The root element of the benchmark XML document.
"""
root = ET.Element('{%s}Benchmark' % XCCDF12_NS)
root.set('id', OSCAP_BENCHMARK + self.id_)
root.set('xmlns:xsi', 'http://www.w3.org/2001/XMLSchema-instance')
root.set(
'xsi:schemaLocation',
'http://checklists.nist.gov/xccdf/1.2 xccdf-1.2.xsd')
root.set('style', 'SCAP_1.2')
root.set('resolved', 'true')
root.set('xml:lang', 'en-US')
status = ET.SubElement(root, '{%s}status' % XCCDF12_NS)
status.set('date', timestamp_yyyy_mm_dd)
status.text = self.status
add_sub_element(root, "title", XCCDF12_NS, self.title)
add_sub_element(root, "description", XCCDF12_NS, self.description)
notice = add_sub_element(
root, "notice", XCCDF12_NS, self.notice_description
)
notice.set('id', self.notice_id)
add_sub_element(root, "front-matter", XCCDF12_NS, self.front_matter)
add_sub_element(root, "rear-matter", XCCDF12_NS, self.rear_matter)
return root
def _add_cpe_xml(self, root, cpe_platforms_to_not_include, product_cpes=None):
"""
Adds CPE XML elements to the given root element.
This method creates a platform-specification element and appends platform elements to it
based on the product CPEs, excluding those specified in cpe_platforms_to_not_include. If
there are any platform elements added, the platform-specification element is appended to
the root element. Additionally, it adds platform elements to the root element based on the
product CPE names.
Args:
root (xml.etree.ElementTree.Element): The root XML element to which the CPE elements
will be added.
cpe_platforms_to_not_include (list): A list of platform IDs to be excluded from the
CPE XML.
product_cpes (dict, optional): An object containing product CPEs. Defaults to None.
Returns:
None
"""
# if there are no platforms, do not output platform-specification at all
cpe_platform_spec = ET.Element(
"{%s}platform-specification" % PREFIX_TO_NS["cpe-lang"])
for platform_id in sorted(self.product_cpes.platforms):
if platform_id in cpe_platforms_to_not_include:
continue
platform = self.product_cpes.platforms[platform_id]
cpe_platform_spec.append(platform.to_xml_element())
if len(cpe_platform_spec) > 0:
root.append(cpe_platform_spec)
# The Benchmark applicability is determined by the CPEs
# defined in the product.yml
for cpe_name in self.product_cpe_names:
plat = ET.SubElement(root, "{%s}platform" % XCCDF12_NS)
plat.set("idref", cpe_name)
def _add_profiles_xml(self, root, components_to_not_include):
"""
Adds profile XML elements to the given root element, excluding specified components.
This method iterates over the profiles and appends their XML representation to the root
element, excluding profiles and their components that are specified in the
components_to_not_include dictionary.
Args:
root (xml.etree.ElementTree.Element): The root XML element to which profile elements
will be added.
components_to_not_include (dict): A dictionary specifying components to exclude. It
should have a key "profiles" with a set of profile
IDs to exclude.
Returns:
None
"""
profiles_to_not_include = components_to_not_include.get("profiles", set())
for profile in self.profiles:
if profile.id_ in profiles_to_not_include:
continue
profile.remove_components_not_included(components_to_not_include)
root.append(profile.to_xml_element())
def _add_values_xml(self, root, components_to_not_include):
"""
Adds XML elements for values to the given root element, excluding specified components.
Args:
root (xml.etree.ElementTree.Element): The root XML element to which value elements
will be added.
components_to_not_include (dict): A dictionary specifying components to exclude. The
key "variables" should map to a set of value IDs to
be excluded.
Returns:
None
"""
variables_to_not_include = components_to_not_include.get("variables", set())
for value_id, value in self.values.items():
if value_id in variables_to_not_include:
continue
root.append(value.to_xml_element())
def _add_groups_xml(self, root, components_to_not_include, env_yaml=None):
"""
Adds XML elements for groups to the given root element.
This method processes the groups defined in the benchmark, reorders them according to a
specified priority, and appends their XML representation to the root element. Groups that
are specified in the components_to_not_include are skipped.
Args:
root (xml.etree.ElementTree.Element): The root XML element to which the group elements
will be appended.
components_to_not_include (dict): A dictionary specifying components (e.g., groups)
that should not be included.
env_yaml (dict, optional): An optional environment YAML configuration that may be passed
to the group's to_xml_element method.
"""
groups_in_bench = list(self.groups.keys())
priority_order = ["system", "services", "auditing"]
groups_in_bench = reorder_according_to_ordering(groups_in_bench, priority_order)
groups_to_not_include = components_to_not_include.get("groups", set())
# Make system group the first, followed by services group
for group_id in groups_in_bench:
if group_id in groups_to_not_include:
continue
group = self.groups.get(group_id)
# Products using application benchmark don't have system or services group
if group is not None:
root.append(group.to_xml_element(env_yaml, components_to_not_include))
def _add_rules_xml(self, root, rules_to_not_include, env_yaml=None):
"""
Adds XML elements for rules to the given root element, excluding specified rules.
Args:
root (xml.etree.ElementTree.Element): The root XML element to which rule elements will be added.
rules_to_not_include (set): A set of rule IDs to be excluded from the XML.
env_yaml (dict, optional): An optional dictionary containing environment variables for the rules.
Returns:
None
"""
for rule in self.rules.values():
if rule.id_ in rules_to_not_include:
continue
root.append(rule.to_xml_element(env_yaml))
def _add_version_xml(self, root):
"""
Adds a version element to the provided XML root element.
This method creates a new 'version' subelement under the given root element and sets its
text to the instance's version attribute. Additionally, it sets the 'update' attribute of
the version element to the latest SSG benchmark URI.
Args:
root (xml.etree.ElementTree.Element): The root element to which the version element
will be added.
"""
version = ET.SubElement(root, '{%s}version' % XCCDF12_NS)
version.text = self.version
version.set('update', SSG_BENCHMARK_LATEST_URI)
def to_xml_element(self, env_yaml=None, product_cpes=None, components_to_not_include=None, include_contributors=True):
"""
Converts the current object to an XML element.
Args:
env_yaml (dict, optional): Environment YAML data. Defaults to None.
product_cpes (list, optional): List of product CPEs. Defaults to None.
components_to_not_include (dict, optional): Components to exclude from the XML.
Defaults to None.
include_contributors (bool, optional): Whether to include contributors in the XML.
Defaults to True.
Returns:
xml.etree.ElementTree.Element: The root XML element representing the object.
"""
if components_to_not_include is None:
cpe_platforms = self.get_not_used_cpe_platforms(self.profiles)
components_to_not_include = {"cpe_platforms": cpe_platforms}
root = self._create_benchmark_xml_skeleton(env_yaml)
add_reference_title_elements(root, env_yaml)
self._add_cpe_xml(
root, components_to_not_include.get("cpe_platforms", set()), product_cpes
)
self._add_version_xml(root)
add_benchmark_metadata(root, include_contributors)
self._add_profiles_xml(root, components_to_not_include)
self._add_values_xml(root, components_to_not_include)
self._add_groups_xml(root, components_to_not_include, env_yaml)
self._add_rules_xml(root, components_to_not_include.get("rules", set()), env_yaml,)
if hasattr(ET, "indent"):
ET.indent(root, space=" ", level=0)
return root
def to_file(self, file_name, env_yaml=None):
"""
Serializes the XML representation of the object to a file.
Args:
file_name (str): The name of the file to which the XML data will be written.
env_yaml (dict, optional): An optional parameter that can be used to customize the XML generation.
Returns:
None
"""
root = self.to_xml_element(env_yaml)
tree = ET.ElementTree(root)
tree.write(file_name, encoding="utf-8")
def add_value(self, value):
"""
Adds a value to the values dictionary if the value is not None.
Args:
value (object): The value to be added. It is expected to have an 'id_' attribute.
Returns:
None
"""
if value is None:
return
self.values[value.id_] = value
# The benchmark is also considered a group, so this function signature needs to match
# Group()'s add_group()
def add_group(self, group, env_yaml=None, product_cpes=None):
"""
Adds a group to the groups dictionary.
Args:
group (Group): The group object to be added. Must have an 'id_' attribute.
env_yaml (dict, optional): Additional environment YAML data. Default is None.
product_cpes (dict, optional): Additional product CPEs data. Default is None.
Returns:
None
"""
if group is None:
return
self.groups[group.id_] = group
def add_rule(self, rule):
"""
Adds a rule to the rules dictionary.