编写shellcode输出hello world
时间: 2023-09-23 10:07:45 浏览: 39
下面是一个简单的shellcode,可以输出"Hello, world!"。
```assembly
section .text
global _start
_start:
; 使用write系统调用输出
; int write(int fd, const void *buf, size_t count);
; fd = 1 (标准输出), buf = address of "Hello, world!", count = 13
mov eax, 4 ; 系统调用号4表示write
mov ebx, 1 ; 文件描述符1表示标准输出
mov ecx, message ; 消息的地址
mov edx, 13 ; 消息的长度
int 0x80 ; 调用系统调用
; 使用exit系统调用退出
; void exit(int status);
xor eax, eax ; 系统调用号1表示exit
xor ebx, ebx ; 退出状态码为0
int 0x80 ; 调用系统调用
section .data
message db 'Hello, world!', 0x0a ; 要输出的消息
```
将上面的代码保存为一个.asm文件,然后使用nasm编译成二进制文件。
```bash
nasm -f elf32 -o hello.o hello.asm
ld -m elf_i386 -o hello hello.o
```
然后通过以下命令将二进制文件转换成shellcode。
```bash
objdump -d ./hello | grep '[0-9a-f]:' | grep -v 'file' | cut -f2 -d: | cut -f1-6 -d' ' | tr -d ' ' | sed 's/.\{2\}/\\x&/g' | paste -s -d ''
```
得到的shellcode为:
```
\xb8\x04\x00\x00\x00\xbb\x01\x00\x00\x00\xb9\x00\x00\x60\x00\xba\r\x00\x00\x00\xcd\x80\x31\xc0\x31\xdb\xb0\x01\xcd\x80\x48\x65\x6c\x6c\x6f\x2c\x20\x77\x6f\x72\x6c\x64\x21\x0a
```
可以在C代码中使用该shellcode,比如:
```c
#include <stdio.h>
#include <string.h>
const char code[] = "\xb8\x04\x00\x00\x00\xbb\x01\x00\x00\x00\xb9\x00\x00\x60\x00\xba\r\x00\x00\x00\xcd\x80\x31\xc0\x31\xdb\xb0\x01\xcd\x80\x48\x65\x6c\x6c\x6f\x2c\x20\x77\x6f\x72\x6c\x64\x21\x0a";
int main(int argc, char **argv) {
// 分配一块可执行内存
void *buf = mmap(NULL, sizeof(code), PROT_READ | PROT_WRITE | PROT_EXEC, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
memcpy(buf, code, sizeof(code));
// 跳转到shellcode执行
((void(*)())buf)();
return 0;
}
```