assembly - 在堆栈上为 execve 创建一个 arg 数组

标签 assembly x86-64 shellcode

我想编写一个汇编程序,通过 EXECVE(系统调用 #0x3C)使用开关 -al 执行程序/bin/ls。

手册页 (man 2 execve) 指出该调用需要三个值:

int execve(const char *文件名, char *const argv[], char *const envp[]);

我不太明白如何构建这三个参数。据我所知,第一个参数进入 RDI,第二个参数进入 RSI,第三个参数进入 RDX。我相信要设置第一个,就足够了

    push 0x736c2f2f         ;sl//
    push 0x6e69622f         ;nib/
    mov rdi, rsp

对于第三个,事情很简单:

    xor r11, r11
    mov rdx, r11

我的问题是我不知道如何构建第二个参数,它应该是一个包含 ['/bin//ls', '-aal']

我需要为 x86-64 编写它,所以请不要使用 int 0x80 建议。

最佳答案

您可以将argv数组放入堆栈并将其地址加载到rsi中。 argv 的第一个成员是指向程序名称的指针,因此我们可以使用加载到 rdi 中的相同地址。

xor edx, edx        ; Load NULL to be used both as the third
                    ; parameter to execve as well as
                    ; to push 0 onto the stack later.
push "-aal"         ; Put second argument string onto the stack.
mov rax, rsp        ; Load the address of the second argument.
mov rcx, "/bin//ls" ; Load the file name string
push rdx            ; and place a null character
push rcx            ; and the string onto the stack.
mov rdi, rsp        ; Load the address of "/bin//ls". This is
                    ; used as both the first member of argv
                    ; and as the first parameter to execve.

; Now create argv.
push rdx            ; argv must be terminated by a NULL pointer.
push rax            ; Second arg is a pointer to "-aal".
push rdi            ; First arg is a pointer to "/bin//ls"
mov rsi, rsp        ; Load the address of argv into the second
                    ; parameter to execve.

这还纠正了问题中代码的一些其他问题。它使用 8 字节推送作为文件名,因为 x86-64 不支持 4 字节推送,并且它确保文件名具有空终止符。

此代码确实使用带有 4 字节立即数的 64 位推送来推送“-aal”,因为该字符串适合 4 个字节。这也使其以空终止,而无需在代码中使用空字节。

我使用了带有双字符的字符串,因为它们在问题中是为了避免代码中出现空字节,但我的偏好是这样的:

mov ecx, "X-al"     ; Load second argument string,
shr ecx, 8          ; shift out the dummy character,
push rcx            ; and write the string to the stack.
mov rax, rsp        ; Load the address of the second argument.
mov rcx, "X/bin/ls" ; Load file name string,
shr rcx, 8          ; shift out the dummy character,
push rcx            ; and write the string onto the stack.

请注意,文件名字符串通过移位获得空终止符,从而避免了额外的推送。此模式适用于双字符不起作用的字符串,并且也可以用于较短的字符串。

关于assembly - 在堆栈上为 execve 创建一个 arg 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59825101/

相关文章:

无法理解简单程序集 x86 中 %rax 的值

c++ - 为什么局部静态对象的初始化使用隐藏的保护标志?

c - gcc 在我的系统上生成什么汇编语言?

assembly - 以下带有 FLDCW 指令的 x86 汇编代码有何作用?

usb - 为什么在 QEMU 上发出 GET_DESCRIPTOR USB 请求后,我会在端点描述符之前获得 2 个接口(interface)描述符?

linux - 如何检查给定 shellcode 执行的命令?

linux - mmap() 系统调用的 prot 参数怎么会是 0x1007?

gdb - Shellcode在gdb中提供SyntaxError

assembly - 在 ARM 程序集中将立即值放入括号中的目的是什么?

c++ - 如何获取指向 Hook 的 COM 方法的指针?