-
Notifications
You must be signed in to change notification settings - Fork 7
/
obfuscator.patch
4135 lines (4124 loc) · 160 KB
/
obfuscator.patch
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
diff --git a/llvm/CMakeLists.txt b/llvm/CMakeLists.txt
index c2fb77d5a371..5ecd674a0c18 100644
--- a/llvm/CMakeLists.txt
+++ b/llvm/CMakeLists.txt
@@ -596,7 +596,7 @@ option(LLVM_ENABLE_LOCAL_SUBMODULE_VISIBILITY "Compile with -fmodules-local-subm
option(LLVM_ENABLE_LIBCXX "Use libc++ if available." OFF)
option(LLVM_ENABLE_LLVM_LIBC "Set to on to link all LLVM executables against LLVM libc, assuming it is accessible by the host compiler." OFF)
option(LLVM_STATIC_LINK_CXX_STDLIB "Statically link the standard library." OFF)
-option(LLVM_ENABLE_LLD "Use lld as C and C++ linker." OFF)
+option(LLVM_ENABLE_LLD "Use lld as C and C++ linker." ON)
option(LLVM_ENABLE_PEDANTIC "Compile with pedantic enabled." ON)
option(LLVM_ENABLE_WERROR "Fail and stop if a warning is triggered." OFF)
diff --git a/llvm/include/llvm/Transforms/Obfuscation/BogusControlFlow.h b/llvm/include/llvm/Transforms/Obfuscation/BogusControlFlow.h
new file mode 100644
index 000000000000..1caa4f6b4d2f
--- /dev/null
+++ b/llvm/include/llvm/Transforms/Obfuscation/BogusControlFlow.h
@@ -0,0 +1,47 @@
+//===- BogusControlFlow.h - bogus control flow obfuscation pass -----------===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file contains includes and defines for the bogus control flow pass
+//
+//===----------------------------------------------------------------------===//
+#ifndef _OBFUSCATION_BOGUSCONTROLFLOW_H_
+#define _OBFUSCATION_BOGUSCONTROLFLOW_H_
+
+#include "llvm/ADT/Statistic.h"
+#include "llvm/CodeGen/ISDOpcodes.h"
+#include "llvm/IR/BasicBlock.h"
+#include "llvm/IR/Constants.h"
+#include "llvm/IR/Function.h"
+#include "llvm/IR/GlobalValue.h"
+#include "llvm/IR/InstrTypes.h"
+#include "llvm/IR/Instructions.h"
+#include "llvm/IR/LLVMContext.h"
+#include "llvm/IR/Module.h"
+#include "llvm/IR/Type.h"
+#include "llvm/Pass.h"
+#include "llvm/Support/CommandLine.h"
+#include "llvm/Support/Debug.h"
+#include "llvm/Support/raw_ostream.h"
+#include "llvm/Transforms/IPO.h"
+#include "llvm/Transforms/Obfuscation/CryptoUtils.h"
+#include "llvm/Transforms/Utils/BasicBlockUtils.h"
+#include "llvm/Transforms/Utils/Cloning.h"
+#include "llvm/IR/PassManager.h" // New PassManager
+
+namespace llvm {
+Pass *createBogus();
+class BogusControlFlowPass : public PassInfoMixin<BogusControlFlowPass>{ // New PassManager
+public:
+ PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM);
+
+ static bool isRequired() { return true; }
+};
+} // namespace llvm
+
+#endif
diff --git a/llvm/include/llvm/Transforms/Obfuscation/CryptoUtils.h b/llvm/include/llvm/Transforms/Obfuscation/CryptoUtils.h
new file mode 100644
index 000000000000..b37f1b18b854
--- /dev/null
+++ b/llvm/include/llvm/Transforms/Obfuscation/CryptoUtils.h
@@ -0,0 +1,152 @@
+//===- CryptoUtils.h - Cryptographically Secure Pseudo-Random Generator ---===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file contains includes and defines for the AES CTR PRNG
+// The AES implementation has been derived and adapted
+// from libtomcrypt (see http://libtom.org)
+// Created on: 22 juin 2012
+// Author(s): jrinaldini, pjunod
+//===----------------------------------------------------------------------===//
+#ifndef _OBFUSCATION_CRYPTUTILS_H
+#define _OBFUSCATION_CRYPTUTILS_H
+
+#include "llvm/Support/ManagedStatic.h"
+
+#include <cstdint>
+#include <cstdio>
+#include <string>
+
+namespace llvm {
+
+class CryptoUtils;
+extern ManagedStatic<CryptoUtils> cryptoutils;
+
+#define BYTE(x, n) (((x) >> (8 * (n))) & 0xFF)
+
+#if defined(__i386) || defined(__i386__) || defined(_M_IX86) || \
+ defined(INTEL_CC) || defined(_WIN64) || defined(_WIN32)
+
+#ifndef ENDIAN_LITTLE
+#define ENDIAN_LITTLE
+#endif
+#define ENDIAN_32BITWORD
+
+#if !defined(_WIN64) || !defined(_WIN32)
+#ifndef UNALIGNED
+#define UNALIGNED
+#endif
+#endif
+
+#elif defined(__alpha)
+
+#ifndef ENDIAN_LITTLE
+#define ENDIAN_LITTLE
+#endif
+#define ENDIAN_64BITWORD
+
+#elif defined(__x86_64__)
+
+#ifndef ENDIAN_LITTLE
+#define ENDIAN_LITTLE
+#endif
+#define ENDIAN_64BITWORD
+#define UNALIGNED
+
+#elif (defined(__R5900) || defined(R5900) || defined(__R5900__)) && \
+ (defined(_mips) || defined(__mips__) || defined(mips))
+
+#ifndef ENDIAN_LITTLE
+#define ENDIAN_LITTLE
+#endif
+#define ENDIAN_64BITWORD
+
+#elif defined(__sparc) || defined(__aarch64__)
+
+#ifndef ENDIAN_BIG
+#define ENDIAN_BIG
+#endif
+#if defined(__arch64__) || defined(__aarch64__)
+#define ENDIAN_64BITWORD
+#else
+#define ENDIAN_32BITWORD
+#endif
+
+#elif defined( __arm ) || defined( __arm__ ) || ( defined( __ARM_ARCH ) && __ARM_ARCH == 4 )
+
+#ifndef ENDIAN_LITTLE
+#define ENDIAN_LITTLE
+#endif
+#define ENDIAN_32BITWORD
+
+#endif
+
+#if defined(__BIG_ENDIAN__) || defined(_BIG_ENDIAN)
+#define ENDIAN_BIG
+#endif
+
+#if !defined(ENDIAN_BIG) && !defined(ENDIAN_LITTLE)
+#error \
+ "Unknown endianness of the compilation platform, check this header aes_encrypt.h"
+#endif
+
+#define CryptoUtils_POOL_SIZE (0x1 << 17) // 2^17
+
+class CryptoUtils {
+public:
+ CryptoUtils();
+ ~CryptoUtils();
+
+ char *get_seed();
+ void get_bytes(char *buffer, const int len);
+ char get_char();
+ bool prng_seed(std::string const &seed);
+
+ // Returns a uniformly distributed 8-bit value
+ uint8_t get_uint8_t();
+ // Returns a uniformly distributed 32-bit value
+ uint32_t get_uint32_t();
+ // Returns an integer uniformly distributed on [0, max[
+ uint32_t get_range(const uint32_t max);
+ // Returns a uniformly distributed 64-bit value
+ uint64_t get_uint64_t();
+
+ // Scramble a 32-bit value depending on a 128-bit value
+ unsigned scramble32(const unsigned in, const char key[16]);
+
+ int sha256(const char *msg, unsigned char *hash);
+
+private:
+ uint32_t ks[44];
+ char key[16];
+ char ctr[16];
+ char pool[CryptoUtils_POOL_SIZE];
+ uint32_t idx;
+ std::string seed;
+ bool seeded;
+
+ typedef struct {
+ uint64_t length;
+ uint32_t state[8], curlen;
+ unsigned char buf[64];
+ } sha256_state;
+
+ void aes_compute_ks(uint32_t *ks, const char *k);
+ void aes_encrypt(char *out, const char *in, const uint32_t *ks);
+ bool prng_seed();
+ void inc_ctr();
+ void populate_pool();
+ int sha256_done(sha256_state *md, unsigned char *out);
+ int sha256_init(sha256_state *md);
+ static int sha256_compress(sha256_state *md, unsigned char *buf);
+ int sha256_process(sha256_state *md, const unsigned char *in,
+ unsigned long inlen);
+};
+} // namespace llvm
+
+#endif
diff --git a/llvm/include/llvm/Transforms/Obfuscation/Flattening.h b/llvm/include/llvm/Transforms/Obfuscation/Flattening.h
new file mode 100644
index 000000000000..fff5e4e2ce1f
--- /dev/null
+++ b/llvm/include/llvm/Transforms/Obfuscation/Flattening.h
@@ -0,0 +1,39 @@
+//===- FlatteningIncludes.h - Flattening Obfuscation pass------------------===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file contains includes and defines for the flattening pass
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _OBFUSCATION_FLATTENING_H_
+#define _OBFUSCATION_FLATTENING_H_
+
+#include "llvm/ADT/Statistic.h"
+#include "llvm/IR/Function.h"
+#include "llvm/IR/Module.h"
+#include "llvm/Pass.h"
+#include "llvm/Support/CommandLine.h"
+#include "llvm/Transforms/IPO.h"
+#include "llvm/Transforms/Obfuscation/CryptoUtils.h"
+#include "llvm/Transforms/Obfuscation/Utils.h"
+#include "llvm/Transforms/Scalar.h"
+#include "llvm/Transforms/Utils/Local.h" // For DemoteRegToStack and DemotePHIToStack
+#include "llvm/IR/PassManager.h" // New PassManager
+
+namespace llvm {
+Pass *createFlattening();
+class FlatteningPass : public PassInfoMixin<FlatteningPass>{ // New PassManager
+public:
+ PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM);
+
+ static bool isRequired() { return true; }
+};
+} // namespace llvm
+
+#endif
diff --git a/llvm/include/llvm/Transforms/Obfuscation/Split.h b/llvm/include/llvm/Transforms/Obfuscation/Split.h
new file mode 100644
index 000000000000..6e96bf609810
--- /dev/null
+++ b/llvm/include/llvm/Transforms/Obfuscation/Split.h
@@ -0,0 +1,38 @@
+//===- FlatteningIncludes.h - Flattening Obfuscation pass------------------===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file contains includes and defines for the split basicblock pass
+//
+//===----------------------------------------------------------------------===//
+#ifndef _OBFUSCATION_SPLIT_H_
+#define _OBFUSCATION_SPLIT_H_
+
+#include "llvm/ADT/Statistic.h"
+#include "llvm/IR/BasicBlock.h"
+#include "llvm/IR/Module.h"
+#include "llvm/Pass.h"
+#include "llvm/Support/CommandLine.h"
+#include "llvm/Transforms/IPO.h"
+#include "llvm/Transforms/Obfuscation/CryptoUtils.h"
+#include "llvm/Transforms/Obfuscation/Utils.h"
+#include "llvm/Transforms/Scalar.h"
+#include "llvm/Transforms/Utils/Local.h" // For DemoteRegToStack and DemotePHIToStack
+#include "llvm/IR/PassManager.h" // New PassManager
+
+namespace llvm {
+Pass *createSplitBasicBlock();
+class SplitBasicBlockPass : public PassInfoMixin<SplitBasicBlockPass>{ // New PassManager
+public:
+ PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM);
+
+ static bool isRequired() { return true; }
+};
+}
+
+#endif
diff --git a/llvm/include/llvm/Transforms/Obfuscation/StringObfuscation.h b/llvm/include/llvm/Transforms/Obfuscation/StringObfuscation.h
new file mode 100755
index 000000000000..9c54defc4c7b
--- /dev/null
+++ b/llvm/include/llvm/Transforms/Obfuscation/StringObfuscation.h
@@ -0,0 +1,13 @@
+// LLVM include
+#include "llvm/Pass.h"
+#include "llvm/IR/PassManager.h" // New PassManager
+
+namespace llvm {
+ Pass* createStringObfuscation(bool flag);
+class StringObfuscationNewPass : public PassInfoMixin<StringObfuscationNewPass>{ // New PassManager
+public:
+ PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM);
+
+ static bool isRequired() { return true; }
+};
+}
diff --git a/llvm/include/llvm/Transforms/Obfuscation/Substitution.h b/llvm/include/llvm/Transforms/Obfuscation/Substitution.h
new file mode 100644
index 000000000000..31d42557cd26
--- /dev/null
+++ b/llvm/include/llvm/Transforms/Obfuscation/Substitution.h
@@ -0,0 +1,37 @@
+//===- SubstitutionIncludes.h - Substitution Obfuscation ------------------===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file contains includes and defines for the substitution pass
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _OBFUSCATION_SUBSTITUTIONS_H_
+#define _OBFUSCATION_SUBSTITUTIONS_H_
+
+#include "llvm/ADT/Statistic.h"
+#include "llvm/IR/Function.h"
+#include "llvm/IR/Instructions.h"
+#include "llvm/IR/Module.h"
+#include "llvm/Pass.h"
+#include "llvm/Support/CommandLine.h"
+#include "llvm/Transforms/IPO.h"
+#include "llvm/Transforms/Obfuscation/CryptoUtils.h"
+#include "llvm/IR/PassManager.h" // New PassManager
+
+namespace llvm {
+Pass *createSubstitution();
+class SubstitutionPass : public PassInfoMixin<SubstitutionPass>{ // New PassManager
+public:
+ PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM);
+
+ static bool isRequired() { return true; }
+};
+} // namespace llvm
+
+#endif
diff --git a/llvm/include/llvm/Transforms/Obfuscation/Utils.h b/llvm/include/llvm/Transforms/Obfuscation/Utils.h
new file mode 100644
index 000000000000..36c69515ae66
--- /dev/null
+++ b/llvm/include/llvm/Transforms/Obfuscation/Utils.h
@@ -0,0 +1,13 @@
+#ifndef _OBFUSCATION_UTILS_H_
+#define _OBFUSCATION_UTILS_H_
+
+#include "llvm/IR/Function.h"
+#include "llvm/IR/Instructions.h"
+#include "llvm/Transforms/Utils/Local.h" // For DemoteRegToStack and DemotePHIToStack
+#include <string>
+
+void fixStack(llvm::Function *f);
+llvm::StringRef readAnnotate(llvm::Function *f, llvm::StringRef attr);
+bool toObfuscate(bool flag, llvm::Function *f, llvm::StringRef attribute);
+
+#endif
diff --git a/llvm/lib/Passes/PassBuilder.cpp b/llvm/lib/Passes/PassBuilder.cpp
index 000594f0e7f4..5537956b5f18 100644
--- a/llvm/lib/Passes/PassBuilder.cpp
+++ b/llvm/lib/Passes/PassBuilder.cpp
@@ -290,6 +290,12 @@
#include "llvm/Transforms/Vectorize/VectorCombine.h"
#include <optional>
+#include "llvm/Transforms/Obfuscation/Flattening.h"
+#include "llvm/Transforms/Obfuscation/Substitution.h"
+#include "llvm/Transforms/Obfuscation/BogusControlFlow.h"
+#include "llvm/Transforms/Obfuscation/Split.h"
+#include "llvm/Transforms/Obfuscation/StringObfuscation.h"
+
using namespace llvm;
static const Regex DefaultAliasRegex(
diff --git a/llvm/lib/Passes/PassBuilderPipelines.cpp b/llvm/lib/Passes/PassBuilderPipelines.cpp
index 6ede86382912..3a7415476968 100644
--- a/llvm/lib/Passes/PassBuilderPipelines.cpp
+++ b/llvm/lib/Passes/PassBuilderPipelines.cpp
@@ -136,6 +136,12 @@
#include "llvm/Transforms/Vectorize/SLPVectorizer.h"
#include "llvm/Transforms/Vectorize/VectorCombine.h"
+#include "llvm/Transforms/Obfuscation/Flattening.h"
+#include "llvm/Transforms/Obfuscation/Substitution.h"
+#include "llvm/Transforms/Obfuscation/BogusControlFlow.h"
+#include "llvm/Transforms/Obfuscation/Split.h"
+#include "llvm/Transforms/Obfuscation/StringObfuscation.h"
+
using namespace llvm;
static cl::opt<InliningAdvisorMode> UseInlineAdvisor(
@@ -285,6 +291,15 @@ cl::opt<bool> EnableMemProfContextDisambiguation(
extern cl::opt<bool> EnableInferAlignmentPass;
} // namespace llvm
+// Flags for obfuscation
+#if defined(LLVM_ENABLE_NEW_PASS_MANAGER) && LLVM_ENABLE_NEW_PASS_MANAGER == 1
+static cl::opt<std::string> AesSeed("aesSeed", cl::init(""),
+ cl::desc("seed for the AES-CTR PRNG"));
+
+static cl::opt<std::string> Seed("seed", cl::init(""),
+ cl::desc("seed for the random"));
+#endif
+
PipelineTuningOptions::PipelineTuningOptions() {
LoopInterleaving = true;
LoopVectorization = true;
@@ -298,6 +313,17 @@ PipelineTuningOptions::PipelineTuningOptions() {
MergeFunctions = EnableMergeFunctions;
InlinerThreshold = -1;
EagerlyInvalidateAnalyses = EnableEagerlyInvalidateAnalyses;
+
+#if defined(LLVM_ENABLE_NEW_PASS_MANAGER) && LLVM_ENABLE_NEW_PASS_MANAGER == 1
+ if(!AesSeed.empty()) {
+ llvm::cryptoutils->prng_seed(AesSeed.c_str());
+ }
+
+ //random generator
+ if(!Seed.empty()) {
+ llvm::cryptoutils->prng_seed(Seed.c_str());
+ }
+#endif
}
namespace llvm {
@@ -1363,6 +1389,13 @@ PassBuilder::buildModuleOptimizationPipeline(OptimizationLevel Level,
invokeOptimizerEarlyEPCallbacks(MPM, Level);
FunctionPassManager OptimizePM;
+
+ // Obfuscation
+ OptimizePM.addPass(BogusControlFlowPass());
+ OptimizePM.addPass(SplitBasicBlockPass());
+ OptimizePM.addPass(FlatteningPass());
+ OptimizePM.addPass(SubstitutionPass());
+
// Scheduling LoopVersioningLICM when inlining is over, because after that
// we may see more accurate aliasing. Reason to run this late is that too
// early versioning may prevent further inlining due to increase of code
@@ -1446,10 +1479,15 @@ PassBuilder::buildModuleOptimizationPipeline(OptimizationLevel Level,
OptimizePM.addPass(
SimplifyCFGPass(SimplifyCFGOptions().convertSwitchRangeToICmp(true)));
+ // Obfuscation
+ OptimizePM.addPass(SubstitutionPass());
+
// Add the core optimizing pipeline.
MPM.addPass(createModuleToFunctionPassAdaptor(std::move(OptimizePM),
PTO.EagerlyInvalidateAnalyses));
+ MPM.addPass(StringObfuscationNewPass());
+
invokeOptimizerLastEPCallbacks(MPM, Level);
// Split out cold code. Splitting is done late to avoid hiding context from
diff --git a/llvm/lib/Passes/PassRegistry.def b/llvm/lib/Passes/PassRegistry.def
index e59795c7b084..4484fcab0b0c 100644
--- a/llvm/lib/Passes/PassRegistry.def
+++ b/llvm/lib/Passes/PassRegistry.def
@@ -115,6 +115,7 @@ MODULE_PASS("print<inline-advisor>", InlineAdvisorAnalysisPrinterPass(dbgs()))
MODULE_PASS("print<module-debuginfo>", ModuleDebugInfoPrinterPass(dbgs()))
MODULE_PASS("pseudo-probe", SampleProfileProbePass(TM))
MODULE_PASS("pseudo-probe-update", PseudoProbeUpdatePass())
+MODULE_PASS("obf-str", StringObfuscationNewPass())
MODULE_PASS("recompute-globalsaa", RecomputeGlobalsAAPass())
MODULE_PASS("rel-lookup-table-converter", RelLookupTableConverterPass())
MODULE_PASS("rewrite-statepoints-for-gc", RewriteStatepointsForGC())
@@ -336,6 +337,10 @@ FUNCTION_PASS("guard-widening", GuardWideningPass())
FUNCTION_PASS("gvn-hoist", GVNHoistPass())
FUNCTION_PASS("gvn-sink", GVNSinkPass())
FUNCTION_PASS("helloworld", HelloWorldPass())
+FUNCTION_PASS("obf-fla", FlatteningPass())
+FUNCTION_PASS("obf-sub", SubstitutionPass())
+FUNCTION_PASS("obf-bcf", BogusControlFlowPass())
+FUNCTION_PASS("obf-split", SplitBasicBlockPass())
FUNCTION_PASS("indirectbr-expand", IndirectBrExpandPass(TM))
FUNCTION_PASS("infer-address-spaces", InferAddressSpacesPass())
FUNCTION_PASS("infer-alignment", InferAlignmentPass())
diff --git a/llvm/lib/Transforms/CMakeLists.txt b/llvm/lib/Transforms/CMakeLists.txt
index 84a7e34147d0..26ab00f2cef6 100644
--- a/llvm/lib/Transforms/CMakeLists.txt
+++ b/llvm/lib/Transforms/CMakeLists.txt
@@ -9,4 +9,5 @@ add_subdirectory(Hello)
add_subdirectory(ObjCARC)
add_subdirectory(Coroutines)
add_subdirectory(CFGuard)
+add_subdirectory(Obfuscation)
add_subdirectory(HipStdPar)
diff --git a/llvm/lib/Transforms/IPO/CMakeLists.txt b/llvm/lib/Transforms/IPO/CMakeLists.txt
index 034f1587ae8d..5c73dfe3c5c2 100644
--- a/llvm/lib/Transforms/IPO/CMakeLists.txt
+++ b/llvm/lib/Transforms/IPO/CMakeLists.txt
@@ -72,4 +72,5 @@ add_llvm_component_library(LLVMipo
TransformUtils
Vectorize
Instrumentation
+ Obfuscation
)
diff --git a/llvm/lib/Transforms/Obfuscation/BogusControlFlow.cpp b/llvm/lib/Transforms/Obfuscation/BogusControlFlow.cpp
new file mode 100644
index 000000000000..f669b2c5bbcd
--- /dev/null
+++ b/llvm/lib/Transforms/Obfuscation/BogusControlFlow.cpp
@@ -0,0 +1,714 @@
+//===- BogusControlFlow.cpp - BogusControlFlow Obfuscation pass ----------===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===---------------------------------------------------------------------===//
+//
+// This file implements BogusControlFlow's pass, inserting bogus control flow.
+// It adds bogus flow to a given basic block this way:
+//
+// Before :
+// entry
+// |
+// ______v______
+// | Original |
+// |_____________|
+// |
+// v
+// return
+//
+// After :
+// entry
+// |
+// ____v_____
+// |condition*| (false)
+// |__________|----+
+// (true)| |
+// | |
+// ______v______ |
+// +-->| Original* | |
+// | |_____________| (true)
+// | (false)| !-----------> return
+// | ______v______ |
+// | | Altered |<--!
+// | |_____________|
+// |__________|
+//
+// * The results of these terminator's branch's conditions are always true, but
+// these predicates are
+// opacificated. For this, we declare two global values: x and y, and replace
+// the FCMP_TRUE predicate with (y < 10 || x * (x + 1) % 2 == 0) (this could
+// be improved, as the global values give a hint on where are the opaque
+// predicates)
+//
+// The altered bloc is a copy of the original's one with junk instructions
+// added accordingly to the type of instructions we found in the bloc
+//
+// Each basic block of the function is choosen if a random number in the range
+// [0,100] is smaller than the choosen probability rate. The default value
+// is 30. This value can be modify using the option -boguscf-prob=[value].
+// Value must be an integer in the range [0, 100], otherwise the default value
+// is taken. Exemple: -bcf -bcf_prob=60
+//
+// The pass can also be loop many times on a function, including on the basic
+// blocks added in a previous loop. Be careful if you use a big probability
+// number and choose to run the loop many times wich may cause the pass to run
+// for a very long time. The default value is one loop, but you can change it
+// with -boguscf-loop=[value]. Value must be an integer greater than 1,
+// otherwise the default value is taken. Exemple: -bcf -bcf_loop=2
+//
+//
+// Defined debug types:
+// - "gen" : general informations
+// - "opt" : concerning the given options (parameter)
+// - "cfg" : printing the various function's cfg before transformation
+// and after transformation if it has been modified, and all
+// the functions at end of the pass, after doFinalization.
+//
+// To use them all, simply use the -debug option.
+// To use only one of them, follow the pass' command by -debug-only=name.
+// Exemple, -bcf -debug-only=cfg
+//
+//
+// Stats:
+// The following statistics will be printed if you use
+// the -stats command:
+//
+// a. Number of functions in this module
+// b. Number of times we run on each function
+// c. Initial number of basic blocks in this module
+// d. Number of modified basic blocks
+// e. Number of added basic blocks in this module
+// f. Final number of basic blocks in this module
+//
+// file : lib/Transforms/Obfuscation/BogusControlFlow.cpp
+// date : june 2012
+// version: 1.0
+// author : [email protected]
+// modifications: pjunod, Rinaldini Julien
+// project: Obfuscator
+// option : -bcf
+//
+//===---------------------------------------------------------------------===//
+
+#include "llvm/Transforms/Obfuscation/BogusControlFlow.h"
+#include "llvm/Transforms/Obfuscation/Utils.h"
+
+// Stats
+#define DEBUG_TYPE "BogusControlFlow"
+STATISTIC(NumFunction, "a. Number of functions in this module");
+STATISTIC(NumTimesOnFunctions, "b. Number of times we run on each function");
+STATISTIC(InitNumBasicBlocks,
+ "c. Initial number of basic blocks in this module");
+STATISTIC(NumModifiedBasicBlocks, "d. Number of modified basic blocks");
+STATISTIC(NumAddedBasicBlocks,
+ "e. Number of added basic blocks in this module");
+STATISTIC(FinalNumBasicBlocks,
+ "f. Final number of basic blocks in this module");
+
+using namespace llvm;
+
+// Options for the pass
+const int defaultObfRate = 30, defaultObfTime = 1;
+
+static cl::opt<bool>
+ BogusControlFlowFlag("bcf", cl::init(false),
+ cl::desc("Enable bogus control flow"));
+
+static cl::opt<int>
+ ObfProbRate("bcf_prob",
+ cl::desc("Choose the probability [%] each basic blocks will be "
+ "obfuscated by the -bcf pass"),
+ cl::value_desc("probability rate"), cl::init(defaultObfRate),
+ cl::Optional);
+
+static cl::opt<int>
+ ObfTimes("bcf_loop",
+ cl::desc("Choose how many time the -bcf pass loop on a function"),
+ cl::value_desc("number of times"), cl::init(defaultObfTime),
+ cl::Optional);
+
+namespace {
+struct BogusControlFlow : public FunctionPass {
+ static char ID; // Pass identification
+ BogusControlFlow() : FunctionPass(ID) {}
+
+ /* runOnFunction
+ *
+ * Overwrite FunctionPass method to apply the transformation
+ * to the function. See header for more details.
+ */
+ virtual bool runOnFunction(Function &F) {
+ // Check if the percentage is correct
+ auto probs = readAnnotate(&F, ObfProbRate.ArgStr);
+ if (!probs.empty()) {
+ int value = ObfProbRate;
+ if (!probs.getAsInteger(0, value))
+ ObfProbRate.setValue(value);
+ }
+ auto loops = readAnnotate(&F, ObfTimes.ArgStr);
+ if (!loops.empty()) {
+ int value = ObfTimes;
+ if (!loops.getAsInteger(0, value))
+ ObfTimes.setValue(value);
+ }
+ if (ObfTimes <= 0) {
+ errs() << "BogusControlFlow application number -bcf_loop=x must be x > 0";
+ return false;
+ }
+
+ // Check if the number of applications is correct
+ if (!((ObfProbRate > 0) && (ObfProbRate <= 100))) {
+ errs() << "BogusControlFlow application basic blocks percentage "
+ "-bcf_prob=x must be 0 < x <= 100";
+ return false;
+ }
+ // If fla annotations
+ if (toObfuscate(BogusControlFlowFlag, &F, "bcf")) {
+ outs() << "Apply bogus control flow obfuscation for " << F.getName()
+ << "\n";
+ bogus(F);
+ doF(*F.getParent());
+ return true;
+ }
+
+ return false;
+ } // end of runOnFunction()
+
+ void bogus(Function &F) {
+ // For statistics and debug
+ ++NumFunction;
+ int NumBasicBlocks = 0;
+ bool firstTime = true; // First time we do the loop in this function
+ bool hasBeenModified = false;
+ DEBUG_WITH_TYPE("opt", errs() << "bcf: Started on function " << F.getName()
+ << "\n");
+ DEBUG_WITH_TYPE("opt",
+ errs() << "bcf: Probability rate: " << ObfProbRate << "\n");
+ if (ObfProbRate < 0 || ObfProbRate > 100) {
+ DEBUG_WITH_TYPE("opt", errs()
+ << "bcf: Incorrect value,"
+ << " probability rate set to default value: "
+ << defaultObfRate << " \n");
+ ObfProbRate = defaultObfRate;
+ }
+ DEBUG_WITH_TYPE("opt", errs()
+ << "bcf: How many times: " << ObfTimes << "\n");
+ if (ObfTimes <= 0) {
+ DEBUG_WITH_TYPE("opt", errs()
+ << "bcf: Incorrect value,"
+ << " must be greater than 1. Set to default: "
+ << defaultObfTime << " \n");
+ ObfTimes = defaultObfTime;
+ }
+ NumTimesOnFunctions = ObfTimes;
+ int NumObfTimes = ObfTimes;
+
+ // Real begining of the pass
+ // Loop for the number of time we run the pass on the function
+ do {
+ DEBUG_WITH_TYPE("cfg", errs() << "bcf: Function " << F.getName()
+ << ", before the pass:\n");
+ DEBUG_WITH_TYPE("cfg", F.viewCFG());
+ // Put all the function's block in a list
+ std::list<BasicBlock *> basicBlocks;
+ for (Function::iterator i = F.begin(); i != F.end(); ++i) {
+ if (!i->isEHPad())
+ basicBlocks.push_back(&*i);
+ }
+ DEBUG_WITH_TYPE(
+ "gen", errs() << "bcf: Iterating on the Function's Basic Blocks\n");
+
+ while (!basicBlocks.empty()) {
+ NumBasicBlocks++;
+ // Basic Blocks' selection
+ if ((int)llvm::cryptoutils->get_range(100) <= ObfProbRate) {
+ DEBUG_WITH_TYPE("opt", errs() << "bcf: Block " << NumBasicBlocks
+ << " selected. \n");
+ hasBeenModified = true;
+ ++NumModifiedBasicBlocks;
+ NumAddedBasicBlocks += 3;
+ FinalNumBasicBlocks += 3;
+ // Add bogus flow to the given Basic Block (see description)
+ BasicBlock *basicBlock = basicBlocks.front();
+ addBogusFlow(basicBlock, F);
+ } else {
+ DEBUG_WITH_TYPE("opt", errs() << "bcf: Block " << NumBasicBlocks
+ << " not selected.\n");
+ }
+ // remove the block from the list
+ basicBlocks.pop_front();
+
+ if (firstTime) { // first time we iterate on this function
+ ++InitNumBasicBlocks;
+ ++FinalNumBasicBlocks;
+ }
+ } // end of while(!basicBlocks.empty())
+ DEBUG_WITH_TYPE("gen",
+ errs() << "bcf: End of function " << F.getName() << "\n");
+ if (hasBeenModified) { // if the function has been modified
+ DEBUG_WITH_TYPE("cfg", errs() << "bcf: Function " << F.getName()
+ << ", after the pass: \n");
+ DEBUG_WITH_TYPE("cfg", F.viewCFG());
+ } else {
+ DEBUG_WITH_TYPE("cfg", errs()
+ << "bcf: Function's not been modified \n");
+ }
+ firstTime = false;
+ } while (--NumObfTimes > 0);
+ }
+
+ /* addBogusFlow
+ *
+ * Add bogus flow to a given basic block, according to the header's
+ * description
+ */
+ virtual void addBogusFlow(BasicBlock *basicBlock, Function &F) {
+
+ // Split the block: first part with only the phi nodes and debug info and
+ // terminator
+ // created by splitBasicBlock. (-> No instruction)
+ // Second part with every instructions from the original
+ // block
+ // We do this way, so we don't have to adjust all the phi nodes, metadatas
+ // and so on for the first block. We have to let the phi nodes in the first
+ // part, because they actually are updated in the second part according to
+ // them.
+ BasicBlock::iterator i1 = basicBlock->begin();
+ if (basicBlock->getFirstNonPHIOrDbgOrLifetime())
+ i1 = (BasicBlock::iterator)basicBlock->getFirstNonPHIOrDbgOrLifetime();
+ Twine *var;
+ var = new Twine("originalBB");
+ BasicBlock *originalBB = basicBlock->splitBasicBlock(i1, *var);
+ DEBUG_WITH_TYPE("gen", errs()
+ << "bcf: First and original basic blocks: ok\n");
+
+ // Creating the altered basic block on which the first basicBlock will jump
+ Twine *var3 = new Twine("alteredBB");
+ BasicBlock *alteredBB = createAlteredBasicBlock(originalBB, *var3, &F);
+ DEBUG_WITH_TYPE("gen", errs() << "bcf: Altered basic block: ok\n");
+
+ // Now that all the blocks are created,
+ // we modify the terminators to adjust the control flow.
+
+ alteredBB->getTerminator()->eraseFromParent();
+ basicBlock->getTerminator()->eraseFromParent();
+ DEBUG_WITH_TYPE("gen", errs() << "bcf: Terminator removed from the altered"
+ << " and first basic blocks\n");
+
+ // Preparing a condition..
+ // For now, the condition is an always true comparaison between 2 float
+ // This will be complicated after the pass (in doFinalization())
+ Value *LHS = ConstantFP::get(Type::getFloatTy(F.getContext()), 1.0);
+ Value *RHS = ConstantFP::get(Type::getFloatTy(F.getContext()), 1.0);
+ DEBUG_WITH_TYPE("gen", errs() << "bcf: Value LHS and RHS created\n");
+
+ // The always true condition. End of the first block
+ Twine *var4 = new Twine("condition");
+ FCmpInst *condition =
+ new FCmpInst(*basicBlock, FCmpInst::FCMP_TRUE, LHS, RHS, *var4);
+ DEBUG_WITH_TYPE("gen", errs() << "bcf: Always true condition created\n");
+
+ // Jump to the original basic block if the condition is true or
+ // to the altered block if false.
+ BranchInst::Create(originalBB, alteredBB, (Value *)condition, basicBlock);
+ DEBUG_WITH_TYPE(
+ "gen",
+ errs() << "bcf: Terminator instruction in first basic block: ok\n");
+
+ // The altered block loop back on the original one.
+ BranchInst::Create(originalBB, alteredBB);
+ DEBUG_WITH_TYPE(
+ "gen", errs() << "bcf: Terminator instruction in altered block: ok\n");
+
+ // The end of the originalBB is modified to give the impression that
+ // sometimes it continues in the loop, and sometimes it return the desired
+ // value (of course it's always true, so it always use the original
+ // terminator..
+ // but this will be obfuscated too;) )
+
+ // iterate on instruction just before the terminator of the originalBB
+ BasicBlock::iterator i = originalBB->end();
+
+ // Split at this point (we only want the terminator in the second part)
+ Twine *var5 = new Twine("originalBBpart2");
+ BasicBlock *originalBBpart2 = originalBB->splitBasicBlock(--i, *var5);
+ DEBUG_WITH_TYPE("gen",
+ errs() << "bcf: Terminator part of the original basic block"
+ << " is isolated\n");
+ // the first part go either on the return statement or on the begining
+ // of the altered block.. So we erase the terminator created when splitting.
+ originalBB->getTerminator()->eraseFromParent();
+ // We add at the end a new always true condition
+ Twine *var6 = new Twine("condition2");
+ FCmpInst *condition2 =
+ new FCmpInst(*originalBB, CmpInst::FCMP_TRUE, LHS, RHS, *var6);
+ BranchInst::Create(originalBBpart2, alteredBB, (Value *)condition2,
+ originalBB);
+ DEBUG_WITH_TYPE("gen", errs()
+ << "bcf: Terminator original basic block: ok\n");
+ DEBUG_WITH_TYPE("gen", errs() << "bcf: End of addBogusFlow().\n");
+
+ } // end of addBogusFlow()
+
+ /* createAlteredBasicBlock
+ *
+ * This function return a basic block similar to a given one.
+ * It's inserted just after the given basic block.
+ * The instructions are similar but junk instructions are added between
+ * the cloned one. The cloned instructions' phi nodes, metadatas, uses and
+ * debug locations are adjusted to fit in the cloned basic block and
+ * behave nicely.
+ */
+ virtual BasicBlock *createAlteredBasicBlock(BasicBlock *basicBlock,
+ const Twine &Name = "gen",
+ Function *F = 0) {
+ // Useful to remap the informations concerning instructions.
+ ValueToValueMapTy VMap;
+ BasicBlock *alteredBB = llvm::CloneBasicBlock(basicBlock, VMap, Name, F);
+ DEBUG_WITH_TYPE("gen", errs() << "bcf: Original basic block cloned\n");
+ // Remap operands.
+ BasicBlock::iterator ji = basicBlock->begin();
+ for (BasicBlock::iterator i = alteredBB->begin(), e = alteredBB->end();
+ i != e; ++i) {
+ // Loop over the operands of the instruction
+ for (User::op_iterator opi = i->op_begin(), ope = i->op_end(); opi != ope;
+ ++opi) {
+ // get the value for the operand
+ Value *v = MapValue(*opi, VMap, RF_None, 0);
+ if (v != 0) {
+ *opi = v;
+ DEBUG_WITH_TYPE("gen",
+ errs() << "bcf: Value's operand has been setted\n");
+ }
+ }
+ DEBUG_WITH_TYPE("gen", errs() << "bcf: Operands remapped\n");
+ // Remap phi nodes' incoming blocks.
+ if (PHINode *pn = dyn_cast<PHINode>(i)) {
+ for (unsigned j = 0, e = pn->getNumIncomingValues(); j != e; ++j) {
+ Value *v = MapValue(pn->getIncomingBlock(j), VMap, RF_None, 0);
+ if (v != 0) {
+ pn->setIncomingBlock(j, cast<BasicBlock>(v));
+ }
+ }
+ }
+ DEBUG_WITH_TYPE("gen", errs() << "bcf: PHINodes remapped\n");
+ // Remap attached metadata.
+ SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
+ i->getAllMetadata(MDs);
+ DEBUG_WITH_TYPE("gen", errs() << "bcf: Metadatas remapped\n");
+ // important for compiling with DWARF, using option -g.
+ i->setDebugLoc(ji->getDebugLoc());
+ ji++;
+ DEBUG_WITH_TYPE("gen", errs()
+ << "bcf: Debug information location setted\n");
+
+ } // The instructions' informations are now all correct
+
+ DEBUG_WITH_TYPE("gen",
+ errs() << "bcf: The cloned basic block is now correct\n");
+ DEBUG_WITH_TYPE(
+ "gen",
+ errs() << "bcf: Starting to add junk code in the cloned bloc...\n");
+
+ // add random instruction in the middle of the bloc. This part can be
+ // improve
+ for (BasicBlock::iterator i = alteredBB->begin(), e = alteredBB->end();
+ i != e; ++i) {
+ // in the case we find binary operator, we modify slightly this part by
+ // randomly insert some instructions
+ if (i->isBinaryOp()) { // binary instructions
+ unsigned opcode = i->getOpcode();
+ BinaryOperator *op, *op1 = NULL;
+ UnaryOperator *op2;
+ Twine *var = new Twine("_");
+ // treat differently float or int
+ // Binary int
+ if (opcode == Instruction::Add || opcode == Instruction::Sub ||
+ opcode == Instruction::Mul || opcode == Instruction::UDiv ||
+ opcode == Instruction::SDiv || opcode == Instruction::URem ||
+ opcode == Instruction::SRem || opcode == Instruction::Shl ||
+ opcode == Instruction::LShr || opcode == Instruction::AShr ||
+ opcode == Instruction::And || opcode == Instruction::Or ||
+ opcode == Instruction::Xor) {
+ for (int random = (int)llvm::cryptoutils->get_range(10); random < 10;
+ ++random) {
+ switch (llvm::cryptoutils->get_range(4)) { // to improve
+ case 0: // do nothing
+ break;
+ case 1:
+ op = BinaryOperator::CreateNeg(i->getOperand(0), *var, &*i);
+ op1 = BinaryOperator::Create(Instruction::Add, op,
+ i->getOperand(1), "gen", &*i);
+ break;
+ case 2:
+ op1 = BinaryOperator::Create(Instruction::Sub, i->getOperand(0),
+ i->getOperand(1), *var, &*i);
+ op = BinaryOperator::Create(Instruction::Mul, op1,
+ i->getOperand(1), "gen", &*i);
+ break;
+ case 3:
+ op = BinaryOperator::Create(Instruction::Shl, i->getOperand(0),
+ i->getOperand(1), *var, &*i);
+ break;
+ }
+ }
+ }