coffee-ldr 0.2.2

Coffee: A COFF loader made in Rust
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
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
// Thanks to: https://github.com/yamakadi/ldr/blob/main/src/functions/mod.rs
// for most of the functions and the idea of how to implement them.
use core::slice;
use std::{
    alloc::Layout,
    ffi::{c_char, c_int, c_short, CStr},
    intrinsics, ptr,
};

use tracing::warn;
use windows::Win32::{
    Foundation::{CloseHandle, HANDLE},
    Security::{GetTokenInformation, RevertToSelf, TokenElevation, TOKEN_ELEVATION, TOKEN_QUERY},
    System::{
        Diagnostics::Debug::WriteProcessMemory,
        Memory::{VirtualAllocEx, MEM_COMMIT, MEM_RESERVE, PAGE_EXECUTE_READWRITE},
        Threading::{
            CreateRemoteThread, GetCurrentProcess, OpenProcess, OpenProcessToken, SetThreadToken,
            PROCESS_INFORMATION, PROCESS_VM_OPERATION, PROCESS_VM_WRITE, STARTUPINFOA,
        },
    },
};

use windows_sys::Win32::{
    Foundation::FreeLibrary,
    System::LibraryLoader::{GetModuleHandleA, GetProcAddress, LoadLibraryA},
};

#[allow(clippy::upper_case_acronyms)]
type BOOL = i32;
const TRUE: BOOL = 1;
const FALSE: BOOL = 0;

// For Windows, we'll use the C runtime directly.
// On MSVC, _vsnprintf is inlined in UCRT and requires legacy_stdio_definitions.lib.
// On GNU, it's already available in the standard C library.
#[cfg_attr(target_env = "msvc", link(name = "legacy_stdio_definitions"))]
extern "C" {
    fn _vsnprintf_s(
        buffer: *mut c_char,
        size_of_buffer: usize,
        count: usize,
        format: *const c_char,
        argptr: core::ffi::VaList,
    ) -> c_int;

    fn _vsnprintf(
        buffer: *mut c_char,
        count: usize,
        format: *const c_char,
        argptr: core::ffi::VaList,
    ) -> c_int;
}

#[repr(C)]
#[derive(Clone, Copy)]
pub struct Formatp {
    original: *mut c_char, // original buffer
    buffer: *mut c_char,   // pointer to the buffer
    length: c_int,         // length of the data in the buffer
    size: c_int,           // total size of the buffer
}

#[repr(C)]
#[derive(Clone, Copy)]
pub struct Datap {
    original: *mut c_char, // original buffer
    buffer: *mut c_char,   // pointer to the buffer
    length: c_int,         // length of the data in the buffer
    size: c_int,           // total size of the buffer
}

/// is generic output. Cobalt Strike will convert this output to UTF-16 (internally) using the target's default character set.
#[allow(dead_code)]
const CALLBACK_OUTPUT: u32 = 0x0;
/// is generic output. Cobalt Strike will convert this output to UTF-16 (internally) using the target's OEM character set. You probably won't need this, unless you're dealing with output from cmd.exe.
#[allow(dead_code)]
const CALLBACK_OUTPUT_OEM: u32 = 0x1e;
/// is a generic error message.
#[allow(dead_code)]
const CALLBACK_OUTPUT_UTF8: u32 = 0x20;
/// is generic output. Cobalt Strike will convert this output to UTF-16 (internally) from UTF-8.
#[allow(dead_code)]
const CALLBACK_ERROR: u32 = 0x0d;

/// List of internal function names.
pub static INTERNAL_FUNCTION_NAMES: [&str; 29] = [
    "BeaconDataParse",
    "BeaconDataPtr",
    "BeaconDataInt",
    "BeaconDataShort",
    "BeaconDataLength",
    "BeaconDataExtract",
    "BeaconFormatAlloc",
    "BeaconFormatReset",
    "BeaconFormatAppend",
    "BeaconFormatPrintf",
    "BeaconFormatToString",
    "BeaconFormatFree",
    "BeaconFormatInt",
    "BeaconOutput",
    "BeaconPrintf",
    "BeaconUseToken",
    "BeaconRevertToken",
    "BeaconIsAdmin",
    "BeaconGetSpawnTo",
    "BeaconInjectProcess",
    "BeaconInjectTemporaryProcess",
    "BeaconSpawnTemporaryProcess",
    "BeaconCleanupProcess",
    "toWideChar",
    "LoadLibraryA",
    "GetProcAddress",
    "FreeLibrary",
    "GetModuleHandleA",
    "__C_specific_handler",
];

/// Match the function name to the internal function pointer.
pub fn get_function_ptr(name: &str) -> Result<usize, Box<dyn std::error::Error>> {
    match name {
        // Data
        "BeaconDataParse" => Ok(beacon_data_parse as *const () as usize),
        "BeaconDataPtr" => Ok(beacon_data_ptr as *const () as usize),
        "BeaconDataInt" => Ok(beacon_data_int as *const () as usize),
        "BeaconDataShort" => Ok(beacon_data_short as *const () as usize),
        "BeaconDataLength" => Ok(beacon_data_length as *const () as usize),
        "BeaconDataExtract" => Ok(beacon_data_extract as *const () as usize),

        // Format
        "BeaconFormatAlloc" => Ok(beacon_format_alloc as *const () as usize),
        "BeaconFormatReset" => Ok(beacon_format_reset as *const () as usize),
        "BeaconFormatAppend" => Ok(beacon_format_append as *const () as usize),
        "BeaconFormatPrintf" => Ok(beacon_format_printf as *const () as usize),
        "BeaconFormatToString" => Ok(beacon_format_to_string as *const () as usize),
        "BeaconFormatFree" => Ok(beacon_format_free as *const () as usize),
        "BeaconFormatInt" => Ok(beacon_format_int as *const () as usize),

        // Output
        "BeaconOutput" => Ok(beacon_output as *const () as usize),
        "BeaconPrintf" => Ok(beacon_printf as *const () as usize),

        // Token
        "BeaconUseToken" => Ok(beacon_use_token as *const () as usize),
        "BeaconRevertToken" => Ok(beacon_revert_token as *const () as usize),
        "BeaconIsAdmin" => Ok(beacon_is_admin as *const () as usize),

        // Spawn / Inject functions
        "BeaconGetSpawnTo" => Ok(beacon_get_spawn_to as *const () as usize),
        "BeaconInjectProcess" => Ok(beacon_inject_process as *const () as usize),
        "BeaconInjectTemporaryProcess" => Ok(beacon_inject_temporary_process as *const () as usize),
        "BeaconSpawnTemporaryProcess" => Ok(beacon_spawn_temporary_process as *const () as usize),
        "BeaconCleanupProcess" => Ok(beacon_cleanup_process as *const () as usize),

        // Utility functions
        "toWideChar" => Ok(to_wide_char as *const () as usize),
        "LoadLibraryA" => Ok(LoadLibraryA as *const () as usize),
        "GetProcAddress" => Ok(GetProcAddress as *const () as usize),
        "FreeLibrary" => Ok(FreeLibrary as *const () as usize),
        "GetModuleHandleA" => Ok(GetModuleHandleA as *const () as usize),
        "__C_specific_handler" => Ok(0),
        _ => Err(format!("Unknown internal function: {name}").into()),
    }
}

#[repr(C)]
#[derive(Clone)]
pub struct Carrier {
    pub output: Vec<c_char>,
    pub offset: usize,
}

impl Carrier {
    pub const fn new() -> Carrier {
        Carrier {
            output: Vec::new(),
            offset: 0,
        }
    }

    /// Append a char array to the output buffer.
    ///
    /// # Safety
    /// This function is unsafe because it dereferences the given pointer.
    /// The caller must ensure that the pointer is valid and points to a valid memory location.
    pub unsafe fn append_char_array(&mut self, s: *mut c_char, len: c_int) {
        let holder = unsafe { slice::from_raw_parts(s, len as usize) };

        self.output.extend_from_slice(holder);
        self.offset = self.output.len() - holder.len();
    }

    #[allow(clippy::cast_possible_wrap)]
    pub fn append_string(&mut self, s: &str) {
        let mut mapped = s.bytes().map(|c| c as i8).collect::<Vec<c_char>>();

        self.output.append(&mut mapped);
        self.offset = self.output.len() - s.len();
    }

    pub fn flush(&mut self) -> String {
        let bytes: Vec<u8> = self
            .output
            .iter()
            .map(|c| {
                let b = *c as u8;
                if b == 0 { b'\n' } else { b }
            })
            .collect();

        String::from_utf8_lossy(&bytes).into_owned()
    }

    #[allow(clippy::len_without_is_empty)]
    pub fn len(&self) -> usize {
        self.output.len()
    }

    pub fn reset(&mut self) {
        self.output.clear();
        self.offset = 0;
    }
}

impl Default for Carrier {
    fn default() -> Self {
        Self::new()
    }
}

static mut OUTPUT: Carrier = Carrier::new();

/// Prepare a data parser to extract arguments from the specified buffer.
#[no_mangle]
extern "C" fn beacon_data_parse(parser: *mut Datap, buffer: *mut c_char, size: c_int) {
    if parser.is_null() {
        return;
    }

    let mut data_parser: Datap = unsafe { *parser };

    data_parser.original = buffer;
    data_parser.buffer = buffer;
    data_parser.length = size - 4;
    data_parser.size = size - 4;

    unsafe {
        data_parser.buffer = data_parser.buffer.add(4);
    }

    unsafe {
        *parser = data_parser;
    }
}

#[no_mangle]
extern "C" fn beacon_data_ptr(_parser: *mut Datap, _size: c_int) -> *mut u8 {
    // Isn't well documented.
    unimplemented!();
}

/// Extract a 4b integer.
#[no_mangle]
extern "C" fn beacon_data_int(parser: *mut Datap) -> c_int {
    if parser.is_null() {
        return 0;
    }

    let mut data_parser: Datap = unsafe { *parser };

    if data_parser.length < 4 {
        return 0;
    }

    let result: &[u8] = unsafe { slice::from_raw_parts(data_parser.buffer as *const u8, 4) };

    let mut dst = [0u8; 4];
    dst.clone_from_slice(&result[0..4]);

    data_parser.buffer = unsafe { data_parser.buffer.add(4) };
    data_parser.length -= 4;

    unsafe {
        *parser = data_parser;
    }

    i32::from_ne_bytes(dst) as c_int
}

/// Extract a 2b integer.
#[no_mangle]
extern "C" fn beacon_data_short(parser: *mut Datap) -> c_short {
    if parser.is_null() {
        return 0;
    }

    let mut data_parser: Datap = unsafe { *parser };

    if data_parser.length < 2 {
        return 0;
    }

    let result: &[u8] = unsafe { slice::from_raw_parts(data_parser.buffer as *const u8, 4) };

    let mut dst = [0u8; 2];
    dst.clone_from_slice(&result[0..2]);

    data_parser.buffer = unsafe { data_parser.buffer.add(2) };
    data_parser.length -= 2;

    unsafe {
        *parser = data_parser;
    }

    i16::from_ne_bytes(dst)
}

/// Get the amount of data left to parse.
#[no_mangle]
extern "C" fn beacon_data_length(parser: *mut Datap) -> c_int {
    if parser.is_null() {
        return 0;
    }

    let data_parser: Datap = unsafe { *parser };

    data_parser.length
}

/// Extract a length-prefixed binary blob. The size argument may be NULL. If an address is provided, size is populated with the number-of-bytes extracted.
#[no_mangle]
#[allow(clippy::cast_possible_wrap)]
extern "C" fn beacon_data_extract(parser: *mut Datap, size: *mut c_int) -> *mut c_char {
    if parser.is_null() {
        return ptr::null_mut();
    }

    let mut data_parser: Datap = unsafe { *parser };

    if data_parser.length < 4 {
        return ptr::null_mut();
    }

    let length_parts: &[u8] = unsafe { slice::from_raw_parts(data_parser.buffer as *const u8, 4) };

    let mut length_holder = [0u8; 4];
    length_holder.clone_from_slice(&length_parts[0..4]);

    let length: u32 = u32::from_ne_bytes(length_holder);

    data_parser.buffer = unsafe { data_parser.buffer.add(4) };

    let result = data_parser.buffer;

    if result.is_null() {
        return ptr::null_mut();
    }

    data_parser.length -= 4;
    data_parser.length -= length as i32;
    data_parser.buffer = unsafe { data_parser.buffer.add(length as usize) };

    if !size.is_null() && !result.is_null() {
        unsafe {
            *size = length as c_int;
        }
    }

    unsafe {
        *parser = data_parser;
    }

    result
}

/// Allocate memory to format complex or large output.
#[no_mangle]
extern "C" fn beacon_format_alloc(format: *mut Formatp, maxsz: c_int) {
    if format.is_null() {
        return;
    }

    if maxsz == 0 {
        return;
    }

    let mut format_parser: Formatp = unsafe { *format };

    let mut align: usize = 1;

    while align < maxsz as usize {
        align *= 2;
    }

    let layout_result = Layout::from_size_align(maxsz as usize, align);

    if let Ok(layout) = layout_result {
        let ptr = unsafe { std::alloc::alloc(layout) };

        format_parser.original = ptr.cast::<i8>();
        format_parser.buffer = format_parser.original;
        format_parser.length = 0;
        format_parser.size = maxsz;

        unsafe {
            *format = format_parser;
        }
    }
}

/// Resets the format object to its default state (prior to re-use).
#[no_mangle]
extern "C" fn beacon_format_reset(format: *mut Formatp) {
    if format.is_null() {
        return;
    }

    let mut format_parser: Formatp = unsafe { *format };

    let size = format_parser.size;

    // Free format
    beacon_format_free(&mut format_parser);

    // Alloc format
    beacon_format_alloc(&mut format_parser, size);

    unsafe {
        *format = format_parser;
    }
}

/// Append data to this format object.
#[no_mangle]
extern "C" fn beacon_format_append(format: *mut Formatp, text: *const c_char, len: c_int) {
    if format.is_null() {
        return;
    }

    let mut format_parser: Formatp = unsafe { *format };

    if format_parser.length + len > format_parser.size {
        return;
    }

    unsafe {
        intrinsics::copy_nonoverlapping(text, format_parser.original, len as usize);
    }

    format_parser.buffer = unsafe { format_parser.buffer.add(len as usize) };
    format_parser.length += len;

    unsafe {
        *format = format_parser;
    }
}

/// Append a formatted string to this object.
#[no_mangle]
unsafe extern "C" fn beacon_format_printf(format: *mut Formatp, fmt: *const c_char, args: ...) {
    if format.is_null() {
        return;
    }

    let mut format_parser: Formatp = *format;

    // Use a buffer large enough for most format operations
    let mut buffer = vec![0u8; 4096];

    // Use Windows CRT vsnprintf
    let bytes_written = _vsnprintf(
        buffer.as_mut_ptr() as *mut c_char,
        buffer.len() - 1, // Leave space for null terminator
        fmt,
        args,
    );

    // Check if the operation was successful
    if bytes_written < 0 || bytes_written >= buffer.len() as c_int {
        return;
    }

    if format_parser.length + bytes_written + 1 > format_parser.size {
        return;
    }

    // Ensure null termination
    buffer[bytes_written as usize] = 0;

    // Copy the formatted string to the format buffer
    intrinsics::copy_nonoverlapping(
        buffer.as_ptr(),
        format_parser.buffer as *mut u8,
        bytes_written as usize + 1, // Include null terminator
    );

    // Update the format parser state
    format_parser.buffer = format_parser.buffer.add(bytes_written as usize);
    format_parser.length += bytes_written;

    *format = format_parser;
}

/// Extract formatted data into a single string. Populate the passed in size variable with the length of this string.
/// These parameters are suitable for use with the `BeaconOutput` function.
#[no_mangle]
extern "C" fn beacon_format_to_string(format: *mut Formatp, size: *mut c_int) -> *mut c_char {
    if format.is_null() {
        return ptr::null_mut();
    }

    let format_parser: Formatp = unsafe { *format };

    if format_parser.length == 0 {
        return ptr::null_mut();
    }

    unsafe {
        *size = format_parser.length;
    }

    format_parser.original
}

/// Free the format object.
#[no_mangle]
extern "C" fn beacon_format_free(format: *mut Formatp) {
    if format.is_null() {
        return;
    }

    let mut format_parser: Formatp = unsafe { *format };

    if !format_parser.original.is_null() {
        let mut align: usize = 1;

        while align < format_parser.size as usize {
            align *= 2;
        }

        let layout_result = Layout::from_size_align(format_parser.size as usize, align);

        if let Ok(layout) = layout_result {
            unsafe { std::alloc::dealloc(format_parser.original.cast::<u8>(), layout) };
        }
    }

    format_parser.original = ptr::null_mut();
    format_parser.buffer = ptr::null_mut();
    format_parser.length = 0;
    format_parser.size = 0;

    unsafe {
        *format = format_parser;
    }
}

/// Append a 4b integer (big endian) to this object.
#[no_mangle]
extern "C" fn beacon_format_int(format: *mut Formatp, value: c_int) {
    if format.is_null() {
        return;
    }

    let mut format_parser: Formatp = unsafe { *format };

    if format_parser.length + 4 > format_parser.size {
        return;
    }

    let swapped = swap_endianness(value as u32);
    let mut result = swapped.to_be_bytes();

    unsafe {
        intrinsics::copy_nonoverlapping(
            result.as_mut_ptr(),
            format_parser.original.cast::<u8>(),
            4,
        );
    }

    format_parser.buffer = unsafe { format_parser.buffer.add(4) };
    format_parser.length += 4;

    unsafe {
        *format = format_parser;
    }
}

/// Send output to the Beacon operator.
#[no_mangle]
#[allow(static_mut_refs)]
extern "C" fn beacon_output(_type: c_int, data: *mut c_char, len: c_int) {
    unsafe { OUTPUT.append_char_array(data, len) }
}

/// Retrieves the output data from the beacon.
#[no_mangle]
#[allow(static_mut_refs)]
pub extern "C" fn beacon_get_output_data() -> &'static mut Carrier {
    unsafe { &mut OUTPUT }
}

/// Format and present output to the Beacon operator.
#[no_mangle]
unsafe extern "C" fn beacon_printf(_type: c_int, fmt: *mut c_char, args: ...) {
    // Use a buffer large enough for most format operations
    let mut buffer = vec![0u8; 4096];

    // Use Windows CRT vsnprintf
    let bytes_written = _vsnprintf(
        buffer.as_mut_ptr() as *mut c_char,
        buffer.len() - 1,
        fmt,
        args,
    );

    // Check if the operation was successful
    if bytes_written < 0 || bytes_written >= buffer.len() as c_int {
        return;
    }

    // Ensure null termination
    buffer[bytes_written as usize] = 0;

    // Convert buffer to String, but only the written portion
    let formatted_str = String::from_utf8_lossy(&buffer[..bytes_written as usize]).into_owned();

    #[allow(static_mut_refs)]
    OUTPUT.append_string(&formatted_str);
}

/// Apply the specified token as Beacon's current thread token.
/// This will report the new token to the user too.
///
/// # Returns
/// Returns TRUE if the token was successfully applied, FALSE otherwise.
#[no_mangle]
extern "C" fn beacon_use_token(token: HANDLE) -> BOOL {
    match unsafe { SetThreadToken(Some(std::ptr::null()), Some(token)) } {
        Ok(()) => TRUE,
        Err(_) => FALSE,
    }
}

/// Drop the current thread token. Use this over direct calls to `RevertToSelf`.
/// This function cleans up other state information about the token.
#[no_mangle]
extern "C" fn beacon_revert_token() {
    if let Ok(()) = unsafe { RevertToSelf() } {
    } else {
        warn!("RevertToSelf Failed!");
    }
}

/// Check if the current Beacon is running in an elevated context.
///
/// # Returns
/// Returns TRUE if Beacon is in a high-integrity context.
#[no_mangle]
extern "C" fn beacon_is_admin() -> BOOL {
    let mut token: HANDLE = HANDLE(std::ptr::null_mut());
    let token_elevated: TOKEN_ELEVATION = TOKEN_ELEVATION { TokenIsElevated: 0 };

    let open_token_result =
        unsafe { OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &mut token) };
    if open_token_result.is_err() {
        return FALSE;
    }

    let get_token_info_result = unsafe {
        GetTokenInformation(
            token,
            TokenElevation,
            Some(std::ptr::from_ref(&token_elevated) as *mut _),
            std::mem::size_of::<TOKEN_ELEVATION>() as u32,
            std::ptr::null_mut(),
        )
    };
    if get_token_info_result.is_err() {
        return FALSE;
    }

    if token_elevated.TokenIsElevated == 1 {
        return TRUE;
    }

    FALSE
}

/// Populate the specified buffer with the x86 or x64 spawnto value configured for this Beacon session.
#[no_mangle]
extern "C" fn beacon_get_spawn_to(_x86: BOOL, _buffer: *const c_char, _length: c_int) {
    unimplemented!();
}

/// This function will inject the specified payload into an existing process.
/// Use `payload_offset` to specify the offset within the payload to begin execution.
/// The arg value is for arguments. arg may be NULL.
#[no_mangle]
extern "C" fn beacon_inject_process(
    _hproc: HANDLE,
    pid: c_int,
    payload: *const c_char,
    p_len: c_int,
    _p_offset: c_int,
    arg: *const c_char,
    a_len: c_int,
) {
    unsafe {
        if let Ok(process_handle) =
            OpenProcess(PROCESS_VM_OPERATION | PROCESS_VM_WRITE, false, pid as u32)
        {
            if process_handle.is_invalid() {
                return;
            }

            let payload_slice = std::slice::from_raw_parts(payload.cast::<u8>(), p_len as usize);
            let _arg_slice = std::slice::from_raw_parts(arg.cast::<u8>(), a_len as usize);

            let remote_payload_address = VirtualAllocEx(
                process_handle,
                None,
                payload_slice.len(),
                MEM_COMMIT | MEM_RESERVE,
                PAGE_EXECUTE_READWRITE,
            );

            if remote_payload_address.is_null() {
                let _ = CloseHandle(process_handle);
                return;
            }

            if WriteProcessMemory(
                process_handle,
                remote_payload_address,
                payload_slice.as_ptr().cast(),
                payload_slice.len(),
                None,
            )
            .is_err()
            {
                let _ = CloseHandle(process_handle);
                return;
            }

            if let Ok(thread) = CreateRemoteThread(
                process_handle,
                None,
                0,
                Some(std::mem::transmute::<
                    *mut std::ffi::c_void,
                    unsafe extern "system" fn(*mut std::ffi::c_void) -> u32,
                >(remote_payload_address)),
                None,
                0,
                None,
            ) {
                let _ = CloseHandle(thread);
            };

            let _ = CloseHandle(process_handle);
        };
    }
}

/// This function will inject the specified payload into a temporary process that your BOF opted to launch.
/// Use `payload_offset` to specify the offset within the payload to begin execution.
///
/// # Arguments
/// The `arg` value is for arguments, which may be NULL.
#[no_mangle]
extern "C" fn beacon_inject_temporary_process(
    _pinfo: *const PROCESS_INFORMATION,
    _pid: c_int,
    _payload: *const c_char,
    _p_len: c_int,
    _p_offset: c_int,
    _arg: *const c_char,
    _a_len: c_int,
) {
    unimplemented!();
}

/// This function spawns a temporary process accounting for ppid, spawnto, and blockdlls options.
/// Grab the handle from `PROCESS_INFORMATION` to inject into or manipulate this process.
#[no_mangle]
extern "C" fn beacon_spawn_temporary_process(
    _x86: BOOL,
    _ignore_token: BOOL,
    _si: *const STARTUPINFOA,
    _pinfo: *const PROCESS_INFORMATION,
) -> BOOL {
    unimplemented!();
}

/// This function cleans up some handles that are often forgotten about. Call this when you're done interacting with the handles for a process. You don't need to wait for the process to exit or finish.
#[no_mangle]
extern "C" fn beacon_cleanup_process(pinfo: *const PROCESS_INFORMATION) {
    unsafe {
        let _ = CloseHandle((*pinfo).hProcess);
        let _ = CloseHandle((*pinfo).hThread);
    }
}

/// Convert the src string to a UTF16-LE wide-character string, using the target's default encoding. max is the size (in bytes!) of the destination buffer.
#[no_mangle]
extern "C" fn to_wide_char(src: *const c_char, dst: *mut c_short, max: c_int) -> BOOL {
    if src.is_null() {
        return FALSE;
    }

    let c_str: &CStr = unsafe { CStr::from_ptr(src) };

    let str_slice: &str = match c_str.to_str() {
        Ok(s) => s,
        Err(_) => return FALSE,
    };

    let mut size = str_slice.len();

    if size > max as usize {
        size = max as usize - 1;
    }

    let mut v: Vec<u16> = str_slice.encode_utf16().take(size).collect();
    v.push(0);

    unsafe { ptr::copy(v.as_ptr(), dst.cast::<u16>(), size) };

    TRUE
}

#[no_mangle]
pub extern "C" fn swap_endianness(src: u32) -> u32 {
    let test: u32 = 0x0000_00ff;

    // if test is 0xff00, then we are little endian, otherwise big endian
    if (((test >> 24) & 0xff) as u8) == 0xff {
        return src.swap_bytes();
    }

    src
}