Пример #1
0
def queryuserbygroup(menu=None, attr_want_dict=None, query=None):
    optdict = menu.all_states()
    target = optdict['Configuration']['Target']
    cmd = ops.cmd.getDszCommand((
        'ldap -target %s -scope 2 -filter objectClass=group -attributes distinguishedName'
        % target))
    ldapobj = cmd.execute()
    group_list = []
    count = 1
    for ldapentries in ldapobj.ldapentries:
        for ldapentry in ldapentries.ldapentry:
            group_list.append({
                'index': count,
                'group': ldapentry.attribute[0].value
            })
            count += 1
    pprint(group_list, header=['Index', 'Group'], dictorder=['index', 'group'])
    want_list = getlist(group_list)
    if (want_list == False):
        return False
    item_list = ''
    for item in want_list:
        item_list += ('(memberOf=%s)' % item['group'])
    group_filter = ('(&(objectCategory=Person)(objectClass=User)(|%s))' %
                    item_list)
    attr_want_dict[group_filter] = [
        'cn', 'givenName', 'displayName', 'name', 'whenCreated', 'whenChanged',
        'lastLogon', 'logonCount', 'badPwdCount', 'pwdLastSet',
        'badPasswordTime', 'lastLogonTimestamp', 'accountExpires',
        'logonCount', 'managedObjects', 'memberOf'
    ]
    runldap(filter=group_filter,
            menu=menu,
            attr_want_dict=attr_want_dict,
            query=query)
Пример #2
0
def checkshutdownlogfiles():
    logfilespath = os.path.join(getenvvar('systemroot'),
                                'system32\\logfiles\\shutdown')
    dircmd = ops.cmd.getDszCommand('dir', mask='*.xml', path=logfilespath)
    dirobject = dircmd.execute()
    file_list = []
    try:
        for file in dirobject.diritem[0].fileitem:
            if ((file.name is not None)
                    and (file.name.lower() not in ['.', '..'])):
                file_list.append({
                    'name': file.name,
                    'accessed': file.filetimes.accessed.time,
                    'created': file.filetimes.created.time,
                    'modified': file.filetimes.modified.time
                })
        file_list.sort(key=(lambda x: x['created']))
        pprint(file_list, ['Dump', 'Modified', 'Accessed', 'Created'],
               ['name', 'modified', 'accessed', 'created'])
        print '\n'
    except:
        dsz.ui.Echo(
            'No logfile xmls found, or there was a problem with the dirs.')
        print '\n'
        return 0
Пример #3
0
def main(args):
    (opts, args) = parse_args(args)
    if (not args):
        return
    column_header = header_from_id(args[0])
    all_rows = data_from_id(args[0])
    print ''
    if (not all_rows):
        dsz.ui.Echo('No valid SQL query data found.', dsz.ERROR)
        return
    dsz.ui.Echo(('Found %s columns...' % len(column_header)), dsz.GOOD)
    if (opts.print_data is None):
        print ''
        opts.print_data = dsz.ui.Prompt('Would you like see the results?', False)
    if opts.print_data:
        print ''
        all_rows = list(all_rows)
        pprint(all_rows, column_header)
    if (opts.write_csv is None):
        print ''
        opts.write_csv = dsz.ui.Prompt('Would you like to write to a CSV file?', False)
    if opts.write_csv:
        output_file = os.path.join(opts.output_dir, ('%s.csv' % format_id(args[0])))
        write(all_rows, column_header, output_file)
    return (all_rows, column_header)
Пример #4
0
def main():
    alltargetsallprojects = ops.project.getAllTargets()
    targetsup = []
    cmd = ops.cmd.getDszCommand('arp')
    cmd.optdict = {'query': True}
    arp = cmd.execute()
    if cmd.success:
        for arptgt in arp.entry:
            for tgt in alltargetsallprojects:
                if (arptgt.mac.lower() in tgt.macs):
                    targetsup.append({
                        'proj': tgt.project.name,
                        'target': tgt.hostname,
                        'id': tgt.implant_id,
                        'ip': arptgt.ip,
                        'mac': arptgt.mac,
                        'interface': arptgt.adapter
                    })
        if (len(targetsup) > 0):
            dsz.ui.Echo('Targets that are up', dsz.GOOD)
            pprint(
                targetsup,
                header=[
                    'Project', 'Target', 'Target ID', 'IP', 'MAC', 'Interface'
                ],
                dictorder=['proj', 'target', 'id', 'ip', 'mac', 'interface'])
        else:
            dsz.ui.Echo("Doesn't look like anything is up", dsz.WARNING)
    else:
        dsz.ui.Echo(('arp -query failed. check command id %d ' % arp._cmdid),
                    dsz.ERROR)
Пример #5
0
def main(args):
    (opts, args) = parse_args(args)
    if (not args):
        return
    column_header = header_from_id(args[0])
    all_rows = data_from_id(args[0])
    print ''
    if (not all_rows):
        dsz.ui.Echo('No valid SQL query data found.', dsz.ERROR)
        return
    dsz.ui.Echo(('Found %s columns...' % len(column_header)), dsz.GOOD)
    if (opts.print_data is None):
        print ''
        opts.print_data = dsz.ui.Prompt('Would you like see the results?',
                                        False)
    if opts.print_data:
        print ''
        all_rows = list(all_rows)
        pprint(all_rows, column_header)
    if (opts.write_csv is None):
        print ''
        opts.write_csv = dsz.ui.Prompt(
            'Would you like to write to a CSV file?', False)
    if opts.write_csv:
        output_file = os.path.join(opts.output_dir,
                                   ('%s.csv' % format_id(args[0])))
        write(all_rows, column_header, output_file)
    return (all_rows, column_header)
Пример #6
0
def main():
    has_al = False
    logon_key = 'SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Winlogon'
    reg_vals = registry_getdict(logon_key, 'l')
    auto_logon = reg_vals['AutoAdminLogon']
    default_domain = reg_vals['DefaultDomainName']
    default_username = reg_vals['DefaultUserName']
    default_password = reg_vals['DefaultPassword']
    alt_domain = reg_vals['AltDefaultDomainName']
    alt_username = reg_vals['AltDefaultUserName']
    alt_password = reg_vals['AltDefaultPassword']
    creds = []
    if ((default_password == '') and (auto_logon == '1')):
        has_al = True
        default_password = '******'
    creds.append(['Default', default_domain, default_username, default_password])
    if ((alt_password == '') and (auto_logon == '1')):
        has_al = True
        alt_password = '******'
    creds.append(['Alternate', alt_domain, alt_username, alt_password])
    if (not has_al):
        print ''
        dsz.ui.Echo('The host is not configured to have an AutoLogon password.', dsz.ERROR)
        print ''
    pprint(creds, header=['Type', 'Domain', 'Username', 'Password'])
Пример #7
0
def main():
    process_list = []
    if (len(sys.argv) > 1):
        pattern = (('.*' + sys.argv[1]) + '.*')
    else:
        pattern = '.*'
    print (('\nFiltering processes with regex:: ' + pattern) + '\n')
    regex = re.compile(pattern, (re.I | re.UNICODE))
    dsz.control.echo.Off()
    cmd = ops.cmd.getDszCommand('processes -list')
    proc_items = cmd.execute()
    if cmd.success:
        for proc_item in proc_items.initialprocesslistitem.processitem:
            pid = str(proc_item.id)
            ppid = str(proc_item.parentid)
            name = str(proc_item.name.encode('utf-8'))
            path = str(proc_item.path.encode('utf-8'))
            user = str(proc_item.user.encode('utf-8'))
            c_time = str(proc_item.created.time)
            c_date = str(proc_item.created.date)
            process = [pid, ppid, path, name, user, c_date, c_time]
            if regex:
                tmp_str = ' '.join(process)
                if re.search(regex, tmp_str):
                    process_list.append(process)
    if (process_list > 1):
        pprint(process_list, header=['PID', 'PPID', 'Path', 'Name', 'User', 'CDate', 'CTime'])
    dsz.control.echo.On()
Пример #8
0
def checksettings(psp):
    try:
        psp[comattribs.installdate] = ('%s' % datetime.datetime.fromtimestamp(
            float(psp[comattribs.installdate])))
    except TypeError:
        mcafeelog.error('Could not get install date: conversion error',
                        exc_info=True)
        mcafeelog.debug('tstamp data: {0}'.format(psp[comattribs.installdate]))
    header = ['Setting', 'State', 'Notes']
    data = []
    echocodes = []

    def addDataLine(setting, compval, rowstr, notetrue, notefalse, echotrue,
                    echofalse):
        data.append([
            rowstr,
            OnOff(setting), (notetrue if (setting == compval) else notefalse)
        ])
        echocodes.append((echotrue if (setting == compval) else echofalse))

    def OnOff(data):
        return ('ON' if (data == '1') else 'OFF')

    try:
        addDataLine(psp.GTIEnabled, '1', 'Cloud Services (GTI)',
                    '!!! PE checksums will be sent to McAfee !!!', '',
                    dsz.ERROR, dsz.GOOD)
        addDataLine(psp.BOPEnabled, '1', 'Buffer Overflow Prot',
                    '(Informational Only)', '', dsz.WARNING, dsz.GOOD)
        addDataLine(psp.HeuristicsEnabled, '1', 'Heuristic Scanning',
                    '(Informational Only)', '', dsz.WARNING, dsz.GOOD)
    except:
        pass
    pprint(data, header, echocodes=echocodes)
Пример #9
0
def checkdrwatson():
    allusersprofile = getenvvar('allusersprofile')
    if (allusersprofile is None):
        dsz.ui.Echo(
            "Could not find the 'ALLUSERSPROFILE' environment variable.")
        print '\n'
        return 0
    log_path = ('"%s"' % os.path.join(allusersprofile, 'documents\\drwatson'))
    dircmd = ops.cmd.getDszCommand('dir', mask='*.log', path=log_path)
    dirobject = dircmd.execute()
    file_list = []
    try:
        for file in dirobject.diritem[0].fileitem:
            if ((file.name is not None)
                    and (file.name.lower() not in ['.', '..'])):
                file_list.append({
                    'name': file.name,
                    'accessed': file.filetimes.accessed.time,
                    'created': file.filetimes.created.time,
                    'modified': file.filetimes.modified.time
                })
        pprint(file_list, ['DrWatson Log', 'Modified', 'Accessed', 'Created'],
               ['name', 'accessed', 'created', 'modified'])
        print '\n'
    except:
        dsz.ui.Echo(
            'No Dr. Watson logs found, or there was a problem with the dirs.')
        print '\n'
        return 0
Пример #10
0
def arpquery(vista):
    arpcmd = ops.cmd.getDszCommand('arp', query=True)
    arpobject = arpcmd.execute()
    arp_list = []
    color_list = []
    for entry in arpobject.entry:
        oui = ''
        if (not ((entry.mac == '') or (entry.mac is None) or ((entry.mac == '00-00-00-00-00-00') or (entry.mac == '00-00-00-00-00-00-00-00-00-00-00-00-00-00')))):
            oui = util.mac.getoui(entry.mac)
            if ((oui is None) or (oui == '')):
                oui = '<unknown oui>'
        else:
            oui = '<blank mac or error>'
        if vista:
            arp_list.append({'adapter': entry.adapter, 'ip': entry.ip, 'iptype': entry.iptype, 'mac': entry.mac, 'isrouter': entry.isrouter, 'isunreachable': entry.isunreachable, 'oui': oui, 'state': entry.state})
        else:
            arp_list.append({'adapter': entry.adapter, 'type': entry.type, 'ip': entry.ip, 'mac': entry.mac, 'isrouter': entry.isrouter, 'isunreachable': entry.isunreachable, 'oui': oui})
        if (oui == '<unknown oui>'):
            color_list.append(dsz.WARNING)
        elif (oui == '<blank mac or error>'):
            color_list.append(dsz.ERROR)
        else:
            color_list.append(dsz.DEFAULT)
    if vista:
        header = ['IP', 'MAC', 'OUI', 'State', 'IPType', 'Adapter', 'IsRouter', 'IsUnreachable']
    else:
        header = ['IP', 'MAC', 'OUI', 'Type', 'Adapter', 'IsRouter', 'IsUnreachable']
    dictorder = [column.lower() for column in header]
    pprint(arp_list, header=header, dictorder=dictorder, echocodes=color_list)
    return 1
Пример #11
0
def main():
    has_al = False
    logon_key = 'SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Winlogon'
    reg_vals = registry_getdict(logon_key, 'l')
    auto_logon = reg_vals['AutoAdminLogon']
    default_domain = reg_vals['DefaultDomainName']
    default_username = reg_vals['DefaultUserName']
    default_password = reg_vals['DefaultPassword']
    alt_domain = reg_vals['AltDefaultDomainName']
    alt_username = reg_vals['AltDefaultUserName']
    alt_password = reg_vals['AltDefaultPassword']
    creds = []
    if ((default_password == '') and (auto_logon == '1')):
        has_al = True
        default_password = '******'
    creds.append(['Default', default_domain, default_username, default_password])
    if ((alt_password == '') and (auto_logon == '1')):
        has_al = True
        alt_password = '******'
    creds.append(['Alternate', alt_domain, alt_username, alt_password])
    if (not has_al):
        print ''
        dsz.ui.Echo('The host is not configured to have an AutoLogon password.', dsz.ERROR)
        print ''
    pprint(creds, header=['Type', 'Domain', 'Username', 'Password'])
Пример #12
0
def arpquery(vista):
    arpcmd = ops.cmd.getDszCommand('arp', query=True)
    arpobject = arpcmd.execute()
    arp_list = []
    color_list = []
    for entry in arpobject.entry:
        oui = ''
        if (not ((entry.mac == '') or (entry.mac is None) or ((entry.mac == '00-00-00-00-00-00') or (entry.mac == '00-00-00-00-00-00-00-00-00-00-00-00-00-00')))):
            oui = util.mac.getoui(entry.mac)
            if ((oui is None) or (oui == '')):
                oui = '<unknown oui>'
        else:
            oui = '<blank mac or error>'
        if vista:
            arp_list.append({'adapter': entry.adapter, 'ip': entry.ip, 'iptype': entry.iptype, 'mac': entry.mac, 'isrouter': entry.isrouter, 'isunreachable': entry.isunreachable, 'oui': oui, 'state': entry.state})
        else:
            arp_list.append({'adapter': entry.adapter, 'type': entry.type, 'ip': entry.ip, 'mac': entry.mac, 'isrouter': entry.isrouter, 'isunreachable': entry.isunreachable, 'oui': oui})
        if (oui == '<unknown oui>'):
            color_list.append(dsz.WARNING)
        elif (oui == '<blank mac or error>'):
            color_list.append(dsz.ERROR)
        else:
            color_list.append(dsz.DEFAULT)
    if vista:
        header = ['IP', 'MAC', 'OUI', 'State', 'IPType', 'Adapter', 'IsRouter', 'IsUnreachable']
    else:
        header = ['IP', 'MAC', 'OUI', 'Type', 'Adapter', 'IsRouter', 'IsUnreachable']
    dictorder = [column.lower() for column in header]
    pprint(arp_list, header=header, dictorder=dictorder, echocodes=color_list)
    return 1
Пример #13
0
def main(args):
    if (len(args) > 1):
        dsz.ui.Echo('Pulls all INFO2 files on the system, parses them for a list of deleted files, and allows you to download chosen files.')
        return 0
    entry_list = []
    dsz.ui.Echo('Obtaining a list of drives', dsz.GOOD)
    drive_list = getdrives()
    if dsz.version.checks.windows.IsVistaOrGreater():
        dsz.ui.Echo('Diring a list of $I* files', dsz.GOOD)
        vistaI_list = getvistaIlist(drive_list)
        dsz.ui.Echo('Diring for a list of trash files', dsz.GOOD)
        (trash_list, trash_dirs) = gettrashlist(vistaI_list)
        dsz.ui.Echo('Getting all $I* files', dsz.GOOD)
        vistaI_files = getvistaIfiles(vistaI_list)
        for file in vistaI_files:
            entry_list = parsevistafile(file['file'], entry_list, file['vistaI'], trash_list, trash_dirs)
    else:
        dsz.ui.Echo('Diring a list of INFO2 files', dsz.GOOD)
        info2_list = getinfo2list(drive_list)
        dsz.ui.Echo('Diring for a list of trash files', dsz.GOOD)
        (trash_list, trash_dirs) = gettrashlist(info2_list)
        dsz.ui.Echo('Getting all INFO2 files', dsz.GOOD)
        info2_files = getinfo2files(info2_list)
        for file in info2_files:
            entry_list = parsefile(file['file'], entry_list, file['info2'], trash_list, trash_dirs)
    if (not entry_list):
        return True
    if dsz.version.checks.windows.IsVistaOrGreater():
        pprint(entry_list, ['Index', 'OriginalFile', 'TrashName', 'Size', 'DateDeleted', 'UnicodeFilename'], ['index', 'originalfile', 'filename', 'size', 'timestamp', 'unicode_filename'])
    else:
        pprint(entry_list, ['Index', 'OriginalFile', 'TrashName', 'Size', 'DateDeleted', 'UnicodeFilename'], ['index', 'originalfile', 'filename', 'size', 'timestamp', 'unicode_filename'])
    get_list = getlist(entry_list)
    getfiles(get_list)
    return True
Пример #14
0
def getwerinfo(wer_list):
    key_list = []
    for item in wer_list:
        hive = item['hive']
        key = item['key']
        regcmd = ops.cmd.getDszCommand('registryquery', hive=hive, key=key)
        regobject = regcmd.execute()
        for key in regobject.key:
            hive = key.hive
            name = key.name
            for value in key.value:
                key_list.append({
                    'name': ('%s\\%s\\%s' % (hive, name, value.name)),
                    'value':
                    value.value
                })
    try:
        key_list.sort(key=(lambda x: x['name']))
        pprint(key_list, ['Windows Error Reporting key', 'Value'],
               ['name', 'value'])
        print '\n'
        showreportqueue()
    except:
        dsz.ui.Echo('Could not find any Windows Error Reporting information.')
        print '\n'
Пример #15
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'])
Пример #16
0
def wifi_networks():
    dsz.ui.Echo(
        '============================WIFI Networks====================================',
        dsz.GOOD)
    home = list()
    home_network = ops.system.registry.get_registrykey(
        'L',
        'SOFTWARE\\Microsoft\\Windows\\currentversion\\HomeGroup\\NetworkLocations\Home'
    )
    for key in home_network.key[0].value:
        profile = 'SOFTWARE\\Microsoft\\Windows NT\\currentversion\\NetworkList\\Profiles\\' + key.name
        details = ops.system.registry.get_registrykey('L', profile)
        for detail in details.key[0].value:
            home.append({'name': detail.name, 'value': detail.value})
    pprint(home, dictorder=['name', 'value'])

    work_network = ops.system.registry.get_registrykey(
        'L',
        'SOFTWARE\\Microsoft\\Windows\\currentversion\\HomeGroup\\NetworkLocations\work'
    )
    for key in work_network.key[0].value:
        profile = 'SOFTWARE\\Microsoft\\Windows NT\\currentversion\\NetworkList\\Profiles\\' + key.name
        details = ops.system.registry.get_registrykey('L', profile)
        for detail in details.key[0].value:
            work.append({'name': detail.name, 'value': detail.value})

    pprint(work, dictorder=['name', 'value'])
Пример #17
0
def checkdumps(dirtocheck):
    if dirtocheck.startswith('%%SystemRoot%%'):
        systemroot = getenvvar('systemroot')
        if (systemroot is None):
            return 0
        dirtocheck = dirtocheck.replace('%%SystemRoot%%', ('%s' % systemroot))
    dirobject = None
    dircmd = ops.cmd.getDszCommand('dir')
    if dirtocheck.endswith('.DMP'):
        dircmd.mask = os.path.basename(dirtocheck)
        dircmd.path = os.path.dirname(dirtocheck)
    else:
        dircmd.mask = '*'
        dircmd.path = dirtocheck
    dirobject = dircmd.execute()
    file_list = []
    try:
        for file in dirobject.diritem[0].fileitem:
            if ((file.name is not None)
                    and (file.name.lower() not in ['.', '..'])):
                file_list.append({
                    'name': file.name,
                    'accessed': file.filetimes.accessed.time,
                    'created': file.filetimes.created.time,
                    'modified': file.filetimes.modified.time
                })
        file_list.sort(key=(lambda x: x['created']))
        pprint(file_list, ['Dump', 'Modified', 'Accessed', 'Created'],
               ['name', 'modified', 'accessed', 'created'])
        print '\n'
    except:
        print 'No dump found, or there was a problem with the dirs.'
        print '\n'
        return 0
Пример #18
0
 def printresults(self,
                  name,
                  dict,
                  titles,
                  keys,
                  sort1,
                  sort2=None,
                  quiet=False):
     bannerstring = ('========== %s Results ==============' % name)
     bannerhead = (len(bannerstring) * '=')
     if (not quiet):
         dsz.ui.Echo(bannerhead, dsz.GOOD)
         dsz.ui.Echo(bannerstring, dsz.GOOD)
         dsz.ui.Echo(bannerhead, dsz.GOOD)
     if (len(dict) > 0):
         dict.sort(key=(lambda x: x[sort1]))
         if (not (sort2 == None)):
             dict.sort(key=(lambda x: x[sort2]))
         if (not quiet):
             pprint(dict, titles, keys)
         pprint(dict, titles, keys, print_handler=self.pprintout)
     else:
         with open(self.scansweep_results, 'a') as f:
             f.write(('No %s data was returned\n' % name))
         if (not quiet):
             dsz.ui.Echo(('No %s data was returned' % name), dsz.WARNING)
     with open(self.scansweep_results, 'a') as f:
         f.write('\n\n')
     if (not quiet):
         print '\n\n'
Пример #19
0
 def postGet(self):
     import shutil
     import sys
     import os, os.path
     import dsz.lp
     import ops.env
     from ops.pprint import pprint
     windowsScripts = (dsz.lp.GetResourcesDirectory() + 'Ops\\PyScripts\\windows')
     sys.path.append(windowsScripts)
     from firefox_decrypt import read_passwords_from_profile
     NOSEND = os.path.join(ops.env.get('_LOGPATH'), 'GetFiles', 'NOSEND')
     profiles = []
     if (not os.path.exists(NOSEND)):
         os.makedirs(NOSEND)
     for f in self.listCollectedFiles():
         remoteFullFile = f[0]
         localFullFile = f[1]
         remotePath = str(os.path.split(remoteFullFile)[0])
         remoteFile = str(os.path.split(remoteFullFile)[1])
         localPath = str(os.path.split(localFullFile)[0])
         localFile = str(os.path.split(localFullFile)[1])
         profile = os.path.split(remotePath)[1]
         localProfileDir = os.path.join(NOSEND, profile)
         if (localProfileDir not in profiles):
             profiles.append(str(localProfileDir))
         if (not os.path.exists(localProfileDir)):
             os.makedirs(localProfileDir)
         destFile = os.path.join(localProfileDir, remoteFile)
         shutil.copy(localFullFile, destFile)
     for profile in profiles:
         passwords = read_passwords_from_profile(profile)
         if passwords:
             pprint(passwords, ['Site', 'Username', 'Password'], ['site', 'user', 'pass'])
         else:
             print ('No passwords found in %s' % profile)
Пример #20
0
def main(ARGS):
    dsz.control.echo.Off()
    (succ, cmdid) = dsz.cmd.RunEx(('registryquery %s' % ARGS),
                                  dsz.RUN_FLAG_RECORD)
    dsz.control.echo.On()
    object = ops.data.getDszObject(cmdid=cmdid)
    reglist = []
    for key in object.key:
        thisdate = time.strptime(('%s %s' % (key.updatedate, key.updatetime)),
                                 '%Y-%m-%d %H:%M:%S')
        if ((thisdate < BEFORE) and (thisdate > AFTER)):
            reglist.append({
                'name': key.name,
                'updatedate': key.updatedate,
                'updatetime': key.updatetime
            })
        for subkey in key.subkey:
            name = ('%s\\%s' % (key.name, subkey.name))
            thisdate = time.strptime(
                ('%s %s' % (subkey.updatedate, subkey.updatetime)),
                '%Y-%m-%d %H:%M:%S')
            if ((thisdate < BEFORE) and (thisdate > AFTER)):
                reglist.append({
                    'name': name,
                    'updatedate': subkey.updatedate,
                    'updatetime': subkey.updatetime
                })
    reglist.sort(key=(lambda x: x['updatetime']))
    reglist.sort(key=(lambda x: x['updatedate']))
    pprint(reglist, ['key', 'updatedate', 'updatetime'],
           ['name', 'updatedate', 'updatetime'])
    return True
Пример #21
0
def listener_log_check():
    print ''
    dsz.ui.Echo('Checking for listener.log files...', dsz.GOOD)
    print ''
    dsz.control.echo.Off()
    if (not dsz.cmd.Prompt('dir -path * -mask listener.log -recursive -max 0', dsz.RUN_FLAG_RECORD)):
        dsz.control.echo.On()
        return
    dsz.control.echo.On()
    dir_items = dsz.cmd.data.Get('diritem', dsz.TYPE_OBJECT)
    items = []
    for item in dir_items:
        denied = dsz.cmd.data.ObjectGet(item, 'denied', dsz.TYPE_STRING)[0]
        if (denied == 'true'):
            continue
        path = dsz.cmd.data.ObjectGet(item, 'path', dsz.TYPE_STRING)[0]
        size = dsz.cmd.data.ObjectGet(item, 'fileitem::size', dsz.TYPE_INT)[0]
        modified_loc = 'fileitem::filetimes::modified::time'
        modified = dsz.cmd.data.ObjectGet(item, modified_loc, dsz.TYPE_STRING)[0]
        items.append({'path': (path + '\\listener.log'), 'size': size, 'modified': modified})
    if items:
        print ''
        pprint(items, ['Path', 'Size', 'Modified'], ['path', 'size', 'modified'])
        print ''
        dsz.ui.Echo(('I found %s listener.log file(s)' % len(items)), dsz.GOOD)
        for item in items:
            print ''
            if dsz.ui.Prompt(('Would you like to pull back the last 5 MB of %s?' % item['path'])):
                dsz.cmd.Run(('get "%s" -tail 5242880' % item['path']))
        print ''
        dsz.ui.Pause("Review the listener.log files you pulled. Make sure you understand how you'll log!")
    else:
        dsz.ui.Echo("I couldn't find any listener.log files... if you're not on the target database itself, you need to go there and clean it!", dsz.WARNING)
Пример #22
0
def main():
    process_list = []
    if (len(sys.argv) > 1):
        pattern = (('.*' + sys.argv[1]) + '.*')
    else:
        pattern = '.*'
    print(('\nFiltering processes with regex:: ' + pattern) + '\n')
    regex = re.compile(pattern, (re.I | re.UNICODE))
    dsz.control.echo.Off()
    cmd = ops.cmd.getDszCommand('processes -list')
    proc_items = cmd.execute()
    if cmd.success:
        for proc_item in proc_items.initialprocesslistitem.processitem:
            pid = str(proc_item.id)
            ppid = str(proc_item.parentid)
            name = str(proc_item.name.encode('utf-8'))
            path = str(proc_item.path.encode('utf-8'))
            user = str(proc_item.user.encode('utf-8'))
            c_time = str(proc_item.created.time)
            c_date = str(proc_item.created.date)
            process = [pid, ppid, path, name, user, c_date, c_time]
            if regex:
                tmp_str = ' '.join(process)
                if re.search(regex, tmp_str):
                    process_list.append(process)
    if (process_list > 1):
        pprint(
            process_list,
            header=['PID', 'PPID', 'Path', 'Name', 'User', 'CDate', 'CTime'])
    dsz.control.echo.On()
Пример #23
0
def database_main(db_class, options):
    db_module = db_class()
    if (not db_module):
        return
    print ''
    dsz.ui.Echo('Loading SCOFFRETAIL and retrieving handle list...\n',
                dsz.GOOD)
    handle_list = sql_utils.handle_list()
    if handle_list:
        pprint(handle_list, ['Handle ID', 'Connection String'])
    else:
        dsz.ui.Echo('No existing connections found.', dsz.GOOD)
    if options.run_audit_check:
        print ''
        dsz.ui.Echo(('Running audit checks for %s...' % db_module.NAME),
                    dsz.GOOD)
        db_module.audit_check()
    handle = connection_string_menu(db_module)
    if (not handle):
        db_module.cleanup(None)
        return
    try:
        query_menu(db_module, handle)
    except Exception as details:
        dsz.ui.Echo('Caught an exception querying:', dsz.ERROR)
        print ''
        print details
        print ''
        dsz.ui.Echo('Cleaning up and starting over.', dsz.ERROR)
    print ''
    dsz.ui.Echo('Done with this database, cleaning up...', dsz.GOOD)
    print ''
    db_module.cleanup(handle)
Пример #24
0
def main():
    parser = OptionParser()
    parser.add_option(
        '--start-monitor',
        dest='startmonitor',
        action='store_true',
        default=False,
        help='Start the process monitor in addition to getting a process list.'
    )
    parser.add_option('--full-list',
                      dest='fulllist',
                      action='store_true',
                      default=False,
                      help='Do a full process list (no -minimal).')
    (options, args) = parser.parse_args()
    proc_cmd = ops.cmd.getDszCommand('processes -list')
    (result, messages) = proc_cmd.safetyCheck()
    minimal_flag = (not result)
    if options.fulllist:
        ops.survey.print_header('Process list')
        cachelist = ops.processes.processlist.get_processlist(
            minimal=minimal_flag, maxage=datetime.timedelta.max)
        curlist = ops.processes.processlist.get_processlist(
            minimal=minimal_flag, maxage=datetime.timedelta(seconds=30))
        ops.survey.print_agestring(curlist[0].dszobjage)
        try:
            if (cachelist.cache_timestamp != curlist.cache_timestamp):
                do_diff = True
        except:
            pass
        proctree = ops.processes.processlist.build_process_tree(curlist)
        displays = treecurse(proctree, 0)
        if (len(displays) != len(curlist)):
            ops.warn(
                'The below tree is not a tree!  There must be a loop in the process tree!  Falling back to non-tree display'
            )
            displays = map((lambda x: prettyproc(x, 0)), curlist)
        codes = list()
        for displayproc in displays:
            proc = displayproc['procobj']
            code = dsz.DEFAULT
            if (proc.proctype == 'MALICIOUS_SOFTWARE'):
                code = dsz.ERROR
            elif (proc.proctype == 'SECURITY_PRODUCT'):
                code = dsz.WARNING
            elif (proc.proctype == 'SAFE'):
                code = dsz.GOOD
            elif (proc.friendlyname == ''):
                code = dsz.WARNING
            codes.append(code)
        fullpathheader = 'Full Path'
        if minimal_flag:
            fullpathheader = 'Image Name'
        pprint(
            displays,
            header=['PID', 'PPID', fullpathheader, 'User', 'Comment'],
            dictorder=['id', 'parentid', 'fullpath', 'user', 'friendlyname'],
            echocodes=codes)
    if options.startmonitor:
        ops.processes.processlist.start_monitor()
Пример #25
0
def _survey(pspobj=None, target=None):
    dsz.ui.Echo('Pulling HKLM\\Software\\Network Associates key...')
    if (target == None):
        if dsz.version.checks.windows.IsXpOrGreater():
            q = ops.cmd.DszCommand('registryquery', hive='L', key='"software\\network associates"', recursive=True, dszquiet=True, wow32=True)
        else:
            q = ops.cmd.DszCommand('registryquery', hive='L', key='"software\\network associates"', recursive=True, dszquiet=True)
    else:
        q = ops.cmd.DszCommand('registryquery', hive='L', key='"software\\network associates"', recursive=True, dszquiet=True, target=target, wow32=True)
    netassoc = q.execute()
    dsz.ui.Echo('Pulling HKLM\\Software\\McAfee key...')
    if (target == None):
        if dsz.version.checks.windows.IsXpOrGreater():
            q = ops.cmd.DszCommand('registryquery', hive='L', key='"software\\mcafee"', recursive=True, dszquiet=True, wow32=True)
        else:
            q = ops.cmd.DszCommand('registryquery', hive='L', key='"software\\mcafee"', recursive=True, dszquiet=True)
    else:
        q = ops.cmd.DszCommand('registryquery', hive='L', key='"software\\mcafee"', recursive=True, dszquiet=True, target=target, wow32=True)
    mcafee = q.execute()
    dsz.ui.Echo('Parsing registry information for installed products\n')
    products = checkInstalled(mcafee, netassoc)
    if (products == False):
        return
    pprint(products)
    dsz.ui.Echo('Parsing settings\n')
    checkInstalledSettings(mcafee, products)
    return
Пример #26
0
def _survey(pspobj=None, target=None):
    dsz.ui.Echo('Pulling HKLM\\Software\\Network Associates key...')
    if (target == None):
        if dsz.version.checks.windows.IsXpOrGreater():
            q = ops.cmd.DszCommand('registryquery', hive='L', key='"software\\network associates"', recursive=True, dszquiet=True, wow32=True)
        else:
            q = ops.cmd.DszCommand('registryquery', hive='L', key='"software\\network associates"', recursive=True, dszquiet=True)
    else:
        q = ops.cmd.DszCommand('registryquery', hive='L', key='"software\\network associates"', recursive=True, dszquiet=True, target=target, wow32=True)
    netassoc = q.execute()
    dsz.ui.Echo('Pulling HKLM\\Software\\McAfee key...')
    if (target == None):
        if dsz.version.checks.windows.IsXpOrGreater():
            q = ops.cmd.DszCommand('registryquery', hive='L', key='"software\\mcafee"', recursive=True, dszquiet=True, wow32=True)
        else:
            q = ops.cmd.DszCommand('registryquery', hive='L', key='"software\\mcafee"', recursive=True, dszquiet=True)
    else:
        q = ops.cmd.DszCommand('registryquery', hive='L', key='"software\\mcafee"', recursive=True, dszquiet=True, target=target, wow32=True)
    mcafee = q.execute()
    dsz.ui.Echo('Parsing registry information for installed products\n')
    products = checkInstalled(mcafee, netassoc)
    if (products == False):
        return
    pprint(products)
    dsz.ui.Echo('Parsing settings\n')
    checkInstalledSettings(mcafee, products)
    return
Пример #27
0
def database_main(db_class, options):
    db_module = db_class()
    if (not db_module):
        return
    print ''
    dsz.ui.Echo('Loading SCOFFRETAIL and retrieving handle list...\n', dsz.GOOD)
    handle_list = sql_utils.handle_list()
    if handle_list:
        pprint(handle_list, ['Handle ID', 'Connection String'])
    else:
        dsz.ui.Echo('No existing connections found.', dsz.GOOD)
    if options.run_audit_check:
        print ''
        dsz.ui.Echo(('Running audit checks for %s...' % db_module.NAME), dsz.GOOD)
        db_module.audit_check()
    handle = connection_string_menu(db_module)
    if (not handle):
        db_module.cleanup(None)
        return
    try:
        query_menu(db_module, handle)
    except Exception as details:
        dsz.ui.Echo('Caught an exception querying:', dsz.ERROR)
        print ''
        print details
        print ''
        dsz.ui.Echo('Cleaning up and starting over.', dsz.ERROR)
    print ''
    dsz.ui.Echo('Done with this database, cleaning up...', dsz.GOOD)
    print ''
    db_module.cleanup(handle)
Пример #28
0
 def postGet(self):
     import shutil
     import sys
     import os, os.path
     import dsz.lp
     import ops.env
     from ops.pprint import pprint
     windowsScripts = (dsz.lp.GetResourcesDirectory() + 'Ops\\PyScripts\\windows')
     sys.path.append(windowsScripts)
     from firefox_decrypt import read_passwords_from_profile
     NOSEND = os.path.join(ops.env.get('_LOGPATH'), 'GetFiles', 'NOSEND')
     profiles = []
     if (not os.path.exists(NOSEND)):
         os.makedirs(NOSEND)
     for f in self.listCollectedFiles():
         remoteFullFile = f[0]
         localFullFile = f[1]
         remotePath = str(os.path.split(remoteFullFile)[0])
         remoteFile = str(os.path.split(remoteFullFile)[1])
         localPath = str(os.path.split(localFullFile)[0])
         localFile = str(os.path.split(localFullFile)[1])
         profile = os.path.split(remotePath)[1]
         localProfileDir = os.path.join(NOSEND, profile)
         if (localProfileDir not in profiles):
             profiles.append(str(localProfileDir))
         if (not os.path.exists(localProfileDir)):
             os.makedirs(localProfileDir)
         destFile = os.path.join(localProfileDir, remoteFile)
         shutil.copy(localFullFile, destFile)
     for profile in profiles:
         passwords = read_passwords_from_profile(profile)
         if passwords:
             pprint(passwords, ['Site', 'Username', 'Password'], ['site', 'user', 'pass'])
         else:
             print ('No passwords found in %s' % profile)
Пример #29
0
def listener_log_check():
    print ''
    dsz.ui.Echo('Checking for listener.log files...', dsz.GOOD)
    print ''
    dsz.control.echo.Off()
    if (not dsz.cmd.Prompt('dir -path * -mask listener.log -recursive -max 0', dsz.RUN_FLAG_RECORD)):
        dsz.control.echo.On()
        return
    dsz.control.echo.On()
    dir_items = dsz.cmd.data.Get('diritem', dsz.TYPE_OBJECT)
    items = []
    for item in dir_items:
        denied = dsz.cmd.data.ObjectGet(item, 'denied', dsz.TYPE_STRING)[0]
        if (denied == 'true'):
            continue
        path = dsz.cmd.data.ObjectGet(item, 'path', dsz.TYPE_STRING)[0]
        size = dsz.cmd.data.ObjectGet(item, 'fileitem::size', dsz.TYPE_INT)[0]
        modified_loc = 'fileitem::filetimes::modified::time'
        modified = dsz.cmd.data.ObjectGet(item, modified_loc, dsz.TYPE_STRING)[0]
        items.append({'path': (path + '\\listener.log'), 'size': size, 'modified': modified})
    if items:
        print ''
        pprint(items, ['Path', 'Size', 'Modified'], ['path', 'size', 'modified'])
        print ''
        dsz.ui.Echo(('I found %s listener.log file(s)' % len(items)), dsz.GOOD)
        for item in items:
            print ''
            if dsz.ui.Prompt(('Would you like to pull back the last 5 MB of %s?' % item['path'])):
                dsz.cmd.Run(('get "%s" -tail 5242880' % item['path']))
        print ''
        dsz.ui.Pause("Review the listener.log files you pulled. Make sure you understand how you'll log!")
    else:
        dsz.ui.Echo("I couldn't find any listener.log files... if you're not on the target database itself, you need to go there and clean it!", dsz.WARNING)
Пример #30
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()
Пример #31
0
def checkdirtyshutdown():
    regcmd = ops.cmd.getDszCommand('registryquery', hive='l', key='software\\microsoft\\windows\\currentversion\reliability')
    regobject = regcmd.execute()
    key_list = []
    for value in regobject.key[0].value:
        key_list.append({'name': value.name, 'value': value.value})
    pprint(key_list, ['Reliability Key', 'Value'], ['name', 'value'])
    print '\n'
Пример #32
0
def main(arguments):
    params = dsz.lp.cmdline.ParseCommandLine(sys.argv, 'processconnections.txt')
    searchpid = None
    if params.has_key('pid'):
        searchpid = int(params['pid'][0])
    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
    proclist = {}
    for process in procobject.initialprocesslistitem.processitem:
        if (searchpid is None):
            proclist[process.id] = {'name': process.name, 'path': process.path, 'user': process.user}
        elif (searchpid == process.id):
            proclist[process.id] = {'name': process.name, 'path': process.path, 'user': process.user}
            break
        else:
            continue
    if (not (len(proclist) > 0)):
        dsz.ui.Echo('Could not find any processes.', dsz.ERROR)
        return 0
    dsz.control.echo.Off()
    cmd = 'netconnections -list'
    (succ, netccmdid) = dsz.cmd.RunEx(cmd, dsz.RUN_FLAG_RECORD)
    dsz.control.echo.On()
    netconobject = None
    try:
        netconobject = ops.data.getDszObject(cmdid=netccmdid, cmdname='netconnections')
    except:
        dsz.ui.Echo('There was an issue with the ops.data.getDszObject.', dsz.ERROR)
        return 0
    connectionlist = []
    for connection in netconobject.initialconnectionlistitem.connectionitem:
        if ((searchpid is not None) and (not (searchpid == connection.pid))):
            continue
        try:
            thisproc = proclist[connection.pid]
        except:
            thisproc = {'path': None, 'name': ('***PID NOT FOUND (PROCESSES CMDID: %s)***' % proccmdid), 'user': None}
        path = ''
        remote = ''
        if ((thisproc['path'] is not None) and (not (thisproc['path'] == ''))):
            path = ('%s\\%s' % (thisproc['path'], thisproc['name']))
        else:
            path = ('%s' % thisproc['name'])
        if (connection.remote.address is not None):
            remote = ('%s:%s' % (connection.remote.address, connection.remote.port))
        connectionlist.append({'state': connection.state, 'type': connection.type, 'pid': connection.pid, 'local': ('%s:%s' % (connection.local.address, connection.local.port)), 'remote': remote, 'path': path, 'user': thisproc['user']})
    if (not (len(connectionlist) > 0)):
        dsz.ui.Echo('Could not find any netconnections.', dsz.ERROR)
        return 0
    pprint(connectionlist, ['TYPE', 'PID', 'LOCAL', 'REMOTE', 'STATE', 'PATH', 'USER'], ['type', 'pid', 'local', 'remote', 'state', 'path', 'user'])
Пример #33
0
def getmaclist(args):
    mac_list = []
    for mac in args:
        if (not util.mac.validate(mac)):
            mac_list.append({'mac': mac, 'oui': 'invalid mac'})
            continue
        mac_list.append({'mac': mac, 'oui': util.mac.getoui(mac)})
    pprint(mac_list, ['MAC', 'OUI'], ['mac', 'oui'])
    return 1
Пример #34
0
def getmaclist(args):
    mac_list = []
    for mac in args:
        if (not util.mac.validate(mac)):
            mac_list.append({'mac': mac, 'oui': 'invalid mac'})
            continue
        mac_list.append({'mac': mac, 'oui': util.mac.getoui(mac)})
    pprint(mac_list, ['MAC', 'OUI'], ['mac', 'oui'])
    return 1
Пример #35
0
def makebootlog(record_list):
    boot_hist = []
    this_event = []
    for record in record_list:
        if (record['id'] == 6009):
            boot_hist.append(this_event)
            this_event = []
        this_event.append(record)
    boot_hist.append(this_event)
    boot_summary = []
    color_list = []
    for this_event in boot_hist:
        if (len(this_event) == 0):
            continue
        boot = None
        shutdown = None
        reason = []
        crash = False
        uptime = None
        for record in this_event:
            if (record['id'] == 6009):
                boot = ('%s %s' % (record['date'], record['time']))
            elif (record['id'] == 6006):
                shutdown = ('%s %s' % (record['date'], record['time']))
            elif (record['id'] == 6008):
                crash = True
            elif (record['id'] == 1001):
                crash = True
            elif (record['id'] == 1074):
                reason.append(record['title'])
        reason = ','.join(reason)
        boot_summary.append({
            'boot': boot,
            'shutdown': shutdown,
            'reason': reason,
            'crash': crash,
            'uptime': uptime
        })
        if crash:
            color_list.append(dsz.ERROR)
        else:
            color_list.append(dsz.DEFAULT)
    for boot in boot_summary:
        if ((boot['boot'] is not None) and (boot['shutdown'] is not None)):
            boottime = datetime.datetime(
                *time.strptime(boot['boot'], '%Y-%m-%d %H:%M:%S')[0:6])
            shutdowntime = datetime.datetime(
                *time.strptime(boot['shutdown'], '%Y-%m-%d %H:%M:%S')[0:6])
            uptime = (shutdowntime - boottime)
            boot['uptime'] = ops.timehelper.get_age_from_seconds(
                (((uptime.days * 3600) * 24) + uptime.seconds))
    pprint(boot_summary,
           header=['Boot', 'Shutdown', 'Uptime', 'Reason', 'Crash'],
           dictorder=['boot', 'shutdown', 'uptime', 'reason', 'crash'],
           echocodes=color_list)
Пример #36
0
def printoutput(masterlist, itemlist):
    masterlist.sort()
    try:
        pprint(masterlist, itemlist)
    except:
        pass
    if (not MINIMAL):
        print '\n\nPDC: Primary domain controller, SQL: Server running Microsoft SQL Server'
        print 'NTP: Server running the Timesource service, PQ: Server sharing print queue'
        print 'DI: Server running dial-in service, Xe: Xenix server, Term: Terminal Server'
        print 'O: Other'
Пример #37
0
def printoutput(masterlist, itemlist):
    masterlist.sort()
    try:
        pprint(masterlist, itemlist)
    except:
        pass
    if (not MINIMAL):
        print '\n\nPDC: Primary domain controller, SQL: Server running Microsoft SQL Server'
        print 'NTP: Server running the Timesource service, PQ: Server sharing print queue'
        print 'DI: Server running dial-in service, Xe: Xenix server, Term: Terminal Server'
        print 'O: Other'
Пример #38
0
def main(args):
    if ((len(args) == 0) or (args == 0)):
        print_usage(args[0])
        return False
    arg_list = args[1:]
    tunnel_commands = []
    if (args[0] == 'imr'):
        if check_dumb_args(args[1:]):
            print_usage(args[0])
            return 0
        tunnel_commands.append(make_imr_args(args[1:]))
    elif (args[0] == 'lpr'):
        if check_dumb_args(args[1:]):
            print_usage(args[0])
            return 0
        tunnel_commands.append(make_lpr_args(args[1:]))
    elif (args[0] == 'hittun'):
        if check_dumb_args(args[1:]):
            print_usage(args[0])
            return 0
        tunnel_commands.extend(make_hittun_args(args[1:]))
    else:
        tunnel_commands.append(arg_list)
    if (arg_list == False):
        dsz.ui.Echo('Error, exiting', dsz.ERROR)
        print_usage(args[0])
        return 0
    max_attempts = 3
    success = False
    errors = []
    for arg_list in tunnel_commands:
        for i in range(0, max_attempts):
            redir_cmd = ops.networking.redirect.generate_tunnel_cmd(arg_list=arg_list, random=True)
            redir_output = ops.networking.redirect.start_tunnel(dsz_cmd=redir_cmd)
            if ((redir_output is not False) and (type(redir_output) is int)):
                dsz.ui.Echo(('Success CMDID: %s, %s' % (redir_output, str(redir_cmd))), dsz.GOOD)
                success = True
                running_tunnel = ops.networking.redirect.verify_local_tunnel(id=redir_output)
                tunnel_header = ['cmdid', 'fullcommand', 'bytessent', 'bytesreceived']
                tunnel_output = [{'cmdid': running_tunnel.id, 'fullcommand': running_tunnel.fullcommand, 'bytesreceived': running_tunnel.bytesreceived, 'bytessent': running_tunnel.bytessent}]
                pprint(tunnel_output, tunnel_header, tunnel_header)
                break
            if (type(redir_output) == type({})):
                moduleerror = ('%s: %s' % (redir_output['ModuleError']['value'], redir_output['ModuleError']['text']))
                oserror = ('%s: %s' % (redir_output['OsError']['value'], redir_output['OsError']['text']))
                errors.append({'CMDID': redir_cmd.channel, 'Command': str(redir_cmd), 'ModuleError': moduleerror, 'OsError': oserror})
    if (len(errors) > 0):
        dsz.ui.Echo('Printing errors for your information.', dsz.ERROR)
        pprint(errors, ['CMDID', 'Command', 'ModuleError', 'OsError'], ['CMDID', 'Command', 'ModuleError', 'OsError'])
    if (not success):
        dsz.ui.Echo('Failed to open three different redirect tunnels. Check your settings and re-evaluate.', dsz.WARNING)
Пример #39
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
Пример #40
0
def print_exclusion_list():
    current = ops.env.get(ops.survey.EXCLUDE, addr='')
    if (current is not None):
        current = json.loads(current)
        if (len(current[0]) == 0):
            disp = None
        else:
            disp = []
            for i in current:
                disp.append([i])
    if (current is not None):
        pprint(disp, header=['Survey Exclusions'])
    else:
        print('No exclusions.')
Пример #41
0
def main(args=[]):
    flags = dsz.control.Method()
    if ((__name__ == '__main__') and (dsz.script.Env['script_parent_echo_disabled'].lower() == 'true')):
        dsz.control.quiet.On()
    parser = ArgumentParser(prog='prettych', add_help=False)
    cmdopts = parser.add_argument_group(title='commands options')
    cmdopts.add_argument('--all', action='store_true', help='Also display finished commands')
    cmdopts.add_argument('--any', action='store_true', help='Display commands from any address')
    locationgrp = cmdopts.add_mutually_exclusive_group()
    locationgrp.add_argument('--local', dest='location', default=LOCATION_LOCAL, const=LOCATION_LOCAL, action='store_const', help='List local commands (default)')
    locationgrp.add_argument('--remote', dest='location', const=LOCATION_REMOTE, action='store_const', help='List remote commands')
    cmdopts.add_argument('--astyped', action='store_true', help='Show commands as typed (rather than displaying expanded aliases)')
    cmdopts.add_argument('--verbose', action='store_true', help='Show additional command information')
    parser.add_argument('--echo', dest='dszquiet', default=True, action='store_false', help='Echo out the raw DSZ commands output in addition to pretty printing.')
    options = parser.parse_args(args)
    commands = ops.cmd.getDszCommand('commands', prefixes=['stopaliasing'], all=options.all, any=options.any, astyped=options.astyped, verbose=options.verbose, dszquiet=options.dszquiet)
    if (options.location == LOCATION_LOCAL):
        header = []
        fields = []
        if options.all:
            header.append('Status')
            fields.append('status')
        header.extend(['ID', 'Target'])
        fields.extend(['id', 'targetaddress'])
        if (options.astyped or options.verbose):
            header.append('Command (as-typed)')
            fields.append('commandastyped')
        if ((not options.astyped) or options.verbose):
            header.append('Full Command')
            fields.append('fullcommand')
        header.extend(['Sent', 'Received'])
        fields.extend(['bytessent', 'bytesreceived'])
    elif (options.location == LOCATION_REMOTE):
        commands.remote = True
        header = ['ID', 'Command']
        fields = ['id', 'name']
    else:
        print 'You win a prize! Also, you fail.'
        sys.exit((-1))
    result = commands.execute()
    if (__name__ == '__main__'):
        ops.data.script_export(result)
    if (__name__ == '__main__'):
        for i in xrange(len(result.command)):
            if (result.command[i].id == int(dsz.script.Env['script_command_id'])):
                del result.command[i]
                break
    pprint(result.command, header=header, dictorder=fields)
    del flags
    return True
Пример #42
0
def print_exclusion_list():
    current = ops.env.get(ops.survey.EXCLUDE, addr='')
    if (current is not None):
        current = json.loads(current)
        if (len(current[0]) == 0):
            disp = None
        else:
            disp = []
            for i in current:
                disp.append([i])
    if (current is not None):
        pprint(disp, header=['Survey Exclusions'])
    else:
        print('No exclusions.')
def main(args):
    if (len(args) > 1):
        dsz.ui.Echo(
            'Pulls all INFO2 files on the system, parses them for a list of deleted files, and allows you to download chosen files.'
        )
        return 0
    entry_list = []
    dsz.ui.Echo('Obtaining a list of drives', dsz.GOOD)
    drive_list = getdrives()
    if dsz.version.checks.windows.IsVistaOrGreater():
        dsz.ui.Echo('Diring a list of $I* files', dsz.GOOD)
        vistaI_list = getvistaIlist(drive_list)
        dsz.ui.Echo('Diring for a list of trash files', dsz.GOOD)
        (trash_list, trash_dirs) = gettrashlist(vistaI_list)
        dsz.ui.Echo('Getting all $I* files', dsz.GOOD)
        vistaI_files = getvistaIfiles(vistaI_list)
        for file in vistaI_files:
            entry_list = parsevistafile(file['file'], entry_list,
                                        file['vistaI'], trash_list, trash_dirs)
    else:
        dsz.ui.Echo('Diring a list of INFO2 files', dsz.GOOD)
        info2_list = getinfo2list(drive_list)
        dsz.ui.Echo('Diring for a list of trash files', dsz.GOOD)
        (trash_list, trash_dirs) = gettrashlist(info2_list)
        dsz.ui.Echo('Getting all INFO2 files', dsz.GOOD)
        info2_files = getinfo2files(info2_list)
        for file in info2_files:
            entry_list = parsefile(file['file'], entry_list, file['info2'],
                                   trash_list, trash_dirs)
    if (not entry_list):
        return True
    if dsz.version.checks.windows.IsVistaOrGreater():
        pprint(entry_list, [
            'Index', 'OriginalFile', 'TrashName', 'Size', 'DateDeleted',
            'UnicodeFilename'
        ], [
            'index', 'originalfile', 'filename', 'size', 'timestamp',
            'unicode_filename'
        ])
    else:
        pprint(entry_list, [
            'Index', 'OriginalFile', 'TrashName', 'Size', 'DateDeleted',
            'UnicodeFilename'
        ], [
            'index', 'originalfile', 'filename', 'size', 'timestamp',
            'unicode_filename'
        ])
    get_list = getlist(entry_list)
    getfiles(get_list)
    return True
Пример #44
0
def doeventlogs():
    global record_list
    record_list = []
    color_list = []
    eventfilter(6005, info='Start of event log service', color=dsz.DEFAULT)
    eventfilter(6006,
                info='Event service stopped (clean shutdown)',
                color=dsz.DEFAULT)
    eventfilter(6008,
                info='System shut down unexpectedly (dirty shutdown)',
                color=dsz.ERROR)
    eventfilter(6009, info='System boot', color=dsz.GOOD)
    eventfilter(1001, info='BugCheck', color=dsz.ERROR)
    eventfilter(1074, info='Shutdown info', color=dsz.WARNING)
    eventfilter(109,
                info='Kernel-Power: Shutdown transition',
                color=dsz.DEFAULT)
    eventfilter(42,
                info='Kernel-Power: Informational',
                source='Microsoft-Windows-Kernel-Power')
    eventfilter(41,
                info='Kernel-Power: Critical',
                color=dsz.ERROR,
                source='Microsoft-Windows-Kernel-Power')
    eventfilter(13,
                info='Kernel: Stop',
                color=dsz.DEFAULT,
                source='Microsoft-Windows-Kernel-General')
    eventfilter(12,
                info='Kernel: Start',
                color=dsz.DEFAULT,
                source='Microsoft-Windows-Kernel-General')
    record_list.sort(key=(lambda x: x['eventlog']))
    record_list.sort(key=(lambda x: x['num']))
    for record in record_list:
        color_list.append(record['color'])
    pprint(record_list,
           header=[
               'Date', 'Time', 'ID', 'Eventlog', 'RecNum', 'Info', 'Process',
               'Hostname', 'Title', 'Code', 'Type', 'Description', 'User'
           ],
           dictorder=[
               'date', 'time', 'id', 'eventlog', 'num', 'info', 'process',
               'host', 'title', 'code', 'type', 'description', 'user'
           ],
           echocodes=color_list)
    print '\n'
    makebootlog(record_list)
    print '\n'
Пример #45
0
def checkHIPS7(mcafee):
    dsz.ui.Echo('NOTE!! The following settings are the settings provided by the ePO server. If the user/admin has changed any settings from the local UI, this list will be incorrect. Keep this in mind.\n', dsz.WARNING)
    enabled_disabled = {'1': 'Enabled', '0': 'Disabled'}
    rules = []
    rules.append({'Name': 'Host IPS Status', 'Value': enabled_disabled[_getValue(mcafee, 'software\\McAfee\\HIP', 'LastEnabledStateHips')]})
    rules.append({'Name': 'Network IPS Status', 'Value': enabled_disabled[_getValue(mcafee, 'software\\McAfee\\HIP', 'LastEnabledStateNips')]})
    rules.append({'Name': 'Firewall Status', 'Value': enabled_disabled[_getValue(mcafee, 'software\\McAfee\\HIP', 'LastEnabledStateFirewall')]})
    rules.append({'Name': 'Patch Version', 'Value': _getValue(mcafee, 'software\\McAfee\\HIP', 'Patch')})
    rules.append({'Name': 'App Creation Protection', 'Value': enabled_disabled[_getValue(mcafee, 'software\\McAfee\\HIP', 'LastEnabledStateAppCreate')]})
    rules.append({'Name': 'App Hooking Protection', 'Value': enabled_disabled[_getValue(mcafee, 'software\\McAfee\\HIP', 'LastEnabledStateAppHook')]})
    rules.append({'Name': 'Prevent High', 'Value': enabled_disabled[_getValue(mcafee, 'software\\McAfee\\HIP\\CounterMeasures', 'PreventHigh')]})
    rules.append({'Name': 'Prevent Medium', 'Value': enabled_disabled[_getValue(mcafee, 'software\\McAfee\\HIP\\CounterMeasures', 'PreventMedium')]})
    rules.append({'Name': 'Prevent Low', 'Value': enabled_disabled[_getValue(mcafee, 'software\\McAfee\\HIP\\CounterMeasures', 'PreventLow')]})
    pprint(rules)
    return
Пример #46
0
def checkHIPS7(mcafee):
    dsz.ui.Echo('NOTE!! The following settings are the settings provided by the ePO server. If the user/admin has changed any settings from the local UI, this list will be incorrect. Keep this in mind.\n', dsz.WARNING)
    enabled_disabled = {'1': 'Enabled', '0': 'Disabled'}
    rules = []
    rules.append({'Name': 'Host IPS Status', 'Value': enabled_disabled[_getValue(mcafee, 'software\\McAfee\\HIP', 'LastEnabledStateHips')]})
    rules.append({'Name': 'Network IPS Status', 'Value': enabled_disabled[_getValue(mcafee, 'software\\McAfee\\HIP', 'LastEnabledStateNips')]})
    rules.append({'Name': 'Firewall Status', 'Value': enabled_disabled[_getValue(mcafee, 'software\\McAfee\\HIP', 'LastEnabledStateFirewall')]})
    rules.append({'Name': 'Patch Version', 'Value': _getValue(mcafee, 'software\\McAfee\\HIP', 'Patch')})
    rules.append({'Name': 'App Creation Protection', 'Value': enabled_disabled[_getValue(mcafee, 'software\\McAfee\\HIP', 'LastEnabledStateAppCreate')]})
    rules.append({'Name': 'App Hooking Protection', 'Value': enabled_disabled[_getValue(mcafee, 'software\\McAfee\\HIP', 'LastEnabledStateAppHook')]})
    rules.append({'Name': 'Prevent High', 'Value': enabled_disabled[_getValue(mcafee, 'software\\McAfee\\HIP\\CounterMeasures', 'PreventHigh')]})
    rules.append({'Name': 'Prevent Medium', 'Value': enabled_disabled[_getValue(mcafee, 'software\\McAfee\\HIP\\CounterMeasures', 'PreventMedium')]})
    rules.append({'Name': 'Prevent Low', 'Value': enabled_disabled[_getValue(mcafee, 'software\\McAfee\\HIP\\CounterMeasures', 'PreventLow')]})
    pprint(rules)
    return
Пример #47
0
def select_database_menu(available_databases, menu):
    print ''
    if (not available_databases):
        dsz.ui.Echo('No list of available databases found.\n', dsz.WARNING)
        db_name = dsz.ui.GetString('Please enter the name of the database')
        menu.set_current_state(db_name)
        return
    dsz.ui.Echo('Available Databases', dsz.GOOD)
    for (i, row) in enumerate(available_databases):
        row['Row'] = (i + 1)
    pprint(available_databases, dictorder=['Row', 'Name', 'Size', 'Modified', 'Path'])
    to_get = (-1)
    while ((to_get < 0) or (to_get >= len(available_databases))):
        print ''
        to_get = dsz.ui.GetInt('Type a number to select a database')
        to_get = (to_get - 1)
    menu.set_current_state(available_databases[to_get]['Name'])
Пример #48
0
def main():
    print ''
    dsz.ui.Echo('Pulling all Martin Prikryl and Simon Tatham registry data...')
    grab_all_regdata()
    print ''
    creds = []
    dsz.ui.Echo('Looking for Registry Storage...')
    creds += get_registry_credentials()
    print ''
    creds += get_ini_credentials()
    print ''
    if creds:
        pprint(creds, header=['Host', 'Port', 'Protocol', 'Username', 'Password'])
    else:
        dsz.ui.Echo('No saved passwords found.', dsz.ERROR)
    print ''
    dsz.ui.Echo('SimonTatham.py Done!', dsz.GOOD)
Пример #49
0
def checkHIPS8(mcafee):
    rules = []
    enabled_disabled = {'1': 'Enabled', '0': 'Disabled'}
    reaction_levels = {'1': 'Ignore', '2': 'Log', '3': 'Prevent'}
    rules.append({'Name': 'Host IPS Status', 'Value': enabled_disabled[_getValue(mcafee, 'software\\McAfee\\HIP\\Config\\Settings', 'IPS_HipsEnabled')]})
    rules.append({'Name': 'Network IPS Status', 'Value': enabled_disabled[_getValue(mcafee, 'software\\McAfee\\HIP\\Config\\Settings', 'IPS_NipsEnabled')]})
    rules.append({'Name': 'Firewall Status', 'Value': enabled_disabled[_getValue(mcafee, 'software\\McAfee\\HIP\\Config\\Settings', 'FW_Enabled')]})
    rules.append({'Name': 'Reaction High', 'Value': reaction_levels[_getValue(mcafee, 'software\\McAfee\\HIP\\Config\\Settings', 'IPS_ReactionForHigh')]})
    rules.append({'Name': 'Reaction Medium', 'Value': reaction_levels[_getValue(mcafee, 'software\\McAfee\\HIP\\Config\\Settings', 'IPS_ReactionForMedium')]})
    rules.append({'Name': 'Reaction Low', 'Value': reaction_levels[_getValue(mcafee, 'software\\McAfee\\HIP\\Config\\Settings', 'IPS_ReactionForLow')]})
    rules.append({'Name': 'Reaction Info', 'Value': reaction_levels[_getValue(mcafee, 'software\\McAfee\\HIP\\Config\\Settings', 'IPS_ReactionForInfo')]})
    rules.append({'Name': 'IPS Rules', 'Value': _getValue(mcafee, 'software\\McAfee\\HIP\\Config\\Settings', 'Client_PolicyName_IpsRulesList')})
    rules.append({'Name': 'FW Rules', 'Value': _getValue(mcafee, 'software\\McAfee\\HIP\\Config\\Settings', 'Client_PolicyName_FwRules')})
    rules.append({'Name': 'Definitions', 'Value': _getValue(mcafee, 'software\\McAfee\\HIP', 'ContentVersion')})
    rules.append({'Name': 'Definitions Date', 'Value': _getValue(mcafee, 'software\\McAfee\\HIP', 'ContentCreated')})
    rules.append({'Name': 'Patch Level', 'Value': _getValue(mcafee, 'software\\McAfee\\HIP', 'Patch')})
    pprint(rules)
    return
Пример #50
0
def main():
    alltargetsallprojects = ops.project.getAllTargets()
    targetsup = []
    cmd = ops.cmd.getDszCommand('arp')
    cmd.optdict = {'query': True}
    arp = cmd.execute()
    if cmd.success:
        for arptgt in arp.entry:
            for tgt in alltargetsallprojects:
                if (arptgt.mac.lower() in tgt.macs):
                    targetsup.append({'proj': tgt.project.name, 'target': tgt.hostname, 'id': tgt.implant_id, 'ip': arptgt.ip, 'mac': arptgt.mac, 'interface': arptgt.adapter})
        if (len(targetsup) > 0):
            dsz.ui.Echo('Targets that are up', dsz.GOOD)
            pprint(targetsup, header=['Project', 'Target', 'Target ID', 'IP', 'MAC', 'Interface'], dictorder=['proj', 'target', 'id', 'ip', 'mac', 'interface'])
        else:
            dsz.ui.Echo("Doesn't look like anything is up", dsz.WARNING)
    else:
        dsz.ui.Echo(('arp -query failed. check command id %d ' % arp._cmdid), dsz.ERROR)
Пример #51
0
 def top_ten_query(self, handle_id, table_query_file=None, top_ten_query_template=None):
     print ''
     dsz.ui.Echo('Running query to find all user tables...', dsz.GOOD)
     while (not table_query_file):
         prompt = 'Please provide a query file that will pull the list of tables'
         table_query_file = dsz.ui.GetString(prompt)
         if (not os.path.exists(table_query_file)):
             dsz.ui.Echo(('%s does not exist... try again.' % table_query_file), dsz.ERROR)
             table_query_file = None
     (status, command_id) = sql_utils.run_query_from_file(handle_id, table_query_file, echo=False)
     if (not status):
         print ''
         dsz.ui.Echo("Couldn't get the table list, try reconnecting.", dsz.ERROR)
         return None
     header = sql_xml_parser.header_from_id(command_id)
     data = [row for row in sql_xml_parser.data_from_id(command_id)]
     if (not data):
         print ''
         dsz.ui.Echo("Couldn't read the XML list of tables. There may be an error in sql_xml_parser. Go find a script dev!", dsz.ERROR)
         return None
     print ''
     if dsz.ui.Prompt(('Found %s tables, would you like to see the names?' % len(data))):
         print ''
         pprint(data, header)
     print ''
     if (not dsz.ui.Prompt('Would you like to pull the first 10 rows of each table?')):
         return None
     print ''
     for row in data:
         table_name = row[0]
         if (not top_ten_query_template):
             top_ten_query_text = ('select top 10 * from %s' % table_name)
         else:
             top_ten_query_text = (top_ten_query_template % table_name)
         (status, command_id) = sql_utils.run_query(handle_id, top_ten_query_text, echo=True, max_col_size=self.max_col_size)
         dsz.ui.Echo(('ID: %s Status: %s' % (command_id, status)))
         if (not status):
             if (not dsz.ui.Prompt('Looks like a query failed, would you like to continue?')):
                 return None
         if (self.csv_output and status):
             sql_utils.write_csv_output(command_id, 'TopTenSurvey', table_name)
     return None
Пример #52
0
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
Пример #53
0
 def showstats(self, session_to_display=None, screenonly=False):
     if (session_to_display is None):
         session_to_display = self.session
     header_list = ['*INFO*']
     dictorder = ['name']
     output_dict = {'queued': {'name': 'Queued', 'total': 0}, 'running': {'name': 'Running', 'total': 0}, 'attempted': {'name': 'Attempted', 'total': 0}, 'results': {'name': 'Results', 'total': 0}}
     job_info = scanbase.all_num_jobs(session_to_display)
     job_types = []
     for job in job_info:
         if (not (job['type'] in job_types)):
             job_types.append(job['type'])
             output_dict['attempted'][job['type']] = 0
             output_dict['running'][job['type']] = 0
             output_dict['queued'][job['type']] = 0
         if (job['complete'] == 'True'):
             output_dict['attempted'][job['type']] += 1
         elif (job['inprogress'] == 'True'):
             output_dict['running'][job['type']] += 1
         else:
             output_dict['queued'][job['type']] += 1
     for type in job_types:
         output_dict['results'][type] = self.findlistsize(type, session=session_to_display)
         output_dict['queued']['total'] += output_dict['queued'][type]
         output_dict['running']['total'] += output_dict['running'][type]
         output_dict['attempted']['total'] += output_dict['attempted'][type]
         output_dict['results']['total'] += output_dict['results'][type]
     for type in ['arp', 'ping', 'netbios', 'banner', 'rpc2', 'scanner', 'rpctouch', 'smbtouch']:
         if (type in job_types):
             dictorder.append(type)
             header_list.append(type)
             job_types.remove(type)
     for type in job_types:
         dictorder.append(type)
         header_list.append(type)
     dictorder.append('total')
     header_list.append('TOTAL')
     pprint([output_dict['queued'], output_dict['running'], output_dict['attempted'], output_dict['results']], header=header_list, dictorder=dictorder)
     if (not screenonly):
         pprint([output_dict['queued'], output_dict['running'], output_dict['attempted'], output_dict['results']], header=header_list, dictorder=dictorder, print_handler=self.pprintout)
Пример #54
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
Пример #55
0
def checksettings(psp):
    try:
        psp[comattribs.installdate] = ('%s' % datetime.datetime.fromtimestamp(float(psp[comattribs.installdate])))
    except TypeError:
        mcafeelog.error('Could not get install date: conversion error', exc_info=True)
        mcafeelog.debug('tstamp data: {0}'.format(psp[comattribs.installdate]))
    header = ['Setting', 'State', 'Notes']
    data = []
    echocodes = []

    def addDataLine(setting, compval, rowstr, notetrue, notefalse, echotrue, echofalse):
        data.append([rowstr, OnOff(setting), (notetrue if (setting == compval) else notefalse)])
        echocodes.append((echotrue if (setting == compval) else echofalse))

    def OnOff(data):
        return ('ON' if (data == '1') else 'OFF')
    try:
        addDataLine(psp.GTIEnabled, '1', 'Cloud Services (GTI)', '!!! PE checksums will be sent to McAfee !!!', '', dsz.ERROR, dsz.GOOD)
        addDataLine(psp.BOPEnabled, '1', 'Buffer Overflow Prot', '(Informational Only)', '', dsz.WARNING, dsz.GOOD)
        addDataLine(psp.HeuristicsEnabled, '1', 'Heuristic Scanning', '(Informational Only)', '', dsz.WARNING, dsz.GOOD)
    except:
        pass
    pprint(data, header, echocodes=echocodes)
Пример #56
0
 def printresults(self, name, dict, titles, keys, sort1, sort2=None, quiet=False):
     bannerstring = ('========== %s Results ==============' % name)
     bannerhead = (len(bannerstring) * '=')
     if (not quiet):
         dsz.ui.Echo(bannerhead, dsz.GOOD)
         dsz.ui.Echo(bannerstring, dsz.GOOD)
         dsz.ui.Echo(bannerhead, dsz.GOOD)
     if (len(dict) > 0):
         dict.sort(key=(lambda x: x[sort1]))
         if (not (sort2 == None)):
             dict.sort(key=(lambda x: x[sort2]))
         if (not quiet):
             pprint(dict, titles, keys)
         pprint(dict, titles, keys, print_handler=self.pprintout)
     else:
         with open(self.scansweep_results, 'a') as f:
             f.write(('No %s data was returned\n' % name))
         if (not quiet):
             dsz.ui.Echo(('No %s data was returned' % name), dsz.WARNING)
     with open(self.scansweep_results, 'a') as f:
         f.write('\n\n')
     if (not quiet):
         print '\n\n'
Пример #57
0
def main():
    if (len(sys.argv) == 1):
        dsz.ui.Echo('====================================')
        dsz.ui.Echo('= Getting a list of prefetch files =')
        dsz.ui.Echo('====================================')
        prefetch = getpretchfiles('c:\\windows\\prefetch')
        pprint(prefetch, header=['Index', 'Name', 'Size', 'Created', 'Modified', 'Accessed'], dictorder=['index', 'name', 'size', 'created', 'modified', 'accessed'])
        dsz.ui.Echo('Found the above files in the prefetch, please select which you would like to pull and parse', dsz.GOOD)
        wantlist = getlist(prefetch)
        shortparse = []
        for file in wantlist:
            localfile = getfile(file)
            file['localfile'] = localfile
            data = readfile(localfile)
            good_data = {'index': file['index'], 'name': file['name'], 'bytes': data['prefetchfilelength'], 'runs': data['numexec'], 'last': data['lastexectimestamp'], 'localfile': file['localfile'], 'sectionc': data['sectionc'], 'sectiond': data['sectiond']}
            shortparse.append(good_data)
        print ''
        dsz.ui.Echo('====================================')
        dsz.ui.Echo('=========== Short Parse ============')
        dsz.ui.Echo('====================================')
        pprint(shortparse, header=['Index', 'Name', 'Byte Length', 'Number of Runs', 'Last Execute Time'], dictorder=['index', 'name', 'bytes', 'runs', 'last'])
        dsz.ui.Echo('Of the files you pulled back, which would you like to see the called files?', dsz.GOOD)
        parselist = getlist(shortparse)
        print ''
        for file in parselist:
            bannerstring = ('================ %s ====================' % file['name'])
            bannercap = ('=' * len(bannerstring))
            dsz.ui.Echo(bannercap, dsz.GOOD)
            dsz.ui.Echo(bannerstring, dsz.GOOD)
            dsz.ui.Echo(bannercap, dsz.GOOD)
            dsz.ui.Echo('Files Accessed:')
            for dll in file['sectionc']:
                dsz.ui.Echo(('\t\t%s' % ops.utf8(dll)))
            dsz.ui.Echo('\\Volumes Accessed:')
            for sectiond in file['sectiond']:
                dsz.ui.Echo(('\tVolume Label: %s' % sectiond['vollabel']))
                dsz.ui.Echo(('\tVolume Serial: %s' % sectiond['volserial']))
                dsz.ui.Echo(('\tAccess timestamp: %s' % sectiond['accesstimestamp']))
                dsz.ui.Echo('\tDirectories Accessed:')
                for directory in sectiond['subsec2']:
                    dsz.ui.Echo(('\t\t%s' % ops.utf8(directory[1])))
    else:
        prefetchFile = sys.argv[1]
        data = readfile(prefetchFile)
        good_data = [{'bytes': data['prefetchfilelength'], 'runs': data['numexec'], 'last': data['lastexectimestamp'], 'sectionc': data['sectionc'], 'sectiond': data['sectiond']}]
        pprint(good_data, header=['Byte Length', 'Number of Runs', 'Last Execute Time'], dictorder=['bytes', 'runs', 'last'])
        dsz.ui.Echo('Files Accessed:')
        for dll in data['sectionc']:
            dsz.ui.Echo(('\t\t%s' % ops.utf8(dll)))
        dsz.ui.Echo('\\Volumes Accessed:')
        for sectiond in data['sectiond']:
            dsz.ui.Echo(('\tVolume Label: %s' % sectiond['vollabel']))
            dsz.ui.Echo(('\tVolume Serial: %s' % sectiond['volserial']))
            dsz.ui.Echo(('\tAccess timestamp: %s' % sectiond['accesstimestamp']))
            dsz.ui.Echo('\tDirectories Accessed:')
            for directory in sectiond['subsec2']:
                dsz.ui.Echo(('\t\t%s' % ops.utf8(directory[1])))
Пример #58
0
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()
    maxage = datetime.timedelta(seconds=options.maxage)
    ops.survey.print_header('User and group queries.')
    ops.survey.print_header('Users')
    lusers = ops.security.principals.get_users_local(maxage=datetime.timedelta(seconds=options.maxage))
    ops.survey.print_agestring(lusers.dszobjage)
    pprint(lusers.user, dictorder=['userid', 'name', 'comment', 'privilege', 'usershell', 'passwordlastchanged', 'passwordexpired'], header=['UID', 'Username', 'Comment', 'Privilege', 'Shell', 'Password changed', 'Password expired'])
    ops.survey.print_header('Local groups')
    lgroups = ops.security.principals.get_groups_local(maxage=datetime.timedelta(seconds=options.maxage))
    ops.survey.print_agestring(lgroups.dszobjage)
    pprint(lgroups.group, dictorder=['group', 'comment'], header=['Group', 'Comment'])
    ops.survey.print_header('Network groups')
    ngroups = ops.security.principals.get_groups_network(maxage=datetime.timedelta(seconds=options.maxage))
    ops.survey.print_agestring(ngroups.dszobjage)
    pprint(ngroups.group, dictorder=['group', 'comment'], header=['Group', 'Comment'])
Пример #59
0
def print_data_with_rownums(data, header):
    for (i, row) in enumerate(data):
        row.insert(0, (i + 1))
    header.insert(0, '#')
    pprint(data, header)