def main(args): vm_name = args['<vm_name>'] symbol = args['<symbol>'] # register SIGINT signal.signal(signal.SIGINT, signal_handler) with Libvmi(vm_name, INIT_DOMAINNAME | INIT_EVENTS) as vmi: vaddr = vmi.translate_ksym2v(symbol) debug_event = DebugEvent(debug_callback) num_vcpus = vmi.get_num_vcpus() sstep_event = SingleStepEvent(range(num_vcpus), enable=False, callback=sstep_callback) with pause(vmi): vmi.register_event(debug_event) vmi.register_event(sstep_event) # set dr0 to our address vmi.set_vcpureg(vaddr, X86Reg.DR0.value, 0) toggle_dr0(vmi, True) # listen while not interrupted: print("Waiting for events") vmi.listen(1000) print("Stop listening") with pause(vmi): vmi.clear_event(debug_event) vmi.clear_event(sstep_event)
def __enter__(self): # init LibVMI self.vmi = Libvmi(self.vm_name, init_flags=INIT_DOMAINNAME | INIT_EVENTS, partial=True) self.vmi.init_paging(flags=0) # catch every exception to force a clean exit with __exit__ # where vmi.destroy() must be called try: # determine debug context if not self.process: self.ctx = RawDebugContext(self.vmi) else: self.vmi.init_os() ostype = self.vmi.get_ostype() if ostype == VMIOS.WINDOWS: self.ctx = WindowsDebugContext(self.vmi, self.process) elif ostype == VMIOS.LINUX: self.ctx = LinuxDebugContext(self.vmi, self.process) else: raise RuntimeError('unhandled ostype: {}'.format( ostype.value)) self.ctx.attach() self.attached = True except: logging.exception('Exception while initializing debug context') return self
def main(args): logging.basicConfig(level=logging.INFO) vm_name = args['<vm_name>'] # register SIGINT signal.signal(signal.SIGINT, signal_handler) # 1 - init LibVMI kvm_socket = { VMIInitData.KVMI_SOCKET: args['--kvmi-socket'] } if args['--kvmi-socket'] else None with Libvmi(vm_name, INIT_DOMAINNAME | INIT_EVENTS, init_data=kvm_socket, partial=True) as vmi: counter = Counter() # 2 - define CR3 callback def cr3_callback(vmi, event): cr3_value = event.value logging.info("CR3 change: %s", hex(cr3_value)) counter[hex(cr3_value)] += 1 # 3 - define and register CR3-write event with pause(vmi): # register CR3-write event reg_event = RegEvent(X86Reg.CR3, RegAccess.W, cr3_callback) vmi.register_event(reg_event) # 4 - listen for events for i in range(0, 100): vmi.listen(500) logging.info(counter)
def vmiev(domain): vm_config = DOMAIN_CONFIGS[domain.name()] with Libvmi(domain.name(), INIT_DOMAINNAME | INIT_EVENTS, config_mode=VMIConfig.DICT, config=vm_config) as vmi: yield vmi
def main(args): logging.basicConfig(level=logging.INFO) vm_name = args['<vm_name>'] # register SIGINT signal.signal(signal.SIGINT, signal_handler) kvm_socket = {VMIInitData.KVMI_SOCKET: args['--kvmi-socket']} if args['--kvmi-socket'] else None with Libvmi(vm_name, INIT_DOMAINNAME | INIT_EVENTS, init_data=kvm_socket, partial=True) as vmi: # init paging to translate virtual addresses vmi.init_paging(0) with pause(vmi): # get current RIP on VCPU 0 rip = vmi.get_vcpureg(X86Reg.RIP.value, 0) # get DTB cr3 = vmi.get_vcpureg(X86Reg.CR3.value, 0) dtb = cr3 & ~0xfff # get gpa paddr = vmi.pagetable_lookup(dtb, rip) gfn = paddr >> 12 # define callback def cb_mem_event(vmi, event): logging.info("Mem event at RIP: %s, frame: %s, offset: %s, permissions: %s", hex(event.x86_regs.rip), hex(event.gla), hex(event.offset), event.out_access.name) mem_event = MemEvent(MemAccess.X, cb_mem_event, gfn=gfn) vmi.register_event(mem_event) # listen while not interrupted: vmi.listen(3000) logging.info("stop listening")
def main(args): if len(args) != 3: print("./mem_vmi.py <process_name> <string_addr>") return 1 vm_name = "ubuntu16.04" process_name = args[1] string_addr = args[2] with Libvmi( vm_name ) as vmi: #class Libvmi,the default parameters calls vmi_init_complete #init offsets values, init libvmi library tasks_offset = vmi.get_offset("linux_tasks") name_offset = vmi.get_offset("linux_name") pid_offset = vmi.get_offset("linux_pid") #pause vm for consistent memory access with pause(vmi): pids = get_pid_by_name(vmi, process_name) if not pids: print("Cannot find process %s" % process_name) pid = pids[0] print("process %s:%d" % (process_name, pid)) #get output string of exp string = vmi.read_str_va(int(string_addr, 16), pid) print("output:%s" % string) #alter output string of exp vmi.write_8_va(int(string_addr, 16), pid, 0x77) return 0
def main(args): if len(args) != 2: print('./process-list.py <vm_name>') return 1 vm_name = args[1] with Libvmi(vm_name) as vmi: # get ostype os = vmi.get_ostype() # init offsets values tasks_offset = None name_offset = None pid_offset = None if os == VMIOS.LINUX: tasks_offset = vmi.get_offset("linux_tasks") name_offset = vmi.get_offset("linux_name") pid_offset = vmi.get_offset("linux_pid") elif os == VMIOS.WINDOWS: tasks_offset = vmi.get_offset("win_tasks") name_offset = vmi.get_offset("win_pname") pid_offset = vmi.get_offset("win_pid") else: logging.info("Unknown OS") return 1 # pause vm with pause(vmi): # demonstrate name and id accessors name = vmi.get_name() id = vmi.get_vmid() logging.info("Process listing for VM %s (id: %s)", name, id) if os == VMIOS.LINUX: list_head = vmi.translate_ksym2v("init_task") list_head += tasks_offset elif os == VMIOS.WINDOWS: list_head = vmi.read_addr_ksym("PsActiveProcessHead") else: return 1 cur_list_entry = list_head next_list_entry = vmi.read_addr_va(cur_list_entry, 0) while True: current_process = cur_list_entry - tasks_offset pid = vmi.read_32_va(current_process + pid_offset, 0) procname = vmi.read_str_va(current_process + name_offset, 0) logging.info("[%s] %s (struct addr:%s)", pid, procname, hex(current_process)) cur_list_entry = next_list_entry next_list_entry = vmi.read_addr_va(cur_list_entry, 0) if os == VMIOS.WINDOWS and next_list_entry == list_head: break elif os == VMIOS.LINUX and cur_list_entry == list_head: break
def __init__(self, vm_name, process_name): self.log = logging.getLogger(__class__.__name__) self.vm_name = vm_name self.target_name = process_name self.target_pid = None self.target_dtb = None self.vmi = Libvmi(self.vm_name, INIT_DOMAINNAME | INIT_EVENTS) self.kernel_base = self.get_kernel_base() logging.info('kernel base address: %s', hex(self.kernel_base))
def __init__(self, base, config, layered=False, **kwargs): self.as_assert(libvmi, "The LibVMI python bindings must be installed") addrspace.BaseAddressSpace.__init__(self, base, config, **kwargs) self.as_assert(base is None or layered, 'Must be first Address Space') self.as_assert(config.LOCATION.startswith("vmi://"), "Location doesn't start with vmi://") domain = config.LOCATION[len("vmi://"):] self.vmi = Libvmi(domain, partial=True) self.dtb = self.vmi.get_vcpu_reg(CR3, 0)
def main(args): if len(args) != 2: print('./module-list.py <vm_name>') return 1 vm_name = args[1] with Libvmi(vm_name) as vmi: # pause vm for consistent memory access with pause(vmi): next_module = None # get ostype os = vmi.get_ostype() if os == VMIOS.LINUX: next_module = vmi.read_addr_ksym("modules") elif os == VMIOS.WINDOWS: next_module = vmi.read_addr_ksym("PsLoadedModuleList") else: logging.info("Unknown OS") list_head = next_module # walk the module list while True: # follow the next pointer tmp_next = vmi.read_addr_va(next_module, 0) # if we are back at the list head, we are done if list_head == tmp_next: break modname = None # print out the module name if os == VMIOS.LINUX: if page_mode == PageMode.IA32E: modname = vmi.read_str_va(next_module + 16, 0) else: modname = vmi.read_str_va(next_module + 8, 0) elif os == VMIOS.WINDOWS: page_mode = vmi.get_page_mode(0) if page_mode == PageMode.IA32E: modname = vmi.read_unicode_str_va( next_module + 0x58, 0) else: modname = vmi.read_unicode_str_va( next_module + 0x2c, 0) else: logging.info("Unkown OS") if modname is not None: logging.info(modname) next_module = tmp_next
def get_backend(domain, listener, syscall_filtering): """Return backend based on libvmi configuration. If analyze if False, returns a dummy backend that does not analyze system calls. Returns None if the backend is missing """ libvmi = Libvmi(domain.name()) os_type = libvmi.get_ostype() try: return BACKENDS[os_type](domain, libvmi, listener, syscall_filtering) except KeyError: raise BackendNotFoundError('Unable to find an appropritate backend for' 'this OS: {}'.format(os_type))
def main(args): if len(args) != 3: print('Incorrect number of args', args) print('arg 2', args[1]) return init_config() vm_name = args[1] p_id = args[2] print('Received : vm_name = ' + vm_name + ' , p_id = ' + p_id) vmi = Libvmi(vm_name) result = change_uid_process(vmi, p_id) if result: print("uid changed successfully!") else: print("something went wrong!")
def __init__(self, base=None, filename=None, session=None, **kwargs): self.as_assert(libvmi, "The LibVMI python bindings must be installed") self.as_assert(base is None, "must be first Address Space") self.session = session url = filename or (session and session.GetParameter("filename")) self.as_assert(url, "Filename must be specified in session (e.g. " "session.SetParameter('filename', 'vmi://domain').") self.as_assert(url.startswith(URL_PREFIX), "The domain must be passed with the URL prefix {}".format(URL_PREFIX)) domain = url[len(URL_PREFIX):] self.as_assert(domain, "domain name missing after {}".format(URL_PREFIX)) super(VMIAddressSpace, self).__init__(base=base, session=session, **kwargs) self.vmi = Libvmi(domain, partial=True)
def __init__(self, vm_name, process_name): self.log = logging.getLogger(__class__.__name__) self.vm_name = vm_name self.full_system_mode = False self.target_name = process_name self.target_pid = None if process_name is None: self.full_system_mode = True self.target_name = 'kernel' # kernel space is represented by PID 0 in LibVMI self.target_pid = 0 self.target_dtb = None self.vmi = Libvmi(self.vm_name, INIT_DOMAINNAME | INIT_EVENTS) self.kernel_base = self.get_kernel_base() if self.kernel_base: logging.info('kernel base address: %s', hex(self.kernel_base))
def get_backend(domain, listener, syscall_filtering): """ Return a suitable backend based on guest operating system. :param domain: libvirt domain :returns: new backend instance :rtype: Backend :raises: BackendNotFoundError """ libvmi = Libvmi(domain.name()) os_type = libvmi.get_ostype() try: return BACKENDS[os_type](domain, libvmi, listener, syscall_filtering) except KeyError: raise BackendNotFoundError('Unable to find an appropritate backend for' 'this OS: {}'.format(os_type))
def main(args): if len(args) != 2: print('./memaccess-event.py <vm_name>') return 1 vm_name = args[1] # register SIGINT signal.signal(signal.SIGINT, signal_handler) with Libvmi(vm_name, INIT_DOMAINNAME | INIT_EVENTS) as vmi: reg_event = RegEvent(X86Reg.CR3, RegAccess.W, callback) vmi.register_event(reg_event) # listen while not interrupted: print("Waiting for events") vmi.listen(3000) print("Stop listening")
def main(args): vm_name = args['<vm_name>'] symbol = args['<symbol>'] sstep_enabled = args['--sstep'] # register SIGINT signal.signal(signal.SIGINT, signal_handler) with Libvmi(vm_name, INIT_DOMAINNAME | INIT_EVENTS) as vmi: vaddr = vmi.translate_ksym2v(symbol) paddr = vmi.translate_kv2p(vaddr) frame = paddr >> 12 print("symbol: {} vaddr: {} paddr: {} frame: {}".format( symbol, hex(vaddr), hex(paddr), hex(frame))) user_data = { 'symbol': symbol, 'target_vaddr': vaddr, 'target_gfn': frame, 'mem_event': None, 'sstep': sstep_enabled } num_vcpus = vmi.get_num_vcpus() ss_event = SingleStepEvent(range(num_vcpus), cb_ss_event, data=user_data, enable=False) mem_event = MemEvent(MemAccess.X, cb_mem_event, gfn=frame, data=user_data) user_data['mem_event'] = mem_event with pause(vmi): vmi.register_event(ss_event) vmi.register_event(mem_event) # listen while not interrupted: print("Waiting for events ({})".format(vmi.are_events_pending())) vmi.listen(3000) print("Stop listening") with pause(vmi): vmi.clear_event(mem_event)
def main(args): if len(args) != 2: print('./singlestep-event.py <vm_name>') return 1 vm_name = args[1] # register SIGINT signal.signal(signal.SIGINT, signal_handler) counter = 0 with Libvmi(vm_name, INIT_DOMAINNAME | INIT_EVENTS) as vmi: num_vcpus = vmi.get_num_vcpus() ss_event = SingleStepEvent(range(num_vcpus), callback, data=counter) vmi.register_event(ss_event) # listen while not interrupted: print("Waiting for events") vmi.listen(500) print("Stop listening") counter = ss_event.data print("Singlestepped {} instructions".format(counter))
def __init__(self, base=None, filename=None, session=None, **kwargs): self.as_assert(libvmi, "The LibVMI python bindings must be installed") self.as_assert(base is None, "must be first Address Space") self.session = session url = filename or (session and session.GetParameter("filename")) self.as_assert( url, "Filename must be specified in session (e.g. " "session.SetParameter('filename', 'vmi:///domain').") vmi_url = urlparse(url) self.as_assert(vmi_url.scheme == SCHEME, "URL scheme must be vmi://") self.as_assert(vmi_url.path, "No domain name specified") domain = vmi_url.path[1:] # hypervisor specified ? self.mode = None hypervisor = vmi_url.netloc if hypervisor: self.mode = VMIMode[hypervisor.upper()] # query parameters ? self.volatile = True if vmi_url.query: params = parse_qs(vmi_url.query, strict_parsing=True) try: self.volatile = strtobool((params['volatile'][0])) except KeyError: raise RuntimeError('Invalid query parameters in vmi:// URI') # build Libvmi instance super(VMIAddressSpace, self).__init__(base=base, session=session, **kwargs) self.vmi = Libvmi(domain, mode=self.mode, partial=True) self.min_addr = 0 self.max_addr = self.vmi.get_memsize() - 1 # pause in case volatile has been disabled if not self.volatile: self.vmi.pause_vm() # register flush hook to destroy vmi instance when session.Flush() is called session.register_flush_hook(self, self.close)
def __enter__(self): # init LibVMI self.vmi = Libvmi(self.vm_name, init_flags=INIT_DOMAINNAME | INIT_EVENTS, partial=True) self.vmi.init_paging(flags=0) # catch every exception to force a clean exit with __exit__ # where vmi.destroy() must be called try: # determine debug context if not self.process: self.ctx = RawDebugContext(self.vmi) else: self.vmi.init_os() ostype = self.vmi.get_ostype() if ostype == VMIOS.WINDOWS: self.ctx = WindowsDebugContext(self.vmi, self.process) elif ostype == VMIOS.LINUX: self.ctx = LinuxDebugContext(self.vmi, self.process) else: raise RuntimeError('unhandled ostype: {}'.format( ostype.value)) # register some events # register interrupt event self.int_event = IntEvent(self.cb_on_int3) self.vmi.register_event(self.int_event) # single step event to handle wrong hits by sw breakpoints # enabled via EventResponse.TOGGLE_SINGLESTEP num_vcpus = self.vmi.get_num_vcpus() self.ss_event_recoil = SingleStepEvent(range(num_vcpus), self.cb_on_sstep_recoil, enable=False) self.vmi.register_event(self.ss_event_recoil) self.ctx.attach() self.attached = True except: logging.exception('Exception while initializing debug context') return self
def _init_vmi(self): """ Initialize LibVMI """ self._vmi = Libvmi(self._vm.name) # get ostype self._os = self._vmi.get_ostype() # init offsets values self._tasks_offset = None self._name_offset = None self._pid_offset = None if self._os == VMIOS.LINUX: self._tasks_offset = self._vmi.get_offset("linux_tasks") self._name_offset = self._vmi.get_offset("linux_name") self._pid_offset = self._vmi.get_offset("linux_pid") elif self._os == VMIOS.WINDOWS: self._tasks_offset = self._vmi.get_offset("win_tasks") self._name_offset = self._vmi.get_offset("win_pname") self._pid_offset = self._vmi.get_offset("win_pid") else: self.logger.error("Unknown OS") return 0 return 1
def main(args): logging.basicConfig(level=logging.INFO) vm_name = args['<vm_name>'] # register SIGINT signal.signal(signal.SIGINT, signal_handler) kvm_socket = { VMIInitData.KVMI_SOCKET: args['--kvmi-socket'] } if args['--kvmi-socket'] else None with Libvmi(vm_name, INIT_DOMAINNAME | INIT_EVENTS, init_data=kvm_socket, partial=True) as vmi: msr_counter = Counter() def msr_callback(vmi, event): try: name = MSR_NAME[event.msr] except KeyError: name = 'MSR' logging.info("%s %s = %s", name, hex(event.msr), hex(event.value)) msr_counter[event.msr] += 1 # EternalBlue exploitation ? if msr_counter[0x176] > 1: logging.warn('MSR 0x176 modified %s times !', msr_counter[0x176]) with pause(vmi): # register MSR event reg_event = RegEvent(MSR.ALL, RegAccess.W, msr_callback) vmi.register_event(reg_event) logging.info("listening") while not interrupted: vmi.listen(500)
target_task = get_task(addr_space, target_pid) if not target_task: print("Task with PID {} not found!".format(target_pid)) sys.exit() # Get a task with root permissions, PID 1 is reliably root always task_with_root = get_task(addr_space, 1) # Get Physical addresses for root task credentials pointers root_real_cred_pa, root_cred_pa = get_credentails_pa( addr_space, task_with_root) # Get physical addresses for target task credentials pointers target_real_cred_pa, target_cred_pa = get_credentails_pa( addr_space, target_task) # Initialize libvmi for writing. Note: the library initialize undesired "[][][]" vmi = Libvmi(pvm_name) # Write root "cred" pointer value to "cred" attribute of the target task root_cred_pointer = addr_space.read_long_long_phys(root_cred_pa) vmi.write_64_pa(target_cred_pa, root_cred_pointer) # Write root "real_cred" pointer value to "real_cred" attribute of the target task root_real_cred_pointer = addr_space.read_long_long_phys(root_real_cred_pa) vmi.write_64_pa(target_real_cred_pa, root_real_cred_pointer) print("\nSuccess!") except Exception as e: print("\nFailed to change UID: {}".format(str(e)))
def vmi(domain): vm_config = DOMAIN_CONFIGS[domain.name()] with Libvmi(domain.name(), config_mode=VMIConfig.DICT, config=vm_config) as vmi: yield vmi
"python /usr/src/volatility/vol.py --profile=LinuxDebian8x64 -f /mnt/mem linux_hidden_modules" ).read() loaded_mods = os.popen( "python /usr/src/volatility/vol.py --profile=LinuxDebian8x64 -f /mnt/mem linux_lsmod" ).read() sp_network = os.popen( "python /usr/src/volatility/vol.py --profile=LinuxDebian8x64 -f /mnt/mem linux_netstat -U | grep -o '[a-z0-9A-Z]*/[0-9]*' | awk -F'/' '{print $2}' | sort | uniq" ).read() sp_lsmod = os.popen( "python /usr/src/volatility/vol.py --profile=LinuxDebian8x64 -f /mnt/mem linux_lsmod | awk '{print $2" "$3}'").read() return (network, hidden_mods, loaded_mods, sp_network, sp_lsmod) if (len(sys.argv) == 4): vmi = Libvmi(sys.argv[1]) f = open(sys.argv[3], 'w') f1 = open("net_be", 'w') f2 = open("lsmod_be", "w") f3 = open("pslist_be", "w") for pid, procname in list_processes(vmi): f.write("%s %s\n" % (pid, procname)) f3.write("%s %s\n" % (pid, procname)) (network, hidden_mods, loaded_mods, sp_network, sp_lsmod) = list_other() f.write("\n%s\n" % network) f.write("%s\n" % hidden_mods) f.write("%s" % loaded_mods) f1.write("%s" % sp_network) f2.write("%s" % sp_lsmod)
import volatility.obj as obj import volatility.addrspace as addrspace import volatility.registry as registry registry.PluginImporter() registry.register_global_options(config, addrspace.BaseAddressSpace) ## Main program starts here: # Initialize address space (same as a=addrspace() in linux_volshell) a=utils.load_as(config) p=a.profile # Lookup kernel symbol pointing to first task task_addr = p.get_symbol("init_task") # Create python object for this task # Note that the "init_task" symbol does not point to the start of the # task_struct data structure "list" element of the data structures. init_task = obj.Object("task_struct", vm=a, offset=task_addr) l = list(init_task.tasks) from libvmi import Libvmi vmi = Libvmi(sys.argv[5]) t_cred_init = l[0].real_cred for t in l: if (t.pid == int(sys.argv[6])): t_cred_pa = a.vtop(t.real_cred.obj_offset) vmi.write_64_pa(t_cred_pa, t_cred_init)