test_pcap_comparator.py 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149
  1. #!/usr/bin/python3
  2. import sys, os
  3. import subprocess, shlex
  4. import time
  5. import unittest
  6. import scapy.all
  7. class PcapComparison(unittest.TestCase):
  8. ID2T_PATH = ".."
  9. ID2T_LOCATION = ID2T_PATH + "/" + "id2t"
  10. NUM_ITERATIONS = 3
  11. PCAP_ENVIRONMENT_VALUE = "ID2T_SRC_PCAP"
  12. SEED_ENVIRONMENT_VALUE = "ID2T_SEED"
  13. DEFAULT_PCAP = "resources/telnet-raw.pcap"
  14. DEFAULT_SEED = "42"
  15. OUTPUT_FILES_PREFIX_LINE = "Output files created:"
  16. def __init__(self, *args, **kwargs):
  17. unittest.TestCase.__init__(self, *args, **kwargs)
  18. # params to call id2t with, as a list[list[str]]
  19. # do a round of testing for each list[str] we get
  20. # if none generate some params itself
  21. self.id2t_params = None
  22. def set_id2t_params(self, params: "list[list[str]]"):
  23. self.id2t_params = params
  24. def setUp(self):
  25. self.generated_files = []
  26. self.keep_files = []
  27. def test_determinism(self):
  28. input_pcap = os.environ.get(self.PCAP_ENVIRONMENT_VALUE, self.DEFAULT_PCAP)
  29. seed = os.environ.get(self.SEED_ENVIRONMENT_VALUE, self.DEFAULT_SEED)
  30. if self.id2t_params is None:
  31. self.id2t_params = self.random_id2t_params()
  32. for params in self.id2t_params:
  33. self.do_test_round(input_pcap, seed, params)
  34. def do_test_round(self, input_pcap, seed, additional_params):
  35. command_args = [self.ID2T_LOCATION, "-i", input_pcap, "--seed", seed, "-a", "MembersMgmtCommAttack"] + additional_params
  36. command = " ".join(map(shlex.quote, command_args))
  37. self.print_warning("The command that gets executed is:", command)
  38. generated_pcap = None
  39. for i in range(self.NUM_ITERATIONS):
  40. retcode, output = subprocess.getstatusoutput(command)
  41. self.print_warning(output)
  42. self.assertEqual(retcode, 0, "For some reason id2t completed with an error")
  43. files = self.parse_files(output)
  44. self.generated_files.extend(files)
  45. pcap = self.find_pcap(files)
  46. if generated_pcap is not None:
  47. try:
  48. self.compare_pcaps(generated_pcap, pcap)
  49. except AssertionError as e:
  50. self.keep_files = [generated_pcap, pcap]
  51. raise e
  52. else:
  53. generated_pcap = pcap
  54. self.print_warning()
  55. time.sleep(1) # let some time pass between calls because files are based on the time
  56. def tearDown(self):
  57. self.print_warning("Cleaning up files generated by the test-calls...")
  58. for file in self.generated_files:
  59. if file in self.keep_files: continue
  60. self.print_warning(file)
  61. os.remove(self.ID2T_PATH + os.path.sep + file)
  62. self.print_warning("Done")
  63. self.print_warning("The following files have been kept: " + ", ".join(self.keep_files))
  64. def parse_files(self, program_output: str) -> "list[str]":
  65. lines = program_output.split(os.linesep)
  66. self.assertIn(self.OUTPUT_FILES_PREFIX_LINE, lines,
  67. "The magic string is not in the program output anymore, has the program output structure changed?")
  68. index = lines.index(self.OUTPUT_FILES_PREFIX_LINE)
  69. return lines[index + 1:]
  70. def find_pcap(self, files: "list[str]") -> str:
  71. return next(file for file in files if file.endswith(".pcap"))
  72. def compare_pcaps(self, one: str, other: str):
  73. packetsA = list(scapy.all.rdpcap(self.ID2T_PATH + "/" + one))
  74. packetsB = list(scapy.all.rdpcap(self.ID2T_PATH + "/" + other))
  75. self.assertEqual(len(packetsA), len(packetsB), "Both pcap's have to have the same amount of packets")
  76. for i in range(len(packetsA)):
  77. p, p2 = packetsA[i], packetsB[i]
  78. self.assertAlmostEqual(p.time, p2.time, "Packets no %i in the pcap's don't appear at the same time" % (i + 1))
  79. self.compare_packets(p, p2, i + 1)
  80. def compare_packets(self, p, p2, packet_number):
  81. if p == p2:
  82. return
  83. while type(p) != scapy.packet.NoPayload or type(p2) != scapy.packet.NoPayload:
  84. if type(p) != type(p2):
  85. self.fail("Packets %i are of incompatible types: %s and %s" % (packet_number, type(p).__name__, type(p2).__name__))
  86. for field in p.fields:
  87. if p.fields[field] != p2.fields[field]:
  88. packet_type = type(p).__name__
  89. v, v2 = p.fields[field], p2.fields[field]
  90. self.fail("Packets %i differ in field %s.%s: %s != %s" %
  91. (packet_number, packet_type, field, v, v2))
  92. p = p.payload
  93. p2 = p2.payload
  94. def print_warning(self, *text):
  95. print(*text, file=sys.stderr)
  96. def random_id2t_params(self):
  97. param = lambda key, val: "-p%s=%s" % (str(key), str(val))
  98. return [
  99. []
  100. ]
  101. if __name__ == "__main__":
  102. import sys
  103. # parameters for this program are interpreted as id2t-parameters
  104. id2t_args = sys.argv[1:]
  105. comparison = PcapComparison("test_determinism")
  106. if id2t_args: comparison.set_id2t_params([id2t_args])
  107. suite = unittest.TestSuite()
  108. suite.addTest(comparison)
  109. unittest.TextTestRunner().run(suite)