File: build_profile.py

package info (click to toggle)
scap-security-guide 0.1.76-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 110,644 kB
  • sloc: xml: 241,883; sh: 73,777; python: 32,527; makefile: 27
file content (837 lines) | stat: -rw-r--r-- 41,558 bytes parent folder | download
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
from __future__ import absolute_import
from __future__ import print_function

import os
import sys

from .build_yaml import ProfileWithInlinePolicies
from .xml import ElementTree
from .constants import XCCDF12_NS, datastream_namespace
from .constants import oval_namespace as oval_ns
from .constants import SCE_SYSTEM as sce_ns
from .constants import bash_system as bash_rem_system
from .constants import ansible_system as ansible_rem_system
from .constants import ignition_system as ignition_rem_system
from .constants import kubernetes_system as kubernetes_rem_system
from .constants import puppet_system as puppet_rem_system
from .constants import anaconda_system as anaconda_rem_system
from .constants import cce_uri
from .constants import ssg_version_uri
from .constants import stig_ns, cis_ns, hipaa_ns, anssi_ns
from .constants import ospp_ns, cui_ns, xslt_ns, ccn_ns, pcidss4_ns
from .constants import OSCAP_PROFILE
from .constants import SSG_REF_URIS
from .yaml import DocumentationNotComplete
console_width = 80


def make_name_to_profile_mapping(profile_files, env_yaml, product_cpes):
    name_to_profile = {}
    for f in profile_files:
        try:
            p = ProfileWithInlinePolicies.from_yaml(f, env_yaml, product_cpes)
            name_to_profile[p.id_] = p
        except Exception as exc:
            msg = "Not building profile from {fname}: {err}".format(
                fname=f, err=str(exc))
            if not isinstance(exc, DocumentationNotComplete):
                raise
            else:
                print(msg, file=sys.stderr)
    return name_to_profile


class RuleStats(object):
    """
    Class representing the content of a rule for statistics generation
    purposes.
    """
    def __init__(self, rule, cis_ns):
        self.id = rule.get("id")
        self.oval = rule.find('./{%s}check[@system="%s"]' % (XCCDF12_NS, oval_ns))
        self.sce = rule.find('./{%s}check[@system="%s"]' % (XCCDF12_NS, sce_ns))
        self.bash_fix = rule.find('./{%s}fix[@system="%s"]' % (XCCDF12_NS, bash_rem_system))
        self.ansible_fix = rule.find(
            './{%s}fix[@system="%s"]' % (XCCDF12_NS, ansible_rem_system)
        )
        self.ignition_fix = rule.find(
            './{%s}fix[@system="%s"]' % (XCCDF12_NS, ignition_rem_system)
        )
        self.kubernetes_fix = rule.find(
            './{%s}fix[@system="%s"]' % (XCCDF12_NS, kubernetes_rem_system)
        )
        self.puppet_fix = rule.find(
            './{%s}fix[@system="%s"]' % (XCCDF12_NS, puppet_rem_system)
        )
        self.anaconda_fix = rule.find(
            './{%s}fix[@system="%s"]' % (XCCDF12_NS, anaconda_rem_system)
        )
        self.cce = rule.find('./{%s}ident[@system="%s"]' % (XCCDF12_NS, cce_uri))
        self.stigid_ref = rule.find(
            './{%s}reference[@href="%s"]' % (XCCDF12_NS, SSG_REF_URIS["stigid"])
        )
        self.stigref_ref = rule.find('./{%s}reference[@href="%s"]' % (XCCDF12_NS, stig_ns))
        self.ccn_ref = rule.find('./{%s}reference[@href="%s"]' % (XCCDF12_NS, ccn_ns))
        self.cis_ref = rule.find('./{%s}reference[@href="%s"]' % (XCCDF12_NS, cis_ns))
        self.hipaa_ref = rule.find('./{%s}reference[@href="%s"]' % (XCCDF12_NS, hipaa_ns))
        self.anssi_ref = rule.find('./{%s}reference[@href="%s"]' % (XCCDF12_NS, anssi_ns))
        self.ospp_ref = rule.find('./{%s}reference[@href="%s"]' % (XCCDF12_NS, ospp_ns))
        self.pcidss4_ref = rule.find(
            './{%s}reference[@href="%s"]' % (XCCDF12_NS, pcidss4_ns)
        )
        self.cui_ref = rule.find('./{%s}reference[@href="%s"]' % (XCCDF12_NS, cui_ns))

        self.check = None
        if self.oval is not None:
            self.check = self.oval
        elif self.sce is not None:
            self.check = self.sce

        self.fix = None
        if self.bash_fix is not None:
            self.fix = self.bash_fix
        elif self.ansible_fix is not None:
            self.fix = self.ansible_fix
        elif self.ignition_fix is not None:
            self.fix = self.ignition_fix
        elif self.kubernetes_fix is not None:
            self.fix = self.kubernetes_fix
        elif self.puppet_fix is not None:
            self.fix = self.puppet_fix
        elif self.anaconda_fix is not None:
            self.fix = self.anaconda_fix


def get_cis_uri(product):
    cis_uri = cis_ns
    if product:
        constants_path = os.path.join(
            os.path.dirname(os.path.dirname(__file__)),
            "products", product, "transforms/constants.xslt")
        if os.path.exists(constants_path):
            root = ElementTree.parse(constants_path)
            cis_var = root.find('./{%s}variable[@name="cisuri"]' % (xslt_ns))
            if cis_var is not None and cis_var.text:
                cis_uri = cis_var.text
    return cis_uri


class XCCDFBenchmark(object):
    """
    Class for processing an XCCDF benchmark to generate
    statistics about the profiles contained within it.
    """

    def __init__(self, filepath, product=""):
        self.tree = None
        try:
            with open(filepath, 'r') as xccdf_file:
                file_string = xccdf_file.read()
                tree = ElementTree.fromstring(file_string)
                if tree.tag == "{%s}Benchmark" % XCCDF12_NS:
                    self.tree = tree
                elif tree.tag == "{%s}data-stream-collection" % datastream_namespace:
                    benchmark_tree = tree.find(".//{%s}Benchmark" % XCCDF12_NS)
                    self.tree = benchmark_tree
                else:
                    raise ValueError("Unknown root element '%s'" % tree.tag)
        except IOError as ioerr:
            print("%s" % ioerr)
            sys.exit(1)

        self.indexed_rules = {}
        for rule in self.tree.findall(".//{%s}Rule" % (XCCDF12_NS)):
            rule_id = rule.get("id")
            if rule_id is None:
                raise RuntimeError("Can't index a rule with no id attribute!")

            if rule_id in self.indexed_rules:
                raise RuntimeError("Multiple rules exist with same id attribute: %s!" % rule_id)

            self.indexed_rules[rule_id] = rule
        self.cis_ns = get_cis_uri(product)

    def get_profile_stats(self, profile):
        """Obtain statistics for the profile"""

        # Holds the intermediary statistics for profile
        profile_stats = {
            'profile_id': "",
            'ssg_version': 0,
            'rules': [],
            'rules_count': 0,
            'implemented_ovals': [],
            'implemented_ovals_pct': 0,
            'missing_ovals': [],
            'implemented_sces': [],
            'implemented_sces_pct': 0,
            'missing_sces': [],
            'implemented_checks': [],
            'implemented_checks_pct': 0,
            'missing_checks': [],
            'implemented_bash_fixes': [],
            'implemented_bash_fixes_pct': 0,
            'implemented_ansible_fixes': [],
            'implemented_ansible_fixes_pct': 0,
            'implemented_ignition_fixes': [],
            'implemented_ignition_fixes_pct': 0,
            'implemented_kubernetes_fixes': [],
            'implemented_kubernetes_fixes_pct': 0,
            'implemented_puppet_fixes': [],
            'implemented_puppet_fixes_pct': 0,
            'implemented_anaconda_fixes': [],
            'implemented_anaconda_fixes_pct': 0,
            'missing_bash_fixes': [],
            'missing_ansible_fixes': [],
            'missing_ignition_fixes': [],
            'missing_kubernetes_fixes': [],
            'missing_puppet_fixes': [],
            'missing_anaconda_fixes': [],
            'implemented_fixes': [],
            'implemented_fixes_pct': 0,
            'missing_fixes': [],
            'assigned_cces': [],
            'assigned_cces_pct': 0,
            'missing_cces': [],
            'missing_stigid_refs': [],
            'missing_stigref_refs': [],
            'missing_ccn_refs': [],
            'missing_cis_refs': [],
            'missing_hipaa_refs': [],
            'missing_anssi_refs': [],
            'missing_ospp_refs': [],
            'missing_pcidss4_refs': [],
            'missing_cui_refs': [],
            'ansible_parity': [],
        }

        rule_stats = []
        ssg_version_elem = self.tree.find("./{%s}version[@update=\"%s\"]" %
                                          (XCCDF12_NS, ssg_version_uri))

        rules = []

        if profile == "all":
            # "all" is a virtual profile that selects all rules
            rules = self.indexed_rules.values()
        else:
            xccdf_profile = self.tree.find("./{%s}Profile[@id=\"%s\"]" %
                                           (XCCDF12_NS, profile))
            if xccdf_profile is None:
                print("No such profile \"%s\" found in the benchmark!"
                      % profile)
                print("* Available profiles:")
                profiles_avail = self.tree.findall(
                    "./{%s}Profile" % (XCCDF12_NS))
                for _profile in profiles_avail:
                    print("** %s" % _profile.get('id'))
                sys.exit(1)

            # This will only work with SSG where the (default) profile has zero
            # selected rule. If you want to reuse this for custom content, you
            # need to change this to look into Rule/@selected
            selects = xccdf_profile.findall("./{%s}select[@selected=\"true\"]" %
                                            XCCDF12_NS)

            for select in selects:
                rule_id = select.get('idref')
                xccdf_rule = self.indexed_rules.get(rule_id)
                if xccdf_rule is not None:
                    # it could also be a Group
                    rules.append(xccdf_rule)

        for rule in rules:
            if rule is not None:
                rule_stats.append(RuleStats(rule, self.cis_ns))

        if not rule_stats:
            print('Unable to retrieve statistics for %s profile' % profile)
            sys.exit(1)

        rule_stats.sort(key=lambda r: r.id)

        for rule in rule_stats:
            profile_stats['rules'].append(rule.id)

        profile_stats['profile_id'] = profile.replace(OSCAP_PROFILE, "")
        if ssg_version_elem is not None:
            profile_stats['ssg_version'] = \
                'SCAP Security Guide %s' % ssg_version_elem.text
        profile_stats['rules_count'] = len(rule_stats)
        profile_stats['implemented_ovals'] = \
            [x.id for x in rule_stats if x.oval is not None]
        profile_stats['implemented_ovals_pct'] = \
            float(len(profile_stats['implemented_ovals'])) / \
            profile_stats['rules_count'] * 100
        profile_stats['missing_ovals'] = \
            [x.id for x in rule_stats if x.oval is None]

        profile_stats['implemented_sces'] = \
            [x.id for x in rule_stats if x.sce is not None]
        profile_stats['implemented_sces_pct'] = \
            float(len(profile_stats['implemented_sces'])) / \
            profile_stats['rules_count'] * 100
        profile_stats['missing_sces'] = \
            [x.id for x in rule_stats if x.sce is None]

        profile_stats['implemented_checks'] = \
            [x.id for x in rule_stats if x.check is not None]
        profile_stats['implemented_checks_pct'] = \
            float(len(profile_stats['implemented_checks'])) / \
            profile_stats['rules_count'] * 100
        profile_stats['missing_checks'] = \
            [x.id for x in rule_stats if x.check is None]

        profile_stats['implemented_bash_fixes'] = \
            [x.id for x in rule_stats if x.bash_fix is not None]
        profile_stats['implemented_bash_fixes_pct'] = \
            float(len(profile_stats['implemented_bash_fixes'])) / \
            profile_stats['rules_count'] * 100
        profile_stats['missing_bash_fixes'] = \
            [x.id for x in rule_stats if x.bash_fix is None]

        profile_stats['implemented_ansible_fixes'] = \
            [x.id for x in rule_stats if x.ansible_fix is not None]
        profile_stats['implemented_ansible_fixes_pct'] = \
            float(len(profile_stats['implemented_ansible_fixes'])) / \
            profile_stats['rules_count'] * 100
        profile_stats['missing_ansible_fixes'] = \
            [x.id for x in rule_stats if x.ansible_fix is None]

        profile_stats['implemented_ignition_fixes'] = \
            [x.id for x in rule_stats if x.ignition_fix is not None]
        profile_stats['implemented_ignition_fixes_pct'] = \
            float(len(profile_stats['implemented_ignition_fixes'])) / \
            profile_stats['rules_count'] * 100
        profile_stats['missing_ignition_fixes'] = \
            [x.id for x in rule_stats if x.ignition_fix is None]

        profile_stats['implemented_kubernetes_fixes'] = \
            [x.id for x in rule_stats if x.kubernetes_fix is not None]
        profile_stats['implemented_kubernetes_fixes_pct'] = \
            float(len(profile_stats['implemented_kubernetes_fixes'])) / \
            profile_stats['rules_count'] * 100
        profile_stats['missing_kubernetes_fixes'] = \
            [x.id for x in rule_stats if x.kubernetes_fix is None]

        profile_stats['implemented_puppet_fixes'] = \
            [x.id for x in rule_stats if x.puppet_fix is not None]
        profile_stats['implemented_puppet_fixes_pct'] = \
            float(len(profile_stats['implemented_puppet_fixes'])) / \
            profile_stats['rules_count'] * 100
        profile_stats['missing_puppet_fixes'] = \
            [x.id for x in rule_stats if x.puppet_fix is None]

        profile_stats['implemented_anaconda_fixes'] = \
            [x.id for x in rule_stats if x.anaconda_fix is not None]

        profile_stats['implemented_fixes'] = \
            [x.id for x in rule_stats if x.fix is not None]
        profile_stats['implemented_fixes_pct'] = \
            float(len(profile_stats['implemented_fixes'])) / \
            profile_stats['rules_count'] * 100
        profile_stats['missing_fixes'] = \
            [x.id for x in rule_stats if x.fix is None]

        profile_stats['missing_stigid_refs'] = []
        if 'stig' in profile_stats['profile_id']:
            profile_stats['missing_stigid_refs'] = \
                [x.id for x in rule_stats if x.stigid_ref is None]

        profile_stats['missing_stigref_refs'] = []
        if 'stig' in profile_stats['profile_id']:
            profile_stats['missing_stigref_refs'] = \
                [x.id for x in rule_stats if x.stigref_ref is None]

        profile_stats['missing_ccn_refs'] = []
        if 'ccn' in profile_stats['profile_id']:
            profile_stats['missing_ccn_refs'] = \
                [x.id for x in rule_stats if x.ccn_ref is None]

        profile_stats['missing_cis_refs'] = []
        if 'cis' in profile_stats['profile_id']:
            profile_stats['missing_cis_refs'] = \
                [x.id for x in rule_stats if x.cis_ref is None]

        profile_stats['missing_hipaa_refs'] = []
        if 'hipaa' in profile_stats['profile_id']:
            profile_stats['missing_hipaa_refs'] = \
                [x.id for x in rule_stats if x.hipaa_ref is None]

        profile_stats['missing_anssi_refs'] = []
        if 'anssi' in profile_stats['profile_id']:
            profile_stats['missing_anssi_refs'] = \
                [x.id for x in rule_stats if x.anssi_ref is None]

        profile_stats['missing_ospp_refs'] = []
        if 'ospp' in profile_stats['profile_id']:
            profile_stats['missing_ospp_refs'] = \
                [x.id for x in rule_stats if x.ospp_ref is None]

        profile_stats['missing_pcidss4_refs'] = []
        if 'pci-dss' in profile_stats['profile_id']:
            profile_stats['missing_pcidss4_refs'] = \
                [x.id for x in rule_stats if x.pcidss4_ref is None]

        profile_stats['missing_cui_refs'] = []
        if 'cui' in profile_stats['profile_id']:
            profile_stats['missing_cui_refs'] = \
                [x.id for x in rule_stats if x.cui_ref is None]

        profile_stats['implemented_anaconda_fixes_pct'] = \
            float(len(profile_stats['implemented_anaconda_fixes'])) / \
            profile_stats['rules_count'] * 100
        profile_stats['missing_anaconda_fixes'] = \
            [x.id for x in rule_stats if x.anaconda_fix is None]

        profile_stats['assigned_cces'] = \
            [x.id for x in rule_stats if x.cce is not None]
        profile_stats['assigned_cces_pct'] = \
            float(len(profile_stats['assigned_cces'])) / \
            profile_stats['rules_count'] * 100
        profile_stats['missing_cces'] = \
            [x.id for x in rule_stats if x.cce is None]

        profile_stats['ansible_parity'] = \
            [rule_id for rule_id in profile_stats["missing_ansible_fixes"] if rule_id not in profile_stats["missing_bash_fixes"]]
        profile_stats['ansible_parity_pct'] = 0
        if len(profile_stats['implemented_bash_fixes']):
            profile_stats['ansible_parity_pct'] = \
                float(len(profile_stats['implemented_bash_fixes']) -
                      len(profile_stats['ansible_parity'])) / \
                len(profile_stats['implemented_bash_fixes']) * 100

        return profile_stats

    def show_profile_stats(self, profile, options):
        """Displays statistics for specific profile"""

        profile_stats = self.get_profile_stats(profile)
        rules_count = profile_stats['rules_count']
        impl_ovals_count = len(profile_stats['implemented_ovals'])
        impl_sces_count = len(profile_stats['implemented_sces'])
        impl_checks_count = len(profile_stats['implemented_checks'])
        impl_bash_fixes_count = len(profile_stats['implemented_bash_fixes'])
        impl_ansible_fixes_count = len(profile_stats['implemented_ansible_fixes'])
        impl_ignition_fixes_count = len(profile_stats['implemented_ignition_fixes'])
        impl_kubernetes_fixes_count = len(profile_stats['implemented_kubernetes_fixes'])
        impl_puppet_fixes_count = len(profile_stats['implemented_puppet_fixes'])
        impl_anaconda_fixes_count = len(profile_stats['implemented_anaconda_fixes'])
        impl_fixes_count = len(profile_stats['implemented_fixes'])
        missing_stigid_refs_count = len(profile_stats['missing_stigid_refs'])
        missing_stigref_refs_count = len(profile_stats['missing_stigref_refs'])
        missing_ccn_refs_count = len(profile_stats['missing_ccn_refs'])
        missing_cis_refs_count = len(profile_stats['missing_cis_refs'])
        missing_hipaa_refs_count = len(profile_stats['missing_hipaa_refs'])
        missing_anssi_refs_count = len(profile_stats['missing_anssi_refs'])
        missing_ospp_refs_count = len(profile_stats['missing_ospp_refs'])
        missing_pcidss4_refs_count = len(profile_stats['missing_pcidss4_refs'])
        missing_cui_refs_count = len(profile_stats['missing_cui_refs'])
        impl_cces_count = len(profile_stats['assigned_cces'])

        if options.format == "plain":
            if not options.skip_overall_stats:
                print("\nProfile %s:" % profile.replace(OSCAP_PROFILE, ""))
                print("* rules:              %d" % rules_count)
                print("* checks (OVAL):      %d\t[%d%% complete]" %
                      (impl_ovals_count,
                       profile_stats['implemented_ovals_pct']))
                print("* checks (SCE):       %d\t[%d%% complete]" %
                      (impl_sces_count,
                       profile_stats['implemented_sces_pct']))
                print("* checks (any):       %d\t[%d%% complete]" %
                      (impl_checks_count,
                       profile_stats['implemented_checks_pct']))

                print("* fixes (bash):       %d\t[%d%% complete]" %
                      (impl_bash_fixes_count,
                       profile_stats['implemented_bash_fixes_pct']))
                print("* fixes (ansible):    %d\t[%d%% complete]" %
                      (impl_ansible_fixes_count,
                       profile_stats['implemented_ansible_fixes_pct']))
                print("* fixes (ignition):   %d\t[%d%% complete]" %
                      (impl_ignition_fixes_count,
                       profile_stats['implemented_ignition_fixes_pct']))
                print("* fixes (kubernetes): %d\t[%d%% complete]" %
                      (impl_kubernetes_fixes_count,
                       profile_stats['implemented_kubernetes_fixes_pct']))
                print("* fixes (puppet):     %d\t[%d%% complete]" %
                      (impl_puppet_fixes_count,
                       profile_stats['implemented_puppet_fixes_pct']))
                print("* fixes (anaconda):   %d\t[%d%% complete]" %
                      (impl_anaconda_fixes_count,
                       profile_stats['implemented_anaconda_fixes_pct']))
                print("* fixes (any):        %d\t[%d%% complete]" %
                      (impl_fixes_count,
                       profile_stats['implemented_fixes_pct']))

                print("* CCEs:               %d\t[%d%% complete]" %
                      (impl_cces_count,
                       profile_stats['assigned_cces_pct']))

            if options.implemented_ovals and \
               profile_stats['implemented_ovals']:
                print("** Rules of '%s' " % profile +
                      "profile having OVAL check: %d of %d [%d%% complete]" %
                      (impl_ovals_count, rules_count,
                       profile_stats['implemented_ovals_pct']))
                self.console_print(profile_stats['implemented_ovals'],
                                   console_width)

            if options.implemented_sces and \
               profile_stats['implemented_sces']:
                print("** Rules of '%s' " % profile +
                      "profile having SCE check: %d of %d [%d%% complete]" %
                      (impl_sces_count, rules_count,
                       profile_stats['implemented_sces_pct']))
                self.console_print(profile_stats['implemented_sces'],
                                   console_width)

            if options.implemented_fixes:
                if profile_stats['implemented_bash_fixes']:
                    print("*** Rules of '%s' profile having "
                          "a bash fix script: %d of %d [%d%% complete]"
                          % (profile, impl_bash_fixes_count, rules_count,
                             profile_stats['implemented_bash_fixes_pct']))
                    self.console_print(profile_stats['implemented_bash_fixes'],
                                       console_width)

                if profile_stats['implemented_ansible_fixes']:
                    print("*** Rules of '%s' profile having "
                          "a ansible fix script: %d of %d [%d%% complete]"
                          % (profile, impl_ansible_fixes_count, rules_count,
                             profile_stats['implemented_ansible_fixes_pct']))
                    self.console_print(
                        profile_stats['implemented_ansible_fixes'],
                        console_width)

                if profile_stats['implemented_ignition_fixes']:
                    print("*** Rules of '%s' profile having "
                          "a ignition fix script: %d of %d [%d%% complete]"
                          % (profile, impl_ignition_fixes_count, rules_count,
                             profile_stats['implemented_ignition_fixes_pct']))
                    self.console_print(
                        profile_stats['implemented_ignition_fixes'],
                        console_width)

                if profile_stats['implemented_kubernetes_fixes']:
                    print("*** Rules of '%s' profile having "
                          "a kubernetes fix script: %d of %d [%d%% complete]"
                          % (profile, impl_kubernetes_fixes_count, rules_count,
                             profile_stats['implemented_kubernetes_fixes_pct']))
                    self.console_print(
                        profile_stats['implemented_kubernetes_fixes'],
                        console_width)

                if profile_stats['implemented_puppet_fixes']:
                    print("*** Rules of '%s' profile having "
                          "a puppet fix script: %d of %d [%d%% complete]"
                          % (profile, impl_puppet_fixes_count, rules_count,
                             profile_stats['implemented_puppet_fixes_pct']))
                    self.console_print(
                        profile_stats['implemented_puppet_fixes'],
                        console_width)

                if profile_stats['implemented_anaconda_fixes']:
                    print("*** Rules of '%s' profile having "
                          "a anaconda fix script: %d of %d [%d%% complete]"
                          % (profile, impl_anaconda_fixes_count, rules_count,
                             profile_stats['implemented_anaconda_fixes_pct']))
                    self.console_print(
                        profile_stats['implemented_anaconda_fixes'],
                        console_width)

            if options.assigned_cces and \
               profile_stats['assigned_cces']:
                print("*** Rules of '%s' " % profile +
                      "profile having CCE assigned: %d of %d [%d%% complete]" %
                      (impl_cces_count, rules_count,
                       profile_stats['assigned_cces_pct']))
                self.console_print(profile_stats['assigned_cces'],
                                   console_width)

            if options.missing_ovals and profile_stats['missing_ovals']:
                print("*** Rules of '%s' " % profile + "profile missing " +
                      "OVAL: %d of %d [%d%% complete]" %
                      (rules_count - impl_ovals_count, rules_count,
                       profile_stats['implemented_ovals_pct']))
                self.console_print(profile_stats['missing_ovals'],
                                   console_width)

            if options.missing_sces and profile_stats['missing_sces']:
                print("*** Rules of '%s' " % profile + "profile missing " +
                      "SCE: %d of %d [%d%% complete]" %
                      (rules_count - impl_sces_count, rules_count,
                       profile_stats['implemented_sces_pct']))
                self.console_print(profile_stats['missing_sces'],
                                   console_width)

            if options.missing_fixes:
                if profile_stats['missing_bash_fixes']:
                    print("*** rules of '%s' profile missing "
                          "a bash fix script: %d of %d [%d%% complete]"
                          % (profile, rules_count - impl_bash_fixes_count,
                             rules_count,
                             profile_stats['implemented_bash_fixes_pct']))
                    self.console_print(profile_stats['missing_bash_fixes'],
                                       console_width)

                if profile_stats['missing_ansible_fixes']:
                    print("*** rules of '%s' profile missing "
                          "a ansible fix script: %d of %d [%d%% complete]"
                          % (profile, rules_count - impl_ansible_fixes_count,
                             rules_count,
                             profile_stats['implemented_ansible_fixes_pct']))
                    self.console_print(profile_stats['missing_ansible_fixes'],
                                       console_width)

                if profile_stats['missing_ignition_fixes']:
                    print("*** rules of '%s' profile missing "
                          "a ignition fix script: %d of %d [%d%% complete]"
                          % (profile, rules_count - impl_ignition_fixes_count,
                             rules_count,
                             profile_stats['implemented_ignition_fixes_pct']))
                    self.console_print(profile_stats['missing_ignition_fixes'],
                                       console_width)

                if profile_stats['missing_kubernetes_fixes']:
                    print("*** rules of '%s' profile missing "
                          "a kubernetes fix script: %d of %d [%d%% complete]"
                          % (profile, rules_count - impl_kubernetes_fixes_count,
                             rules_count,
                             profile_stats['implemented_kubernetes_fixes_pct']))
                    self.console_print(profile_stats['missing_kubernetes_fixes'],
                                       console_width)

                if profile_stats['missing_puppet_fixes']:
                    print("*** rules of '%s' profile missing "
                          "a puppet fix script: %d of %d [%d%% complete]"
                          % (profile, rules_count - impl_puppet_fixes_count,
                             rules_count,
                             profile_stats['implemented_puppet_fixes_pct']))
                    self.console_print(profile_stats['missing_puppet_fixes'],
                                       console_width)

                if profile_stats['missing_anaconda_fixes']:
                    print("*** rules of '%s' profile missing "
                          "a anaconda fix script: %d of %d [%d%% complete]"
                          % (profile, rules_count - impl_anaconda_fixes_count,
                             rules_count,
                             profile_stats['implemented_anaconda_fixes_pct']))
                    self.console_print(profile_stats['missing_anaconda_fixes'],
                                       console_width)

            if options.missing_stigid_refs and profile_stats['missing_stigid_refs']:
                print("*** rules of '%s' profile missing "
                      "stigid references: %d of %d have them [%d%% missing]"
                      % (profile, rules_count - missing_stigid_refs_count,
                         rules_count,
                         (100.0 * missing_stigid_refs_count / rules_count)))
                self.console_print(profile_stats['missing_stigid_refs'],
                                   console_width)

            if options.missing_stigref_refs and profile_stats['missing_stigref_refs']:
                print("*** rules of '%s' profile missing "
                      "stigref references: %d of %d have them [%d%% missing]"
                      % (profile, rules_count - missing_stigref_refs_count,
                         rules_count,
                         (100.0 * missing_stigref_refs_count / rules_count)))
                self.console_print(profile_stats['missing_stigref_refs'],
                                   console_width)

            if options.missing_ccn_refs and profile_stats['missing_ccn_refs']:
                print("*** rules of '%s' profile missing "
                      "CCN Refs: %d of %d have them [%d%% missing]"
                      % (profile, rules_count - missing_ccn_refs_count,
                         rules_count,
                         (100.0 * missing_ccn_refs_count / rules_count)))
                self.console_print(profile_stats['missing_ccn_refs'],
                                   console_width)

            if options.missing_cis_refs and profile_stats['missing_cis_refs']:
                print("*** rules of '%s' profile missing "
                      "CIS Refs: %d of %d have them [%d%% missing]"
                      % (profile, rules_count - missing_cis_refs_count,
                         rules_count,
                         (100.0 * missing_cis_refs_count / rules_count)))
                self.console_print(profile_stats['missing_cis_refs'],
                                   console_width)

            if options.missing_hipaa_refs and profile_stats['missing_hipaa_refs']:
                print("*** rules of '%s' profile missing "
                      "HIPAA Refs: %d of %d have them [%d%% missing]"
                      % (profile, rules_count - missing_hipaa_refs_count,
                         rules_count,
                         (100.0 * missing_hipaa_refs_count / rules_count)))
                self.console_print(profile_stats['missing_hipaa_refs'],
                                   console_width)

            if options.missing_anssi_refs and profile_stats['missing_anssi_refs']:
                print("*** rules of '%s' profile missing "
                      "ANSSI Refs: %d of %d have them [%d%% missing]"
                      % (profile, rules_count - missing_anssi_refs_count,
                         rules_count,
                         (100.0 * missing_anssi_refs_count / rules_count)))
                self.console_print(profile_stats['missing_anssi_refs'],
                                   console_width)

            if options.missing_ospp_refs and profile_stats['missing_ospp_refs']:
                print("*** rules of '%s' profile missing "
                      "OSPP Refs: %d of %d have them [%d%% missing]"
                      % (profile, rules_count - missing_ospp_refs_count,
                         rules_count,
                         (100.0 * missing_ospp_refs_count / rules_count)))
                self.console_print(profile_stats['missing_ospp_refs'],
                                   console_width)

            if options.missing_pcidss4_refs and profile_stats['missing_pcidss4_refs']:
                print("*** rules of '%s' profile missing "
                      "PCI-DSS v4 Refs: %d of %d have them [%d%% missing]"
                      % (profile, rules_count - missing_pcidss4_refs_count,
                         rules_count,
                         (100.0 * missing_pcidss4_refs_count / rules_count)))
                self.console_print(profile_stats['missing_pcidss4_refs'],
                                   console_width)

            if options.missing_cui_refs and profile_stats['missing_cui_refs']:
                print("*** rules of '%s' profile missing "
                      "CUI Refs: %d of %d have them [%d%% missing]"
                      % (profile, rules_count - missing_cui_refs_count,
                         rules_count,
                         (100.0 * missing_cui_refs_count / rules_count)))
                self.console_print(profile_stats['missing_cui_refs'],
                                   console_width)

            if options.missing_cces and profile_stats['missing_cces']:
                print("***Rules of '%s' " % profile + "profile missing " +
                      "CCE identifier: %d of %d [%d%% complete]" %
                      (rules_count - impl_cces_count, rules_count,
                       profile_stats['assigned_cces_pct']))
                self.console_print(profile_stats['missing_cces'],
                                   console_width)

            if options.ansible_parity:
                print("*** rules of '%s' profile with bash fix that implement "
                      "ansible fix scripts: %d out of %d [%d%% complete]"
                      % (profile, impl_bash_fixes_count - len(profile_stats['ansible_parity']),
                         impl_bash_fixes_count,
                         profile_stats['ansible_parity_pct']))
                self.console_print(profile_stats['ansible_parity'],
                                   console_width)

        elif options.format == "html":
            del profile_stats['implemented_ovals']
            del profile_stats['implemented_sces']
            del profile_stats['implemented_bash_fixes']
            del profile_stats['implemented_ansible_fixes']
            del profile_stats['implemented_ignition_fixes']
            del profile_stats['implemented_kubernetes_fixes']
            del profile_stats['implemented_puppet_fixes']
            del profile_stats['implemented_anaconda_fixes']
            del profile_stats['assigned_cces']

            profile_stats['missing_stigid_refs_count'] = missing_stigid_refs_count
            profile_stats['missing_stigref_refs_count'] = missing_stigref_refs_count
            profile_stats['missing_ccn_refs_count'] = missing_ccn_refs_count
            profile_stats['missing_cis_refs_count'] = missing_cis_refs_count
            profile_stats['missing_hipaa_refs_count'] = missing_hipaa_refs_count
            profile_stats['missing_anssi_refs_count'] = missing_anssi_refs_count
            profile_stats['missing_ospp_refs_count'] = missing_ospp_refs_count
            profile_stats['missing_pcidss4_refs_count'] = missing_pcidss4_refs_count
            profile_stats['missing_cui_refs_count'] = missing_cui_refs_count
            profile_stats['missing_ovals_count'] = len(profile_stats['missing_ovals'])
            profile_stats['missing_sces_count'] = len(profile_stats['missing_sces'])
            profile_stats['missing_bash_fixes_count'] = len(profile_stats['missing_bash_fixes'])
            profile_stats['missing_ansible_fixes_count'] = len(profile_stats['missing_ansible_fixes'])
            profile_stats['missing_ignition_fixes_count'] = len(profile_stats['missing_ignition_fixes'])
            profile_stats['missing_kubernetes_fixes_count'] = \
                    len(profile_stats['missing_kubernetes_fixes'])
            profile_stats['missing_puppet_fixes_count'] = len(profile_stats['missing_puppet_fixes'])
            profile_stats['missing_anaconda_fixes_count'] = len(profile_stats['missing_anaconda_fixes'])
            profile_stats['missing_cces_count'] = len(profile_stats['missing_cces'])

            del profile_stats['implemented_ovals_pct']
            del profile_stats['implemented_sces_pct']
            del profile_stats['implemented_bash_fixes_pct']
            del profile_stats['implemented_ansible_fixes_pct']
            del profile_stats['implemented_ignition_fixes_pct']
            del profile_stats['implemented_kubernetes_fixes_pct']
            del profile_stats['implemented_puppet_fixes_pct']
            del profile_stats['implemented_anaconda_fixes_pct']
            del profile_stats['assigned_cces_pct']
            del profile_stats['ssg_version']
            del profile_stats['ansible_parity_pct']
            del profile_stats['implemented_checks_pct']
            del profile_stats['implemented_fixes_pct']

            return profile_stats
        else:
            # First delete the not requested information
            if not options.missing_ovals:
                del profile_stats['missing_ovals']
            if not options.missing_sces:
                del profile_stats['missing_sces']
            if not options.missing_fixes:
                del profile_stats['missing_bash_fixes']
                del profile_stats['missing_ansible_fixes']
                del profile_stats['missing_ignition_fixes']
                del profile_stats['missing_kubernetes_fixes']
                del profile_stats['missing_puppet_fixes']
                del profile_stats['missing_anaconda_fixes']
                del profile_stats['missing_stigid_refs']
                del profile_stats['missing_stigref_refs']
                del profile_stats['missing_ccn_refs']
                del profile_stats['missing_cis_refs']
                del profile_stats['missing_hipaa_refs']
                del profile_stats['missing_anssi_refs']
                del profile_stats['missing_ospp_refs']
                del profile_stats['missing_pcidss4_refs']
                del profile_stats['missing_cui_refs']
            if not options.missing_cces:
                del profile_stats['missing_cces']
            if not options.implemented_ovals:
                del profile_stats['implemented_ovals']
            if not options.implemented_sces:
                del profile_stats['implemented_sces']
            if not options.implemented_fixes:
                del profile_stats['implemented_bash_fixes']
                del profile_stats['implemented_ansible_fixes']
                del profile_stats['implemented_ignition_fixes']
                del profile_stats['implemented_kubernetes_fixes']
                del profile_stats['implemented_puppet_fixes']
                del profile_stats['implemented_anaconda_fixes']
            if not options.assigned_cces:
                del profile_stats['assigned_cces']

            del profile_stats['rules']

            return profile_stats

    def _process_all_profile_stats(self, function_to_process_profile, *args):
        all_profile_elems = self.tree.findall("./{%s}Profile" % (XCCDF12_NS))
        ret = []
        for elem in all_profile_elems:
            profile = elem.get('id')
            if profile is not None:
                ret.append(function_to_process_profile(profile, *args))
        return ret

    def show_all_profile_stats(self, options):
        return self._process_all_profile_stats(self.show_profile_stats, options)

    def get_all_profile_stats(self):
        return self._process_all_profile_stats(self.get_profile_stats)

    def console_print(self, content, width):
        """Prints the 'content' array left aligned, each time 45 characters
           long, each row 'width' characters wide"""

        msg = ''
        for item in content:
            if len(msg) + len(item) < width - 6:
                msg += '   ' + "%-45s" % item
            else:
                print("%s" % msg)
                msg = '   ' + "%-45s" % item
        if msg != '':
            print("%s" % msg)