def run(self): """Runs the interface and waits for user input commands.""" completer = WordCompleter(['capture', 'spoof', 'clear']) history = FileHistory(self._polym_path + '/.minterface_history') while True: try: command = prompt(HTML("<bold><red>PH</red> > </bold>"), history=history, completer=completer, complete_style=CompleteStyle.READLINE_LIKE, auto_suggest=AutoSuggestFromHistory(), enable_history_search=True) except KeyboardInterrupt: self.exit_program() continue command = command.split(" ") if command[0] in self.EXIT: self.exit_program() elif command[0] in ["capture", "c"]: self._capture(command) elif command[0] in ["spoof", "s"]: self._spoof(command) elif command[0] == "clear": Interface._clear() elif command[0] == "": continue else: Interface._wrong_command()
def run(self): """Runs the interface and waits for user input commands.""" completer = WordCompleter([ 'show', 'name', 'layer', 'dump', 'layers', 'preconditions', 'postconditions', 'executions', 'intercept', 'timestamp', 'version', 'save', 'description', 'spoof', 'clear', 'back' ]) # Initialization of the command history history = FileHistory(join(self._polym_path, '.tinterface_history')) while True: try: command = prompt(HTML("<bold>PH:cap/<red>t%d</red> > </bold>" % self._index), history=history, completer=completer, complete_style=CompleteStyle.READLINE_LIKE, auto_suggest=AutoSuggestFromHistory(), enable_history_search=True) except KeyboardInterrupt: self.exit_program() continue command = command.split(" ") if command[0] in self.EXIT: self.exit_program() elif command[0] in self.RET: break elif command[0] == "name": self._name(command) elif command[0] in ["dump", "d"]: self._dump(command) elif command[0] in ["layer", "l"]: self._layer(command) elif command[0] in ['precs', 'preconditions']: self._conditions(command, 'preconditions') elif command[0] in ['posts', 'postconditions']: self._conditions(command, 'postconditions') elif command[0] in ['execs', 'executions']: self._conditions(command, 'executions') elif command[0] in ["show", "s"]: self._show(command) elif command[0] in ["intercept", "i"]: self._intercept(command) elif command[0] in ["layers", "ls"]: self._layers(command) elif command[0] == "timestamp": print(self._t.timestamp, '\n') elif command[0] == "version": self._version(command) elif command[0] in ['desc', 'description']: self._description(command) elif command[0] == "save": self._save(command) elif command[0] in ["spoof"]: self._spoof(command) elif command[0] == "clear": Interface._clear() elif command[0] == "": continue else: Interface._wrong_command()
def _intercept(self, command): """Starts intercepting packets between two machines""" if len(command) == 1: i = Interceptor(self._t) i.intercept() return # Parsing arguments cp = CommandParser(TemplateInterface._intercept_opts()) args = cp.parse(command) if not args: Interface._argument_error() return # Print the help if args["-h"]: Interface.print_help(TemplateInterface._intercept_help()) # Add localhost iptables rule elif args["-localhost"]: i = Interceptor( self._t, iptables_rule="iptables -I OUTPUT -j NFQUEUE --queue-num 1", ip6tables_rule="ip6tables -I OUTPUT -j NFQUEUE --queue-num 1") i.intercept() # Adds a new iptables rule elif args["-ipt"] or args["-ip6t"]: i = Interceptor(self._t, iptables_rule=args["-ipt"], ip6tables_rule=args["-ip6t"]) i.intercept()
def run(self): """Runs the interface and waits for user input commands.""" completer = WordCompleter(['show', 'dissect', 'template', 'wireshark', 'clear', 'back']) history = FileHistory(self._polym_path + '/.tlinterface_history') session = PromptSession(history=history) while True: try: command = session.prompt(HTML("<bold>PH:<red>cap</red> > </bold>"), completer=completer, complete_style=CompleteStyle.READLINE_LIKE, auto_suggest=AutoSuggestFromHistory(), enable_history_search=True) except KeyboardInterrupt: self.exit_program() continue command = command.split(" ") if command[0] in self.EXIT: self.exit_program() elif command[0] in self.RET: break elif command[0] in ["show", "s"]: self._show(command) elif command[0] == "dissect": self._dissect(command) elif command[0] in ["template", "t"]: self._template(command) elif command[0] in ["wireshark", "w"]: self._wireshark(command) elif command[0] == "clear": Interface._clear() elif command[0] == "": continue else: Interface._wrong_command()
def _capture(self, command): """Handles the capture command and the options.""" def run_tlistinterface(tlist): """Runs the interface that handles the list of Templates.""" tlistinterface = TListInterface(tlist, self._poisoner) tlistinterface.run() def capture_banner(): """Shows a banner before capturing.""" Interface._print_info("Waiting for packets...") print("(Press Ctr-C to exit)\n") def no_captured(): """Shows no packets captured.""" Interface._print_error("No packets have been captured.") # If not additional options if len(command) == 1: capture_banner() cap = capture() if cap: # Showing the new interface to the user run_tlistinterface(cap) else: no_captured() return # Parsing additional options cp = CommandParser(MainInterface._capture_opts()) args = cp.parse(command) # Wrong arguments will return None if not args: Interface._argument_error() return # This variable handles the verbose option func = None # Print the help if args["-h"]: Interface.print_help(MainInterface.capture_help()) return # Capture with verbose elif args["-v"]: func = MainInterface._print_v # Capture with lot of verbose elif args["-vv"]: func = MainInterface._print_vv # Capturing capture_banner() cap = capture(userfilter=args["-f"], count=args["-c"], time=args["-t"], func=func) if cap: run_tlistinterface(cap) else: no_captured()
def _layers(self, command): """Shows the layers of the `Template`.""" if len(command) == 1: print(colored("\n".join(self._t.layernames()), 'cyan'), "\n") return cp = CommandParser(TemplateInterface._layers_opts()) args = cp.parse(command) if not args: Interface._argument_error() return # Print the help if args["-h"]: Interface.print_help(TemplateInterface._layers_help())
def _show(self, command): """Pretty print the `Template` fields.""" if len(command) == 1: self._t.show() return # Parsing the arguments cp = CommandParser(TemplateInterface._show_opts()) args = cp.parse(command) if not args: Interface._argument_error() return # Print the help if args["-h"]: Interface.print_help(TemplateInterface._show_help()) # Show a particular layer elif args["-l"]: self._t.getlayer(args["-l"]).show()
def _show(self, command): """Shows the contents of the `TLayer`""" if len(command) == 1: self._l.show() return # Parsing the arguemnts cp = CommandParser(LayerInterface._show_opts()) args = cp.parse(command) if not args: Interface._argument_error() return # Print the help if args["-h"]: Interface.print_help(LayerInterface._show_help()) # Shows a particular field elif args["-f"]: self._l.getlayer(args["-f"]).show()
def _layers(self, command): """Shows the layers of the `Template`.""" if len(command) == 1: print(colored("\n".join(self._t.layernames()), 'cyan'), "\n") return cp = CommandParser(TemplateInterface._layers_opts()) args = cp.parse(command) if not args: Interface._argument_error() return # Print the help if args["-h"]: Interface.print_help(TemplateInterface._layers_help()) # Prints the custom layers (layers added by the user) elif args["-c"]: clayers = [l.name for l in self._t.customlayers()] print(colored("\n".join(clayers), 'cyan'), "\n")
def _show(self, command): """Shows the list of `Template`.""" if len(command) == 1: self._t.show() return # Parsing arguments cp = CommandParser(TListInterface._show_opts()) args = cp.parse(command) if not args: Interface._argument_error() return # Print the help if args["-h"]: Interface.print_help(TListInterface._show_help()) # Print a particular Template elif args["-t"]: self._t[args["-t"]].show()
def _fields(self, command): """Show all the fields in the layer.""" if len(command) == 1: print(colored("\n".join(self._l.fieldnames()), 'cyan'), "\n") return # Parsing arguments cp = CommandParser(LayerInterface._fields_opts()) args = cp.parse(command) if not args: Interface._argument_error() return # Print the help if args["-h"]: Interface.print_help(LayerInterface._fields_help()) # Prints the custom fields elif args["-c"]: cfields = [f.name for f in self._l.customfields()] print(colored("\n".join(cfields), 'cyan'), "\n")
def run(self): """Runs the interface and waits for user input commands.""" completer = WordCompleter([ 'show', 'name', 'field', 'fields', 'dump', 'recalculate', 'clear', 'back' ]) history = FileHistory(self._polym_path + '/.linterface_history') while True: try: command = prompt( HTML("<bold>PH:cap/t%d/<red>%s</red> > </bold>" % (self._tindex, self._l.name)), history=history, completer=completer, complete_style=CompleteStyle.READLINE_LIKE, auto_suggest=AutoSuggestFromHistory(), enable_history_search=True) except KeyboardInterrupt: self.exit_program() continue # Argument parsing command = command.split(" ") if command[0] in self.EXIT: self.exit_program() elif command[0] in self.RET: break elif command[0] in ["s", "show"]: self._show(command) elif command[0] == "name": self._name(command) elif command[0] in ["field", "f"]: self._field(command) elif command[0] in ["fields", "fs"]: self._fields(command) elif command[0] in ["dump", "d"]: self._dump(command) elif command[0] in ["recalculate", "r"]: self._recalculate(command) elif command[0] == "clear": Interface._clear() elif command[0] == "": continue else: Interface._wrong_command()
def run(self): """Runs the interface and waits for user input commands.""" completer = WordCompleter([ 'value', 'type', 'show', 'name', 'slice', 'size', 'dump', 'clear', 'back' ]) history = FileHistory(self._polym_path + '/.finterface_history') session = PromptSession(history=history) while True: try: command = session.prompt( HTML("<bold>PH:cap/t%d/%s/<red>%s</red> > </bold>" % (self._tindex, self._lname, self._f.name)), completer=completer, complete_style=CompleteStyle.READLINE_LIKE, auto_suggest=AutoSuggestFromHistory(), enable_history_search=True) except KeyboardInterrupt: self.exit_program() continue try: command = command.rstrip().split(" ") if command[0] in self.EXIT: self.exit_program() elif command[0] in self.RET: break elif command[0] in ['v', 'value']: self._value(command) elif command[0] in ['s', 'show']: self._show(command) elif command[0] == 'name': print(self._f.name, '\n') elif command[0] == "slice": print(self._f.slice, '\n') elif command[0] == "type": self._type(command) elif command[0] == "size": print(self._f.size, '\n') elif command[0] in ['d', 'dump']: Interface.color_dump(self._f.pkt_raw, self._f.slice.start, self._f.slice.stop) elif command[0] == "clear": Interface._clear() elif command[0] == "": continue else: Interface._wrong_command() except SystemExit: raise except Exception as e: Interface._print_error( "Exception: Error processing the previous command. More info:" ) print(e)
def _value(self, command): """Manages the value of the `TField`.""" if len(command) == 1: print(self._f.value, '\n') return # Parsing the arguments cp = CommandParser(FieldInterface._value_opts()) args = cp.parse(command) if not args: Interface._argument_error() return # Print the help if args["-h"]: Interface.print_help(FieldInterface._value_help()) # Prints the value encoded in hex if args["-hex"]: print(self._f.hex(), '\n') # Prints the value encoded in bytes elif args["-b"]: print(self._f.raw, '\n')
def _template(self, command): """Manages the access to a particular `Template` in the list.""" if len(command) == 1: Interface.print_help(TListInterface._template_help()) elif len(command) == 2: # Print the help if command[1] == "-h": Interface.print_help(TListInterface._template_help()) # Select a particular Template elif command[1].isdecimal(): index = int(command[1]) if index > len(self._t): Interface._argument_error() return ti = TemplateInterface(self._t[index], index, self._poisoner) ti.run() else: Interface._argument_error() else: Interface._argument_error()
def _dissect(self, command): """Dissects the Template List with the Tshark dissectors.""" if len(command) == 1: Interface._print_info("Dissecting the packets...") self._t[-1] Interface._print_info("Finished!") return # Parsing the arguments cp = CommandParser(TListInterface._dissect_opts()) args = cp.parse(command) if not args: Interface._argument_error() return # Prints the help if args["-h"]: Interface.print_help(TListInterface._dissect_help()) # Dissects until a particular Template elif args["-t"]: Interface._print_info("Dissecting packets until %d" % args["-t"]) self._t[args["-t"]]
def _dump(self, command): """Dumps the packet/template bytes in different formats.""" if len(command) == 1: hexdump.hexdump(self._t.raw) print("") return # Parsing the arguments cp = CommandParser(TemplateInterface._dump_opts()) args = cp.parse(command) if not args: Interface._argument_error() return if args["-hex"]: hexdump.hexdump(self._t.raw) print("") elif args["-b"]: print(str(self._t.raw), "\n") elif args["-hexstr"]: print(hexdump.dump(self._t.raw), "\n") elif args["-h"]: Interface.print_help(TemplateInterface._dump_help())
def _dump(self, command): """Dumps the layer bytes in different formats.""" if len(command) == 1: Interface.color_dump(self._l.raw, self._l.slice.start) return # Parsing the arguments cp = CommandParser(LayerInterface._dump_opts()) args = cp.parse(command) if not args: Interface._argument_error() return if args["-hex"]: Interface.color_dump(self._l.raw, self._l.slice.start) elif args["-b"]: print(str(self._l.raw[self._l.slice.start:]), '\n') elif args["-hexstr"]: d = hexdump.dump(self._l.raw).split(" ") print(" ".join(d[self._l.slice.start:]), '\n') elif args["-h"]: Interface.print_help(LayerInterface._dump_help())
def _wireshark(self, command): """Opens Wireshark with the actual `Template` List in pcap format.""" if len(command) == 1: Interface._print_info("Opening Wireshark...") os.system("nohup wireshark %s &" % join(self._polym_path, ".tmp.pcap")) return # Parsing arguments cp = CommandParser(TListInterface._wireshark_opts()) args = cp.parse(command) if not args: Interface._argument_error() return # Print the help if args["-h"]: Interface.print_help(TListInterface._wireshark_help()) # Select a new path for the Wireshark binary elif args["-p"]: Interface._print_info("Opening Wireshark...") os.system("nohup %s %s &" % (args["-p"], join(self._polym_path, ".tmp.pcap")))
def _custom(self, command): """Manages the custom parameter of the field.""" if len(command) == 1: print(self._f.is_custom(), '\n') return # Parsing the arguments cp = CommandParser(FieldInterface._custom_opts()) args = cp.parse(command) if not args: Interface._argument_error() return # Print the help if args["-h"]: Interface.print_help(FieldInterface._custom_help()) # Sets custom to True elif args["-set"]: self._f.set_custom() Interface._print_info("Custom set to True") # Sets custom to False elif args["-unset"]: self._f.unset_custom() Interface._print_info("Custom set to False")
def run(self): """Runs the interface and waits for user input commands.""" completer = WordCompleter([ 'value', 'type', 'show', 'name', 'slice', 'custom', 'size', 'dump', 'clear', 'back' ]) history = FileHistory(self._polym_path + '/.finterface_history') while True: try: command = prompt( HTML("<bold>PH:cap/t%d/%s/<red>%s</red> > </bold>" % (self._tindex, self._lname, self._f.name)), history=history, completer=completer, complete_style=CompleteStyle.READLINE_LIKE, auto_suggest=AutoSuggestFromHistory(), enable_history_search=True) except KeyboardInterrupt: self.exit_program() continue command = command.split(" ") if command[0] in self.EXIT: self.exit_program() elif command[0] in self.RET: break elif command[0] in ['t', 'type']: self._type(command) elif command[0] in ['v', 'value']: self._value(command) elif command[0] in ['s', 'show']: self._show(command) elif command[0] == 'name': self._name(command) elif command[0] == "slice": print(self._f.slice, '\n') elif command[0] == "custom": self._custom(command) elif command[0] == "size": print(self._f.size, '\n') elif command[0] in ['d', 'dump']: Interface.color_dump(self._f.raw, self._f.slice.start, self._f.slice.stop) elif command[0] == "clear": Interface._clear() elif command[0] == "": continue else: Interface._wrong_command()
def _version(self, command): """Manages the version of the `Template`.""" if len(command) == 1: print(self._t.version, "\n") return cp = CommandParser(TemplateInterface._version_opts()) args = cp.parse(command) if not args: Interface._argument_error() return # Print the help if args["-h"]: Interface.print_help(TemplateInterface._version_help()) # Add a new version elif args["-n"]: self._t.version = args["-n"] Interface._print_info("New version %s added" % args["-n"])
def _name(self, command): """Manages the name of the `Template`.""" if len(command) == 1: print(self._t.name, '\n') return # Parsing the arguments cp = CommandParser(TemplateInterface._name_opts()) args = cp.parse(command) if not args: Interface._argument_error() return # Print the help if args["-h"]: Interface.print_help(TemplateInterface._name_help()) # Set a new name elif args["-n"]: self._t.name = args["-n"] Interface._print_info("New name added: %s" % args["-n"])
def _name(self, command): """Manages the name of the `TLayer`.""" if len(command) == 1: print(self._l.name, '\n') return # Parsing the arguments cp = CommandParser(LayerInterface._name_opts()) args = cp.parse(command) if not args: Interface._argument_error() return # Print the help if args["-h"]: Interface.print_help(LayerInterface._name_help()) # Add a new name elif args["-n"]: self._l.name = args["-n"] Interface._print_info("New name %s added" % args['-n'])
def _name(self, command): """Manages the name of the field.""" if len(command) == 1: print(self._f.name, '\n') return # Parsing field arguments cp = CommandParser(FieldInterface._name_opts()) args = cp.parse(command) if not args: Interface._argument_error() return # Print the help if args["-h"]: Interface.print_help(FieldInterface._name_help()) # Adding a new name to the field elif args["-n"]: self._f.name = args["-n"] Interface._print_info("New name %s added to the field" % args["-n"])
def no_captured(): """Shows no packets captured.""" Interface._print_error("No packets have been captured.")
def capture_banner(): """Shows a banner before capturing.""" Interface._print_info("Waiting for packets...") print("(Press Ctr-C to exit)\n")
def _conditions(self, command, cond): """Manages the preconditions, postconditions and executions for a particular `Template`.""" if len(command) == 1: self._t.show_conditions(cond) return # Parsing the arguments cp = CommandParser(TemplateInterface._conditions_opts()) args = cp.parse(command) if not args: Interface._argument_error() return if len(command) == 2: # Print the help if args['-h']: Interface.print_help(TemplateInterface._conditions_help(cond)) # Show the source code elif args['-s']: self._t.show_conditions(cond, True) # Show all conditions on disk elif args['-sa']: self._t.show_all_conds(cond) # Show all conditions source on disk elif args['-sas']: self._t.show_all_conds(cond, True) else: # Deletes a condition if args['-d']: try: self._t.del_function(cond, args['-d']) Interface._print_info("Condition %s deleted" % args['-d']) except KeyError: Interface._print_error( "The condition %s is not in the list" % args['-d']) return # Adds a condition elif args['-a']: # Create the new file self._create_cond(cond, args["-a"]) ret = os.system( "%s %s.py" % (args["-e"], join(self._conds_path, cond, args["-a"]))) if ret != 0: Interface._print_error( "The editor is not installed or is not in the PATH") return # Save the condition to the Template try: self._add_cond(cond, args["-a"]) except: Interface._print_error( "Bad syntax, please check the code syntax") return # If user wants, delete condition from disk keepindisk = confirm('Keep file on disk (%s)? [y/N] ' % join(self._conds_path, cond)) if not keepindisk: os.remove("%s.py" % join(self._conds_path, cond, args["-a"])) Interface._print_info("Condition %s added" % args["-a"]) # Imports a condition from disk elif args['-i']: name = args['-i'] if name[-3:] == ".py": name = name[:-3] try: self._add_cond(cond, name) Interface._print_info("Condition %s imported" % args['-i']) except ModuleNotFoundError: Interface._print_error("The condition %s is not in disk" % args['-i']) print("(Please place your .py file in %s folder)\n" % join(self._conds_path, cond)) return
def _layer(self, command): """Manages the access to a `TLayer` of the `Template`.""" if len(command) == 1: Interface.print_help(TemplateInterface._layer_help()) elif len(command) == 2 and command[1].upper() in self._t.layernames(): li = LayerInterface(self._t.getlayer(command[1].upper()), self._index, self._poisoner) li.run() else: cp = CommandParser(TemplateInterface._layer_opts()) args = cp.parse(command) if not args: Interface._argument_error() return # Print the help if args["-h"]: Interface.print_help(TemplateInterface._layer_help()) # Adds a new layer elif args["-a"]: hexdump.hexdump(self._t.raw) print() start = input("Start byte of the custom layer: ") end = input("End byte of the custom layer: ") if start.isdecimal() and end.isdecimal(): lslice = str(slice(int(start), int(end))).encode().hex() new_layer = TLayer(args["-a"], raw=self._t.raw.hex(), lslice=lslice, custom=True) self._t.addlayer(new_layer) Interface._print_info( "New layer %s added to the Template" % args["-a"]) else: Interface._print_error( "The start or end byte is not a number") # Deletes an existing layer elif args["-d"]: del_layer = self._t.getlayer(args["-d"]) if del_layer: self._t.dellayer(del_layer) Interface._print_info("Layer %s deleted" % args["-d"]) else: Interface._print_error("The layer %s does not exist" % args["-d"])
def _save(self, command): """Saves the `Template` to disk.""" if len(command) == 1: path = input("Introduce the path and the file name: ") try: self._t.write(path) Interface._print_info("Template saved to disk") except: Interface._print_error("The path %s does not exist" % path) return # Parsing arguments cp = CommandParser(TemplateInterface._save_opts()) args = cp.parse(command) if not args: Interface._argument_error() return # Print the help if args["-h"]: Interface.print_help(TemplateInterface._save_help()) # Write to a specific path elif args["-p"]: try: self._t.write(args['-p']) Interface._print_info("Template saved to disk") except: Interface._print_error("The path %s does not exist" % args['-p'])