CLI.py 7.0 KB

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