blob: 0e73850434b9a7cf5ed931ca85ba13cc526a6003 [file] [log] [blame]
Nick Child4983ddf2022-12-14 15:04:40 -06001#!/usr/bin/env python3
2#
3# Copyright The Mbed TLS Contributors
4# SPDX-License-Identifier: Apache-2.0
5#
6# Licensed under the Apache License, Version 2.0 (the "License"); you may
7# not use this file except in compliance with the License.
8# You may obtain a copy of the License at
9#
10# http://www.apache.org/licenses/LICENSE-2.0
11#
12# Unless required by applicable law or agreed to in writing, software
13# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
14# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15# See the License for the specific language governing permissions and
16# limitations under the License.
17#
18
19"""
20Make fuzz like testing for pkcs7 tests
21Given a valid DER pkcs7 file add tests to the test_suite_pkcs7.data file
22 - It is expected that the pkcs7_asn1_fail( data_t *pkcs7_buf )
23 function is defined in test_suite_pkcs7.function
24 - This is not meant to be portable code, if anything it is meant to serve as
25 documentation for showing how those ugly tests in test_suite_pkcs7.data were created
26"""
27
28
29import sys
30from os.path import exists
31
Nick Childc7c94df2023-02-07 20:01:49 +000032PKCS7_TEST_FILE = "../suites/test_suite_pkcs7.data"
Nick Child4983ddf2022-12-14 15:04:40 -060033
Nick Childc7c94df2023-02-07 20:01:49 +000034class Test: # pylint: disable=too-few-public-methods
35 """
36 A instance of a test in test_suite_pkcs7.data
37 """
Nick Child4983ddf2022-12-14 15:04:40 -060038 def __init__(self, name, depends, func_call):
39 self.name = name
40 self.depends = depends
41 self.func_call = func_call
42
Nick Childc7c94df2023-02-07 20:01:49 +000043 # pylint: disable=no-self-use
Nick Child4983ddf2022-12-14 15:04:40 -060044 def to_string(self):
Nick Child6291cc22023-02-01 18:40:21 +000045 return "\n" + self.name + "\n" + self.depends + "\n" + self.func_call + "\n"
Nick Child4983ddf2022-12-14 15:04:40 -060046
47class TestData:
Nick Childc7c94df2023-02-07 20:01:49 +000048 """
49 Take in test_suite_pkcs7.data file.
50 Allow for new tests to be added.
51 """
Manuel Pégourié-Gonnard93302422023-03-21 17:23:08 +010052 mandatory_dep = "MBEDTLS_MD_CAN_SHA256"
Nick Child4983ddf2022-12-14 15:04:40 -060053 test_name = "PKCS7 Parse Failure Invalid ASN1"
54 test_function = "pkcs7_asn1_fail:"
55 def __init__(self, file_name):
56 self.file_name = file_name
57 self.last_test_num, self.old_tests = self.read_test_file(file_name)
58 self.new_tests = []
59
Dave Rodgman4f70b3c2023-02-08 16:40:40 +000060 # pylint: disable=no-self-use
Nick Child4983ddf2022-12-14 15:04:40 -060061 def read_test_file(self, file):
Nick Childc7c94df2023-02-07 20:01:49 +000062 """
63 Parse the test_suite_pkcs7.data file.
64 """
Nick Child4983ddf2022-12-14 15:04:40 -060065 tests = []
66 if not exists(file):
Nick Child6291cc22023-02-01 18:40:21 +000067 print(file + " Does not exist")
Nick Childc7c94df2023-02-07 20:01:49 +000068 sys.exit()
69 with open(file, "r", encoding='UTF-8') as fp:
70 data = fp.read()
Nick Child4983ddf2022-12-14 15:04:40 -060071 lines = [line.strip() for line in data.split('\n') if len(line.strip()) > 1]
72 i = 0
73 while i < len(lines):
74 if "depends" in lines[i+1]:
Nick Childc7c94df2023-02-07 20:01:49 +000075 tests.append(Test(lines[i], lines[i+1], lines[i+2]))
Nick Child4983ddf2022-12-14 15:04:40 -060076 i += 3
77 else:
78 tests.append(Test(lines[i], None, lines[i+1]))
79 i += 2
80 latest_test_num = float(tests[-1].name.split('#')[1])
81 return latest_test_num, tests
82
83 def add(self, name, func_call):
84 self.last_test_num += 1
Nick Childc7c94df2023-02-07 20:01:49 +000085 self.new_tests.append(Test(self.test_name + ": " + name + " #" + \
86 str(self.last_test_num), "depends_on:" + self.mandatory_dep, \
87 self.test_function + '"' + func_call + '"'))
Nick Child4983ddf2022-12-14 15:04:40 -060088
89 def write_changes(self):
Nick Childc7c94df2023-02-07 20:01:49 +000090 with open(self.file_name, 'a', encoding='UTF-8') as fw:
91 fw.write("\n")
92 for t in self.new_tests:
93 fw.write(t.to_string())
Nick Child4983ddf2022-12-14 15:04:40 -060094
95
96def asn1_mutate(data):
Nick Childc7c94df2023-02-07 20:01:49 +000097 """
98 We have been given an asn1 structure representing a pkcs7.
99 We want to return an array of slightly modified versions of this data
100 they should be modified in a way which makes the structure invalid
Nick Child4983ddf2022-12-14 15:04:40 -0600101
Nick Childc7c94df2023-02-07 20:01:49 +0000102 We know that asn1 structures are:
103 |---1 byte showing data type---|----byte(s) for length of data---|---data content--|
104 We know that some data types can contain other data types.
105 Return a dictionary of reasons and mutated data types.
106 """
Nick Child4983ddf2022-12-14 15:04:40 -0600107
108 # off the bat just add bytes to start and end of the buffer
Nick Childc7c94df2023-02-07 20:01:49 +0000109 mutations = []
110 reasons = []
Nick Child4983ddf2022-12-14 15:04:40 -0600111 mutations.append(["00"] + data)
112 reasons.append("Add null byte to start")
113 mutations.append(data + ["00"])
114 reasons.append("Add null byte to end")
115 # for every asn1 entry we should attempt to:
116 # - change the data type tag
117 # - make the length longer than actual
118 # - make the length shorter than actual
119 i = 0
120 while i < len(data):
121 tag_i = i
122 leng_i = tag_i + 1
123 data_i = leng_i + 1 + (int(data[leng_i][1], 16) if data[leng_i][0] == '8' else 0)
124 if data[leng_i][0] == '8':
125 length = int(''.join(data[leng_i + 1: data_i]), 16)
126 else:
127 length = int(data[leng_i], 16)
128
129 tag = data[tag_i]
Nick Childc7c94df2023-02-07 20:01:49 +0000130 print("Looking at ans1: offset " + str(i) + " tag = " + tag + \
131 ", length = " + str(length)+ ":")
Nick Child6291cc22023-02-01 18:40:21 +0000132 print(''.join(data[data_i:data_i+length]))
Nick Child4983ddf2022-12-14 15:04:40 -0600133 # change tag to something else
134 if tag == "02":
135 # turn integers into octet strings
136 new_tag = "04"
137 else:
138 # turn everything else into an integer
139 new_tag = "02"
140 mutations.append(data[:tag_i] + [new_tag] + data[leng_i:])
Nick Child6291cc22023-02-01 18:40:21 +0000141 reasons.append("Change tag " + tag + " to " + new_tag)
Nick Child4983ddf2022-12-14 15:04:40 -0600142
143 # change lengths to too big
144 # skip any edge cases which would cause carry over
145 if int(data[data_i - 1], 16) < 255:
146 new_length = str(hex(int(data[data_i - 1], 16) + 1))[2:]
147 if len(new_length) == 1:
148 new_length = "0"+new_length
149 mutations.append(data[:data_i -1] + [new_length] + data[data_i:])
Nick Childc7c94df2023-02-07 20:01:49 +0000150 reasons.append("Change length from " + str(length) + " to " \
151 + str(length + 1))
152 # we can add another test here for tags that contain other tags \
153 # where they have more data than there containing tags account for
Nick Child4983ddf2022-12-14 15:04:40 -0600154 if tag in ["30", "a0", "31"]:
Nick Childc7c94df2023-02-07 20:01:49 +0000155 mutations.append(data[:data_i -1] + [new_length] + \
156 data[data_i:data_i + length] + ["00"] + \
157 data[data_i + length:])
158 reasons.append("Change contents of tag " + tag + " to contain \
159 one unaccounted extra byte")
Nick Child4983ddf2022-12-14 15:04:40 -0600160 # change lengths to too small
161 if int(data[data_i - 1], 16) > 0:
162 new_length = str(hex(int(data[data_i - 1], 16) - 1))[2:]
163 if len(new_length) == 1:
164 new_length = "0"+new_length
165 mutations.append(data[:data_i -1] + [new_length] + data[data_i:])
Nick Child6291cc22023-02-01 18:40:21 +0000166 reasons.append("Change length from " + str(length) + " to " + str(length - 1))
Nick Child4983ddf2022-12-14 15:04:40 -0600167
168 # some tag types contain other tag types so we should iterate into the data
169 if tag in ["30", "a0", "31"]:
170 i = data_i
171 else:
172 i = data_i + length
173
174 return list(zip(reasons, mutations))
175
Nick Childc7c94df2023-02-07 20:01:49 +0000176if __name__ == "__main__":
177 if len(sys.argv) < 2:
178 print("USAGE: " + sys.argv[0] + " <pkcs7_der_file>")
179 sys.exit()
Nick Child4983ddf2022-12-14 15:04:40 -0600180
Nick Childc7c94df2023-02-07 20:01:49 +0000181 DATA_FILE = sys.argv[1]
182 TEST_DATA = TestData(PKCS7_TEST_FILE)
183 with open(DATA_FILE, 'rb') as f:
184 DATA_STR = f.read().hex()
185 # make data an array of byte strings eg ['de','ad','be','ef']
186 HEX_DATA = list(map(''.join, [[DATA_STR[i], DATA_STR[i+1]] for i in range(0, len(DATA_STR), \
187 2)]))
188 # returns tuples of test_names and modified data buffers
189 MUT_ARR = asn1_mutate(HEX_DATA)
Nick Child4983ddf2022-12-14 15:04:40 -0600190
Nick Childc7c94df2023-02-07 20:01:49 +0000191 print("made " + str(len(MUT_ARR)) + " new tests")
192 for new_test in MUT_ARR:
193 TEST_DATA.add(new_test[0], ''.join(new_test[1]))
Nick Child4983ddf2022-12-14 15:04:40 -0600194
Nick Childc7c94df2023-02-07 20:01:49 +0000195 TEST_DATA.write_changes()