-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStringDeobfuscator.java
More file actions
264 lines (216 loc) · 9.25 KB
/
StringDeobfuscator.java
File metadata and controls
264 lines (216 loc) · 9.25 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
//Finds strings obfuscated by https://github.com/adamyaxley/Obfuscate and deobfuscates them.
//Check out the program in the obfuscated-example directory as an example target.
//Different compilers and optimization levels may require changes to the script.
//@author uintmax
//@category Deobfuscation
//@keybinding
//@menupath
//@toolbar
//@runtime Java
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HexFormat;
import java.util.List;
import ghidra.app.script.GhidraScript;
import ghidra.util.task.TaskMonitor;
import ghidra.program.model.address.*;
import ghidra.program.model.lang.OperandType;
import ghidra.program.model.listing.Instruction;
import ghidra.program.model.listing.Listing;
import ghidra.program.model.listing.Program;
import ghidra.program.model.mem.Memory;
class Utils {
public static List<Address> findPattern(String pattern, Memory mem) {
var byteStrArr = pattern.split(" ");
byte[] patternBytes = new byte[byteStrArr.length];
byte[] mask = new byte[byteStrArr.length];
for (int i = 0; i < byteStrArr.length; i++) {
// Wildcard
if (byteStrArr[i].equals("??")) {
patternBytes[i] = 0x00;
mask[i] = 0x00;
} else {
patternBytes[i] = (byte) Integer.parseInt(byteStrArr[i], 16);
mask[i] = (byte) 0xFF;
}
}
var patternLocations = new ArrayList<Address>();
var blocks = mem.getBlocks();
for (var block : blocks) {
if (block.isExecute()) {
var nextStartAddr = block.getStart();
Address patternAddr;
do {
patternAddr = mem.findBytes(nextStartAddr, block.getEnd(), patternBytes, mask, true,
TaskMonitor.DUMMY);
if (patternAddr != null) {
patternLocations.add(patternAddr);
nextStartAddr = patternAddr.add(patternBytes.length);
}
} while (patternAddr != null);
}
}
return patternLocations;
}
public static Instruction findFirstInstruction(String mnemonic, Address startAddr, Listing listing, boolean forward,
int searchLimit) {
Instruction currInstr = listing.getInstructionAt(startAddr);
Instruction targetInstr = null;
for (int iCounter = 0; iCounter < searchLimit; iCounter++) {
if (currInstr.getMnemonicString().equals(mnemonic)) {
targetInstr = currInstr;
break;
}
currInstr = forward ? currInstr.getNext() : currInstr.getPrevious();
}
if (targetInstr == null) {
throw new RuntimeException("Could not find " + mnemonic + " instruction");
}
return targetInstr;
}
}
abstract class ObfuscatedString {
public ObfuscatedString(Address addr, Program program) {
this.program = program;
this.listing = program.getListing();
this.mem = program.getMemory();
this.addr = addr;
key = extractKey();
len = extractLength();
var obfuscatedBytes = extractObfuscatedStr(len);
deobfuscatedStr = decryptObfStr(obfuscatedBytes, key);
}
protected Address addr;
protected Program program;
protected Listing listing;
protected Memory mem;
private byte[] key;
private long len;
private String deobfuscatedStr;
protected abstract long extractLength();
private List<Byte> extractObfuscatedStr(long strLen) {
List<Byte> obfuscatedBytes = new ArrayList();
Instruction movInstr = null;
int searchLimit = 20;
Address searchAddr = addr;
do {
/*- TODO: Add optional parameter to findFirstInstruction so we don't need this loop anymore */
movInstr = Utils.findFirstInstruction("MOV", searchAddr, listing, false, 50);
searchAddr = movInstr.getPrevious().getAddress();
searchLimit--;
}
/*- TODO: Improve comparison, find something better than the string representation */
while (!movInstr.getDefaultOperandRepresentation(0).startsWith("byte ptr [RSP") && searchLimit > 0);
if (searchLimit == 0)
throw new RuntimeException("Could not find MOV instruction");
var currentMnemonic = movInstr.getMnemonicString();
int bytesMoved = 0;
// TODO: Improve length check
while (currentMnemonic.equals("MOV") && bytesMoved != strLen
&& movInstr.getDefaultOperandRepresentation(0).startsWith("byte ptr [RSP")) {
if (movInstr.getOperandType(1) != OperandType.SCALAR) {
throw new RuntimeException("Second operand of mov is not a scalar");
}
var b = (byte) movInstr.getScalar(1).getValue();
obfuscatedBytes.add(b);
movInstr = movInstr.getPrevious();
currentMnemonic = movInstr.getMnemonicString();
bytesMoved++;
}
return obfuscatedBytes.reversed();
}
private byte[] extractKey() {
var keyInstruction = listing.getInstructionAt(addr);
if (keyInstruction.getOperandType(1) != OperandType.SCALAR) {
throw new RuntimeException("Could not extract decryption key, second operand of MOV is not a scalar");
}
var keyBytes = keyInstruction.getScalar(1).byteArrayValue();
return keyBytes;
}
private String decryptObfStr(List<Byte> obfBytes, byte[] key) {
byte[] deobfBytes = new byte[obfBytes.size()];
for (int i = 0; i < obfBytes.size(); i++) {
deobfBytes[i] = (byte) (obfBytes.get(i).byteValue() ^ key[7 - (i % 8)]);
}
return new String(deobfBytes, StandardCharsets.UTF_8);
}
public Address getAddress() {
return addr;
}
public byte[] getKey() {
return key;
}
public long getLength() {
return len;
}
public String getDeobfuscatedStr() {
return deobfuscatedStr;
}
}
class ObfLongString extends ObfuscatedString {
public ObfLongString(Address addr, Program program) {
super(addr, program);
}
@Override
protected long extractLength() {
var cmpLenInstruction = Utils.findFirstInstruction("CMP", addr, listing, true, 20);
if (cmpLenInstruction.getOperandType(1) != OperandType.SCALAR) {
throw new RuntimeException("Second operand of CMP is not a scalar");
}
var len = cmpLenInstruction.getScalar(1).getValue();
return len;
}
}
class ObfShortString extends ObfuscatedString {
public ObfShortString(Address addr, Program program) {
super(addr, program);
}
@Override
protected long extractLength() {
return 0;
}
}
public class StringDeobfuscator extends GhidraScript {
public void run() throws Exception {
/*-
* Pattern for long string decryption:
* 48 be ?? ?? ?? ?? ?? ?? ?? ?? MOV RSI, <8_byte_decryption_key>
* 48 89 c1 MOV RCX,RAX
* 83 e1 07 AND ECX,0x7 // Modulo 8
* 48 c1 e1 03 SHL RCX,0x3 // Multiply by 8 -> Next byte
* 48 89 ?? MOV ??,RSI // Register varies
* 48 d3 ?? SHR ??,CL // Register varies
*/
final var longStringPattern = "48 be ?? ?? ?? ?? ?? ?? ?? ?? 48 89 c1 83 e1 07 48 c1 e1 03 48 89 ?? 48 d3 ??";
/*-
* Pattern for short string decryption:
* 48 be ?? ?? ?? ?? ?? ?? ?? ?? MOV RSI, <8_byte_decryption_key>
* 48 89 f2 MOV RDX,RSI
* 48 d3 ea SHR RDX,CL // Next byte
* 30 10 XOR byte ptr [RAX],DL
*/
final var shortStringPattern = "48 be ?? ?? ?? ?? ?? ?? ?? ?? 48 89 f2 48 d3 ea 30 10";
var longStringLocations = Utils.findPattern(longStringPattern, currentProgram.getMemory());
var shortStringLocations = Utils.findPattern(shortStringPattern, currentProgram.getMemory());
println("Long string patterns found: " + longStringLocations.size());
println("Short string patterns found: " + shortStringLocations.size());
var keyFormat = HexFormat.ofDelimiter(" ");
List<ObfuscatedString> obfuscatedStrings = new ArrayList();
// TODO: Catch exceptions
for (var longStr : longStringLocations) {
ObfuscatedString obfStr = new ObfLongString(longStr, currentProgram);
obfuscatedStrings.add(obfStr);
}
for (var shortStr : shortStringLocations) {
ObfuscatedString obfStr = new ObfShortString(shortStr, currentProgram);
obfuscatedStrings.add(obfStr);
}
// TODO: Sort
for (var obfStr : obfuscatedStrings) {
println("Obfuscated string at " + obfStr.getAddress());
println("\tKey: " + keyFormat.formatHex(obfStr.getKey()));
println("\tLength: " + obfStr.getLength());
println("\tDeobfuscated string: " + obfStr.getDeobfuscatedStr());
}
}
}