-
Notifications
You must be signed in to change notification settings - Fork 1
/
Stackstrings.java
188 lines (170 loc) · 6.3 KB
/
Stackstrings.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
//
//@author
//@category
//@keybinding shift a
//@menupath File.Run.Stackstrings
//@toolbar
import java.math.BigInteger;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.TreeSet;
import ghidra.app.emulator.EmulatorHelper;
import ghidra.app.script.GhidraScript;
import ghidra.program.model.address.Address;
import ghidra.program.model.address.AddressRange;
import ghidra.program.model.lang.Register;
import ghidra.program.model.listing.CodeUnit;
import ghidra.program.model.listing.Variable;
import ghidra.program.model.symbol.SourceType;
import ghidra.util.exception.CancelledException;
public class Stackstrings extends GhidraScript {
public static boolean isPureAscii(String v) {
return Charset.forName("US-ASCII").newEncoder().canEncode(v);
// or "ISO-8859-1" for ISO Latin 1
// or StandardCharsets.US_ASCII with JDK1.7+
}
Address getAddress(Integer offset) {
return currentProgram.getAddressFactory().getDefaultAddressSpace().getAddress(offset);
}
Register[] getProgramRegisterList() {
var pc = currentProgram.getProgramContext();
return pc.getRegisters();
}
public String toHex(String arg) {
return String.format("%040x", new BigInteger(1, arg.getBytes(/*YOUR_CHARSET?*/)));
}
HashMap<Address, Address> emulate(EmulatorHelper emuHelper, Address beg, Address end) {
print("[*] Emulation started\n");
printf("Beginning: %08x\n", beg.getOffset());
printf("Ending: %08x\n", end.getOffset());
emuHelper.writeRegister(emuHelper.getPCRegister(), beg.getOffset());
List<AddressRange> prevMemRange = new ArrayList<AddressRange>();
var tableEipMemMod = new HashMap<Address, Address>();
while (monitor.isCancelled() == false) {
var executionAddr = emuHelper.getExecutionAddress();
if (executionAddr.getOffset() == end.getOffset()) {
print("[*] Emulation finished\n");
return tableEipMemMod;
}
boolean success;
try {
var eip = emuHelper.getExecutionAddress();
success = emuHelper.step(monitor);
var memsMod = emuHelper.getTrackedMemoryWriteSet();
for (var mem : memsMod) {
if (mem.getAddressSpace().getName().equalsIgnoreCase("ram") == true) {
var included = false;
for (var i = 0; i < prevMemRange.size(); i++) {
var range = prevMemRange.get(i);
// Test if ranges already in prevMemRange were updated
if (range.getMinAddress().equals(mem.getMinAddress()) == false && range.getMaxAddress().equals(mem.getMaxAddress()) == true) {
included = true;
prevMemRange.set(i, mem);
tableEipMemMod.put(mem.getMinAddress(), eip);
break;
} else if (range.getMinAddress().equals(mem.getMinAddress()) == true && range.getMaxAddress().equals(mem.getMaxAddress()) == false) {
included = true;
prevMemRange.set(i, mem);
// add(0x1) is there to cover the cases where the binary writes more than 1 byte
// example mov word [ebp + 0x5], 0x41
// it will move the range and without the add, you will read a null byte
tableEipMemMod.put(range.getMaxAddress().add(0x1), eip);
break;
} else if (range.getMinAddress().equals(mem.getMinAddress()) == true && range.getMaxAddress().equals(mem.getMaxAddress()) == true) {
included = true;
break;
}
}
// If there is a new range, adds it to prevMemRange
if (included == false) {
prevMemRange.add(mem);
tableEipMemMod.put(mem.getMinAddress(), eip);
}
}
}
if (success == false) {
var error = emuHelper.getLastError();
printf("[!] Error during emulation: %s\n", error);
return tableEipMemMod;
}
} catch (CancelledException e) {
e.printStackTrace();
return tableEipMemMod;
}
}
return tableEipMemMod;
}
@Override
protected void run() throws Exception {
var emuHelper = new EmulatorHelper(currentProgram);
emuHelper.enableMemoryWriteTracking(true);
emuHelper.writeRegister(emuHelper.getStackPointerRegister(), 0x1000);
emuHelper.writeRegister("EBP", 0x8000);
var fnManager = currentProgram.getFunctionManager();
Address beg;
Address end;
try {
beg = currentSelection.getFirstRange().getMinAddress();
end = currentSelection.getLastRange().getMaxAddress();
}
catch (Exception e) {
printf("[x] Selection is empty. Please, select the instructions to emulate.\n");
return;
}
var function = fnManager.getFunctionContaining(beg);
var fnVars = function.getLocalVariables();
var mapFnVars = new HashMap<Integer, Variable>();
for(var variable : fnVars) {
try {
var stackOffset = variable.getStackOffset();
mapFnVars.put(stackOffset, variable);
} catch (Exception e) {
printf("[!] Error for variable %s: %s\n", variable.getName(), e.getMessage());
}
}
/*
* See https://stackoverflow.com/questions/922528/how-to-sort-map-values-by-key-in-java
* I wanted to have the memory areas printed from the lowest address to the highest to debug
* more easily.
*/
var mems = emulate(emuHelper, beg, end);
Comparator<Address> comparator = (Address a1, Address a2) -> {
return a1.compareTo(a2);
};
var keys = new TreeSet<>(comparator);
keys.addAll(mems.keySet());
for (var addr : keys) {
var decrStr = "";
var addrInstr = mems.get(addr);
try {
decrStr = emuHelper.readNullTerminatedString(addr, 0xffff);
}
catch (Exception e) {
printf("[!] Error: %s\n", e.getMessage());
continue;
}
if(!decrStr.isEmpty()) {
printf("%s => %s => %s\n", addrInstr, addr, decrStr);
}
if (isPureAscii(decrStr)) {
var instruction = currentProgram.getListing().getInstructionAt(addrInstr);
instruction.setComment(CodeUnit.EOL_COMMENT, decrStr);
instruction.setComment(CodeUnit.PRE_COMMENT, decrStr);
// try/catch => dirty. Should check if there are multiple operands and if there is a variable for that offset
try {
var toAddr = (int)instruction.getPrimaryReference(0).getToAddress().getOffset(); // cast to int otherwise doesn't work...
var decrStrName = decrStr.strip().replaceAll(" ", "_");
var name = "local_" + decrStrName;
var variable = mapFnVars.get(toAddr);
variable.setName(name, SourceType.USER_DEFINED);
} catch (Exception e) {
continue;
}
}
}
emuHelper.dispose();
}
}