desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Unset a global variable'
def do_unsetg(self, input):
(argc, argv) = util.parseinput(input, 2) if (argc == 0): args = {'title': 'Global Variables', 'vars': self.fbglobalvars.items()} self.io.print_set_names(args) else: try: del self.fbglobalvars[argv[0]] except KeyError: raise exception.CmdErr, 'Invali...
'Paste and convert data from external tool output'
def do_toolpaste(self, input):
(argc, argv) = util.parseinput(input, 2) if (argc in (0, 1)): self.help_toolpaste() elif (argc == 2): try: self.conv_tools[argv[0]](argv[1]) except KeyError: raise exception.CmdErr, 'Invalid input'
'Gets a list of directories, which should be coverterms'
def _get_projectlist(self, d):
dirlist = [] try: os.makedirs(d) except: if (not os.path.exists(d)): raise map((lambda x: (os.path.isdir(os.path.join(d, x)) and dirlist.append(x))), os.listdir(d)) return dirlist
'Set basic target info'
def do_retarget(self, *ignore):
self.do_back(self) self.io.newline() self.io.print_msg('Retargetting Session') self.io.newline() try: target = self.getip_prompt('Target IP Address', self.fbglobalvars.get('targetip', '')) callback = self.getip_prompt('Callback IP Address', '') redirection = se...
'Print standard OP usage message'
def do_standardop(self, *ignore):
self.help_standardop()
'Set the prompt for the current context. Append the name of the current plugin to the prompt'
def setprompt(self, prompt=None):
if (prompt is None): if (self.getcontext().get_name() == self.defaultcontext.get_name()): context = ' ' else: context = (PROMPT_FMTSTR % (self.getcontext().get_type(), self.getcontext().get_name())) prompt = ((self.promptpre + context) + PROMPT_POST) self.promp...
'Change contexts'
def setcontext(self, new_context):
if (new_context is None): new_context = self.defaultcontext self.ctx = new_context
'Retrieve the current plugin context'
def getcontext(self):
return self.ctx
'Change the command prompt'
def do_changeprompt(self, input):
newprompt = input.strip() if newprompt: self.promptpre = newprompt else: self.promptpre = PROMPT_PRE self.setprompt()
'Repeatedly issue a prompt, accept input, parse an initial prefix off the received input, and dispatch to action methods, passing them the remainder of the line as argument.'
def cmdloop(self):
self.preloop() self.io.pre_input(self.complete) try: stop = None while (not stop): if self.cmdqueue: line = self.cmdqueue.pop(0) else: line = self.io.get_input(self.prompt) stop = self.runcmd(line) self.postloop() ...
'Register a new shortcut key expansion. If a shortcut key is reused the old command will be deleted.'
def register_shortcut(self, shortcutChar, expansion):
if (shortcutChar in self.shortcutKeys): del self.shortcutKeys[shortcutChar] self.shortcutKeys[shortcutChar] = expansion
'Executed before each command. Append the line to history and then log the line to the output.'
def precmd(self, line):
if len(line.strip()): self.cmdhistory.append(line) self.io.log((self.prompt + line)) return line
'Parse the line into a command name and a string containing the arguments. Returns a tuple containing (command, args, line). \'command\' and \'args\' may be None if line couldn\'t be parsed. Check for registered special handlers.'
def parseline(self, line):
line = line.strip() if (not line): return (None, None, line) if (line[(-1):] in self.helpKeys): line = ((self.helpKeys[line[(-1):]] + ' ') + line[:(-1)]) if (line[0] in self.shortcutKeys): line = ((self.shortcutKeys[line[0]] + ' ') + line[1:]) (i, n) = (0, len(line)) ...
'Run a single command. Exceptions should be caught by the caller'
def onecmd(self, line):
(cmd, arg, line) = self.parseline(line) if (not line): return self.emptyline() if (cmd is None): return self.default(line) self.lastcmd = line if (cmd == ''): return self.default(line) else: try: func = getattr(self, ('do_' + cmd.lower())) exce...
'Called when an empty line is encountered'
def emptyline(self):
pass
'Called when command prefix is not recognized.'
def default(self, line):
(cmd, arg, line) = self.parseline(line) try: func = self.ctx.lookup_function(cmd) except AttributeError: self.io.print_error(('Unknown syntax: %s' % line)) else: func(arg)
'Return a list of command names for command completion.'
def completenames(self, text, *ignored):
dotext = ('do_' + text) return ([a[3:] for a in self.ctx.get_names() if a.startswith(dotext)] + [a[3:] for a in self.get_names() if a.startswith(dotext)])
'Return the next possible completion for \'text\'.'
def complete(self, text, state):
if (state == 0): try: import readline except ImportError: import pyreadline as readline origline = readline.get_line_buffer() begidx = readline.get_begidx() endidx = readline.get_endidx() if (begidx > 0): (cmd, args, foo) = self.par...
'Shortcut help'
def get_shortcut_help(self):
return [(key, ('Shortcut for %s' % val)) for (key, val) in self.shortcutKeys.items()]
'Print out help'
def do_help(self, input):
args = input.strip().split() if (len(args) > 0): arg = args[0] try: func = self.ctx.lookup_helpfunction(arg) func() except AttributeError: pass try: func = getattr(self, ('help_' + arg.lower())) func() except Att...
'Run a previous command.'
def do_history(self, arg):
self.cmdhistory.pop() if (len(arg) == 0): history = {'items': enumerate(self.cmdhistory)} self.io.print_history(history) else: try: index = int(arg) except ValueError: self.io.print_error('Bad history index') return try: ...
'Sleep for n seconds'
def do_sleep(self, count):
try: count = int(count) except ValueError: self.io.print_error('Invalid delay') return self.io.print_msg(('Sleeping for %d seconds' % count)) try: time.sleep(count) except KeyboardInterrupt: self.io.print_error('User Interrupt')
'Echo a message'
def do_echo(self, msg):
self.io.print_msg(msg.strip())
'Execute a shell command'
def do_shell(self, arg):
try: retcode = subprocess.call(arg, shell=True) del retcode except OSError as e: self.io.print_error(('Execution failed: ' + e.message)) except KeyboardInterrupt: self.io.print_warning('Execution aborted by user: Ctrl-c')
'Quit program (CTRL-D)'
def do_eof(self, arg):
return self.do_quit(arg)
'Quit program'
def do_quit(self, arg):
return True
'Drop to an interactive Python interpreter'
def do_python(self, arg):
raise exception.Interpreter
'Run a script'
def do_script(self, input):
inputList = input.strip().split() if (len(inputList) == 0): self.help_script() else: try: self.scripting(True) try: script = [line.strip() for line in open(inputList[0]).readlines() if (not line.startswith('#'))] except IOError: ...
'Execute the current plugin'
def do_execute(self, input):
session = None self.io.newline() inputList = input.strip().split() if (len(inputList) > 0): consolemode = inputList[0].lower() consolemode = util.convert_consolemode(consolemode) else: consolemode = 0 plugin = self.get_active_plugin() self.io.print_warning(('Preparing...
'Helper function for forceful termination of the plugin executable, primarily used for testing'
def killPlugin(self):
for p in self.procs: p.kill() self.procs = []
'Rewrite the inconfig, substituting variables'
def write_interpreted_xml_file(self, inConfFile, globalvars={}):
tmpFile = open(inConfFile, 'w') configdata = self.getMarshalledInConfig() configlines = configdata.split('\n') newlines = [] for line in configlines: newlines.append(util.variable_replace(line, globalvars)) newconfig = '\n'.join(newlines) tmpFile.write(newconfig) tmpFile.close() ...
'Return the following boolean flags: newconsole - the plugin should execute in a new console waitmode - Execution should wait for the plugin to finish executing'
def get_runflags(self, mode, interactive, scripted):
if interactive: if (not mode): mode = self.getConsoleMode() else: mode = util.CONSOLE_REUSE if (mode == util.CONSOLE_REUSE): newconsole = False else: newconsole = True waitmode = True if (interactive and (not scripted) and newconsole): waitmode...
'Get the name of the context'
def get_name(self):
return self.name
'Get the type of the context'
def get_type(self):
return self.type
'Set the name of the context'
def set_name(self, name):
self.name = name
'Set the type of the context'
def set_type(self, type):
self.type = type
'Print context info'
def print_info(self):
return
'Set the active plugin'
def set_active_plugin(self, unused):
pass
'Get the name of the active plugin'
def get_active_name(self):
return self.get_name()
'Return a list of all plugins'
def get_plugins(self):
return []
'Resolve a value from one of session, params, or the hard value'
def conv_param(self, val, params, session_data={}):
try: if (val in session_data): return session_data[val] if is_identifier(val): return params[val] except: return None return val
'Prompt for a redirect value and set it in Truantchild'
def prompt_redir(self, plugin, var, msg, default):
done = None while (not done): try: line = self.io.prompt_user(msg, default) plugin.set(var, line) done = plugin.hasValidValue(var) except exception.PromptHelp as err: self.io.print_warning('No help available') except exception.PromptE...
'Effectively just print the straight path to the target'
def straight_local(self, l, plugin):
params = iDict(plugin.getParameters()) laddr = self.conv_param(l.listenaddr, params) lport = self.conv_param(l.listenport, params) if ((not laddr) or (not lport)): return enable_hack = False try: cache = {l.destaddr: plugin.get(l.destaddr), l.destport: plugin.get(l.destport)} ...
'(destaddr, destport) = r-xform(listenaddr, listenport) * Each of the identifiers above specifies a variable for the plug-in (1) Prompt for Listen IP - Likely the ultimate redirector\'s IP (2) Prompt for Listen Port - Likely the ultimate redirector\'s port (3) Prompt for Destination - Likel...
def redirect_remote(self, r, plugin, session_data):
params = iDict(plugin.getParameters()) lport = self.conv_param(r.listenport, params, session_data['params']) dport = self.conv_param(r.destport, params, session_data['params']) laddr = self.conv_param(r.listenaddr, params, session_data['params']) daddr = self.conv_param(r.destaddr, params, session_d...
'targetip = Destination IP (on the target) targetport = Destination Port (on the target) redirip = IP of the LP redirport = Port on the LP'
def redirect_local(self, l, plugin, session_data):
params = iDict(plugin.getParameters()) laddr = self.conv_param(l.listenaddr, params, session_data['params']) lport = self.conv_param(l.listenport, params, session_data['params']) daddr = self.conv_param(l.destaddr, params, session_data['params']) dport = self.conv_param(l.destport, params, session_d...
'Configure whether the plug-in should perform redirection plugin - An instance of a plugin do_redir - Should we do redirection? (True or False)'
def config_redirect(self, plugin, do_redir):
redir = plugin.getRedirection() session_data = {'params': {}, 'remote': [], 'local': []} if do_redir: id = uuid.uuid4() else: id = 0 try: self.io.newline() self.io.print_success('Configure Plugin Local Tunnels') for l in redir['local']: if...
'Get a specific parameter value'
def get(self, name):
return self._trch_get(name)
'Set a parameter to value'
@safesetparameter def set_parameter(self, name, value):
self._trch_set(name, value)
'Set a choice to a value.'
@safesetchoice def set_choice(self, name, value):
self._trch_set(name, value)
'Cache values, Ignore hidden'
def cache_choiceparams(self, name):
paramcache = [] choice = self._trch_findparamchoice(name) if choice: for param in choice.getParameterList(): if (param.name == name): continue paramcache.append(param) paramcache += self.cache_choiceparams(param.name) return paramcache
'Get the description of a parameter'
def getDescription(self, name):
return self._trch_getdescription(name)
'Get the type of a parameter'
def getType(self, name):
return self._trch_gettype(name)
'Get the format of a parameter'
def getFormat(self, name):
return self._trch_getformat(name)
'Get the attribute list of a parameter'
def getAttributeList(self, name):
return self._trch_getattributelist(name)
'Get the parameter struct'
def getParameter(self, name):
return self._trch_findoption(name)
'Given a parameter name, is that parameter hidden?'
def isHiddenParameter(self, name):
param = self.getParameter(name) if self.isParameter(name): return param.isHidden() return False
'Get the current parameter list'
def getParameters(self, hidden=True):
plist = self._trch_getparameterlist() if (not hidden): plist = [x for x in plist if (not self.isHiddenParameter(x.name))] if (not self.param_order): return plist pdict = util.iDict(plist) order = [util.Param(pname, (pdict.pop(pname) or '')) for pname in self.param_order if (pname in ...
'Get the output parameter list'
def getOutputParameters(self):
return self._trch_getoutputparameters()
'Return the defaults parameters'
def getDefaultParameters(self):
return self._defaults
'Check if a parameter of the whole set has a valid value'
def hasValidValue(self, name):
return self._trch_hasvalidvalue(name)
'Check if a parameter or the whole set is invalid'
def isValid(self, name=None):
return self._trch_isvalid(name)
'Get a list of all parameters with invalid values'
def getInvalid(self):
return [(param.name, param.value, self.getDescription(param.name)) for param in self.getParameters() if (not self.isValid(param.name))]
'Execute the plugin'
def execute(self, session, mode):
pass
'Validate the plugin'
def validate(self):
return True
'Extra information about a session'
def getSessionDescription(self):
return ''
'Do required actions to complete EDF Rendezvous'
def doRendezvous(self, value):
return False
'Set a parameter to a value'
@setwrapper def _trch_set(self, name, value):
self._curParams.set(name, value)
'Return the value of a parameter'
@getwrapper def _trch_get(self, name):
return self._curParams.get(name)
'Get the currently active plugin and print various informational items about it: * Name, Version, Type * Redirection information * Parameters established for that context'
def print_info(self, pname=None):
if (pname == None): plugin = self.get_active_plugin() else: plugin = self.get_plugin(pname) self.io.write((EDF_PLUGIN_INFO % (plugin.getName(), plugin.getVersion(), self.get_type()))) self.io.write('Redirection:') self.io.print_redir_info(plugin.getRedirection(), plugin.getParameters...
'Execute the current plugin'
def do_execute(self, input):
session = None self.io.newline() inputList = input.strip().split() if (len(inputList) > 0): consolemode = inputList[0].lower() consolemode = util.convert_consolemode(consolemode) else: consolemode = 0 plugin = self.get_active_plugin() self.io.print_warning(('Preparing...
'Validate the current parameter settings'
def do_validate(self, *ignore):
plugin = self.get_active_plugin() self.io.print_msg(('Checking %s parameters' % plugin.getName())) self.io.newline() if (plugin.validate(self.session.get_dirs(), globalvars=self.fb.fbglobalvars) and self.activePlugin.isValid()): self.io.print_success('Parameters are valid') else:...
'Command completion for apply command.'
def complete_apply(self, text, line, arglist, state, begidx, endidx):
itemList = [str(i) for (i, item) in enumerate(sorted(self.session.get_itemlist()))] if (state == 1): return [i for i in itemList if i.startswith(text)] return ['']
'Apply parameters values from session items'
def do_apply(self, input):
plugin = self.get_active_plugin() params = util.iDict() inputList = input.strip().split() if (not inputList): for contract in self.session.get_contractlist(): for param in contract.get_paramlist(): params.setdefault(param.name, []).append((param, contract)) se...
'Prompt for a parameter, and set the value in the session on response'
def prompt_param(self, name, value, plugin):
valid_convert = {1: 'YES', 0: 'NO'} param = plugin.getParameter(name) attribs = util.iDict(param.getAttributeList()) attribvals = param.getAttributeValueList() args = {'name': name, 'value': value, 'description': attribs['Description'], 'required': attribs['Required'], 'valid': valid_convert[plugin....
'Walk through all parameters prompting for a value for each one'
def do_prompt(self, input):
plugin = self.get_active_plugin() self.io.newline() self.io.print_warning(('Enter Prompt Mode :: %s' % plugin.name)) inputList = input.strip().split() if ((len(inputList) == 1) and (inputList[0].lower() == 'confirm')): self.do_set('') if plugin.isValid(): self...
'Set a configuration parameter'
@util.charconvert def do_set(self, input):
plugin = self.get_active_plugin() inputList = input.strip().split() if (not inputList): args = {'title': plugin.getName(), 'vars': plugin.getParameters(hidden=False)} self.io.print_set_names(args) elif (len(inputList) == 1): param = plugin.getParameter(inputList[0]) try: ...
'Reset a configuration parameter'
def do_reset(self, input):
plugin = self.get_active_plugin() inputList = input.strip().split() if (not inputList): args = {'title': plugin.getName(), 'vars': plugin.getParameters()} self.io.print_set_names(args) elif (len(inputList) == 1): plugin.reset(inputList[0]) self.io.print_success(('Reset ...
'Export a local parameter as a global'
def do_export(self, input):
plugin = self.get_active_plugin() inputList = input.strip().split() if (not inputList): args = {'title': plugin.getName(), 'vars': plugin.getParameters()} self.io.print_set_names(args) elif (len(inputList) == 1): param = plugin.getParameter(inputList[0]) try: ...
'Run a touch plugin'
def do_touch(self, input):
(argc, argv) = util.parseinput(input, 1) if (argc == 0): args = {'touchlist': [(t['displayname'], t['description'], t['name']) for t in self.get_active_plugin().getTouchList()]} self.io.print_touch_info(args) elif (argc == 1): if (argv[0].lower() == 'all'): index = None ...
'Create a rendezvous input parameter'
def do_rendezvous(self, input):
self.get_active_plugin().doRendezvous('0')
'Initialize the Console object. newbuffer=1 will allocate a new buffer so the old content will be restored on exit.'
def __init__(self, newbuffer=0):
self.serial = 0 self.attr = System.Console.ForegroundColor self.saveattr = winattr[str(System.Console.ForegroundColor).lower()] self.savebg = System.Console.BackgroundColor log((u'initial attr=%s' % self.attr))
'Cleanup the console when finished.'
def __del__(self):
pass
'Move or query the window cursor.'
def pos(self, x=None, y=None):
if (x is not None): System.Console.CursorLeft = x else: x = System.Console.CursorLeft if (y is not None): System.Console.CursorTop = y else: y = System.Console.CursorTop return (x, y)
'Move to home.'
def home(self):
self.pos(0, 0)
'write text at current cursor position while watching for scrolling. If the window scrolls because you are at the bottom of the screen buffer, all positions that you are storing will be shifted by the scroll amount. For example, I remember the cursor position of the prompt so that I can redraw the line but if the windo...
def write_scrolling(self, text, attr=None):
(x, y) = self.pos() (w, h) = self.size() scroll = 0 chunks = self.motion_char_re.split(text) for chunk in chunks: n = self.write_color(chunk, attr) if (len(chunk) == 1): if (chunk[0] == u'\n'): x = 0 y += 1 elif (chunk[0] == u'\...
'write text at current cursor position and interpret color escapes. return the number of characters written.'
def write_color(self, text, attr=None):
log((u'write_color("%s", %s)' % (text, attr))) chunks = self.terminal_escape.split(text) log((u'chunks=%s' % repr(chunks))) bg = self.savebg n = 0 if (attr is None): attr = self.attr try: fg = self.trtable[(15 & attr)] bg = self.trtable[((240 & attr) >> 4)] exc...
'write text at current cursor position.'
def write_plain(self, text, attr=None):
log((u'write("%s", %s)' % (text, attr))) if (attr is None): attr = self.attr n = c_int(0) self.SetConsoleTextAttribute(self.hout, attr) self.WriteConsoleA(self.hout, text, len(text), byref(n), None) return len(text)
'Fill the entire screen.'
def page(self, attr=None, fill=u' '):
System.Console.Clear()
'Write text at the given position.'
def text(self, x, y, text, attr=None):
self.pos(x, y) self.write_color(text, attr)
'Fill Rectangle.'
def rectangle(self, rect, attr=None, fill=u' '):
oldtop = self.WindowTop oldpos = self.pos() (x0, y0, x1, y1) = rect if (attr is None): attr = self.attr if fill: rowfill = (fill[:1] * abs((x1 - x0))) else: rowfill = (u' ' * abs((x1 - x0))) for y in range(y0, y1): System.Console.SetCursorPosition(x0, y) ...
'Scroll a rectangle.'
def scroll(self, rect, dx, dy, attr=None, fill=' '):
raise NotImplementedError
'Scroll the window by the indicated number of lines.'
def scroll_window(self, lines):
top = (self.WindowTop + lines) if (top < 0): top = 0 if ((top + System.Console.WindowHeight) > System.Console.BufferHeight): top = System.Console.BufferHeight self.WindowTop = top
'Return next key press event from the queue, ignoring others.'
def getkeypress(self):
ck = System.ConsoleKey while 1: e = System.Console.ReadKey(True) if (e.Key == System.ConsoleKey.PageDown): self.scroll_window(12) elif (e.Key == System.ConsoleKey.PageUp): self.scroll_window((-12)) elif (str(e.KeyChar) == u'\x00'): log((u'Deadk...
'Set/get title.'
def title(self, txt=None):
if txt: System.Console.Title = txt else: return System.Console.Title
'Set/get window size.'
def size(self, width=None, height=None):
sc = System.Console if ((width is not None) and (height is not None)): (sc.BufferWidth, sc.BufferHeight) = (width, height) else: return (sc.BufferWidth, sc.BufferHeight) if ((width is not None) and (height is not None)): (sc.WindowWidth, sc.WindowHeight) = (width, height) els...
'Set cursor on or off.'
def cursor(self, visible=True, size=None):
System.Console.CursorVisible = visible
'Get next event serial number.'
def next_serial(self):
self.serial += 1 return self.serial
'Initialize an event from the Windows input structure.'
def __init__(self, console, input):
self.type = u'??' self.serial = console.next_serial() self.width = 0 self.height = 0 self.x = 0 self.y = 0 self.char = str(input.KeyChar) self.keycode = input.Key self.state = input.Modifiers log((u'%s,%s,%s' % (input.Modifiers, input.Key, input.KeyChar))) self.type = 'KeyRel...
'write text at current cursor position and interpret color escapes. return the number of characters written.'
def write_color(self, text, attr=None):
if isinstance(attr, AnsiState): defaultstate = attr elif (attr is None): attr = self.defaultstate.copy() else: defaultstate = AnsiState() defaultstate.winattr = attr attr = defaultstate chunks = terminal_escape.split(text) n = 0 res = [] for chunk in c...
'Move or query the window cursor.'
def pos(self, x=None, y=None):
raise NotImplementedError