import re
import pefile
import binascii

def find_pattern_des(data):
	#pattern = r"([1-9a-fA-F][0-9a-fA-F]){1,}(00){4}([1-9a-fA-F][0-9a-fA-F]){8}(00){4}([1-9a-fA-F][0-9a-fA-F]){8}(00){4}"
	pattern_des = r"(00){4}([1-9a-fA-F][0-9a-fA-F]){8}(00){4}([1-9a-fA-F][0-9a-fA-F]){8}(00){4}([1-9a-fA-F][0-9a-fA-F]){8}(00){4}([1-9a-fA-F][0-9a-fA-F]){8}"
	pattern_des_strings = r"(00){4}([1-9a-fA-F][0-9a-fA-F]){20,}(00){4}"

	data_des = data
	data_strings = data

	match_object = re.search(pattern_des, data_des)
	tdes_one = extract_key_des(data_des[match_object.start():match_object.end()])

	data_des = data_des[match_object.end():]

	match_object = re.search(pattern_des, data_des)
	tdes_two = extract_key_des(data_des[match_object.start():match_object.end()])

	"""while(len(data_strings) >= match_object.end()):
		match_object = re.search(pattern_des_strings, data_strings)
		print(data[match_object.start():match_object.end()])
		data_strings = data_strings[match_object.end():]"""


	return tdes_one, tdes_two
	

def extract_key_des(data):
	data_des = ""

	key_dict = {
		"iv": 0,
		"Tdes": 0
	}

	key_dict["iv"] = data[8:24]
	data = data[24:]
	
	while(len(data) >= 16):
		data = data[8:]
		data_des = data_des + (data[:16])
		data = data[16:]
	
	key_dict["Tdes"] = data_des

	return key_dict

def find_pattern_x(data):
	#pattern = r"([1-9a-fA-F][0-9a-fA-F]){1,}(00){4}([1-9a-fA-F][0-9a-fA-F]){8}(00){4}([1-9a-fA-F][0-9a-fA-F]){8}(00){4}"
	pattern_des = r"(90){1}([1-9a-fA-F][0-9a-fA-F]){1,}(00){2}"

	match_object = re.search(pattern_des, data)
	xor_string = (data[match_object.start():match_object.end()])
	xor_byte_string = bytes.fromhex(xor_string)
	return decrypt_xor(xor_byte_string)

def decrypt_xor(data):
	bl = 0xff
	final = ""
	for byte in data:
		xor = byte ^ bl
		final = final + chr(xor)
	
	return final[final.find("http"):-2]


def main():
	pe = pefile.PE(r"C:\Users\user\Desktop\Analysis\Zero2Auto\Lesson 2\Lesson 2.2\LokiBot\Unpacked LokiBot\\lokibot_fix.bin ")
	section_addr_rdata = None
	section_addr_x = None

	for section in pe.sections:
		if(".rdata" in section.Name.decode()):
			section_addr_rdata = section
		
		if(".x" in section.Name.decode()):
			section_addr_x = section


	print("Virtual Location rdata:", hex(section_addr_rdata.VirtualAddress))
	data = section_addr_rdata.get_data()[89:]
	data = binascii.hexlify(data).decode()
	tdes_one, tdes_two = find_pattern_des(data)
	print(tdes_one)
	print(tdes_two)

	print()

	print("Virtual Location x:", hex(section_addr_x.VirtualAddress))
	data = section_addr_x.get_data()
	data = binascii.hexlify(data).decode()
	final = find_pattern_x(data)
	print(final)


if __name__ == "__main__":
	main()
