1a8e1175bSopenharmony_ci#!/usr/bin/env python3
2a8e1175bSopenharmony_ci#
3a8e1175bSopenharmony_ci#  Copyright The Mbed TLS Contributors
4a8e1175bSopenharmony_ci#  SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
5a8e1175bSopenharmony_ci#
6a8e1175bSopenharmony_ci
7a8e1175bSopenharmony_ci"""
8a8e1175bSopenharmony_ciMake fuzz like testing for pkcs7 tests
9a8e1175bSopenharmony_ciGiven a valid DER pkcs7 file add tests to the test_suite_pkcs7.data file
10a8e1175bSopenharmony_ci - It is expected that the pkcs7_asn1_fail( data_t *pkcs7_buf )
11a8e1175bSopenharmony_ci    function is defined in test_suite_pkcs7.function
12a8e1175bSopenharmony_ci - This is not meant to be portable code, if anything it is meant to serve as
13a8e1175bSopenharmony_ci   documentation for showing how those ugly tests in test_suite_pkcs7.data were created
14a8e1175bSopenharmony_ci"""
15a8e1175bSopenharmony_ci
16a8e1175bSopenharmony_ci
17a8e1175bSopenharmony_ciimport sys
18a8e1175bSopenharmony_cifrom os.path import exists
19a8e1175bSopenharmony_ci
20a8e1175bSopenharmony_ciPKCS7_TEST_FILE = "../suites/test_suite_pkcs7.data"
21a8e1175bSopenharmony_ci
22a8e1175bSopenharmony_ciclass Test: # pylint: disable=too-few-public-methods
23a8e1175bSopenharmony_ci    """
24a8e1175bSopenharmony_ci    A instance of a test in test_suite_pkcs7.data
25a8e1175bSopenharmony_ci    """
26a8e1175bSopenharmony_ci    def __init__(self, name, depends, func_call):
27a8e1175bSopenharmony_ci        self.name = name
28a8e1175bSopenharmony_ci        self.depends = depends
29a8e1175bSopenharmony_ci        self.func_call = func_call
30a8e1175bSopenharmony_ci
31a8e1175bSopenharmony_ci    # pylint: disable=no-self-use
32a8e1175bSopenharmony_ci    def to_string(self):
33a8e1175bSopenharmony_ci        return "\n" + self.name + "\n" + self.depends + "\n" + self.func_call + "\n"
34a8e1175bSopenharmony_ci
35a8e1175bSopenharmony_ciclass TestData:
36a8e1175bSopenharmony_ci    """
37a8e1175bSopenharmony_ci    Take in test_suite_pkcs7.data file.
38a8e1175bSopenharmony_ci    Allow for new tests to be added.
39a8e1175bSopenharmony_ci    """
40a8e1175bSopenharmony_ci    mandatory_dep = "MBEDTLS_MD_CAN_SHA256"
41a8e1175bSopenharmony_ci    test_name = "PKCS7 Parse Failure Invalid ASN1"
42a8e1175bSopenharmony_ci    test_function = "pkcs7_asn1_fail:"
43a8e1175bSopenharmony_ci    def __init__(self, file_name):
44a8e1175bSopenharmony_ci        self.file_name = file_name
45a8e1175bSopenharmony_ci        self.last_test_num, self.old_tests = self.read_test_file(file_name)
46a8e1175bSopenharmony_ci        self.new_tests = []
47a8e1175bSopenharmony_ci
48a8e1175bSopenharmony_ci    # pylint: disable=no-self-use
49a8e1175bSopenharmony_ci    def read_test_file(self, file):
50a8e1175bSopenharmony_ci        """
51a8e1175bSopenharmony_ci        Parse the test_suite_pkcs7.data file.
52a8e1175bSopenharmony_ci        """
53a8e1175bSopenharmony_ci        tests = []
54a8e1175bSopenharmony_ci        if not exists(file):
55a8e1175bSopenharmony_ci            print(file + " Does not exist")
56a8e1175bSopenharmony_ci            sys.exit()
57a8e1175bSopenharmony_ci        with open(file, "r", encoding='UTF-8') as fp:
58a8e1175bSopenharmony_ci            data = fp.read()
59a8e1175bSopenharmony_ci        lines = [line.strip() for line in data.split('\n') if len(line.strip()) > 1]
60a8e1175bSopenharmony_ci        i = 0
61a8e1175bSopenharmony_ci        while i < len(lines):
62a8e1175bSopenharmony_ci            if "depends" in lines[i+1]:
63a8e1175bSopenharmony_ci                tests.append(Test(lines[i], lines[i+1], lines[i+2]))
64a8e1175bSopenharmony_ci                i += 3
65a8e1175bSopenharmony_ci            else:
66a8e1175bSopenharmony_ci                tests.append(Test(lines[i], None, lines[i+1]))
67a8e1175bSopenharmony_ci                i += 2
68a8e1175bSopenharmony_ci        latest_test_num = float(tests[-1].name.split('#')[1])
69a8e1175bSopenharmony_ci        return latest_test_num, tests
70a8e1175bSopenharmony_ci
71a8e1175bSopenharmony_ci    def add(self, name, func_call):
72a8e1175bSopenharmony_ci        self.last_test_num += 1
73a8e1175bSopenharmony_ci        self.new_tests.append(Test(self.test_name + ": " + name +  " #" + \
74a8e1175bSopenharmony_ci                str(self.last_test_num), "depends_on:" + self.mandatory_dep, \
75a8e1175bSopenharmony_ci                self.test_function + '"' + func_call + '"'))
76a8e1175bSopenharmony_ci
77a8e1175bSopenharmony_ci    def write_changes(self):
78a8e1175bSopenharmony_ci        with open(self.file_name, 'a', encoding='UTF-8') as fw:
79a8e1175bSopenharmony_ci            fw.write("\n")
80a8e1175bSopenharmony_ci            for t in self.new_tests:
81a8e1175bSopenharmony_ci                fw.write(t.to_string())
82a8e1175bSopenharmony_ci
83a8e1175bSopenharmony_ci
84a8e1175bSopenharmony_cidef asn1_mutate(data):
85a8e1175bSopenharmony_ci    """
86a8e1175bSopenharmony_ci    We have been given an asn1 structure representing a pkcs7.
87a8e1175bSopenharmony_ci    We want to return an array of slightly modified versions of this data
88a8e1175bSopenharmony_ci    they should be modified in a way which makes the structure invalid
89a8e1175bSopenharmony_ci
90a8e1175bSopenharmony_ci    We know that asn1 structures are:
91a8e1175bSopenharmony_ci    |---1 byte showing data type---|----byte(s) for length of data---|---data content--|
92a8e1175bSopenharmony_ci    We know that some data types can contain other data types.
93a8e1175bSopenharmony_ci    Return a dictionary of reasons and mutated data types.
94a8e1175bSopenharmony_ci    """
95a8e1175bSopenharmony_ci
96a8e1175bSopenharmony_ci    # off the bat just add bytes to start and end of the buffer
97a8e1175bSopenharmony_ci    mutations = []
98a8e1175bSopenharmony_ci    reasons = []
99a8e1175bSopenharmony_ci    mutations.append(["00"] + data)
100a8e1175bSopenharmony_ci    reasons.append("Add null byte to start")
101a8e1175bSopenharmony_ci    mutations.append(data + ["00"])
102a8e1175bSopenharmony_ci    reasons.append("Add null byte to end")
103a8e1175bSopenharmony_ci    # for every asn1 entry we should attempt to:
104a8e1175bSopenharmony_ci    #    - change the data type tag
105a8e1175bSopenharmony_ci    #    - make the length longer than actual
106a8e1175bSopenharmony_ci    #    - make the length shorter than actual
107a8e1175bSopenharmony_ci    i = 0
108a8e1175bSopenharmony_ci    while i < len(data):
109a8e1175bSopenharmony_ci        tag_i = i
110a8e1175bSopenharmony_ci        leng_i = tag_i + 1
111a8e1175bSopenharmony_ci        data_i = leng_i + 1 + (int(data[leng_i][1], 16) if data[leng_i][0] == '8' else 0)
112a8e1175bSopenharmony_ci        if data[leng_i][0] == '8':
113a8e1175bSopenharmony_ci            length = int(''.join(data[leng_i + 1: data_i]), 16)
114a8e1175bSopenharmony_ci        else:
115a8e1175bSopenharmony_ci            length = int(data[leng_i], 16)
116a8e1175bSopenharmony_ci
117a8e1175bSopenharmony_ci        tag = data[tag_i]
118a8e1175bSopenharmony_ci        print("Looking at ans1: offset " + str(i) + " tag = " + tag + \
119a8e1175bSopenharmony_ci                ", length = " + str(length)+ ":")
120a8e1175bSopenharmony_ci        print(''.join(data[data_i:data_i+length]))
121a8e1175bSopenharmony_ci        # change tag to something else
122a8e1175bSopenharmony_ci        if tag == "02":
123a8e1175bSopenharmony_ci            # turn integers into octet strings
124a8e1175bSopenharmony_ci            new_tag = "04"
125a8e1175bSopenharmony_ci        else:
126a8e1175bSopenharmony_ci            # turn everything else into an integer
127a8e1175bSopenharmony_ci            new_tag = "02"
128a8e1175bSopenharmony_ci        mutations.append(data[:tag_i] + [new_tag] + data[leng_i:])
129a8e1175bSopenharmony_ci        reasons.append("Change tag " + tag + " to " + new_tag)
130a8e1175bSopenharmony_ci
131a8e1175bSopenharmony_ci        # change lengths to too big
132a8e1175bSopenharmony_ci        # skip any edge cases which would cause carry over
133a8e1175bSopenharmony_ci        if int(data[data_i - 1], 16) < 255:
134a8e1175bSopenharmony_ci            new_length = str(hex(int(data[data_i - 1], 16) + 1))[2:]
135a8e1175bSopenharmony_ci            if len(new_length) == 1:
136a8e1175bSopenharmony_ci                new_length = "0"+new_length
137a8e1175bSopenharmony_ci            mutations.append(data[:data_i -1] + [new_length] + data[data_i:])
138a8e1175bSopenharmony_ci            reasons.append("Change length from " + str(length) + " to " \
139a8e1175bSopenharmony_ci                    + str(length + 1))
140a8e1175bSopenharmony_ci            # we can add another test here for tags that contain other tags \
141a8e1175bSopenharmony_ci            # where they have more data than there containing tags account for
142a8e1175bSopenharmony_ci            if tag in ["30", "a0", "31"]:
143a8e1175bSopenharmony_ci                mutations.append(data[:data_i -1] + [new_length] + \
144a8e1175bSopenharmony_ci                        data[data_i:data_i + length] + ["00"] + \
145a8e1175bSopenharmony_ci                        data[data_i + length:])
146a8e1175bSopenharmony_ci                reasons.append("Change contents of tag " + tag + " to contain \
147a8e1175bSopenharmony_ci                        one unaccounted extra byte")
148a8e1175bSopenharmony_ci        # change lengths to too small
149a8e1175bSopenharmony_ci        if int(data[data_i - 1], 16) > 0:
150a8e1175bSopenharmony_ci            new_length = str(hex(int(data[data_i - 1], 16) - 1))[2:]
151a8e1175bSopenharmony_ci            if len(new_length) == 1:
152a8e1175bSopenharmony_ci                new_length = "0"+new_length
153a8e1175bSopenharmony_ci            mutations.append(data[:data_i -1] + [new_length] + data[data_i:])
154a8e1175bSopenharmony_ci            reasons.append("Change length from " + str(length) + " to " + str(length - 1))
155a8e1175bSopenharmony_ci
156a8e1175bSopenharmony_ci        # some tag types contain other tag types so we should iterate into the data
157a8e1175bSopenharmony_ci        if tag in ["30", "a0", "31"]:
158a8e1175bSopenharmony_ci            i = data_i
159a8e1175bSopenharmony_ci        else:
160a8e1175bSopenharmony_ci            i = data_i + length
161a8e1175bSopenharmony_ci
162a8e1175bSopenharmony_ci    return list(zip(reasons, mutations))
163a8e1175bSopenharmony_ci
164a8e1175bSopenharmony_ciif __name__ == "__main__":
165a8e1175bSopenharmony_ci    if len(sys.argv) < 2:
166a8e1175bSopenharmony_ci        print("USAGE: " + sys.argv[0] + " <pkcs7_der_file>")
167a8e1175bSopenharmony_ci        sys.exit()
168a8e1175bSopenharmony_ci
169a8e1175bSopenharmony_ci    DATA_FILE = sys.argv[1]
170a8e1175bSopenharmony_ci    TEST_DATA = TestData(PKCS7_TEST_FILE)
171a8e1175bSopenharmony_ci    with open(DATA_FILE, 'rb') as f:
172a8e1175bSopenharmony_ci        DATA_STR = f.read().hex()
173a8e1175bSopenharmony_ci    # make data an array of byte strings eg ['de','ad','be','ef']
174a8e1175bSopenharmony_ci    HEX_DATA = list(map(''.join, [[DATA_STR[i], DATA_STR[i+1]] for i in range(0, len(DATA_STR), \
175a8e1175bSopenharmony_ci            2)]))
176a8e1175bSopenharmony_ci    # returns tuples of test_names and modified data buffers
177a8e1175bSopenharmony_ci    MUT_ARR = asn1_mutate(HEX_DATA)
178a8e1175bSopenharmony_ci
179a8e1175bSopenharmony_ci    print("made " + str(len(MUT_ARR)) + " new tests")
180a8e1175bSopenharmony_ci    for new_test in MUT_ARR:
181a8e1175bSopenharmony_ci        TEST_DATA.add(new_test[0], ''.join(new_test[1]))
182a8e1175bSopenharmony_ci
183a8e1175bSopenharmony_ci    TEST_DATA.write_changes()
184