CLI.py 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180
  1. #! /usr/bin/env python3
  2. import argparse
  3. import sys
  4. import random
  5. from ID2TLib.Controller import Controller
  6. class LoadFromFile(argparse.Action):
  7. """
  8. Parses the parameter file given by application param -c/--config.
  9. """
  10. def __call__(self, parser, namespace, values, option_string=None):
  11. with values as f:
  12. parser.parse_args(f.read().split(), namespace)
  13. class CLI(object):
  14. def __init__(self):
  15. """
  16. Creates a new CLI object used to handle
  17. """
  18. # Reference to PcapFile object
  19. self.args = None
  20. self.attack_config = None
  21. def parse_arguments(self, args):
  22. """
  23. Defines the allowed application arguments and invokes the evaluation of the arguments.
  24. :param args: The application arguments
  25. """
  26. # Create parser for arguments
  27. parser = argparse.ArgumentParser(description="Intrusion Detection Dataset Toolkit (ID2T) - A toolkit for "
  28. "injecting synthetically created attacks into PCAP files.",
  29. prog="id2t")
  30. # Required arguments
  31. required_group = parser.add_argument_group('required arguments')
  32. required_args_group = required_group.add_mutually_exclusive_group(required=True)
  33. required_args_group.add_argument('-i', '--input', metavar="PCAP_FILE",
  34. help='path to the input pcap file')
  35. required_args_group.add_argument('-l', '--list-attacks', action='store_true')
  36. # Optional arguments
  37. parser.add_argument('-c', '--config', metavar='CONFIG_FILE', help='file containing configuration parameters.',
  38. action=LoadFromFile, type=open)
  39. parser.add_argument('-e', '--export',
  40. help='store statistics as a ".stat" file',
  41. action='store_true', default=False)
  42. parser.add_argument('-r', '--recalculate',
  43. help='recalculate statistics even if a cached version exists.',
  44. action='store_true', default=False)
  45. parser.add_argument('-s', '--statistics', help='print file statistics to stdout.', action='store_true',
  46. default=False)
  47. parser.add_argument('-p', '--plot', help='creates the following plots: the values distributions of TTL, MSS, Window Size, '
  48. 'protocol, and the novelty distributions of IP, port, TTL, MSS, Window Size,'
  49. ' and ToS. In addition to packets count in interval-wise.', action='append',
  50. nargs='?')
  51. parser.add_argument('-q', '--query', metavar="QUERY",
  52. action='append', nargs='?',
  53. help='query the statistics database. If no query is provided, the application enters query mode.')
  54. parser.add_argument('-t', '--extraTests', help='perform extra tests on the input pcap file, including calculating IP entropy'
  55. 'in interval-wise, TCP checksum, and checking payload availability.', action='store_true')
  56. parser.add_argument('--seed', help='random seed for the program, call the program with the same seed to get the same output')
  57. # Attack arguments
  58. parser.add_argument('-a', '--attack', metavar="ATTACK", action='append',
  59. help='injects ATTACK into a PCAP file.', nargs='+')
  60. # Parse arguments
  61. self.args = parser.parse_args(args)
  62. self.process_arguments()
  63. def process_arguments(self):
  64. """
  65. Decide what to do with each of the command line parameters.
  66. """
  67. if self.args.seed is not None:
  68. self.seed_rng(self.args.seed)
  69. if self.args.list_attacks:
  70. # User wants to see the available attacks
  71. self.process_attack_listing()
  72. else:
  73. # User wants to process a PCAP
  74. self.process_pcap()
  75. def seed_rng(self, seed):
  76. try: # try to convert the seed to int
  77. seed = int(seed)
  78. except: pass # otherwise use the strings hash, random.seed does this automatically
  79. random.seed(seed)
  80. def process_attack_listing(self):
  81. import pkgutil
  82. import importlib
  83. import Attack
  84. # Find all attacks, exclude some classes
  85. package = Attack
  86. attack_names = []
  87. for _, name, __ in pkgutil.iter_modules(package.__path__):
  88. if name != 'BaseAttack' and name != 'AttackParameters':
  89. attack_names.append(name)
  90. # List the attacks and their parameters
  91. emph_start = '\033[1m'
  92. emph_end = '\033[0m'
  93. for attack_name in attack_names:
  94. attack_module = importlib.import_module('Attack.{}'.format(attack_name))
  95. attack_class = getattr(attack_module, attack_name)
  96. # Instantiate the attack to get to its definitions.
  97. attack_obj = attack_class()
  98. print('* {}{}{}'.format(emph_start, attack_obj.attack_name, emph_end))
  99. print('\t- {}Description:{} {}'.format(emph_start, emph_end,
  100. attack_obj.attack_description))
  101. print('\t- {}Type:{} {}'.format(emph_start, emph_end,
  102. attack_obj.attack_type))
  103. print('\t- {}Supported Parameters:{}'.format(emph_start, emph_end), end=' ')
  104. # Get all the parameter names in a list and sort them
  105. param_list = []
  106. for key in attack_obj.supported_params:
  107. param_list.append(key.value)
  108. param_list.sort()
  109. # Print each parameter type per line
  110. last_prefix = None
  111. current_prefix = None
  112. for param in param_list:
  113. current_prefix = param.split('.')[0]
  114. if not last_prefix or current_prefix != last_prefix:
  115. print('\n\t + |', end=' ')
  116. print(param, end=' | ')
  117. last_prefix = current_prefix
  118. # Print an empty line
  119. print()
  120. def process_pcap(self):
  121. """
  122. Loads the application controller, the PCAP file statistics and if present, processes the given attacks. Evaluates
  123. given queries.
  124. """
  125. # Create ID2T Controller
  126. controller = Controller(self.args.input, self.args.extraTests)
  127. # Load PCAP statistics
  128. controller.load_pcap_statistics(self.args.export, self.args.recalculate, self.args.statistics)
  129. # Create statistics plots
  130. if self.args.plot is not None:
  131. controller.create_statistics_plot(self.args.plot)
  132. # Process attack(s) with given attack params
  133. if self.args.attack is not None:
  134. # If attack is present, load attack with params
  135. controller.process_attacks(self.args.attack)
  136. # Parameter -q without arguments was given -> go into query loop
  137. if self.args.query == [None]:
  138. controller.enter_query_mode()
  139. # Parameter -q with arguments was given -> process query
  140. elif self.args.query is not None:
  141. controller.process_db_queries(self.args.query, True)
  142. def main(args):
  143. """
  144. Creates a new CLI object and invokes the arguments parsing.
  145. :param args: The provided arguments
  146. """
  147. cli = CLI()
  148. # Check arguments
  149. cli.parse_arguments(args)
  150. # Uncomment to enable calling by terminal
  151. if __name__ == '__main__':
  152. main(sys.argv[1:])