File: most_used_rules.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 (66 lines) | stat: -rw-r--r-- 1,921 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
import sys
from collections import defaultdict

from ssg.build_profile import XCCDFBenchmark

from .common import generate_output


PYTHON_2 = sys.version_info[0] < 3

if not PYTHON_2:
    from .profile import get_profile
    from ..controleval import (
        load_controls_manager,
        get_product_profiles_files,
    )


def _count_rules_per_rules_list(rules_list, rules):
    for rule in rules_list:
        rules[rule] += 1


def _count_rules_per_benchmark(benchmark, rules):
    benchmark = XCCDFBenchmark(benchmark)
    for profile in benchmark.get_all_profile_stats():
        _count_rules_per_rules_list(profile.get("rules", []), rules)


def _get_profiles_for_product(ctrls_mgr, product):
    profiles_files = get_product_profiles_files(product)

    profiles = []
    for file in profiles_files:
        if "default.profile" not in file:
            profiles.append(get_profile(profiles_files, file, ctrls_mgr.policies))
    return profiles


def _process_all_products_from_controls(rules, products):
    if PYTHON_2:
        raise Exception("This feature is not supported for python2.")

    for product in products:
        controls_manager = load_controls_manager("./controls/", product)
        for profile in _get_profiles_for_product(controls_manager, product):
            _count_rules_per_rules_list(profile.rules, rules)


def _sorted_dict_by_num_value(dict_):
    sorted_ = {k: v for k, v in sorted(dict_.items(), key=lambda x: x[1], reverse=True)}
    return sorted_


def command_most_used_rules(args):
    rules = defaultdict(int)

    if not args.BENCHMARKS:
        _process_all_products_from_controls(rules, args.products)
    else:
        for benchmark in args.BENCHMARKS:
            _count_rules_per_benchmark(benchmark, rules)

    sorted_rules = _sorted_dict_by_num_value(rules)
    csv_header = "rule_id,count_of_profiles"
    generate_output(sorted_rules, args.format, csv_header)