该代码在使用 Windows API 创建可执行内存时,没有指定正确的内存保护级别,导致在执行时发生了内存错误。解决方法是将 windows.VirtualProtect() 函数中的第四个参数改为 windows.PAGE_EXECUTE_READ

修改后的代码如下:

package main

import (
    "golang.org/x/sys/windows"
    "unsafe"
)

func main() {
    shellcode := []byte{0x31, 0xc0, 0x50, 0x68, 0x2e, 0x74, 0x78, 0x74, 0x68, 0x63, 0x6d, 0x64, 0x2e, 0x50, 0x68, 0x6f, 0x77, 0x6e, 0x33, 0x68, 0x74, 0x68, 0x69, 0x73, 0x54, 0xff, 0xd5}

    addr, err := windows.VirtualAlloc(0, uintptr(len(shellcode)),
        windows.MEM_COMMIT|windows.MEM_RESERVE,
        windows.PAGE_EXECUTE_READWRITE)

    if err != nil {
        panic(err)
    }

    var oldProtect uint32
    err = windows.VirtualProtect(addr, uintptr(len(shellcode)), windows.PAGE_EXECUTE_READ, &oldProtect)

    if err != nil {
        panic(err)
    }

    data := (*[1000]byte)(unsafe.Pointer(addr))

    copy(data[:], shellcode)

    f := *(*func())(unsafe.Pointer(&data))

    f()
}
Golang Windows API内存分配错误:`unexpected fault address` 解决方法

原文地址: https://www.cveoy.top/t/topic/lVv2 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录