예제 #1
0
def main(argv=None):
    setupLogging("admemanalysis.log", logging.INFO)
    registry.PluginImporter()
    config = conf.ConfObject()
    config.add_option('OUTPUT-PATH',
                      default=None,
                      help='Where to create output files',
                      action='store',
                      type='str')
    config.process_id = None
    registry.register_global_options(config, commands.Command)
    registry.register_global_options(config, addrspace.BaseAddressSpace)

    if not os.path.isfile("inputdata.json"):
        raise NameError("Input file(inpudata.json) was not found")
    data = None

    with open("inputdata.json") as data_file:
        data = json.load(data_file)
    operations = data['operationdata']

    sys.argv.append("-f")
    sys.argv.append(data["filestreamtoanalyze"])
    sys.argv.append("--profile")
    profile = data["profiletypename"] or ProfileGeneratorClass().GetProfile()
    logging.info('profile detected is {0}'.format(profile))
    sys.argv.append(profile)

    output_path = data.get('outputpath') or ''

    config.parse_options(False)
    sys.argv.append("--output-path")
    sys.argv.append(output_path)

    config.parse_options()

    if utils.getConfigValue(operations, 'process') == True:
        adprocessesfactory.ADProcesses().execute(operations, config)

    if utils.getConfigValue(operations, 'drivers') == True:
        addriveranddevicefactory.DriverDeviceScan().execute(config)

    if utils.getConfigValue(operations, 'modules') == True:
        adkernelmodulesfactory.ADKernelModules().execute(config)

    if utils.getConfigValue(operations, 'sdts') == True:
        adsdtfactory.ADSdtGenerator().execute(config)

    if utils.getConfigValue(operations, 'yarascan') == True:
        adyarascanfactory.ADYaraScan().execute("", config)

    if utils.getConfigValue(operations, 'idt') == True:
        processors = kpcr.doProcessors(config)
        f = open(config.OUTPUT_PATH + 'processors.xml', 'w')
        #f.write(processors.SerializeToString())
        f.write(proto2xml(processors, indent=0))

    if utils.getConfigValue(operations, 'registry') == True:
        adregistryfactory.ADRegistryExtractor().execute(config)
예제 #2
0
def main(argv=None):
    setupLogging("admemanalysis.log",logging.INFO)
    registry.PluginImporter()
    config = conf.ConfObject()
    config.add_option('OUTPUT-PATH', default=None,
                      help='Where to create output files',
                      action='store', type='str')
    config.process_id = None
    registry.register_global_options(config, commands.Command)
    registry.register_global_options(config, addrspace.BaseAddressSpace)

    if not os.path.isfile("inputdata.json"):
        raise NameError("Input file(inpudata.json) was not found")
    data = None

    with open("inputdata.json") as data_file:
        data = json.load(data_file)
    operations = data['operationdata']

    sys.argv.append("-f")
    sys.argv.append(data["filestreamtoanalyze"])
    sys.argv.append("--profile")
    profile = data["profiletypename"] or ProfileGeneratorClass().GetProfile()
    logging.info('profile detected is {0}'.format(profile))
    sys.argv.append(profile)

    output_path = data.get('outputpath') or ''

    config.parse_options(False)
    sys.argv.append("--output-path")
    sys.argv.append(output_path)

    config.parse_options()

    if utils.getConfigValue(operations,'process') == True:
        adprocessesfactory.ADProcesses().execute(operations,config)

    if utils.getConfigValue(operations,'drivers') == True:
        addriveranddevicefactory.DriverDeviceScan().execute(config)

    if utils.getConfigValue(operations,'modules') == True:
        adkernelmodulesfactory.ADKernelModules().execute(config)

    if utils.getConfigValue(operations,'sdts')== True:
        adsdtfactory.ADSdtGenerator().execute(config)

    if utils.getConfigValue(operations,'yarascan') == True:
        adyarascanfactory.ADYaraScan().execute("",config)

    if utils.getConfigValue(operations,'idt') == True:
        processors = kpcr.doProcessors(config)
        f = open(config.OUTPUT_PATH + 'processors.xml','w')
        #f.write(processors.SerializeToString())
        f.write(proto2xml(processors,indent=0))

    if utils.getConfigValue(operations,'registry') == True:
        adregistryfactory.ADRegistryExtractor().execute(config)
예제 #3
0
    def execute(self,config):
        regObjList = datastructs.rootType()

        keys = volregistry.PrintKey(config).calculate()
        for reg, key in keys:
            self.getregistrykeyobject(reg,key,regObjList)
            self.LoadSubKeys(reg,key,regObjList)

        registryfile = open(config.OUTPUT_PATH + "registry.xml", "w")
        #registryfile.write(regObjList.SerializeToString())
        registryfile.write(proto2xml(regObjList,indent=0))
예제 #4
0
    def execute(self, config):
        regObjList = datastructs.rootType()

        keys = volregistry.PrintKey(config).calculate()
        for reg, key in keys:
            self.getregistrykeyobject(reg, key, regObjList)
            self.LoadSubKeys(reg, key, regObjList)

        registryfile = open(config.OUTPUT_PATH + "registry.xml", "w")
        #registryfile.write(regObjList.SerializeToString())
        registryfile.write(proto2xml(regObjList, indent=0))
예제 #5
0
    def execute(self, config):
        addr_space = utils.load_as(config)
        syscalls = addr_space.profile.syscalls
        bits32 = addr_space.profile.metadata.get('memory_model',
                                                 '32bit') == '32bit'
        data = SSDTS.SSDT(config).calculate()
        sdtObjectList = datastructs.rootType()

        # Print out the entries for each table
        for idx, table, n, vm, mods, mod_addrs in data:
            sdtObject = sdtObjectList.SSDTs.SSDT.add()
            sdtObject.VirtAddr = table

            sdtEntries = sdtObject.SSDTEntries
            sdtEntries.count = n

            for i in range(n):
                if bits32:
                    # These are absolute function addresses in kernel memory.
                    syscall_addr = obj.Object('address', table + (i * 4),
                                              vm).v()
                else:
                    # These must be signed long for x64 because they are RVAs relative
                    # to the base of the table and can be negative.
                    offset = obj.Object('long', table + (i * 4), vm).v()
                    # The offset is the top 20 bits of the 32 bit number.
                    syscall_addr = table + (offset >> 4)
                try:
                    syscall_name = syscalls[idx][i]
                except IndexError:
                    syscall_name = "UNKNOWN"

                syscall_mod = tasks.find_module(
                    mods, mod_addrs, addr_space.address_mask(syscall_addr))
                if syscall_mod:
                    syscall_modname = syscall_mod.BaseDllName
                else:
                    syscall_modname = "UNKNOWN"

                sdtEntry = sdtEntries.SSDTEntry.add()
                sdtEntry.FunctionName = adutils.SmartUnicode(syscall_name)
                sdtEntry.ModuleName = adutils.SmartUnicode(syscall_modname)
                sdtEntry.VirtAddr = int(syscall_addr)

        sdtsfile = open(config.OUTPUT_PATH + "sdts.xml", "w")
        #sdtsfile.write(sdtObjectList.SerializeToString())
        sdtsfile.write(proto2xml(sdtObjectList, indent=0))

        logging.debug("Completed exporting the sdts on the system")
예제 #6
0
 def execute(self, config):
     data = krnlModules.Modules(config).calculate()
     moduleObjList = datastructs.rootType()
     for module in data:
         moduleObj = moduleObjList.Module.add(resultitemtype=13)
         moduleObj.Name = utils._utf8_encode(module.BaseDllName)
         moduleObj.Path = utils._utf8_encode(module.FullDllName)
         moduleObj.Address = long(module.DllBase.v())
         # This is always 2 in my reference xml from a MemoryAnalysis job.
         # I don't know if that is a mistake, but that doesn't seem useful.
         moduleObj.EntryPoint = long(module.EntryPoint.v())
         moduleObj.Size = int(module.SizeOfImage)
     file = open(config.OUTPUT_PATH + "modules.xml", "w")
     #file.write(moduleObjList.SerializeToString())
     file.write(proto2xml(moduleObjList, indent=0))
     logging.debug("Completed calculating the kernel modules")
예제 #7
0
 def execute(self,config):
     data = krnlModules.Modules(config).calculate()
     moduleObjList = datastructs.rootType()
     for module in data:
         moduleObj = moduleObjList.Module.add(resultitemtype=13)
         moduleObj.Name=utils._utf8_encode(module.BaseDllName)
         moduleObj.Path=utils._utf8_encode(module.FullDllName)
         moduleObj.Address=long(module.DllBase.v())
         # This is always 2 in my reference xml from a MemoryAnalysis job.
         # I don't know if that is a mistake, but that doesn't seem useful.
         moduleObj.EntryPoint=long(module.EntryPoint.v())
         moduleObj.Size=int(module.SizeOfImage)
     file = open(config.OUTPUT_PATH + "modules.xml", "w")
     #file.write(moduleObjList.SerializeToString())
     file.write(proto2xml(moduleObjList,indent=0))
     logging.debug("Completed calculating the kernel modules")
예제 #8
0
    def execute(self,config):
        addr_space = utils.load_as(config)
        syscalls = addr_space.profile.syscalls
        bits32 = addr_space.profile.metadata.get('memory_model', '32bit') == '32bit'
        data = SSDTS.SSDT(config).calculate()
        sdtObjectList = datastructs.rootType()

        # Print out the entries for each table
        for idx, table, n, vm, mods, mod_addrs in data:
            sdtObject = sdtObjectList.SSDTs.SSDT.add()
            sdtObject.VirtAddr=table

            sdtEntries = sdtObject.SSDTEntries
            sdtEntries.count=n

            for i in range(n):
                if bits32:
                    # These are absolute function addresses in kernel memory.
                    syscall_addr = obj.Object('address', table + (i * 4), vm).v()
                else:
                    # These must be signed long for x64 because they are RVAs relative
                    # to the base of the table and can be negative.
                    offset = obj.Object('long', table + (i * 4), vm).v()
                    # The offset is the top 20 bits of the 32 bit number.
                    syscall_addr = table + (offset >> 4)
                try:
                    syscall_name = syscalls[idx][i]
                except IndexError:
                    syscall_name = "UNKNOWN"

                syscall_mod = tasks.find_module(mods, mod_addrs, addr_space.address_mask(syscall_addr))
                if syscall_mod:
                    syscall_modname = syscall_mod.BaseDllName
                else:
                    syscall_modname = "UNKNOWN"

                sdtEntry = sdtEntries.SSDTEntry.add()
                sdtEntry.FunctionName=adutils.SmartUnicode(syscall_name)
                sdtEntry.ModuleName=adutils.SmartUnicode(syscall_modname)
                sdtEntry.VirtAddr=int(syscall_addr)

        sdtsfile = open(config.OUTPUT_PATH + "sdts.xml", "w")
        #sdtsfile.write(sdtObjectList.SerializeToString())
        sdtsfile.write(proto2xml(sdtObjectList,indent=0))

        logging.debug("Completed exporting the sdts on the system")
예제 #9
0
    def doDevices(self, config, devices):
        print "Doing DoDevices"
        deviceObjList = devicedatastructs.rootType()

        for device_name,device_object in devices:
            deviceObj = deviceObjList.Device.add(
                Name=device_name,
                DeviceObj_Location=device_object.v() or 0,
                DriverObj_Location=device_object.obj_native_vm.vtop(device_object.DriverObject.v() or 0) or 0,
                NextDeviceObj_Location=device_object.obj_native_vm.vtop(device_object.NextDevice.v() or 0) or 0,
                AttachedDeviceObj_Location=device_object.obj_native_vm.vtop(device_object.AttachedDevice.v() or 0) or 0
            )

        file = open(config.OUTPUT_PATH + "devices.xml", "w")
        #file.write(deviceObjList.SerializeToString())
        file.write(proto2xml(deviceObjList,indent=0))
        logging.debug("Completed exporting the deviceObjects on the system")
예제 #10
0
    def doDevices(self, config, devices):
        print "Doing DoDevices"
        deviceObjList = devicedatastructs.rootType()

        for device_name, device_object in devices:
            deviceObj = deviceObjList.Device.add(
                Name=device_name,
                DeviceObj_Location=device_object.v() or 0,
                DriverObj_Location=device_object.obj_native_vm.vtop(
                    device_object.DriverObject.v() or 0) or 0,
                NextDeviceObj_Location=device_object.obj_native_vm.vtop(
                    device_object.NextDevice.v() or 0) or 0,
                AttachedDeviceObj_Location=device_object.obj_native_vm.vtop(
                    device_object.AttachedDevice.v() or 0) or 0)

        file = open(config.OUTPUT_PATH + "devices.xml", "w")
        #file.write(deviceObjList.SerializeToString())
        file.write(proto2xml(deviceObjList, indent=0))
        logging.debug("Completed exporting the deviceObjects on the system")
예제 #11
0
    def execute(self, options, config):
        with UpdateCounterForScope('ADFloatingDriver'):
            output = FileOutputClass(getattr(config, "OUTPUT_PATH"), type(self).operation_name)
            if not output.Open():
                return

            data = modules.Modules(config).calculate()

            floatingDrivers = datastructs.rootType()
            for module in data:
                driverName = utils._utf8_encode(module.BaseDllName)
                driverPath = utils._utf8_encode(module.FullDllName)
                driverFullPath = ExpandPath(driverPath)
                if not os.path.exists(driverFullPath):
                    driver = floatingDrivers.FloatingDriver.add()
                    driver.Name = driverName
                    driver.Path = driverFullPath

            output.File.write(proto2xml(floatingDrivers, indent=0))
            output.Close()
예제 #12
0
    def doDrivers(self, config, drivers, devices):
        print "Doing DoDrivers"

        driverObjList = driverdatastructs.rootType()

        for driver_name, driver_object in drivers:
            driverObj = driverObjList.Driver.add(
                resultitemtype=5)  #ResultDriverItem

            baseaddress = driver_object.DriverStart.v()
            module = find_module(config, baseaddress)
            driverObj.ImagePath = module.FullDllName.v(
            ) if module and module.FullDllName else ''

            driverObj.BaseAddress = baseaddress
            driverObj.Type = driver_object.Type.v()
            driverObj.DeviceObj_Location = driver_object.obj_native_vm.vtop(
                driver_object.DeviceObject.v()) or 0
            driverObj.Driver_Init = driver_object.DriverInit.v()
            driverObj.Driver_StartIO = driver_object.DriverStartIo.v()
            driverObj.Driver_Unload = driver_object.DriverUnload.v()
            driverObj.StartTime = '0000-00-00 00:00:00'  # currently we don't have a reliable source for this info
            driverObj.Dependencies = ''  # this is a linux thing
            driverObj.Size = driver_object.DriverSize.v()
            driverObj.Instances = 0  # this is a linux thing
            driverObj.Name = driver_object.DriverName.v()
            driverObj.StartedAs = ''
            driverObj.State = 4  #running
            driverObj.RealState = -1  #unknown
            driverObj.StartMode = -1  #unknown
            driverObj.RealStartMode = -1  #unknown
            driverObj.RealType = 0  #unknown
            driverObj.Path = ''
            driverObj.plist = ''
            driverObj.MD5 = BLANK_MD5
            driverObj.SHA1 = BLANK_SHA1
            #Leave out FuzzyHash for now
            #FuzzySize =
            #Fuzzy =
            #Fuzzy2X =
            driverObj.KFFStatus = 0  #I guess we don't do this
            driverObj.processid = 0  #meaningless for drivers

            major_functions = driver_object.MajorFunction
            driverObj.IRP_MJ_CREATE = major_functions[0].v()
            driverObj.IRP_MJ_CREATE_NAMED_PIPE = major_functions[1].v()
            driverObj.IRP_MJ_CLOSE = major_functions[2].v()
            driverObj.IRP_MJ_READ = major_functions[3].v()
            driverObj.IRP_MJ_WRITE = major_functions[4].v()
            driverObj.IRP_MJ_QUERY_INFORMATION = major_functions[5].v()
            driverObj.IRP_MJ_SET_INFORMATION = major_functions[6].v()
            driverObj.IRP_MJ_QUERY_EA = major_functions[7].v()
            driverObj.IRP_MJ_SET_EA = major_functions[8].v()
            driverObj.IRP_MJ_FLUSH_BUFFERS = major_functions[9].v()
            driverObj.IRP_MJ_QUERY_VOLUME_INFORMATION = major_functions[10].v()
            driverObj.IRP_MJ_SET_VOLUME_INFORMATION = major_functions[11].v()
            driverObj.IRP_MJ_DIRECTORY_CONTROL = major_functions[12].v()
            driverObj.IRP_MJ_FILE_SYSTEM_CONTROL = major_functions[13].v()
            driverObj.IRP_MJ_DEVICE_CONTROL = major_functions[14].v()
            driverObj.IRP_MJ_INTERNAL_DEVICE_CONTROL = major_functions[15].v()
            driverObj.IRP_MJ_SHUTDOWN = major_functions[16].v()
            driverObj.IRP_MJ_LOCK_CONTROL = major_functions[17].v()
            driverObj.IRP_MJ_CLEANUP = major_functions[18].v()
            driverObj.IRP_MJ_CREATE_MAILSLOT = major_functions[19].v()
            driverObj.IRP_MJ_QUERY_SECURITY = major_functions[20].v()
            driverObj.IRP_MJ_SET_SECURITY = major_functions[21].v()
            driverObj.IRP_MJ_POWER = major_functions[22].v()
            driverObj.IRP_MJ_SYSTEM_CONTROL = major_functions[23].v()
            driverObj.IRP_MJ_DEVICE_CHANGE = major_functions[24].v()
            driverObj.IRP_MJ_QUERY_QUOTA = major_functions[25].v()
            driverObj.IRP_MJ_SET_QUOTA = major_functions[26].v()
            driverObj.IRP_MJ_PNP = major_functions[27].v()

            # Use DriverExtension struct to get some additional information
            try:
                driver_extension = driver_object.DriverExtension
                driverObj.ServiceKeyName = driver_extension.ServiceKeyName or '<UNAVAILABLE>'
                driverObj.DriverObj_Location = driver_object.obj_native_vm.vtop(
                    driver_extension.DriverObject.v()) or 0

            except:
                # I guess we just won't have this data
                driverObj.ServiceKeyName = '<UNAVAILABLE>'
                driverObj.DriverObj_Location = 0

            #associated devices
            for device_name, device_object in devices:
                if device_object.obj_native_vm.vtop(
                        device_object.DriverObject.v()) == driver_object.v():
                    deviceObj = driverObj.Driver_Device_List.Device.add(
                        Name=device_name,
                        DeviceObj_Location=device_object.v() or 0,
                        DriverObj_Location=device_object.obj_native_vm.vtop(
                            device_object.DriverObject.v() or 0) or 0,
                        NextDeviceObj_Location=device_object.obj_native_vm.
                        vtop(device_object.NextDevice.v() or 0) or 0,
                        AttachedDeviceObj_Location=device_object.obj_native_vm.
                        vtop(device_object.AttachedDevice.v() or 0) or 0)

        file = open(config.OUTPUT_PATH + "drivers.xml", "w")
        #file.write(driverObjList.SerializeToString())
        file.write(proto2xml(driverObjList, indent=0))
        logging.debug("Completed exporting the drivers on the system")
예제 #13
0
    def execute(self,options,config,yarapath):
        addr_space = utils.load_as(config)

        if not os.path.isfile("kdcopydatablock.txt"):
            if (addr_space.profile.metadata.get("os") == "windows" and addr_space.profile.metadata.get("memory_model") == "64bit" and addr_space.profile.metadata.get("major") >= 6 and addr_space.profile.metadata.get("minor") >= 2):
                kdbg = tasks.get_kdbg(addr_space)
                fout = open('kdcopydatablock.txt', 'w')
                kdblockaddr = '{0:#x}'.format(kdbg.KdCopyDataBlock)
                fout.write(kdblockaddr)
                fout.close()
                sys.argv.append("--kdbg")
                sys.argv.append(kdblockaddr)
        
        processList = tasks.pslist(addr_space)

        if adutils.getConfigValue(options,'sockets') == True:
            getSocketsDelegate = adsockets.getSocketsFactory(addr_space.profile)
            sockets = getSocketsDelegate(config,addr_space)

        if adutils.getConfigValue(options,'yarascan') == True:
            getYaraDelegate = adyarascan.getYaraFactory(addr_space.profile)
            config.update('YARA_RULES_DIRECTORY',yarapath)
            compiledrules = getYaraDelegate(config).compile_rules()

        list_head_offset = None
        has_service_table = False

        process_obj_list = datastructs.rootType()

        for processIndex, eprocess in enumerate(processList):
            config.process_id = eprocess.UniqueProcessId
            config.dtb = eprocess.Pcb.DirectoryTableBase

            all_mods = list(eprocess.get_load_modules())

            # get Token for Privileges
            token = eprocess.Token.dereference_as('_TOKEN')
            if hasattr(token.Privileges, 'Present'):
                privileges = token.Privileges.Present
            else:
                # Current memory analysis erroneously points
                # to token.ModifiedId for privileges for XP
                # The line below will match what the current memory analysis collects:
                # privileges = token.ModifiedId.LowPart
                # I don't think this is correct, either.
                luid = token.Privileges.dereference_as('_LUID_AND_ATTRIBUTES')
                privileges = luid.Luid.LowPart
            
            validName = "Unknown"    
            if eprocess.ImageFileName:
                validName = eprocess.ImageFileName
            name = self.get_full_name(name=validName, path=eprocess.Peb.ProcessParameters.ImagePathName or '')
            try:
                process_obj = process_obj_list.Process.add(
                    resultitemtype=18,
                    Name=name,
                    Path=adutils.SmartUnicode(eprocess.Peb.ProcessParameters.ImagePathName or ""),
                    StartTime=adutils.SmartUnicode(eprocess.CreateTime or ""),
                    WorkingDir=adutils.SmartUnicode(eprocess.Peb.ProcessParameters.CurrentDirectory.DosPath or ""),
                    CommandLine=adutils.SmartUnicode(eprocess.Peb.ProcessParameters.CommandLine or ""),
                    LinkTime=0,
                    Subsystem=long(eprocess.Peb.ImageSubsystem),
                    Imagebase=long(eprocess.Peb.ImageBaseAddress),
                    Characteristics=0,
                    Checksum=0,
                    KernelTime=long(eprocess.Pcb.KernelTime),
                    UserTime=long(eprocess.Pcb.UserTime),
                    Privileges=long(privileges),
                    PID=int(eprocess.UniqueProcessId),
                    ParentPID=int(eprocess.InheritedFromUniqueProcessId),
                    User='',
                    Group='',
                    MD5=BLANK_MD5,
                    SHA1=BLANK_SHA1,
                    FuzzySize=0,
                    Fuzzy='',
                    Fuzzy2X='',
                    KFFStatus=0,
                    FromMemory='',
                    EffectiveUser='',
                    EffectiveGroup='',
                    Size=calculate_image_size(eprocess),
                    EProcBlockLoc=long(eprocess.obj_vm.vtop(eprocess.obj_offset)) or 0,
                    WindowTitle=adutils.SmartUnicode(eprocess.Peb.ProcessParameters.WindowTitle or "")
                )
            except:
                debug.info('Caught error in adding process, continuing')
                continue

            kthread = eprocess.Pcb.ThreadListHead.Flink.dereference_as('_KTHREAD')
            list_head_offset = kthread.ThreadListEntry.obj_offset - kthread.obj_offset
            kthread = obj.Object('_KTHREAD', offset=eprocess.Pcb.ThreadListHead.Flink - list_head_offset, vm=eprocess.obj_vm)
            if hasattr(kthread, 'ServiceTable'):
                SDTs = set()
                for i in range(eprocess.ActiveThreads):
                    if _is_valid_service_table_address(address=kthread.ServiceTable, memory_model=eprocess.obj_vm.profile.metadata.get('memory_model', '32bit')):
                        SDTs.add(long(kthread.ServiceTable))
                    kthread = obj.Object('_KTHREAD', offset=kthread.ThreadListEntry.Flink - list_head_offset, vm=eprocess.obj_vm)
                for sdt in SDTs:
                    process_obj.SDT.append(sdt)

            if adutils.getConfigValue(options,'processdlls') == True:
                for moduleIndex, module in enumerate(all_mods):
                    baseName = "Unknown"
                    if module.BaseDllName:
                        baseName = module.BaseDllName
                    dll_obj = process_obj.Loaded_DLL_List.DLL.add(
                        Name=adutils.SmartUnicode(baseName or ''),
                        Description='',
                        Path=adutils.SmartUnicode(module.FullDllName or ''),
                        Version='',
                        MD5=BLANK_MD5,
                        SHA1=BLANK_SHA1,
                        FuzzySize=0,
                        Fuzzy='',
                        Fuzzy2X='',
                        CreateTime=u"0000-00-00 00:00:00", #adutils.SmartUnicode(module.TimeDateStamp),
                        KFFStatus=0,
                        PID=int(eprocess.UniqueProcessId),
                        baseAddress=long(module.DllBase),
                        ImageSize=long(module.SizeOfImage),
                        ProcessName=name,
                        FromMemory=''
                    )
            if adutils.getConfigValue(options,'sockets') == True:
                pid = int(eprocess.UniqueProcessId)
                if pid in sockets:
                    process_obj.Open_Sockets_List.CopyFrom(sockets[pid])

            if adutils.getConfigValue(options,'handles') == True:
                if eprocess.ObjectTable.HandleTableList:
                    for handle in eprocess.ObjectTable.handles():
                        if not handle.is_valid():
                            continue
                        handle_obj = process_obj.Open_Handles_List.OpenHandle.add(
                            ID=long(handle.HandleValue),
                            Type=adutils.SmartUnicode(handle.get_object_type()),
                            Path=get_handle_name(handle),
                            AccessMask=int(handle.GrantedAccess),
                            Name='',
                            PID=int(eprocess.UniqueProcessId),
                            PointerCount=long(handle.PointerCount),
                            ObjectAddress=long(handle.obj_offset),
                            FromMemory='',
                            Owner='',
                            Group='',
                            Permissions=''
                        )
            if adutils.getConfigValue(options,'vad') == True:
                for vad in eprocess.VadRoot.traverse():
                    longflags = 0
                    if hasattr(vad, 'u'):
                        longflags = long(vad.u.LongFlags)
                    elif hasattr(vad, 'Core'):
                        longflags = long(vad.Core.u.LongFlags)
                    vad_obj = process_obj.Vad_List.Vad.add(
                        Protection=int(vad.VadFlags.Protection),
                        StartVpn=long(vad.Start >> PAGE_SIZE),
                        EndVpn=long(vad.End >> PAGE_SIZE),
                        Address=long(vad.obj_offset),
                        Flags=longflags,
                        Mapped=u'False',
                        ProcessName=process_obj.Name,
                        PID=process_obj.PID,
                        FromMemory='')
                    if not vad.Tag in _MMVAD_SHORT_TAGS:
                        if vad.FileObject and vad.FileObject.FileName:
                            name = str(vad.FileObject.FileName)
                            if len(name) > 0 and name[0] == '\\':
                                vad_obj.Filename = adutils.SmartUnicode(name)
                                vad_obj.Mapped = u'True'
                            else:
                                print name

            if adutils.getConfigValue(options,'yarascan') == True:
                pid = int(eprocess.UniqueProcessId)
                config.update('pid',str(pid))
                yara = getYaraDelegate(config).calculateonvad(compiledrules, eprocess)
                try:
                    for hit in yara:
                        process_obj.YaraHits.YaraHit.add(
                            id='',
                            Name=hit[2].rule,
                            Category='')
                except:
                    debug.info('Caught error in adding yarahit, continuing')

        file = open(config.OUTPUT_PATH + "processes.xml", "w")
        #file.write(process_obj_list.SerializeToString())
        file.write(proto2xml(process_obj_list,indent=0))
예제 #14
0
    def doDrivers(self, config, drivers, devices):
        print "Doing DoDrivers"

        driverObjList = driverdatastructs.rootType()

        for driver_name, driver_object in drivers:
            driverObj = driverObjList.Driver.add(resultitemtype=5) #ResultDriverItem

            baseaddress = driver_object.DriverStart.v()
            module = find_module(config, baseaddress)
            driverObj.ImagePath=module.FullDllName.v() if module and module.FullDllName else ''

            driverObj.BaseAddress=baseaddress
            driverObj.Type=driver_object.Type.v()
            driverObj.DeviceObj_Location=driver_object.obj_native_vm.vtop(driver_object.DeviceObject.v()) or 0
            driverObj.Driver_Init=driver_object.DriverInit.v()
            driverObj.Driver_StartIO=driver_object.DriverStartIo.v()
            driverObj.Driver_Unload=driver_object.DriverUnload.v()
            driverObj.StartTime='0000-00-00 00:00:00' # currently we don't have a reliable source for this info
            driverObj.Dependencies='' # this is a linux thing
            driverObj.Size=driver_object.DriverSize.v()
            driverObj.Instances=0 # this is a linux thing
            driverObj.Name=adutils.SmartUnicode(driver_object.DriverName.v() or "Unknown")
            driverObj.StartedAs=''
            driverObj.State=4 #running
            driverObj.RealState=-1 #unknown
            driverObj.StartMode=-1 #unknown
            driverObj.RealStartMode=-1 #unknown
            driverObj.RealType=0 #unknown
            driverObj.Path=''
            driverObj.plist=''
            driverObj.MD5=BLANK_MD5
            driverObj.SHA1=BLANK_SHA1
            #Leave out FuzzyHash for now
            #FuzzySize =
            #Fuzzy =
            #Fuzzy2X =
            driverObj.KFFStatus=0 #I guess we don't do this
            driverObj.processid=0 #meaningless for drivers

            major_functions = driver_object.MajorFunction
            driverObj.IRP_MJ_CREATE=major_functions[0].v()
            driverObj.IRP_MJ_CREATE_NAMED_PIPE=major_functions[1].v()
            driverObj.IRP_MJ_CLOSE=major_functions[2].v()
            driverObj.IRP_MJ_READ=major_functions[3].v()
            driverObj.IRP_MJ_WRITE=major_functions[4].v()
            driverObj.IRP_MJ_QUERY_INFORMATION=major_functions[5].v()
            driverObj.IRP_MJ_SET_INFORMATION=major_functions[6].v()
            driverObj.IRP_MJ_QUERY_EA=major_functions[7].v()
            driverObj.IRP_MJ_SET_EA=major_functions[8].v()
            driverObj.IRP_MJ_FLUSH_BUFFERS=major_functions[9].v()
            driverObj.IRP_MJ_QUERY_VOLUME_INFORMATION=major_functions[10].v()
            driverObj.IRP_MJ_SET_VOLUME_INFORMATION=major_functions[11].v()
            driverObj.IRP_MJ_DIRECTORY_CONTROL=major_functions[12].v()
            driverObj.IRP_MJ_FILE_SYSTEM_CONTROL=major_functions[13].v()
            driverObj.IRP_MJ_DEVICE_CONTROL=major_functions[14].v()
            driverObj.IRP_MJ_INTERNAL_DEVICE_CONTROL=major_functions[15].v()
            driverObj.IRP_MJ_SHUTDOWN=major_functions[16].v()
            driverObj.IRP_MJ_LOCK_CONTROL=major_functions[17].v()
            driverObj.IRP_MJ_CLEANUP=major_functions[18].v()
            driverObj.IRP_MJ_CREATE_MAILSLOT=major_functions[19].v()
            driverObj.IRP_MJ_QUERY_SECURITY=major_functions[20].v()
            driverObj.IRP_MJ_SET_SECURITY=major_functions[21].v()
            driverObj.IRP_MJ_POWER=major_functions[22].v()
            driverObj.IRP_MJ_SYSTEM_CONTROL=major_functions[23].v()
            driverObj.IRP_MJ_DEVICE_CHANGE=major_functions[24].v()
            driverObj.IRP_MJ_QUERY_QUOTA=major_functions[25].v()
            driverObj.IRP_MJ_SET_QUOTA=major_functions[26].v()
            driverObj.IRP_MJ_PNP=major_functions[27].v()

            # Use DriverExtension struct to get some additional information
            try:
                driver_extension = driver_object.DriverExtension
                driverObj.ServiceKeyName=driver_extension.ServiceKeyName or '<UNAVAILABLE>'
                driverObj.DriverObj_Location=driver_object.obj_native_vm.vtop(driver_extension.DriverObject.v()) or 0

            except:
                # I guess we just won't have this data
                driverObj.ServiceKeyName='<UNAVAILABLE>'
                driverObj.DriverObj_Location=0

            #associated devices
            for device_name, device_object in devices:
                if device_object.obj_native_vm.vtop(device_object.DriverObject.v()) == driver_object.v():
                    deviceObj = driverObj.Driver_Device_List.Device.add(
                        Name=device_name,
                        DeviceObj_Location=device_object.v() or 0,
                        DriverObj_Location=device_object.obj_native_vm.vtop(device_object.DriverObject.v() or 0) or 0,
                        NextDeviceObj_Location=device_object.obj_native_vm.vtop(device_object.NextDevice.v() or 0) or 0,
                        AttachedDeviceObj_Location= device_object.obj_native_vm.vtop(device_object.AttachedDevice.v() or 0) or 0
                    )

        file = open(config.OUTPUT_PATH + "drivers.xml", "w")
        #file.write(driverObjList.SerializeToString())
        file.write(proto2xml(driverObjList,indent=0))
        logging.debug("Completed exporting the drivers on the system")