1#!/usr/bin/env python
2
3import re
4import sys
5import SELinuxNeverallowTestFrame
6
7usage = "Usage: ./gen_SELinux_CTS_neverallows.py <input policy file> <output cts java source>"
8
9# extract_neverallow_rules - takes an intermediate policy file and pulls out the
10# neverallow rules by taking all of the non-commented text between the 'neverallow'
11# keyword and a terminating ';'
12# returns: a list of strings representing these rules
13def extract_neverallow_rules(policy_file):
14    with open(policy_file, 'r') as in_file:
15        policy_str = in_file.read()
16        # remove comments
17        no_comments = re.sub(r'#.+?$', r'', policy_str, flags = re.M)
18        # match neverallow rules
19        return re.findall(r'(^neverallow\s.+?;)', no_comments, flags = re.M |re.S);
20
21# neverallow_rule_to_test - takes a neverallow statement and transforms it into
22# the output necessary to form a cts unit test in a java source file.
23# returns: a string representing a generic test method based on this rule.
24def neverallow_rule_to_test(neverallow_rule, test_num):
25    squashed_neverallow = neverallow_rule.replace("\n", " ")
26    method  = SELinuxNeverallowTestFrame.src_method
27    method = method.replace("testNeverallowRules()",
28        "testNeverallowRules" + str(test_num) + "()")
29    return method.replace("$NEVERALLOW_RULE_HERE$", squashed_neverallow)
30
31if __name__ == "__main__":
32    # check usage
33    if len(sys.argv) != 3:
34        print usage
35        exit()
36    input_file = sys.argv[1]
37    output_file = sys.argv[2]
38
39    src_header = SELinuxNeverallowTestFrame.src_header
40    src_body = SELinuxNeverallowTestFrame.src_body
41    src_footer = SELinuxNeverallowTestFrame.src_footer
42
43    # grab the neverallow rules from the policy file and transform into tests
44    neverallow_rules = extract_neverallow_rules(input_file)
45    i = 0
46    for rule in neverallow_rules:
47        src_body += neverallow_rule_to_test(rule, i)
48        i += 1
49
50    with open(output_file, 'w') as out_file:
51        out_file.write(src_header)
52        out_file.write(src_body)
53        out_file.write(src_footer)
54