Showing posts with label kernel32. Show all posts
Showing posts with label kernel32. Show all posts

Saturday, February 15, 2020

python pefile ctypes kernel32.dll examples

import pefile
import ctypes
kfile = pefile.PE(r'Kernel32.dll')


--- *** displays all exports such as *** ---
for export in kfile.DIRECTORY_ENTRY_EXPORT.symbols:
 print(export.name)


--- *** executes a command like whoami *** ---
k32.WinExec(b'whoami')


--- *** creates a new folder *** ---
k32.CreateDirectoryW(r'c:\users\win10\testfolder', None)


--- *** prints length of a string *** ---
k32.lstrlenA(b'something')

--- *** start and stop a timer *** ---
start = k32.GetTickCount()
end = k32.GetTickCount()
elaspedTime = (end-start)/1000

--- *** get process id for the python.exe program running this code *** ---
k32.GetCurrentProcessId()

--- *** get current working directory *** ---
s=ctypes.create_string_buffer(50)
k32.GetCurrentDirectoryA(len(s), s)
string = ""
for i in s:
 if not i.decode() == "\x00":
  string = string + i.decode()

--- *** get environment variables APPDATA value *** --
s=ctypes.create_string_buffer(50)
k32.GetEnvironmentVariableA(b'APPDATA',s,len(s))
string = ""
for i in s:
 if not i.decode() == "\x00":
  string = string + i.decode()

Thursday, March 29, 2018

debugging create process, dumping executable content

try setting breakpoint on
   kernel32.dll
     CreateProcessInternalA
     CreateProcessInternalW

because those are one of lowest level apis for creating a process and a lot of the higher level api calls will funnel down to this one eventually

then once breakpoint, go to x64dbg Memory Map and look for "Protection=ERW" which means executable, read, and write ... and look for it outside the normal spots

Looking for MZ (to find a full executable in memory)

Once found, in memory map right-click "Dump memory to file" and save this executable

Load into PE Bear
If text segment is all zeros, then it's unmapped, so you must
- copy Virtual Addr. column values to the Raw Addr. column values on the section headers tab
- under optional header tab, change the image base to the 'address' field in the memory map on the x64dbg
- save the executable under a different name


api monitor places to capture unpacked buffer

ntdll.RtlDecompressBuffer (breakpoint AFTER)
_Out_ PUCHAR UncompressedBuffer,

kernel32.WriteProcessMemory (breakpoint BEFORE)
_In_  LPCVOID lpBuffer,