在Go中执行字节数组 [英] Executing Byte Array in Go

查看:595
本文介绍了在Go中执行字节数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在Go程序中执行shellcode,类似于您可以使用其他语言来执行。

示例1 - C程序中的Shellcode a>



示例2 - http://www.debasish.in/2012/04/execute-shellcode-using-python.html



所有方法有大致相同的技术 - 通过操作系统特定分配(mmap,virtualalloc等)将shellcode分配给可执行的内存,然后通过在执行之前创建一个指向该位置的函数指针来执行代码。



这是我在Go中执行同样的事情时可怕的黑客例子。 shellcode在传递给函数之前对其执行了操作,所以它的格式为[]字节是固定的。说mmap需要传递一个文件描述符,这就是为什么存在可怕的写入tmp文件部分。

  func osxExec(shellcode [] byte){
f,err:= os.Create(data / shellcode。 tmp)
if err!= nil {
fmt.Println(err)
}
推迟f.Close()
_,_ = f.Write( shellcode)
f.Sync()

b,err:= syscall.Mmap(int(f.Fd()),0,len(shellcode),syscall.PROT_READ | syscall.PROT_WRITE | syscall.PROT_EXEC,syscall.MAP_SHARED)
if err!= nil {
fmt.Println(err)
}

fmt.Printf(%p ,b)
}

在代码的最后我有一个指针(切片?)到我认为是可执行内存的代码中 - 但我不知道如何将此地址转换为执行的函数指针。我询问了一些IRC频道,但有人建议它可能不可能。



非常感谢任何帮助。

干杯。

解决方案

有多种方式可以做到这一点,尽管我自己也没有测试过它们。 b $ b

您可能需要查看 https:// github .com / nelhage / gojit / blob / master / jit.go
它实现了一个基于cgo的解决方案(它更安全,但速度更慢)以及基于直接调用的解决方案。查看所有与构建相关的功能。


I'm trying to execute shellcode within a Go program, similar to how you can do it with other languages.

Example 1 - Shellcode in C program

Example 2 - http://www.debasish.in/2012/04/execute-shellcode-using-python.html

All methods have broadly similar techniques - assign the shellcode to executable memory via the OS specific allocation (mmap, virtualalloc, etc) and then execute the code by creating a function pointer pointing to that location before executing.

Here is my horrible hacky example at performing the same thing in Go. The shellcode has manipulations performed on it before being passed to the function, so it's format as a []byte is fixed. Saying that mmap expects a file descriptor passed in which is why the horrible "writing to a tmp file" section exists.

func osxExec(shellcode []byte) {
    f, err := os.Create("data/shellcode.tmp")
    if err != nil {
        fmt.Println(err)
    }
    defer f.Close()
    _,_ = f.Write(shellcode)
    f.Sync()

    b, err := syscall.Mmap(int(f.Fd()), 0, len(shellcode), syscall.PROT_READ|syscall.PROT_WRITE|syscall.PROT_EXEC, syscall.MAP_SHARED)
    if err != nil {
        fmt.Println(err)
    }

    fmt.Printf("%p", b)
}

At the end of the code I've got a pointer (slice?) to the code in what I presume is executable memory - but I've got no idea how to cast this address into a function pointer for execution. I asked on some IRC channels but it was suggested that it may not be possible.

Any help is greatly appreciated.

Cheers.

解决方案

There are multiple ways to do it, though I have not tested them myself.

You may want to have a look at https://github.com/nelhage/gojit/blob/master/jit.go It implements a solution based on cgo (which is safer, but slower), and a solution based on a direct call. Look at all the build related functions.

这篇关于在Go中执行字节数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆