CLI.py 7.6 KB

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