forked from ck0i/Cloakwork
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcloakwork.h
More file actions
6566 lines (5786 loc) · 273 KB
/
Copy pathcloakwork.h
File metadata and controls
6566 lines (5786 loc) · 273 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
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#ifndef CLOAKWORK_H
#define CLOAKWORK_H
// Cloakwork advanced obfuscation library - header-only c++20 implementation
// Comprehensive protection against static and dynamic analysis
// ██████╗██╗ ██████╗ █████╗ ██╗ ██╗██╗ ██╗ ██████╗ ██████╗ ██╗ ██╗
//██╔════╝██║ ██╔═══██╗██╔══██╗██║ ██╔╝██║ ██║██╔═══██╗██╔══██╗██║ ██╔╝
//██║ ██║ ██║ ██║███████║█████╔╝ ██║ █╗ ██║██║ ██║██████╔╝█████╔╝
//██║ ██║ ██║ ██║██╔══██║██╔═██╗ ██║███╗██║██║ ██║██╔══██╗██╔═██╗
//╚██████╗███████╗╚██████╔╝██║ ██║██║ ██╗╚███╔███╔╝╚██████╔╝██║ ██║██║ ██╗
// ╚═════╝╚══════╝ ╚═════╝ ╚═╝ ╚═╝╚═╝ ╚═╝ ╚══╝╚══╝ ╚═════╝ ╚═╝ ╚═╝╚═╝ ╚═╝
// Created by @ck0i on Discord.
// Inspiration from obfusheader.h, Zapcrash's nimrodhide.h, and qengine.
/*++
Most of the docs here (~line 540) were
generated by Claude Code, the documentation
does reflect Cloakwork's capabilities.
Refer to the README.md for usage.
--*/
#ifndef CW_KERNEL_MODE
#if defined(_KERNEL_MODE)
#define CW_KERNEL_MODE 1
#else
#define CW_KERNEL_MODE 0
#endif
#endif
#if CW_KERNEL_MODE
// syscalls don't make sense in kernel mode
#ifdef CW_ENABLE_SYSCALLS
#undef CW_ENABLE_SYSCALLS
#endif
#define CW_ENABLE_SYSCALLS 0
// std::unique_ptr not available in kernel
#ifdef CW_ENABLE_DATA_HIDING
#undef CW_ENABLE_DATA_HIDING
#endif
#define CW_ENABLE_DATA_HIDING 0
// std::initializer_list not available
#ifdef CW_ENABLE_METAMORPHIC
#undef CW_ENABLE_METAMORPHIC
#endif
#define CW_ENABLE_METAMORPHIC 0
// static destructors need atexit
#ifdef CW_ENABLE_STRING_ENCRYPTION
#undef CW_ENABLE_STRING_ENCRYPTION
#endif
#define CW_ENABLE_STRING_ENCRYPTION 0
// needs C++20 concepts and std::bit_cast
#ifdef CW_ENABLE_VALUE_OBFUSCATION
#undef CW_ENABLE_VALUE_OBFUSCATION
#endif
#define CW_ENABLE_VALUE_OBFUSCATION 0
// PEB walking needs different impl in kernel
#ifdef CW_ENABLE_IMPORT_HIDING
#undef CW_ENABLE_IMPORT_HIDING
#endif
#define CW_ENABLE_IMPORT_HIDING 0
// requires usermode APIs
#ifdef CW_ENABLE_ANTI_VM
#undef CW_ENABLE_ANTI_VM
#endif
#define CW_ENABLE_ANTI_VM 0
// requires VirtualQuery
#ifdef CW_ENABLE_INTEGRITY_CHECKS
#undef CW_ENABLE_INTEGRITY_CHECKS
#endif
#define CW_ENABLE_INTEGRITY_CHECKS 0
// needs concepts
#ifdef CW_ENABLE_FUNCTION_OBFUSCATION
#undef CW_ENABLE_FUNCTION_OBFUSCATION
#endif
#define CW_ENABLE_FUNCTION_OBFUSCATION 0
// depends on value obfuscation (mba)
#ifdef CW_ENABLE_CONTROL_FLOW
#undef CW_ENABLE_CONTROL_FLOW
#endif
#define CW_ENABLE_CONTROL_FLOW 0
#endif
#ifndef CW_ENABLE_ALL
#define CW_ENABLE_ALL 1
#endif
#ifndef CW_ENABLE_COMPILE_TIME_RANDOM
#define CW_ENABLE_COMPILE_TIME_RANDOM CW_ENABLE_ALL
#endif
#ifndef CW_ENABLE_STRING_ENCRYPTION
#define CW_ENABLE_STRING_ENCRYPTION CW_ENABLE_ALL
#endif
#ifndef CW_ENABLE_VALUE_OBFUSCATION
#define CW_ENABLE_VALUE_OBFUSCATION CW_ENABLE_ALL
#endif
#ifndef CW_ENABLE_CONTROL_FLOW
#define CW_ENABLE_CONTROL_FLOW CW_ENABLE_ALL
#endif
#ifndef CW_ENABLE_ANTI_DEBUG
#define CW_ENABLE_ANTI_DEBUG CW_ENABLE_ALL
#endif
#ifndef CW_ENABLE_FUNCTION_OBFUSCATION
#define CW_ENABLE_FUNCTION_OBFUSCATION CW_ENABLE_ALL
#endif
#ifndef CW_ENABLE_DATA_HIDING
#define CW_ENABLE_DATA_HIDING CW_ENABLE_ALL
#endif
#ifndef CW_ENABLE_METAMORPHIC
#define CW_ENABLE_METAMORPHIC CW_ENABLE_ALL
#endif
#ifndef CW_ENABLE_IMPORT_HIDING
#define CW_ENABLE_IMPORT_HIDING CW_ENABLE_ALL
#endif
#ifndef CW_ENABLE_SYSCALLS
#define CW_ENABLE_SYSCALLS CW_ENABLE_ALL
#endif
#ifndef CW_ENABLE_ANTI_VM
#define CW_ENABLE_ANTI_VM CW_ENABLE_ALL
#endif
#ifndef CW_ENABLE_INTEGRITY_CHECKS
#define CW_ENABLE_INTEGRITY_CHECKS CW_ENABLE_ALL
#endif
#ifndef CW_ANTI_DEBUG_RESPONSE
#define CW_ANTI_DEBUG_RESPONSE 1 // 0=ignore, 1=crash, 2=fake data
#endif
#if CW_ENABLE_DATA_HIDING && !CW_ENABLE_COMPILE_TIME_RANDOM
#error "CW_ENABLE_DATA_HIDING requires CW_ENABLE_COMPILE_TIME_RANDOM to be enabled"
#endif
#if CW_ENABLE_CONTROL_FLOW && !CW_ENABLE_COMPILE_TIME_RANDOM
#error "CW_ENABLE_CONTROL_FLOW requires CW_ENABLE_COMPILE_TIME_RANDOM to be enabled"
#endif
#if CW_KERNEL_MODE
#ifndef _NTDDK_
#error "In kernel mode, include <ntddk.h> before cloakwork.h"
#endif
#include <intrin.h>
extern "C" {
NTSYSAPI NTSTATUS NTAPI ZwQuerySystemInformation(
ULONG SystemInformationClass,
PVOID SystemInformation,
ULONG SystemInformationLength,
PULONG ReturnLength
);
}
// define _fltused to satisfy linker when floating point is used
// selectany allows multiple definitions across translation units
extern "C" __declspec(selectany) int _fltused = 0;
// WDK doesn't ship usermode STL headers
using int8_t = signed char;
using int16_t = short;
using int32_t = int;
using int64_t = long long;
using uint8_t = unsigned char;
using uint16_t = unsigned short;
using uint32_t = unsigned int;
using uint64_t = unsigned long long;
using size_t = SIZE_T;
using ptrdiff_t = SSIZE_T;
namespace std {
template<typename T, size_t N>
struct array {
T _data[N];
constexpr T& operator[](size_t i) { return _data[i]; }
constexpr const T& operator[](size_t i) const { return _data[i]; }
constexpr T* data() { return _data; }
constexpr const T* data() const { return _data; }
constexpr size_t size() const { return N; }
};
template<typename T>
constexpr T rotl(T value, int shift) {
constexpr int bits = sizeof(T) * 8;
shift &= (bits - 1);
if (shift == 0) return value;
return (value << shift) | (value >> (bits - shift));
}
template<typename T>
constexpr T rotr(T value, int shift) {
constexpr int bits = sizeof(T) * 8;
shift &= (bits - 1);
if (shift == 0) return value;
return (value >> shift) | (value << (bits - shift));
}
template<size_t... Is>
struct index_sequence {};
template<size_t N, size_t... Is>
struct make_index_sequence_impl : make_index_sequence_impl<N - 1, N - 1, Is...> {};
template<size_t... Is>
struct make_index_sequence_impl<0, Is...> {
using type = index_sequence<Is...>;
};
template<size_t N>
using make_index_sequence = typename make_index_sequence_impl<N>::type;
template<bool B, class T = void>
struct enable_if {};
template<class T>
struct enable_if<true, T> { using type = T; };
template<bool B, class T = void>
using enable_if_t = typename enable_if<B, T>::type;
template<class T, class U>
struct is_same { static constexpr bool value = false; };
template<class T>
struct is_same<T, T> { static constexpr bool value = true; };
template<class T, class U>
inline constexpr bool is_same_v = is_same<T, U>::value;
template<class T>
struct remove_cv { using type = T; };
template<class T>
struct remove_cv<const T> { using type = T; };
template<class T>
struct remove_cv<volatile T> { using type = T; };
template<class T>
struct remove_cv<const volatile T> { using type = T; };
template<class T>
using remove_cv_t = typename remove_cv<T>::type;
template<class T>
struct remove_reference { using type = T; };
template<class T>
struct remove_reference<T&> { using type = T; };
template<class T>
struct remove_reference<T&&> { using type = T; };
template<class T>
using remove_reference_t = typename remove_reference<T>::type;
template<class T>
struct is_integral { static constexpr bool value = false; };
template<> struct is_integral<bool> { static constexpr bool value = true; };
template<> struct is_integral<char> { static constexpr bool value = true; };
template<> struct is_integral<signed char> { static constexpr bool value = true; };
template<> struct is_integral<unsigned char> { static constexpr bool value = true; };
// wchar_t is unsigned short in kernel mode with /Zc:wchar_t-, skip to avoid duplicate
template<> struct is_integral<short> { static constexpr bool value = true; };
template<> struct is_integral<unsigned short> { static constexpr bool value = true; };
template<> struct is_integral<int> { static constexpr bool value = true; };
template<> struct is_integral<unsigned int> { static constexpr bool value = true; };
template<> struct is_integral<long> { static constexpr bool value = true; };
template<> struct is_integral<unsigned long> { static constexpr bool value = true; };
template<> struct is_integral<long long> { static constexpr bool value = true; };
template<> struct is_integral<unsigned long long> { static constexpr bool value = true; };
template<class T>
inline constexpr bool is_integral_v = is_integral<remove_cv_t<T>>::value;
template<class T>
struct is_floating_point { static constexpr bool value = false; };
template<> struct is_floating_point<float> { static constexpr bool value = true; };
template<> struct is_floating_point<double> { static constexpr bool value = true; };
template<> struct is_floating_point<long double> { static constexpr bool value = true; };
template<class T>
inline constexpr bool is_floating_point_v = is_floating_point<remove_cv_t<T>>::value;
template<class T>
struct is_arithmetic { static constexpr bool value = is_integral_v<T> || is_floating_point_v<T>; };
template<class T>
inline constexpr bool is_arithmetic_v = is_arithmetic<T>::value;
template<class T>
struct is_pointer { static constexpr bool value = false; };
template<class T>
struct is_pointer<T*> { static constexpr bool value = true; };
template<class T>
struct is_pointer<T* const> { static constexpr bool value = true; };
template<class T>
struct is_pointer<T* volatile> { static constexpr bool value = true; };
template<class T>
struct is_pointer<T* const volatile> { static constexpr bool value = true; };
template<class T>
inline constexpr bool is_pointer_v = is_pointer<T>::value;
template<class T>
T&& declval() noexcept;
template<class T>
constexpr T&& forward(remove_reference_t<T>& t) noexcept {
return static_cast<T&&>(t);
}
template<class T>
constexpr T&& forward(remove_reference_t<T>&& t) noexcept {
return static_cast<T&&>(t);
}
template<class T>
constexpr remove_reference_t<T>&& move(T&& t) noexcept {
return static_cast<remove_reference_t<T>&&>(t);
}
}
namespace cloakwork_internal {
class kernel_spinlock {
private:
KSPIN_LOCK lock;
KIRQL old_irql;
public:
kernel_spinlock() {
KeInitializeSpinLock(&lock);
}
void acquire() {
KeAcquireSpinLock(&lock, &old_irql);
}
void release() {
KeReleaseSpinLock(&lock, old_irql);
}
};
class spinlock_guard {
private:
kernel_spinlock& lock;
public:
spinlock_guard(kernel_spinlock& l) : lock(l) { lock.acquire(); }
~spinlock_guard() { lock.release(); }
spinlock_guard(const spinlock_guard&) = delete;
spinlock_guard& operator=(const spinlock_guard&) = delete;
};
template<typename T>
class kernel_atomic {
private:
volatile T value;
public:
kernel_atomic() : value{} {}
kernel_atomic(T val) : value(val) {}
T load(int = 0) const {
MemoryBarrier();
return value;
}
void store(T val, int = 0) {
value = val;
MemoryBarrier();
}
T fetch_add(T val, int = 0) {
if constexpr (sizeof(T) == 4) {
return static_cast<T>(InterlockedExchangeAdd(
reinterpret_cast<volatile LONG*>(&value),
static_cast<LONG>(val)));
} else if constexpr (sizeof(T) == 8) {
return static_cast<T>(InterlockedExchangeAdd64(
reinterpret_cast<volatile LONG64*>(&value),
static_cast<LONG64>(val)));
} else {
T old = value;
value += val;
return old;
}
}
T operator++() {
return fetch_add(1) + 1;
}
T operator++(int) {
return fetch_add(1);
}
};
inline void* kernel_alloc(size_t size) {
// use NonPagedPoolNx for security (no-execute)
return ExAllocatePool2(POOL_FLAG_NON_PAGED, size, 'kwlC');
}
inline void kernel_free(void* ptr) {
if (ptr) {
ExFreePoolWithTag(ptr, 'kwlC');
}
}
// different layout than the usermode PEB version
struct KLDR_DATA_TABLE_ENTRY {
LIST_ENTRY InLoadOrderLinks;
PVOID ExceptionTable;
ULONG ExceptionTableSize;
PVOID GpValue;
PVOID NonPagedDebugInfo;
PVOID DllBase;
PVOID EntryPoint;
ULONG SizeOfImage;
UNICODE_STRING FullDllName;
UNICODE_STRING BaseDllName;
ULONG Flags;
USHORT LoadCount;
USHORT __Unused;
PVOID SectionPointer;
ULONG CheckSum;
ULONG TimeDateStamp;
};
}
#define CW_ATOMIC(T) cloakwork_internal::kernel_atomic<T>
#define CW_MUTEX cloakwork_internal::kernel_spinlock
#define CW_LOCK_GUARD(m) cloakwork_internal::spinlock_guard _cw_guard(m)
#define CW_MO_RELAXED 0
#define CW_MO_ACQUIRE 0
#define CW_MO_RELEASE 0
#else
#include <array>
#include <vector>
#include <algorithm>
#include <atomic>
#include <mutex>
#include <memory>
#include <bit>
#ifdef _WIN32
#include <windows.h>
#include <intrin.h>
#include <winternl.h>
#include <tlhelp32.h>
#include <iphlpapi.h>
#pragma comment(lib, "iphlpapi.lib")
// full LDR_DATA_TABLE_ENTRY structure (winternl.h has incomplete definition, fuck those guys)
namespace cloakwork_internal {
struct CW_LDR_DATA_TABLE_ENTRY {
LIST_ENTRY InLoadOrderLinks;
LIST_ENTRY InMemoryOrderLinks;
LIST_ENTRY InInitializationOrderLinks;
PVOID DllBase;
PVOID EntryPoint;
ULONG SizeOfImage;
UNICODE_STRING FullDllName;
UNICODE_STRING BaseDllName;
ULONG Flags;
USHORT LoadCount;
USHORT TlsIndex;
union {
LIST_ENTRY HashLinks;
struct {
PVOID SectionPointer;
ULONG CheckSum;
};
};
union {
ULONG TimeDateStamp;
PVOID LoadedImports;
};
PVOID EntryPointActivationContext;
PVOID PatchInformation;
};
}
#else
#include <cstdint>
#include <cpuid.h>
#endif
#define CW_ATOMIC(T) std::atomic<T>
#define CW_MUTEX std::mutex
#define CW_LOCK_GUARD(m) std::lock_guard<std::mutex> _cw_guard(m)
#define CW_MO_RELAXED std::memory_order_relaxed
#define CW_MO_ACQUIRE std::memory_order_acquire
#define CW_MO_RELEASE std::memory_order_release
#endif // CW_KERNEL_MODE
#ifdef _MSC_VER
#define CW_FORCEINLINE __forceinline
#define CW_NOINLINE __declspec(noinline)
#define CW_SECTION(x) __declspec(allocate(x))
#define CW_COMPILER_BARRIER() _ReadWriteBarrier()
// optimization barriers - prevents LTCG/WPO from seeing through obfuscation
#define CW_OPT_OFF __pragma(optimize("", off))
#define CW_OPT_ON __pragma(optimize("", on))
#pragma warning(push)
#pragma warning(disable: 4996 4244 4267)
#define CW_RDSEED
#elif defined(__GNUC__) || defined(__clang__)
#define CW_FORCEINLINE __attribute__((always_inline)) inline
#define CW_NOINLINE __attribute__((noinline))
#define CW_SECTION(x) __attribute__((section(x)))
#define CW_COMPILER_BARRIER() asm volatile("" ::: "memory")
#define CW_OPT_OFF _Pragma("GCC push_options") _Pragma("GCC optimize(\"O0\")")
#define CW_OPT_ON _Pragma("GCC pop_options")
#define CW_RDSEED __attribute__((target("rdseed")))
#else
#define CW_FORCEINLINE inline
#define CW_NOINLINE
#define CW_SECTION(x)
#define CW_COMPILER_BARRIER() std::atomic_signal_fence(std::memory_order_seq_cst)
#define CW_OPT_OFF
#define CW_OPT_ON
#define CW_RDSEED
#endif
// =================================================================
// CLOAKWORK QUICK REFERENCE WIKI
// =================================================================
//
// STRING ENCRYPTION
// -----------------
// CW_STR("text") - encrypts string at compile-time, decrypts at runtime
// usage: const char* msg = CW_STR("secret message");
//
// CW_STR_LAYERED("text") - multi-layer encrypted string with polymorphic re-encryption
// usage: const char* msg = CW_STR_LAYERED("secret");
//
// CW_STR_STACK("text") - stack-based encrypted string (auto-cleanup)
// usage: auto msg = CW_STR_STACK("secret");
//
// INTEGER/VALUE OBFUSCATION
// -------------------------
// CW_INT(value) - obfuscates integer/numeric values
// usage: int x = CW_INT(42);
//
// CW_ADD(a, b) - obfuscated addition using MBA
// usage: int sum = CW_ADD(x, y);
//
// CW_SUB(a, b) - obfuscated subtraction using MBA
// usage: int diff = CW_SUB(x, y);
//
// CW_SCATTER(value) - scatters data across memory chunks
// usage: auto scattered = CW_SCATTER(myStruct);
//
// CW_POLY(value) - creates polymorphic value that mutates internally
// usage: auto poly = CW_POLY(100);
//
// BOOLEAN OBFUSCATION
// -------------------
// CW_TRUE - obfuscated true using opaque predicates
// usage: if (CW_TRUE) { /* always executes */ }
//
// CW_FALSE - obfuscated false using opaque predicates
// usage: if (CW_FALSE) { /* never executes */ }
//
// CW_BOOL(expr) - obfuscates a boolean expression
// usage: bool result = CW_BOOL(x > 0);
//
// obfuscated_bool - class for storing obfuscated boolean values
// usage: obfuscated_bool flag(true);
//
// obfuscated_value<T> - template class for obfuscating any value type
// usage: obfuscated_value<int> val(42);
//
// mba_obfuscated<T> - mixed boolean arithmetic obfuscation
// usage: mba_obfuscated<int> val(42);
//
// CONTROL FLOW OBFUSCATION
// ------------------------
// CW_IF(condition) - obfuscated if statement with opaque predicates
// usage: CW_IF(x > 0) { /* code */ }
//
// CW_ELSE - obfuscated else clause
// usage: CW_IF(cond) { } CW_ELSE { }
//
// CW_BRANCH(condition) - indirect branching with obfuscation
// usage: CW_BRANCH(isValid) { /* code */ }
//
// CW_FLATTEN(func, args...) - flattens control flow via state machine
// usage: auto result = CW_FLATTEN(myFunc, arg1, arg2);
//
// CFG FLATTENING (block-level state machine)
// -------------------------------------------
// CW_FLAT_FUNC(ret_type) - begin flattened function returning ret_type
// usage: auto r = CW_FLAT_FUNC(int) ... CW_FLAT_END;
//
// CW_FLAT_VOID - begin void flattened function
// usage: CW_FLAT_VOID ... CW_FLAT_VOID_END;
//
// CW_FLAT_VARS(...) - declare shared variables across blocks
// usage: CW_FLAT_VARS(int x = 0; int y = 0;)
//
// CW_FLAT_ENTRY(id) - set entry block ID
// usage: CW_FLAT_ENTRY(0)
//
// CW_FLAT_BEGIN - begin dispatch loop (auto-inserts dead blocks)
//
// CW_FLAT_BLOCK(id) - start a block with given ID
// usage: CW_FLAT_BLOCK(0) x = 42; CW_FLAT_GOTO(1)
//
// CW_FLAT_GOTO(id) - unconditional jump to block
// usage: CW_FLAT_GOTO(1)
//
// CW_FLAT_GOTO_OBF(id) - obfuscated jump (adds fake dead-block branch)
// usage: CW_FLAT_GOTO_OBF(1)
//
// CW_FLAT_IF(cond, true_id, false_id) - conditional branch
// usage: CW_FLAT_IF(x > 0, 2, 3)
//
// CW_FLAT_IF_OBF(cond, t, f) - obfuscated conditional (volatile + opaque pred)
// usage: CW_FLAT_IF_OBF(x > 0, 2, 3)
//
// CW_FLAT_RETURN(val) - return value and exit
// usage: CW_FLAT_RETURN(x * 2)
//
// CW_FLAT_EXIT() - exit without return value
// usage: CW_FLAT_EXIT()
//
// CW_FLAT_SWITCH2..4(expr, ...) - multi-way dispatch (2-4 cases + default)
// usage: CW_FLAT_SWITCH3(cmd, 0,blk_a, 1,blk_b, 2,blk_c, blk_def)
//
// CW_FLAT_END - close dispatch loop (non-void)
// CW_FLAT_VOID_END - close dispatch loop (void)
//
// SIMPLIFIED CFG PROTECTION (automatic state machine wrapping)
// -------------------------------------------------------------
// CW_PROTECT(ret_type, body) - wraps code in encrypted state machine, returns ret_type
// usage: int r = CW_PROTECT(int, { return x * 2; });
//
// CW_PROTECT_VOID(body) - wraps void code in encrypted state machine
// usage: CW_PROTECT_VOID({ do_work(); });
//
// FUNCTION CALL PROTECTION
// ------------------------
// CW_CALL(function) - obfuscates function pointer and adds anti-debug
// usage: auto obf_func = CW_CALL(originalFunc);
// obf_func(args);
//
// obfuscated_call<Func> - template class for function pointer obfuscation
// usage: obfuscated_call<decltype(func)> obf{func};
//
// ANTI-DEBUGGING/ANALYSIS
// -----------------------
// CW_ANTI_DEBUG() - crashes if debugger detected (comprehensive checks)
// usage: CW_ANTI_DEBUG();
//
//
// anti_debug::is_debugger_present() - returns true if debugger detected (basic checks)
// usage: if(anti_debug::is_debugger_present()) { }
//
// anti_debug::comprehensive_check() - advanced multi-layered debugger detection
// usage: if(anti_debug::comprehensive_check()) { }
//
// anti_debug::timing_check(func) - detects debuggers via timing analysis
// usage: if(timing_check([](){}, 1000)) { }
//
// anti_debug::verify_code_integrity() - checks if code has been modified
// usage: if(!verify_code_integrity(func, size)) { }
//
// COMPILE-TIME RANDOMIZATION
// --------------------------
// CW_RANDOM_CT() - generates compile-time random value (unique per build)
// usage: constexpr auto rand = CW_RANDOM_CT();
//
// CW_RANDOM_RT() - generates runtime random value (unique per execution)
// usage: uint64_t rand = CW_RANDOM_RT();
//
// CW_RAND_CT(min, max) - compile-time random in range [min, max]
// usage: constexpr int x = CW_RAND_CT(1, 100);
//
// CW_RAND_RT(min, max) - runtime random in range [min, max]
// usage: int x = CW_RAND_RT(1, 100);
//
// WIDE STRING ENCRYPTION
// ----------------------
// CW_WSTR(L"text") - encrypts wide string at compile-time
// usage: const wchar_t* msg = CW_WSTR(L"secret");
//
// STRING HASHING
// --------------
// CW_HASH("text") - compile-time FNV-1a hash of string (case-sensitive)
// usage: constexpr uint32_t h = CW_HASH("NtClose");
//
// CW_HASH_CI("text") - compile-time case-insensitive hash (for module names)
// usage: constexpr uint32_t h = CW_HASH_CI("kernel32.dll");
//
// CW_HASH_WIDE(L"text") - compile-time hash of wide string
// usage: constexpr uint32_t h = CW_HASH_WIDE(L"ntdll.dll");
//
// hash::fnv1a_runtime(str) - runtime hash of string
// usage: uint32_t h = hash::fnv1a_runtime(dynamicStr);
//
// IMPORT HIDING
// -------------
// CW_IMPORT(mod, func) - resolve function without import table
// usage: auto pFunc = CW_IMPORT("kernel32.dll", VirtualAlloc);
//
// imports::getModuleBase(hash) - get module base by hash
// usage: void* ntdll = imports::getModuleBase(CW_HASH("ntdll.dll"));
//
// imports::getProcAddress(mod, hash) - get function by hash
// usage: void* func = imports::getProcAddress(mod, CW_HASH("NtClose"));
//
// DIRECT SYSCALLS
// ---------------
// CW_SYSCALL_NUMBER(func) - get syscall number for ntdll function
// usage: uint32_t num = CW_SYSCALL_NUMBER(NtClose);
//
// syscall::getSyscallNumber(hash) - get syscall number by function hash
// usage: uint32_t num = syscall::getSyscallNumber(CW_HASH("NtClose"));
//
// ANTI-VM/SANDBOX DETECTION
// -------------------------
// CW_ANTI_VM() - crashes if VM/sandbox detected
// usage: CW_ANTI_VM();
//
// CW_CHECK_VM() - returns true if VM/sandbox detected
// usage: if(CW_CHECK_VM()) { /* in VM */ }
//
// anti_vm::comprehensive_check() - comprehensive VM/sandbox detection
// usage: if(anti_debug::anti_vm::comprehensive_check()) { }
//
// OBFUSCATED COMPARISONS
// ----------------------
// CW_EQ(a, b) - obfuscated equality check (a == b)
// usage: if(CW_EQ(x, 42)) { }
//
// CW_NE(a, b) - obfuscated not-equals (a != b)
// CW_LT(a, b) - obfuscated less-than (a < b)
// CW_GT(a, b) - obfuscated greater-than (a > b)
// CW_LE(a, b) - obfuscated less-or-equal (a <= b)
// CW_GE(a, b) - obfuscated greater-or-equal (a >= b)
//
// ENCRYPTED CONSTANTS
// -------------------
// CW_CONST(value) - encrypted compile-time constant
// usage: int x = CW_CONST(0xDEADBEEF);
//
// constants::runtime_constant<T> - runtime-keyed constant (unique per execution)
// usage: runtime_constant<int> val(42);
//
// JUNK CODE INSERTION
// -------------------
// CW_JUNK() - insert junk computation
// usage: CW_JUNK();
//
// CW_JUNK_FLOW() - insert junk with fake control flow
// usage: CW_JUNK_FLOW();
//
// RETURN ADDRESS SPOOFING
// -----------------------
// CW_SPOOF_CALL(func) - call with spoofed return address
// usage: auto spoof = CW_SPOOF_CALL(myFunc);
//
// spoof::getRetGadget() - get cached ret gadget for spoofing
// usage: void* gadget = spoof::getRetGadget();
//
// INTEGRITY VERIFICATION
// ----------------------
// CW_INTEGRITY_CHECK(func, size) - wrap function with integrity checking
// usage: auto checked = CW_INTEGRITY_CHECK(myFunc, 64);
//
// CW_DETECT_HOOK(func) - check if function is hooked
// usage: if(CW_DETECT_HOOK(VirtualAlloc)) { /* hooked */ }
//
// integrity::computeHash(data, size) - compute hash of memory region
// usage: uint32_t h = integrity::computeHash(ptr, 100);
//
// integrity::verifyFunctions(...) - verify multiple functions at once
// usage: if(!integrity::verifyFunctions(f1, f2)) { }
//
// CONVENIENCE MACROS & TYPE ALIASES
// ----------------------------------
// CW_IS_DEBUGGED() - is_debugger_present() (PEB + NtGlobalFlag)
// CW_HAS_HWBP() - has_hardware_breakpoints() (DR0-DR3)
// CW_CHECK_DEBUG() - comprehensive_check() (all anti-debug combined)
// CW_DETECT_HIDING() - detect anti-anti-debug tools (ScyllaHide etc.)
// CW_DETECT_PARENT() - check if parent is a debugger
// CW_DETECT_KERNEL_DBG() - kernel debugger detection
// CW_TIMING_CHECK() - rdtsc vs QPC timing check
// CW_DETECT_DBG_ARTIFACTS() - debugger registry artifacts
// CW_DETECT_HYPERVISOR() - hypervisor present (CPUID)
// CW_DETECT_VM_VENDOR() - VM vendor string detection
// CW_DETECT_LOW_RESOURCES() - low CPU/RAM (sandbox indicator)
// CW_DETECT_SANDBOX_DLLS() - sandbox DLL detection
// CW_GET_MODULE(name) - getModuleBase via PEB walk (string → hash)
// usage: void* ntdll = CW_GET_MODULE("ntdll.dll");
// CW_GET_PROC(mod, func) - getProcAddress via export walk (string → hash)
// usage: void* fn = CW_GET_PROC(ntdll, "NtClose");
// CW_HASH_RT(str) - runtime FNV-1a hash (case-sensitive)
// CW_HASH_RT_CI(str) - runtime FNV-1a hash (case-insensitive)
// CW_COMPUTE_HASH(ptr, size) - compute hash of memory region
// CW_VERIFY_FUNCS(...) - verify multiple functions aren't hooked
// CW_RET_GADGET() - get cached ret gadget for return address spoofing
// CW_NEG(a) - obfuscated negation using MBA (~x + 1)
//
// Type aliases (in cloakwork namespace):
// cloakwork::obf_bool - shorthand for obfuscated_bool
// cloakwork::meta_func<Sig> - shorthand for metamorphic_function<Sig>
// cloakwork::rt_const<T> - shorthand for runtime_constant<T>
//
// =================================================================
namespace cloakwork {
#if CW_ENABLE_COMPILE_TIME_RANDOM
namespace detail {
template<size_t N>
constexpr uint32_t fnv1a_hash(const char (&str)[N], uint32_t basis = 0x811c9dc5) {
uint32_t hash = basis;
for(size_t i = 0; i < N-1; ++i) {
hash ^= static_cast<uint32_t>(str[i]);
hash *= 0x01000193;
}
return hash;
}
inline bool try_hardware_random(uint64_t& out) {
static bool has_rdseed = [] {
#if defined(_MSC_VER)
int cpuInfo[4];
__cpuidex(cpuInfo, 7, 0);
return (cpuInfo[1] & (1 << 18)) != 0;
#elif defined(__GNUC__) || defined(__clang__)
unsigned int eax, ebx, ecx, edx;
return __get_cpuid_count(7, 0, &eax, &ebx, &ecx, &edx) && (ebx & (1 << 18)) != 0;
#endif
}();
return has_rdseed && _rdseed64_step(reinterpret_cast<unsigned long long*>(&out));
}
// not cryptographic - just makes runtime keys unique per execution
// to frustrate static analysis
inline uint64_t runtime_entropy_seed() {
uint64_t entropy = 0;
if (try_hardware_random(entropy)) {
return entropy;
}
#if CW_KERNEL_MODE
entropy ^= __rdtsc();
// kaslr makes these different per boot
entropy ^= reinterpret_cast<uint64_t>(PsGetCurrentProcess());
entropy ^= reinterpret_cast<uint64_t>(PsGetCurrentThread());
entropy ^= static_cast<uint64_t>(HandleToULong(PsGetCurrentProcessId())) << 32;
entropy ^= static_cast<uint64_t>(HandleToULong(PsGetCurrentThreadId()));
volatile char stack_var;
entropy ^= reinterpret_cast<uint64_t>(&stack_var);
LARGE_INTEGER perf_counter;
perf_counter = KeQueryPerformanceCounter(nullptr);
entropy ^= static_cast<uint64_t>(perf_counter.QuadPart);
LARGE_INTEGER system_time;
KeQuerySystemTime(&system_time);
entropy ^= static_cast<uint64_t>(system_time.QuadPart);
entropy ^= static_cast<uint64_t>(KeQueryInterruptTime());
void* pool_alloc = cloakwork_internal::kernel_alloc(16);
if (pool_alloc) {
entropy ^= reinterpret_cast<uint64_t>(pool_alloc);
cloakwork_internal::kernel_free(pool_alloc);
}
#elif defined(_WIN32)
entropy ^= __rdtsc();
// aslr makes these different per run
entropy ^= static_cast<uint64_t>(GetCurrentProcessId()) << 32;
entropy ^= static_cast<uint64_t>(GetCurrentThreadId());
volatile char stack_var;
entropy ^= reinterpret_cast<uint64_t>(&stack_var);
HMODULE module = GetModuleHandleA(nullptr);
entropy ^= reinterpret_cast<uint64_t>(module);
LARGE_INTEGER perf_counter;
QueryPerformanceCounter(&perf_counter);
entropy ^= static_cast<uint64_t>(perf_counter.QuadPart);
FILETIME ft;
GetSystemTimeAsFileTime(&ft);
entropy ^= (static_cast<uint64_t>(ft.dwHighDateTime) << 32) | ft.dwLowDateTime;
void* heap_alloc = HeapAlloc(GetProcessHeap(), 0, 16);
if (heap_alloc) {
entropy ^= reinterpret_cast<uint64_t>(heap_alloc);
HeapFree(GetProcessHeap(), 0, heap_alloc);
}
#else
entropy ^= reinterpret_cast<uint64_t>(&entropy);
entropy ^= static_cast<uint64_t>(time(nullptr));
#endif
// knuth multiplicative hash mixing
entropy ^= std::rotl(entropy, 31);
entropy *= 0x9e3779b97f4a7c15ULL;
entropy ^= entropy >> 27;
entropy *= 0x94d049bb133111ebULL;
entropy ^= entropy >> 31;
return entropy;
}
// xorshift64*
inline uint64_t runtime_entropy() {
#if CW_KERNEL_MODE
// thread_local doesn't work in kernel drivers, use interlocked state
static volatile LONG64 state = 0;
LONG64 current = InterlockedCompareExchange64(&state, 0, 0);
if (current == 0) {
LONG64 seed = static_cast<LONG64>(runtime_entropy_seed());
InterlockedCompareExchange64(&state, seed, 0);
current = InterlockedCompareExchange64(&state, 0, 0);
if (current == 0) current = seed;
}
LONG64 x = current;
x ^= x >> 12;
x ^= x << 25;
x ^= x >> 27;
InterlockedExchange64(&state, x);
return static_cast<uint64_t>(x) * 0x2545F4914F6CDD1DULL;
#else
thread_local uint64_t state = runtime_entropy_seed();
uint64_t x = state;
x ^= x >> 12;
x ^= x << 25;
x ^= x >> 27;
state = x;
return x * 0x2545F4914F6CDD1DULL;
#endif
}
#if CW_KERNEL_MODE
// consteval with __TIME__/__DATE__ doesn't work properly in WDK
constexpr uint32_t compile_seed_impl(uint32_t line, uint32_t counter) {
uint32_t seed = 0xDEADBEEF;
seed ^= line * 0x01000193;
seed ^= counter * 0x811c9dc5;
seed *= 0x1664525;
seed += 0x1013904223;
return seed;
}
#define CW_COMPILE_SEED() (cloakwork::detail::compile_seed_impl(__LINE__, __COUNTER__))
template<uint32_t Seed>
struct random_generator {
static constexpr uint32_t value() {
return (Seed * 1664525u + 1013904223u);
}
static constexpr uint32_t next() {
return random_generator<value()>::value();
}
};
}
#define CW_RANDOM_CT() (cloakwork::detail::random_generator<CW_COMPILE_SEED()>::value())
#define CW_RAND_CT(min, max) ((min) + (CW_RANDOM_CT() % ((max) - (min) + 1)))
#else
constexpr uint32_t compile_seed() {
constexpr uint32_t time_hash = fnv1a_hash(__TIME__);