package main
import (
"fmt"
"syscall"
"unsafe"
)
func main() {
// 加载DLL库
dllName := "mydll.dll"
dllHandle, err := syscall.LoadLibrary(dllName)
if err != nil {
fmt.Println("LoadLibrary error:", err)
return
}
defer syscall.FreeLibrary(dllHandle)
// 获取DLL中的函数地址
functionName := "myFunction"
functionAddr, err := syscall.GetProcAddress(dllHandle, functionName)
if err != nil {
fmt.Println("GetProcAddress error:", err)
return
}
// 打开目标进程
targetProcess, err := syscall.OpenProcess(syscall.PROCESS_CREATE_THREAD|syscall.PROCESS_VM_WRITE|syscall.PROCESS_VM_OPERATION, false, targetProcessID)
if err != nil {
fmt.Println("OpenProcess error:", err)
return
}
defer syscall.CloseHandle(targetProcess)
// 在目标进程中分配内存空间
memSize := len(dllName) + 1
remoteMemAddr, err := syscall.VirtualAllocEx(targetProcess, 0, memSize, syscall.MEM_COMMIT|syscall.MEM_RESERVE, syscall.PAGE_READWRITE)
if err != nil {
fmt.Println("VirtualAllocEx error:", err)
return
}
defer syscall.VirtualFreeEx(targetProcess, remoteMemAddr, 0, syscall.MEM_RELEASE)
// 在目标进程中写入DLL名称
dllNameBytes := []byte(dllName)
_, err = syscall.WriteProcessMemory(targetProcess, remoteMemAddr, unsafe.Pointer(&dllNameBytes[0]), uintptr(memSize))
if err != nil {
fmt.Println("WriteProcessMemory error:", err)
return
}
// 在目标进程中创建远程线程,执行DLL中的函数
threadID, err := syscall.CreateRemoteThread(targetProcess, nil, 0, uintptr(functionAddr), remoteMemAddr, 0, nil)
if err != nil {
fmt.Println("CreateRemoteThread error:", err)
return
}
defer syscall.CloseHandle(threadID)
fmt.Println("DLL injected successfully!")
}