-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCObfuscator.java
387 lines (290 loc) · 13.3 KB
/
CObfuscator.java
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
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class CObfuscator {
public static LinkedHashMap<String, String> defineKeywordsHashMap = new LinkedHashMap<String, String>();
public static LinkedHashMap<String, String> defineNumericHashMap = new LinkedHashMap<String, String>();
public static Set<String> variablesAndFunctionsSet = new HashSet<String>();
public static Set<String> numericConstantsSet = new HashSet<String>();
public static String[] variablesAndFunctionsList = null;
public static String[] numericConstantsList = null;
public static boolean commentClosed = true;
public static void main(String[] args) throws IOException {
if (args.length > 0) {
// 1. We open the file (1st pass) to identify variables, function names, numeric cosntants
// We do not need to modify anything inside the code yet
File originalCodeFile = new File(args[0]);
FileReader fileReader = new FileReader(originalCodeFile);
BufferedReader bufferedReader = new BufferedReader(fileReader);
StringBuffer stringBuffer = new StringBuffer();
String lineOfCode;
// Identifying variables&function names and numeric constants and putting them in a HashSet
while ((lineOfCode = bufferedReader.readLine()) != null) {
identifyVarAndFuncNames(lineOfCode);
identifyNumericCostants(lineOfCode);
}
fileReader.close();
bufferedReader.close();
// 2. Transforming sets into arrays so we can order them (HashSets don't maintain order)
// We need them ordered from largest to smallest because we will replace the longest variables & constants first
variablesAndFunctionsList = variablesAndFunctionsSet.toArray(new String[variablesAndFunctionsSet.size()]);
Arrays.sort(variablesAndFunctionsList, (a, b) -> Integer.compare(b.length(), a.length()));
numericConstantsList = numericConstantsSet.toArray(new String[numericConstantsSet.size()]);
Arrays.sort(numericConstantsList, (a, b) -> Integer.compare(b.length(), a.length()));
// 3. 2nd pass through the file - We add DEFINES for C language keywords
// We only need to include the DEFINES section after first #include, not after every #include
boolean definesIncluded = false;
lineOfCode = null;
String modifiedCodeline = null;
fileReader = new FileReader(originalCodeFile);
bufferedReader = new BufferedReader(fileReader);
while ((lineOfCode = bufferedReader.readLine()) != null) {
if (lineOfCode.startsWith("#include") && (!definesIncluded)) {
stringBuffer.append(lineOfCode);
stringBuffer = appendKeywordsDefines(stringBuffer);
definesIncluded = true;
} else {
// If it's a line containing hardcoded strings
if (lineOfCode.contains("\"")) {
lineOfCode = obfuscateStringInCodeLine(lineOfCode);
}
// Replacing C keywords in the code with what is specified in the #define
// section
for (String key : defineKeywordsHashMap.keySet()) {
if (lineOfCode.contains(key)) {
lineOfCode = lineOfCode.replace(key, defineKeywordsHashMap.get(key));
}
}
// 4. Removing the unnecessary spaces, the comments, replacing the variables and
// obfuscating the hardcoded strings
modifiedCodeline = removeTheSpaces(lineOfCode);
modifiedCodeline = removeAllComments(modifiedCodeline);
if (!modifiedCodeline.contains("#define")) {
modifiedCodeline = replaceVariableAndFunctionNames(modifiedCodeline);
}
if (!modifiedCodeline.contains("\"")) {
modifiedCodeline = replaceNumeric(modifiedCodeline);
}
stringBuffer.append(modifiedCodeline);
// stringBuffer.append("\n");
}
}
fileReader.close();
// 5 Generating a truly random number in the range [10000, 1000000]
// And exporting the obfuscated code in the same directory as the original file
String sourceFileName = originalCodeFile.getName();
String sourceFilePath = originalCodeFile.getAbsolutePath();
String pathToWrite = sourceFilePath.replace(sourceFileName, "");
String nameWithoutExtension = sourceFileName.substring(0, sourceFileName.indexOf("."));
int randomNumber = 0;
try {
randomNumber = getTrulyRandomNumber();
} catch (IOException e) {
} catch (InterruptedException e) {
}
String obfuscatedFileName = nameWithoutExtension + String.valueOf(randomNumber) + ".c";
pathToWrite = pathToWrite + obfuscatedFileName;
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(new File(pathToWrite)));
// Write contents of stringBuffer to a file
bufferedWriter.write(stringBuffer.toString());
bufferedWriter.flush();
bufferedWriter.close();
System.out.println("Obfuscated source code file succesfully generated at --- " + pathToWrite);
} else {
System.out.println("Please pass the source code file path as argument");
}
}
private static String replaceNumeric(String modifiedCodeline) {
for (String key : defineNumericHashMap.keySet()) {
if (modifiedCodeline.contains(key)) {
modifiedCodeline = modifiedCodeline.replace(key, defineNumericHashMap.get(key));
}
}
return modifiedCodeline;
}
private static String obfuscateStringInCodeLine(String codeLine) {
// Looks for the content that is between " "
Pattern pattern = Pattern.compile("(?<=\")(.*)(?=\")"); // something that is between " "
Matcher matcher = pattern.matcher(codeLine);
String lineBetweenApostrophe = null;
matcher.find();
lineBetweenApostrophe = codeLine.substring(matcher.start(), matcher.end());
String lineBeforeApostrophe = codeLine.substring(0, codeLine.indexOf("\"") + 1);
if (lineBeforeApostrophe.contains("printf")) {
lineBeforeApostrophe = lineBeforeApostrophe.replace("printf", defineKeywordsHashMap.get("printf"));
}
lineBetweenApostrophe = obfuscateString(lineBetweenApostrophe);
int closingApostropheIndex = codeLine.indexOf("\"", codeLine.indexOf("\"") + 1);
String lineAfterApostrophe = codeLine.substring(closingApostropheIndex, codeLine.length());
for (int i = 0; i < variablesAndFunctionsList.length; i++) {
if (lineAfterApostrophe.contains(variablesAndFunctionsList[i])) {
lineAfterApostrophe = lineAfterApostrophe.replace(variablesAndFunctionsList[i],
String.join("", Collections.nCopies(3 * (i + 1), "a")));
}
}
codeLine = lineBeforeApostrophe + lineBetweenApostrophe + lineAfterApostrophe;
return codeLine;
}
static void identifyVarAndFuncNames(String lineOfCode) {
// Regex demo -> https://regex101.com/r/m6Ugbo/1
Pattern pattern = Pattern.compile("(?:(?<=void|int|char|double|float|short|long)(?:\\s+\\*?)"
+ "([a-zA-Z_$][\\w$]*)(?:\\s*)|(?<=\\G,)(?:\\s*)"
+ "([a-zA-Z_$][\\w$]*)(?:\\s*))(?=;|=|,|\\[|\\(|\\))");
Matcher matcher = pattern.matcher(lineOfCode);
while (matcher.find()) {
String identifier = lineOfCode.substring(matcher.start(), matcher.end()).trim();
// We skip the function main, it is a C keyword and will be defined later
if (!identifier.equals("main")) {
variablesAndFunctionsSet.add(identifier); // We add the variables in a set (we only need each element once)
}
}
}
static String removeTheSpaces(String lineOfCode) {
if (lineOfCode.startsWith("#")) {
return lineOfCode.concat("\n");
} else {
return lineOfCode.trim();
}
}
static String removeAllComments(String codeLine) {
String lineWithoutComment = codeLine;
if (commentClosed == false)
lineWithoutComment = "";
if (codeLine.contains("//")) {
int indexToDeleteFrom = codeLine.indexOf("//");
lineWithoutComment = codeLine.substring(0, indexToDeleteFrom);
}
if (codeLine.startsWith("/*") && codeLine.endsWith("*/")) {
lineWithoutComment = "";
commentClosed = true;
}
if (codeLine.startsWith("/*") && !codeLine.contains("*/")) {
commentClosed = false;
int indexToDeleteFrom = codeLine.indexOf("/*");
lineWithoutComment = codeLine.substring(0, indexToDeleteFrom);
}
if (!codeLine.startsWith("/*") && codeLine.endsWith("*/"))
commentClosed = true;
return lineWithoutComment;
}
static String replaceVariableAndFunctionNames(String codeLine) {
// We relace each variable & function name, from the longest one to the shortest
// with as many number of "a" as the index of that variable
// in the sorted array of variables & function names
for (int i = 0; i < variablesAndFunctionsList.length; i++) {
if (codeLine.contains(variablesAndFunctionsList[i])) {
codeLine = codeLine.replace(variablesAndFunctionsList[i],
String.join("", Collections.nCopies(3 * (i + 1), "a")));
}
}
return codeLine;
}
static String obfuscateString(String line) {
// We transform every character into its ASCII counterpart, turn it to hex
// and add "\x" before so it can be correctly displayed by the C compiler
StringBuilder stringBuilder = new StringBuilder();
char[] charArray = line.toCharArray();
for (int i = 0; i < charArray.length; i++) {
int asciiChar = (int) charArray[i];
String hexAsciiChar = Integer.toHexString(asciiChar);
stringBuilder.append("\\x");
stringBuilder.append(hexAsciiChar);
}
return stringBuilder.toString();
}
static void showProgramIdentifiers() {
// Identifiers = variable names & function names
if (variablesAndFunctionsSet.isEmpty()) {
System.out.println("No variables or functions identified yet!");
} else {
System.out.println("The variables are: ");
for (int i = 0; i < variablesAndFunctionsList.length; i++) {
System.out.println(variablesAndFunctionsList[i]);
}
}
}
static void identifyNumericCostants(String lineOfCode) {
Pattern pattern = Pattern.compile("[0-9]+");
Matcher matcher = pattern.matcher(lineOfCode);
while (matcher.find()) {
String identifiedNumber = lineOfCode.substring(matcher.start(), matcher.end()).trim();
numericConstantsSet.add(identifiedNumber);
}
}
static int getTrulyRandomNumber() throws IOException, InterruptedException {
String postEndpoint = "https://api.random.org/json-rpc/4/invoke";
// Generate random number between 10_000 and 1_000_000
// https://api.random.org/json-rpc/4/request-builder
// My API key from random.org is 1450ff6f-9cb3-4b78-bae7-8b6c9b7e83d0
String inputJson = "{\"jsonrpc\":\"2.0\",\"method\":\"generateIntegers"
+ "\",\"params\":{\"apiKey\":\"1450ff6f-9cb3-4b78-bae7-8b6c9b7e83d0"
+ "\",\"n\":1,\"min\":1000,\"max\":10000000,\"replacement\":true,"
+ "\"base\":10,\"pregeneratedRandomization\":null},\"id\":2699}";
HttpRequest request = HttpRequest.newBuilder().uri(URI.create(postEndpoint))
.header("Content-Type", "application/json").POST(HttpRequest.BodyPublishers.ofString(inputJson))
.build();
HttpClient client = HttpClient.newHttpClient();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
String responseString = response.body();
Pattern pattern = Pattern.compile("(?<=\\[)(.*)(?=\\])"); // what is between [ ]
Matcher matcher = pattern.matcher(responseString);
matcher.find();
String randomNumberString = responseString.substring(matcher.start(), matcher.end());
int randomNumber = Integer.parseInt(randomNumberString);
return randomNumber;
}
private static StringBuffer appendKeywordsDefines(StringBuffer stringBuffer) {
// We add the keyword-define corespondencies
// We use a LinkedHashMap because its keeps the order in which keywords were added
// Later, when we replace C langauge keyword, we want to replace "printf" before "int"
// This is because "printf" containt "int" and we don't want to relace the "int" in "printf"
// This is way it's important to keep printf before int in the HashMap
String defineString, replacement, toReplace;
String[] cLanguageKeyWords = { "auto", "continue", "extern", "volatile", "typedef", "union", "sizeof",
"default", "struct", "switch", "void", "printf", "scanf", "int", "double", "float", "long", "char",
"short", "signed", "unsigned", "static", "const", "if", "while", "for", "else", "do", "break", "case",
"enum", "register", "goto", "return", "main", "getch" };
List<String> linesWithDefines = new ArrayList<>();
stringBuffer.append("\n");
for (int i = 0; i < cLanguageKeyWords.length; i++) {
replacement = String.join("", Collections.nCopies((i + 1), "_"));
;
defineString = "#define " + replacement + " " + cLanguageKeyWords[i];
linesWithDefines.add(defineString);
defineKeywordsHashMap.put(cLanguageKeyWords[i], replacement);
}
for (int i = 0; i < numericConstantsList.length; i++) {
// stringBuffer.append("\n");
replacement = String.join("", Collections.nCopies(3 * (i + 1), "b"));
;
defineString = "#define " + replacement + " " + numericConstantsList[i];
linesWithDefines.add(defineString);
toReplace = numericConstantsList[i];
defineNumericHashMap.put(toReplace, replacement);
}
// We want to shuffle the #define lines randomly
Collections.shuffle(linesWithDefines);
for (String line : linesWithDefines) {
stringBuffer.append(line);
stringBuffer.append("\n");
}
// stringBuffer.append("\n");
return stringBuffer;
}
}