Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
FLARE-ON Challenge 2015: challenge 5 brute-force script
import time
import BaseHTTPServer
import urlparse
import base64
HOST_NAME = 'localhost'
PORT_NUMBER = 80
key_enc = "UDYs1D7bNmdE1o3g5ms1V6RrYCVvODJF1DpxKTxAJ9xuZW=="
#UDYs1D7bNmdE1o3g5ms1V6RrYCVvODJF1DpxKTxAJW
import subprocess
import threading
import os
import Queue
import string
guess = threading.Event()
guesses = Queue.Queue()
result_server = ''
import logging
logger = logging.getLogger('sender')
hdlr = logging.FileHandler('key.log')
formatter = logging.Formatter('%(asctime)s %(message)s')
hdlr.setFormatter(formatter)
logger.addHandler(hdlr)
logger.setLevel(logging.INFO)
class MyClient(threading.Thread):
def __init__(self, threadID, name, counter):
threading.Thread.__init__(self)
self.threadID = threadID
self.name = name
self.counter = counter
#1. create alphabet
self.letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/@"
self.letters = string.printable
self.letters = "!\"#$&'()*+,-.0123456789:;<=>@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]_abcdefghijklmnopqrstuvwxyz~"
#self.letters = "apc"
self.key = "Sp1cy_7_layer_OSI_dip"
self.candidates = []
def comparebytes(self, a, b):
match = 0
a_bytes = base64.b64decode(a)
b_bytes = base64.b64decode(b)
match = 0
different = 0
for cnt in range(0,len(b_bytes)):
#print("{0:02X}\t{1:02X}".format((ord(a_bytes[cnt])),(ord(b_bytes[cnt]))))
different = (ord(a_bytes[cnt]) ^ ord(b_bytes[cnt]));
if ord(a_bytes[cnt]) > ord(b_bytes[cnt]):
print("{0:02X}\t{1:02X}\tbigger".format((ord(a_bytes[cnt])),(ord(b_bytes[cnt]))))
elif ord(a_bytes[cnt]) < ord(b_bytes[cnt]):
print("{0:02X}\t{1:02X}\tsmaller".format((ord(a_bytes[cnt])),(ord(b_bytes[cnt]))))
#different <> char
if different == 0:
match += 1
#print("{0:02X}\t{1:02X}".format((ord(a_bytes[cnt])),(ord(b_bytes[cnt]))))
#print("{0}\t{1}".format(cnt,different))
else:
break
return match
def run(self):
print "Starting " + self.name
time.sleep(5)
print "Do something"
cur_key = ""
env = os.environ
#2. iterate current char at pos x
finish = False
while not finish:
for c in self.letters:
print("-------")
cur_key = self.key + c
cur_key_b64 = base64.b64encode(cur_key)
#print("current key {0}".format(cur_key))
#3. write string to "key.txt"
with open('Y:\\05\\key.txt','w') as fh:
fh.write(cur_key)
#4. run "sender"
process = subprocess.Popen(['Y:\\05\\sender','Y:\\05\\key.txt'],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
cwd='Y:\\05\\',
env=os.environ)
out, err = process.communicate()
if out:
print(out.strip())
#5. get responses from server
result_server = ""
num = len(cur_key_b64)/4
#print("waiting for {0} answers".format(num))
for cnt in range(0,num):
result_server += guesses.get(True)
#print("server got: {0}".format(result_server))
match = self.comparebytes(key_enc, result_server)
logger.info('{0}\t{1}'.format(cur_key,result_server))
print('{0}\t{1}'.format(cur_key,result_server))
#5a. increase pos
if match == len(base64.b64decode(result_server)):
"""
b_bytes = base64.b64decode(result_server)
b_byte = b_bytes[-1]
a_byte = base64.b64decode(key_enc)[len(b_bytes)-1]
print("{0:02X}\t{1:02X}".format(ord(a_byte),ord(b_byte)))
if ord(a_byte) < ord(b_byte):
#adjust only if already bigger than expected?
#cl = self.key[-1:]
#cn = self.letters[(self.letters.find(c)+1)%len(self.letters)]
print(c)
print(chr(ord(c)-1))
self.key = self.key + chr(ord(c)-1)
else:
self.key += c
"""
if result_server == key_enc[:len(result_server)]:
self.key = self.key + c
else:
self.key = self.key + chr(ord(c)-1)
if c == "@":
finish = True
break
#6. Got 2
continue
else:
cl = self.key[-1:]
#iterate letters
#TODO: increment/decrement logic?
cn = self.letters[(self.letters.find(cl)+1)%len(self.letters)]
print("no answer found, modifying latest char {0}".format(cl))
self.key = self.key[:-1] + cn
print(self.key)
print "Exiting " + self.name
class MyHandler(BaseHTTPServer.BaseHTTPRequestHandler):
def do_POST(self):
"""Respond to a POST request."""
self.send_response(200)
self.send_header("Content-type", "text/html")
self.send_header("Server", "BaseHTTP/0.3 Python/2.7.9")
self.end_headers()
self.wfile.write("1")
length = int(self.headers['Content-Length'])
datain = self.rfile.read(length).decode('utf-8')
"""
#decoding
bindata = base64.b64decode(datain)
out = ' '.join(x.encode('hex') for x in bindata)
print(datain, out)
#publish response
result_server = bindata
"""
guesses.put(datain)
return
def do_GET(self):
"""Respond to a POST request."""
self.send_response(200)
self.send_header("Content-type", "text/html")
self.send_header("Server", "BaseHTTP/0.3 Python/2.7.9")
self.end_headers()
self.wfile.write("1")
#publish response
result_server = "TEST"
guesses.put(result_server)
return
def log_message(self, format, *args):
pass
if __name__ == '__main__':
sender = MyClient(1, "sender", 1)
sender.daemon = True
server_class = BaseHTTPServer.HTTPServer
httpd = server_class((HOST_NAME, PORT_NUMBER), MyHandler)
httpdt = threading.Thread(target=httpd.serve_forever)
httpdt.daemon = True
print time.asctime(), "Server Starts - %s:%s" % (HOST_NAME, PORT_NUMBER)
try:
#httpdt.start()
#httpd.serve_forever()
print("hoho")
print("huhu")
sender.start()
print("haha")
httpd.serve_forever()
except KeyboardInterrupt:
pass
httpd.server_close()
print time.asctime(), "Server Stops - %s:%s" % (HOST_NAME, PORT_NUMBER)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment