test_pcap_comparator.py 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116
  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 setUp(self):
  17. self.generated_files = []
  18. self.keep_files = []
  19. def test_determinism(self):
  20. input_pcap = os.environ.get(self.PCAP_ENVIRONMENT_VALUE, self.DEFAULT_PCAP)
  21. seed = os.environ.get(self.SEED_ENVIRONMENT_VALUE, self.DEFAULT_SEED)
  22. command_args = [self.ID2T_LOCATION, "-i", input_pcap, "--seed", seed, "-a", "MembersMgmtCommAttack"]
  23. command = " ".join(map(shlex.quote, command_args))
  24. self.print_warning("The command that gets executed is:", command)
  25. generated_pcap = None
  26. for i in range(self.NUM_ITERATIONS):
  27. retcode, output = subprocess.getstatusoutput(command)
  28. self.print_warning(output)
  29. self.assertEqual(retcode, 0, "For some reason id2t completed with an error")
  30. files = self.parse_files(output)
  31. self.generated_files.extend(files)
  32. pcap = self.find_pcap(files)
  33. if generated_pcap is not None:
  34. try: self.compare_pcaps(generated_pcap, pcap)
  35. except AssertionError as e:
  36. self.keep_files = [generated_pcap, pcap]
  37. raise e
  38. else:
  39. generated_pcap = pcap
  40. self.print_warning()
  41. time.sleep(1) # let some time pass between calls because files are based on the time
  42. def tearDown(self):
  43. self.print_warning("Cleaning up files generated by the test-calls...")
  44. for file in self.generated_files:
  45. if file in self.keep_files: continue
  46. self.print_warning(file)
  47. os.remove(self.ID2T_PATH + os.path.sep + file)
  48. self.print_warning("Done")
  49. self.print_warning("The following files have been kept: " + ", ".join(self.keep_files))
  50. def parse_files(self, program_output: str) -> "list[str]":
  51. lines = program_output.split(os.linesep)
  52. self.assertIn(self.OUTPUT_FILES_PREFIX_LINE, lines,
  53. "The magic string is not in the program output anymore, has the program output structure changed?")
  54. index = lines.index(self.OUTPUT_FILES_PREFIX_LINE)
  55. return lines[index + 1:]
  56. def find_pcap(self, files: "list[str]") -> str:
  57. return next(file for file in files if file.endswith(".pcap"))
  58. def compare_pcaps(self, one: str, other: str):
  59. packetsA = list(scapy.all.rdpcap(self.ID2T_PATH + "/" + one))
  60. packetsB = list(scapy.all.rdpcap(self.ID2T_PATH + "/" + other))
  61. self.assertEqual(len(packetsA), len(packetsB), "Both pcap's have to have the same amount of packets")
  62. for i in range(len(packetsA)):
  63. p, p2 = packetsA[i], packetsB[i]
  64. self.assertAlmostEqual(p.time, p2.time, "Packets no %i in the pcap's don't appear at the same time" % (i + 1))
  65. self.compare_packets(p, p2, i + 1)
  66. def compare_packets(self, p, p2, packet_number):
  67. if p == p2:
  68. return
  69. while type(p) != scapy.packet.NoPayload or type(p2) != scapy.packet.NoPayload:
  70. if type(p) != type(p2):
  71. self.fail("Packets %i are of incompatible types: %s and %s" % (packet_number, type(p).__name__, type(p2).__name__))
  72. for field in p.fields:
  73. if p.fields[field] != p2.fields[field]:
  74. packet_type = type(p).__name__
  75. v, v2 = p.fields[field], p2.fields[field]
  76. self.fail("Packets %i differ in field %s.%s: %s != %s" %
  77. (packet_number, packet_type, field, v, v2))
  78. p = p.payload
  79. p2 = p2.payload
  80. def print_warning(self, *text):
  81. print(*text, file=sys.stderr)
  82. if __name__ == "__main__":
  83. suite = unittest.TestSuite()
  84. suite.addTest(PcapComparison("test_determinism"))
  85. unittest.TextTestRunner().run(suite)