generate_pkcs7_tests.py 7.3 KB

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