Java Code Examples for ghidra.program.model.mem.Memory#findBytes()

The following examples show how to use ghidra.program.model.mem.Memory#findBytes() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: MemSearcherAlgorithm.java    From ghidra with Apache License 2.0 6 votes vote down vote up
private void searchRange(Accumulator<MemSearchResult> accumulator, AddressRange range,
		TaskMonitor monitor, int progressCount) {

	Memory mem = program.getMemory();
	Address startAddress = forwardSearch ? range.getMinAddress() : range.getMaxAddress();
	Address endAddress = forwardSearch ? range.getMaxAddress() : range.getMinAddress();
	int length = searchData.getBytes().length;
	while (startAddress != null && !monitor.isCancelled()) {
		Address matchAddress = mem.findBytes(startAddress, endAddress, searchData.getBytes(),
			searchData.getMask(), forwardSearch, monitor);
		if (isMatchingAddress(matchAddress)) {
			MemSearchResult result = new MemSearchResult(matchAddress, length);
			accumulator.add(result);
			if (accumulator.size() >= matchLimit) {
				return;
			}
			monitor.setProgress(progressCount + getRangeDifference(range, matchAddress));
		}
		startAddress = getNextAddress(matchAddress, range);
	}
}
 
Example 2
Source File: FindAudioInProgramScript.java    From ghidra with Apache License 2.0 6 votes vote down vote up
List<Address> scanForAudioData(byte[] imageBytes, byte[] mask) {
	Memory memory = currentProgram.getMemory();
	MemoryBlock[] blocks = memory.getBlocks();

	List<Address> foundImages = new ArrayList<Address>();

	for (int i = 0; i < blocks.length; i++) {
		if (blocks[i].isInitialized()) {
			Address start = blocks[i].getStart();
			Address found = null;
			while (true) {
				if (monitor.isCancelled()) {
					break;
				}
				found =
					memory.findBytes(start, blocks[i].getEnd(), imageBytes, mask, true, monitor);
				if (found != null) {
					foundImages.add(found);
					start = found.add(1);
				}
				else
					break;
			}
		}
	}
	return foundImages;
}
 
Example 3
Source File: SearchBaseExtended.java    From ghidra with Apache License 2.0 5 votes vote down vote up
private void findLocations(MaskValueCase searchArrays, ArrayList<Case> localDatabase) {

		if (currentProgram == null || localDatabase == null || searchArrays == null) {
			throw new IllegalArgumentException("Null Data-Structure");
		}
		if (searchArrays.mask.length != searchArrays.value.length) {
			throw new IllegalArgumentException("Mask and value lengths are different.");
		}

		if (containsOnBit(searchArrays.mask)) {
			Memory mem = currentProgram.getMemory();

			//Gets the start and end address to search through
			Address endAddress = currentProgram.getMaxAddress();

			Address currentPosition = currentProgram.getMinAddress();
			while (currentPosition.compareTo(endAddress) < 0) {

				//Searches memory for the given mask and value.
				currentPosition = mem.findBytes(currentPosition, endAddress, searchArrays.value,
					searchArrays.mask, true, monitor);

				//Determines if a new location was found.
				if (currentPosition == null) {
					break;
				}

				Case temp = new Case();
				temp.mask = searchArrays.mask;
				temp.value = searchArrays.value;
				temp.addr = currentPosition;
				localDatabase.add(temp);

				currentPosition = currentPosition.add(1);
			}
		}
		else {
			return;
		}
	}
 
Example 4
Source File: FindImagesScript.java    From ghidra with Apache License 2.0 5 votes vote down vote up
List<Address> scanForImages(byte[] imageBytes) {
	Memory memory = currentProgram.getMemory();
	MemoryBlock[] blocks = memory.getBlocks();

	byte maskBytes[] = null;

	List<Address> foundImages = new ArrayList<Address>();

	for (int i = 0; i < blocks.length; i++) {
		if (blocks[i].isInitialized()) {
			Address start = blocks[i].getStart();
			Address found = null;
			while (true) {
				if (monitor.isCancelled()) {
					break;
				}
				found =
					memory.findBytes(start, blocks[i].getEnd(), imageBytes, maskBytes, true,
						monitor);
				if (found != null) {
					foundImages.add(found);
					start = found.add(1);
				}
				else
					break;
			}
		}
	}
	return foundImages;
}
 
Example 5
Source File: FindRunsOfPointersWithTableScript.java    From ghidra with Apache License 2.0 5 votes vote down vote up
Address findRef(Address topAddress, long dist) {

		Memory memory = currentProgram.getMemory();
		Address ref = null;

		//change later to handle 64 bits too
		byte[] maskBytes = new byte[4];
		for (int i = 0; i < 4; i++) {
			maskBytes[i] = (byte) 0xff;
		}

		// search memory for the byte patterns within the range of topAddr and topAddr - dist
		// make a structure of found bytes/topAddr offset????
		boolean noRefFound = true;
		boolean tryPrevAddr = true;
		long longIndex = 0;
		while (noRefFound && tryPrevAddr) {
			Address testAddr = topAddress.subtract(longIndex);
			byte[] addressBytes = turnAddressIntoBytes(testAddr);

			//println("TestAddr = " + testAddr.toString());
			Address found = memory.findBytes(currentProgram.getMinAddress(), addressBytes,
				maskBytes, true, monitor);
			if (found != null) {
				ref = found;
				//	println("Found ref at " + found.toString());				
				noRefFound = false;
			}
			else {
				longIndex++;
				// check to see if we are at the top of the range of possible refs
				if (longIndex > (dist - 4)) {// change the four to pointer size when I add 64bit 
					tryPrevAddr = false;
				}

			}
		}
		return ref;
	}
 
Example 6
Source File: GenerateMaskedBitStringScript.java    From ghidra with Apache License 2.0 5 votes vote down vote up
public void run() throws Exception {
	Memory mem = currentProgram.getMemory();

	//Gets the start and end address to search through
	Address endAddress = currentProgram.getMaxAddress();

	Address currentPosition = currentProgram.getMinAddress();
	byte[] values =
		askBytes("Enter byte values",
			"Please enter the list of byte values you want to search for");
	byte[] masks =
		askBytes("Enter byte masks", "Please enter the list of byte masks you want to use");

	createMaskedBitString(values, masks);

	int count = 0;
	while (currentPosition.compareTo(endAddress) < 0) {
		if (monitor.isCancelled())
			return;

		//Searches memory for the given mask and value.
		currentPosition =
			mem.findBytes(currentPosition, endAddress, values, masks, true, monitor);

		//Determines if a new location was found.
		if (currentPosition == null) {
			break;
		}

		//	println(currentPosition.toString());
		count++;

		currentPosition = currentPosition.add(1);
	}
	println("\nTotal count: " + count);
}
 
Example 7
Source File: FindRunsOfPointersScript.java    From ghidra with Apache License 2.0 5 votes vote down vote up
Address findRef(Address topAddress, long dist) {

		Memory memory = currentProgram.getMemory();
		Address ref = null;

		//change later to handle 64 bits too
		byte[] maskBytes = new byte[4];
		for (int i = 0; i < 4; i++) {
			maskBytes[i] = (byte) 0xff;
		}

		// search memory for the byte patterns within the range of topAddr and topAddr - dist
		// make a structure of found bytes/topAddr offset????
		boolean noRefFound = true;
		boolean tryPrevAddr = true;
		long longIndex = 0;
		while (noRefFound && tryPrevAddr) {
			Address testAddr = topAddress.subtract(longIndex);
			byte[] addressBytes = turnAddressIntoBytes(testAddr);

			//println("TestAddr = " + testAddr.toString());
			Address found =
				memory.findBytes(currentProgram.getMinAddress(), addressBytes, maskBytes, true,
					monitor);
			if (found != null) {
				ref = found;
				//	println("Found ref at " + found.toString());				
				noRefFound = false;
			}
			else {
				longIndex++;
				// check to see if we are at the top of the range of possible refs
				if (longIndex > (dist - 4)) {// change the four to pointer size when I add 64bit 
					tryPrevAddr = false;
				}

			}
		}
		return ref;
	}
 
Example 8
Source File: InstructionSearchData.java    From ghidra with Apache License 2.0 4 votes vote down vote up
/**
 * Searches the given program for a specific byte pattern, returning all
 * found results
 *
 * @param program the program to search
 * @param searchBounds the addresses to search
 * @param taskMonitor the task monitor
 * @throws IllegalArgumentException if there's a problem parsing addresses
 * @return list of found instructions
 */
public List<InstructionMetadata> search(Program program, AddressRange searchBounds,
		TaskMonitor taskMonitor) throws IllegalArgumentException {

	List<InstructionMetadata> searchResults = new ArrayList<>();

	if (program == null) {
		throw new IllegalArgumentException("Program provided to search is null");
	}

	// Do a quick check to make sure the search bounds are within the bounds of the 
	// program.
	if (searchBounds.getMinAddress().compareTo(program.getMinAddress()) < 0 ||
		searchBounds.getMaxAddress().compareTo(program.getMaxAddress()) > 0) {
		throw new IllegalArgumentException(
			"Search bounds are not valid; must be within the bounds of the program.");
	}

	MaskContainer maskContainer = this.getAllMasks();

	if (InstructionSearchUtils.containsOnBit(maskContainer.getMask())) {
		Memory mem = program.getMemory();

		// Get the min and max address positions - we'll use these
		// for iterating.
		Address currentPosition = searchBounds.getMinAddress();
		Address endAddress = searchBounds.getMaxAddress();

		while (currentPosition.compareTo(endAddress) < 0) {

			// Search program memory for the given mask and val.
			currentPosition = mem.findBytes(currentPosition, endAddress,
				maskContainer.getValue(), maskContainer.getMask(), true, taskMonitor);

			// If no match was found, currentPosition will be null.
			if (currentPosition == null) {
				break;
			}

			// Otherwise construct a new entry to put in our results table.
			MaskContainer masks =
				new MaskContainer(maskContainer.getMask(), maskContainer.getValue());
			InstructionMetadata temp = new InstructionMetadata(masks);
			temp.setAddr(currentPosition);
			searchResults.add(temp);

			// And update the position pointer so we'll process the next item.
			currentPosition = currentPosition.next();
		}
	}

	return searchResults;
}
 
Example 9
Source File: EmbeddedFinderScript.java    From ghidra with Apache License 2.0 4 votes vote down vote up
@Override
  public void run() throws Exception {
byte[] MAGIC_DOS_HEADER = new byte[] { 0x4d, 0x5a };				// M Z
byte[] MAGIC_NT_HEADER  = new byte[] { 0x50, 0x45, 0x00, 0x00 };	// P E 0x00 0x00

List<Address> allFound = new ArrayList<Address>();

Memory memory = currentProgram.getMemory();
Address baseAddr = memory.getMinAddress();
Address currAddr = baseAddr;

while (currAddr != null) {
	// The purpose of breaking each check into small segments (where they could be combined)
	// is to make way for future file type support, keep code clean, and to encourage readability.
	boolean DOSExists = false;
	boolean NTExists = false;
	boolean DOSAgreesWithNT = false;

	Address DOS = memory.findBytes(currAddr, MAGIC_DOS_HEADER, null, true, getMonitor());
	if (DOS != null) {
		// IMAGE_DOS_HEADER is 128 bytes in length, so let's check if that much memory is available
		if (memory.contains(DOS.add(128)))
			DOSExists = true;
	}

	Address NT = memory.findBytes(DOS, MAGIC_NT_HEADER, null, true, getMonitor());
	if (NT != null) {
		// IMAGE_NT_HEADERS32 is 80 bytes in length, so let's check if that much memory is available
		if (memory.contains(NT.add(80)))
			NTExists = true;
	}

	if (DOSExists && NTExists) {
		// It would be better to import the proper structs rather than hard coding offsets.
		// However I'm unsure of what the best way of doing this would be. It's possible to include WINNT.h
		// but this requires the non-development environment to have access to it which makes things
		// less flexible and renders it brittle for future embedded target-type searches.
		// IMAGE_DOS_HEADER + 0x3c is the IMAGE_NT_HEADERS32 offset
		long impliedOffset = memory.getShort(DOS.add(0x3c));
		long actualOffset = NT.getAddressableWordOffset() - DOS.getAddressableWordOffset();
		if (impliedOffset == actualOffset)
			DOSAgreesWithNT = true;
	}

	if (DOSAgreesWithNT) {
		byte[] MAGIC_NT_HEADER_TEST = new byte[4];	// [TODO] Get this to dynamically pull correct size, not hardcoded
		memory.getBytes(NT, MAGIC_NT_HEADER_TEST);

		if (Arrays.equals(MAGIC_NT_HEADER, MAGIC_NT_HEADER_TEST)) {
			if (DOS != baseAddr)
				allFound.add(DOS);		// We only care about targets that are not also the parent file
		}
	}

	if (DOS != null)
		currAddr = DOS.add(1);	// Ensure next search doesn't overlap with current target
	else
		currAddr = null;
}

// Present user with target discovery(s)

if (allFound.isEmpty())
	println("No embedded targets identified");
else {
	println("Embedded targets identified");
	for (Address found : allFound)
		println("\t" + found.toString());
}
  }
 
Example 10
Source File: MakeFunctionsScript.java    From ghidra with Apache License 2.0 4 votes vote down vote up
@Override
public void run() throws Exception {

	Memory memory = currentProgram.getMemory();
	byte[] functionBytes =
		askBytes("Enter Byte Pattern",
			"Please enter your function byte pattern separated by spaces");

	while ((!monitor.isCancelled()) && ((functionBytes == null) || (functionBytes.length == 0))) {
		functionBytes =
			askBytes("Invalid Byte Pattern",
				"Please re-enter your function byte pattern in separated by spaces");
	}
	String textBytes = "";
	for (int i = 0; i < functionBytes.length; i++) {
		textBytes = textBytes.concat(toHexString(functionBytes[i], true, false));
		textBytes = textBytes.concat(" ");
	}
	println("Searching for " + textBytes + ". . .");

	MemoryBlock[] memoryBlock = currentProgram.getMemory().getBlocks();
	if (memoryBlock.length == 1) {
		Address dataAddress =
			askAddress("Create data block",
				"Please enter the start address of the data section.");
		memory.split(memoryBlock[0], dataAddress);
		// get the blocks again to get new split one
		memoryBlock = currentProgram.getMemory().getBlocks();
		if (memoryBlock[1].contains(dataAddress)) {
			memoryBlock[1].setName("Data");
			memoryBlock[1].setExecute(false);
		}
		else {
			if (memoryBlock[0].contains(dataAddress)) {
				memoryBlock[0].setName("Data");
				memoryBlock[0].setExecute(false);
			}
		}
	}
	int foundCount = 0;
	int madeCount = 0;
	for (int i = 0; i < memoryBlock.length; i++) {
		if (memoryBlock[i].isExecute()) {
			boolean keepSearching = true;
			Address start = memoryBlock[i].getStart();
			Address end = memoryBlock[i].getEnd();

			while ((keepSearching) && (!monitor.isCancelled())) {
				Address found =
					memory.findBytes(start, end, functionBytes, null, true, monitor);
				if ((found != null) && memoryBlock[i].contains(found)) {
					foundCount++;
					Function testFunc = getFunctionContaining(found);
					if (testFunc == null) {
						boolean didDisassemble = disassemble(found);
						if (didDisassemble) {
							Function func = createFunction(found, null);
							if (func != null) {
								println("Made function at address: " + found.toString());
								madeCount++;
							}
							else {
								println("***Function could not be made at address: " +
									found.toString());
							}
						}
					}
					else {
						println("Function already exists at address: " + found.toString());
					}
					start = found.add(4);
				}
				else {
					keepSearching = false;
				}
			}

		}

	}
	if (foundCount == 0) {
		println("No functions found with given byte pattern.");
		return;
	}
	if (madeCount == 0) {
		println("No new functions made with given byte pattern.");
	}

}