Skip to content

Instantly share code, notes, and snippets.

@bsmt
Created February 15, 2020 05:17
Show Gist options
  • Save bsmt/93c8edf994c8d0f2d4d657698693a50a to your computer and use it in GitHub Desktop.
Save bsmt/93c8edf994c8d0f2d4d657698693a50a to your computer and use it in GitHub Desktop.
Ghidra script to XOR two arbitrary size regions of memory together and write the resulting buffer somewhere. *dest = *src_1 ^ *src_2
// XOR two memory regions together and write result at a third location.
//@author bsmt
//@category Memory
//@keybinding
//@menupath
//@toolbar
import ghidra.app.script.GhidraScript;
import ghidra.program.model.util.*;
import ghidra.program.model.reloc.*;
import ghidra.program.model.data.*;
import ghidra.program.model.block.*;
import ghidra.program.model.symbol.*;
import ghidra.program.model.scalar.*;
import ghidra.program.model.mem.*;
import ghidra.program.model.listing.*;
import ghidra.program.model.lang.*;
import ghidra.program.model.pcode.*;
import ghidra.program.model.address.*;
public class XORRegions extends GhidraScript {
public void run() throws Exception {
monitor.setIndeterminate(false);
monitor.setShowProgressValue(true);
Address region_0 = askAddress("XORRegions", "First region address:");
Address region_1 = askAddress("XORRegions", "Second region address:");
Address dest = askAddress("XORRegions", "Destination address:");
int size = askInt("XORRegions", "Region size (in bytes):");
Memory memory = currentProgram.getMemory();
printf("XORRegions: Doing %d byte %s = %s ^ %s\n", size,
dest.toString(), region_0.toString(), region_1.toString());
monitor.setMaximum((long)size);
monitor.setProgress((long)0.0);
for (int i = 0; i < size; ++i) {
if(monitor.isCancelled()) {
break;
}
Address addr_0 = region_0.add((long)i);
Address addr_1 = region_1.add((long)i);
Address dest_addr = dest.add((long)i);
byte byte_0 = memory.getByte(addr_0);
byte byte_1 = memory.getByte(addr_1);
byte dest_byte = (byte)(byte_0 ^ byte_1);
//printf("%s (%x) = %s (%x) ^ %s (%x)\n", dest_addr.toString(),
// dest_byte, addr_0.toString(), byte_0,
// addr_1.toString(), byte_1);
memory.setByte(dest_addr, dest_byte);
monitor.setProgress((long)i);
}
// don't set comment if there is something already there,
// just so we don't clobber anything.
// could probably just append it to the existing comment but meh
if (getPlateComment(dest) == null) {
setPlateComment(dest,
String.format(("This %d byte region does not reflect the inital state.\n" +
"It has been overwritten with a computed XOR of *%s ^ *%s"),
size, region_0.toString(), region_1.toString()));
}
// TODO: maybe rename the destination region to LABEL_xored or something if it has a label
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment