Ejemplo n.º 1
0
        def get_anwsers():
            answers = bytearray()
            pi_ports = self._get_all_pi_ports()
            for port in pi_ports:
                domain = 'pi{}.{}'.format(port, self.dns_domain)

                answer = bytearray(b'\xc0\x0c')
                answer += serialize.Serialize({
                    'Type': ('2B', 33),
                    'class': ('2B', 1),
                    'TTL': ('4B', 300)
                }).packetize()

                target = self._get_host_bytes(domain)
                data_length = 2 + 2 + 2 + len(target)
                answer += serialize.Serialize({
                    'Data length': ('2B', data_length),
                    'Priority': ('2B', 1),
                    'Weight': ('2B', 1),
                    'Port': ('2B', 9100)
                }).packetize()
                answer += target
                answers += answer

            return answers, len(pi_ports)
Ejemplo n.º 2
0
    def resolve_host(self, from_client, pack):

        def _get_mapped_ip(host):
            pi_port = host.split('.')[0].replace('pi', '')
            ip = '{}.{}'.format(self.network_addr, pi_port)

            if self._is_pi_ip(ip):
                return ip
            else:
                raise Exception('Invalid IP')

        self.server_socket.connect(from_client)

        header = serialize.Serialize({
            'ID': ('2B', pack.get_field('ID').value),
            'Response': (1, 1),
            'Opcode': 4,
            'Authoritative': 1,
            'Truncated': 1,
            'RD': (1, 1),
            'RA': (1, 1),
            'Z': 1,
            'Answer authenticated': 1,
            'non-auth data': 1,
            'Reply code': 4,
            'Questions': ('2B', 1),
            'Answer RRs': ('2B', 1),
            'Authority RRs': '2B',
            'Additional RRs': '2B'
        }).packetize()

        query = self._get_query_section(pack)

        # prepare anwser section
        ip = _get_mapped_ip(pack.get_field('Name').value)
        ip_bytes = bytes(map(int, ip.split('.')))
        data_length = len(ip_bytes)

        answer = bytearray(b'\xc0\x0c')
        answer += serialize.Serialize({
            'Type': ('2B', 1),
            'class': ('2B', 1),
            'TTL': ('4B', 24),
            'Data length': ('2B', data_length)
        }).packetize()
        answer += ip_bytes

        res = header + query + answer

        self.server_socket.send(res)
Ejemplo n.º 3
0
    def to_bytes(self):
        # Implementation with serializeme API
        packet_format = {   "message_type"              : ("1B", self.message_type),
                            "hardware_type"             : ("1B", self.hardware_type),
                            "hardware_address_length"   : ("1B", self.hardware_address_length),
                            "hops"                      : ("1B", self.hops),
                            "transaction_id"            : ("4B", self.transaction_id),
                            "seconds_elapsed"           : ("2B", self.seconds_elapsed),
                            "bootp_flags"               : ("2B", self.bootp_flags),
                            "client_ip_address"         : ("4B", int(ipaddress.IPv4Address(self.client_ip_address))),
                            "your_ip_address"           : ("4B", int(ipaddress.IPv4Address(self.your_ip_address))),
                            "next_server_ip_address"    : ("4B", int(ipaddress.IPv4Address(self.next_server_ip_address))),
                            "relay_agent_ip_address"    : ("4B", int(ipaddress.IPv4Address(self.relay_agent_ip_address))),
                            "client_mac_address"        : ("6B", int(self.client_mac_address.translate({ord(i): None for i in ':.- '}), 16)),
                            "rest_of_bootp"             : "202B",
                            "magic_cookie"              : ("4B", int(ipaddress.IPv4Address(self.magic_cookie)))}

        result = serializeme.Serialize(packet_format).packetize()

        # No API used so no change for this last part of the function
        for option in self.options:
            value = self.get_option(option)
            # print(option, value)
            if value is None:
                continue
            result += bytes([option, len(value)]) + value
        result += bytes([255])
        #logger.info(result)
        return bytes(result)
Ejemplo n.º 4
0
    def resolve_ip(self, from_client, pack):
        self.server_socket.connect(from_client)

        header = serialize.Serialize({
            'ID': ('2B', pack.get_field('ID').value),
            'Response': (1, 1),
            'Opcode': 4,
            'Authoritative': 1,
            'Truncated': 1,
            'RD': (1, 1),
            'RA': (1, 1),
            'Z': 1,
            'Answer authenticated': 1,
            'non-auth data': 1,
            'Reply code': 4,
            'Questions': ('2B', 1),
            'Answer RRs': ('2B', 1),
            'Authority RRs': '2B',
            'Additional RRs': ('2B', 1)
        }).packetize()

        query = self._get_query_section(pack)

        # prepare anwser section
        pi_port = pack.get_field('Name').value.split('.')[0]
        host = 'pi{}.{}'.format(pi_port, self.dns_domain)
        domain_name = self._get_host_bytes(host)
        data_length = len(domain_name)

        answer = bytearray(b'\xc0\x0c')
        answer += serialize.Serialize({
            'Type': ('2B', 12),
            'class': ('2B', 1),
            'TTL': ('4B', 4150),
            'Data length': ('2B', data_length)
        }).packetize()
        answer += domain_name
        res = header + query + answer

        self.server_socket.send(res)
Ejemplo n.º 5
0
    def resolve_srv_records(self, from_client, pack):

        def get_anwsers():
            answers = bytearray()
            pi_ports = self._get_all_pi_ports()
            for port in pi_ports:
                domain = 'pi{}.{}'.format(port, self.dns_domain)

                answer = bytearray(b'\xc0\x0c')
                answer += serialize.Serialize({
                    'Type': ('2B', 33),
                    'class': ('2B', 1),
                    'TTL': ('4B', 300)
                }).packetize()

                target = self._get_host_bytes(domain)
                data_length = 2 + 2 + 2 + len(target)
                answer += serialize.Serialize({
                    'Data length': ('2B', data_length),
                    'Priority': ('2B', 1),
                    'Weight': ('2B', 1),
                    'Port': ('2B', 9100)
                }).packetize()
                answer += target
                answers += answer

            return answers, len(pi_ports)

        self.server_socket.connect(from_client)
        query = self._get_query_section(pack)
        answers, num_answers = get_anwsers()
        header = serialize.Serialize({
            'ID': ('2B', pack.get_field('ID').value),
            'Response': (1, 1),
            'Opcode': 4,
            'Authoritative': 1,
            'Truncated': 1,
            'RD': (1, 1),
            'RA': (1, 1),
            'Z': 1,
            'Answer authenticated': 1,
            'non-auth data': 1,
            'Reply code': 4,
            'Questions': ('2B', 1),
            'Answer RRs': ('2B', num_answers),
            'Authority RRs': '2B',
            'Additional RRs': '2B'
        }).packetize()
        res = header + query + answers
        self.server_socket.send(res)
Ejemplo n.º 6
0
    def to_bytes(self):
        '''result = bytearray(236)
        
        result[0] = self.message_type
        result[1] = self.hardware_type
        result[2] = self.hardware_address_length
        result[3] = self.hops

        result[4:8] = struct.pack('>I', self.transaction_id)

        result[8:10] = shortpack(self.seconds_elapsed)
        result[10:12] = shortpack(self.bootp_flags)

        result[12:16] = inet_aton(self.client_ip_address)
        result[16:20] = inet_aton(self.your_ip_address)
        result[20:24] = inet_aton(self.next_server_ip_address)
        result[24:28] = inet_aton(self.relay_agent_ip_address)

        result[28:28 + self.hardware_address_length] = macpack(self.client_mac_address)
        
        result += inet_aton(self.magic_cookie)'''
        form = {
            "op": ("1B", self.message_type),
            "htype": ("1B", self.hardware_type),
            "hlen": ("1B", self.hardware_address_length),
            "hops": ("1B", self.hops),
            "xid": ("4B", self.transaction_id),
            "secs": ("2B", self.seconds_elapsed),
            "flags": ("2B", self.bootp_flags),
            "ciaddr": ("4B", inet_aton(self.client_ip_address)),
            "yiaddr": ("4B", inet_aton(self.your_ip_address)),
            "siaddr": ("4B", inet_aton(self.next_server_ip_address)),
            "giaddr": ("4B", inet_aton(self.relay_agent_ip_address)),
            "chaddr": (str(self.hardware_address_length) + "B",
                       macpack(self.client_mac_address)),
            "cookie": ("4B", inet_aton(self.magic_cookie))
        }
        for option in self.options:
            value = self.get_option(option)
            opt = {"option_" + str(option): (str(len(value)) + "B", value)}
            # print(option, value)
            if value is None:
                continue
            # result += bytes([option, len(value)]) + value
            form.update(opt)
        # result += bytes([255])
        form.update({"term": ("1B", 255)})
        return serializeme.Serialize(form).packetize()
Ejemplo n.º 7
0
def construct_packet(inter, dmac, sip, dip, bootp):
    # Implementation of this function with serializeme API
    bootp = bootp.to_bytes()
    udp_length = len(bootp) + 8

    # Legacy code from old implementation, needed for IP checksum
    ip = bytearray(IP)
    ip[ 2: 4] = (udp_length + 20).to_bytes(2, 'big')
    identification = randrange(0, 65535)
    ip[ 4: 6] = identification.to_bytes(2, 'big')
    ip[12:16] = inet_aton(sip)
    ip[16:20] = inet_aton(dip)

    try:
        mac = open('/sys/class/net/'+inter+'/address').readline()
    except:
        print("Failed to get mac adress for ", inter)

    # building the packet header
    header_format = {   # start of ethernet frame
                        "destination"           : ("6B", int(dmac.translate({ord(i): None for i in ':.- '}), 16)),
                        "source"                : ("6B", int(mac[0:17].translate({ord(i): None for i in ':.- '}), 16)),
                        "type"                  : ("2B", 2048),   # equivalent to type \x08\x00 for ETHER
                        # start of IP header
                        "version"               : (4, 4),   # version 4
                        "ihl"                   : (4, 5),   # ip header length = 5*4 = 20 bytes
                        "type_of_service"       : "1B",
                        "total_length"          : ("2B", udp_length + 20),
                        "identification"        : ("2B", identification),
                        "flags"                 : (3, 2),
                        "fragment_offset"       : 13,
                        "time_to_live"          : ("1B", 64),
                        "protocol"              : ("1B", 17),   # protocol 17 for UDP
                        "header_checksum"       : ("2B", int.from_bytes(IP_checksum(ip), "big")),
                        "source_address"        : ("4B", int(ipaddress.IPv4Address(sip))),
                        "destination_address"   : ("4B", int(ipaddress.IPv4Address(dip))),
                        # start of UDP header
                        "source_port"           : ("2B", 67),
                        "destination_port"      : ("2B", 68),
                        "length"                : ("2B", udp_length),
                        "checksum"              : ("2B", int.from_bytes(udp_checksum(sip, dip, bootp), "big"))}

    packet = serializeme.Serialize(header_format).packetize() + bootp
    return packet
Ejemplo n.º 8
0
    def _get_query_section(self, pack):
        q_name = pack.get_field('Name').value
        q_type = pack.get_field('Type').value
        q_class = pack.get_field('class').value

        data = bytearray()
        for part in q_name.split('.'):
            data += bytearray([len(part)])
            data += str.encode(part)
        data += b'\x00'

        rest = serialize.Serialize({
            'Type': ('2B', int(q_type)),
            'class': ('2B', int(q_class))
        }).packetize()

        data += rest

        return data
Ejemplo n.º 9
0
    def __create_thread_and_process_requests(self, pkt, addr):

        # initial block number and variable for filename
        block_number = 0
        filename = ''

        # prepare the UDP socket
        client_dedicated_sock = socket(AF_INET, SOCK_DGRAM)
        # bind to 0 for an ephemeral port
        client_dedicated_sock.bind((self.connection_address, 0))
        # set timeout for the socket
        client_dedicated_sock.settimeout(10)

        # RRQ is a series of strings, the first two being the filename
        # and mode but there may also be options. see RFC 2347.
        #
        # we skip the first 2 bytes (the opcode) and split on b'\0'
        # since the strings are null terminated.
        #
        # because b'\0' is at the end of all strings split will always
        # give us an extra empty string at the end, so skip it with [:-1]
        packet = serializeme.Deserialize(pkt, {
            "opcode": ("2B", 1),
            "filename": (serializeme.NULL_TERMINATE, serializeme.HOST),
            "mode": (serializeme.NULL_TERMINATE, serializeme.HOST),
            "ANSWERS": {
                "option": (serializeme.NULL_TERMINATE, serializeme.HOST),
                "value": (serializeme.NULL_TERMINATE, serializeme.HOST)
            }
        })

        strings_in_RRQ = pkt[2:].split(b"\0")[:-1]

        logger.info("got {} from {}".format(strings_in_RRQ, addr))

        filename = packet.get_field("filename")

        # opens the file once for the socket, opening multiple times causes tftp to be slow
        try:
            transfer_file = self.res_open(filename)

            while True:

                # the first two bytes of all TFTP packets is the opcode, so we can
                # extract that here. the '!' is for big endian, and 'H' is to say it is an integer

                [opcode] = packet.get_field("opcode")

                if opcode == TFTPServer.RRQ_OPCODE:

                    if len(strings_in_RRQ) > 4:
                        for index, string in enumerate(strings_in_RRQ[2:]):
                            if string.decode() == 'tsize':
                                temp_file = self.res_open(filename)
                                temp_file.seek(0, 2)
                                t_size = temp_file.tell()

                            if string.decode() == 'blksize':
                                block_size = int(strings_in_RRQ[index + 1])

                        # construct oack
                        packet = serializeme.Serialize({
                            "OACK_opcode": ("2B", TFTPServer.OACK_OPCODE),
                            "t_size_str": (serializeme.NULL_TERMINATE, "tsize"),
                            "t_size_len": ("4B", t_size),
                            "t_zero": "1B",
                            "block_size_str": (serializeme.NULL_TERMINATE, "block_size"),
                            "block_size": ("2B", block_size),
                            "blk_zero": "1B"
                        })
                        client_dedicated_sock.sendto(packet.packetize(), addr)

                    # read up to the appropriate 512 bytes of data
                    if len(strings_in_RRQ) > 4:
                        data = transfer_file.read(block_size)
                    else:
                        data = transfer_file.read(512)

                    # if data is received increment block number, contruct the packet, and send it
                    if data:
                        block_number += 1
                        packet_format = {"opcode": ("2B", TFTPServer.DATA_OPCODE),
                                         "blk": ("2B", block_number),
                                         "data": "TBD"}
                        if len(strings_in_RRQ) > 4:
                            packet_format['data'] = (str(block_size) + "B", data)
                        else:
                            packet_format['data'] = ("512B", data)
                        packet = serializeme.Serialize(packet_format)
                        client_dedicated_sock.sendto(packet.packetize(), addr)

                # ACK received, so we can now read the next block, if it doesn't match resend the previous block of data
                elif opcode == TFTPServer.ACK_OPCODE:
                    packet = serializeme.Deserialize(pkt, {
                        "opcode": "2B",
                        "Block#": "2B"
                    })
                    [acked_block] = packet.get_field("Block#")

                    # block number matches, the block sent was successfully received
                    if acked_block == block_number:

                        data = transfer_file.read(512)

                        # if data read, increment block number, construct packet, and send it on the socket
                        if data:
                            block_number += 1
                            # transfer_block_number = pack("!H", block_number)
                            pkt_format = {
                                "opcode": ("2B", TFTPServer.DATA_OPCODE),
                                "block": ("2B", block_number),
                                "data": ("512B", data)
                            }
                            packet = serializeme.Serialize(pkt_format)
                            client_dedicated_sock.sendto(packet.packetize(), addr)

                        # if no data was read, read returns b'', then EOF was reached and download complete
                        else:
                            # sending a packet of zero data - to acknowledge end of transfer
                            block_number += 1
                            # transfer_block_number = pack("!H", block_number)
                            pkt_format = {
                                "opcode": ("2B", TFTPServer.DATA_OPCODE),
                                "block": ("2B", block_number)
                            }
                            packet = serializeme.Serialize(pkt_format)
                            client_dedicated_sock.sendto(packet.packetize(), addr)
                            logger.warning('download complete, closing socket')
                            client_dedicated_sock.close()
                            break

                    # if the block number doesn't match, means data sent was not received
                    # here you can just resend the data you already read because, no need for seek or another read
                    # because you already read it and it was not received, doing seek or read would slow down tftp
                    elif block_number != acked_block:

                        # decrement block number
                        block_number = block_number - 1

                        # transfer_block_number = pack("!H", block_number)
                        pkt_format = {
                            "opcode": ("2B", TFTPServer.DATA_OPCODE),
                            "block": ("2B", block_number),
                            "data": ("512B", data)
                        }
                        packet = serializeme.Serialize(pkt_format)

                        client_dedicated_sock.sendto(packet.packetize(), addr)

                    else:
                        # form an error packet and send it to the invalid TID
                        # error_opcode = pack("!H", TFTPServer.ERROR_OPCODE)
                        # error_code = pack("!H", 21)
                        # error_message = b"incorrect TID\0"
                        pkt_format = {
                            "opcode": ("2B", TFTPServer.ERROR_OPCODE),
                            "errorcode": ("2B", 21),
                            "errormsg": (serializeme.NULL_TERMINATE, "incorrect TID")
                        }
                        logger.error("incorrect TID")
                        packet = serializeme.Serialize(pkt_format)
                        client_dedicated_sock.sendto(packet.packetize(), addr)
                else:
                    # form an error packet and send it to the invalid TID
                    # error_opcode = pack("!H", TFTPServer.ERROR_OPCODE)
                    # error_code = pack("!H", 20)
                    # error_message = b"illegal operation specified\0"
                    pkt_format = {
                        "opcode": ("2B", TFTPServer.ERROR_OPCODE),
                        "errorcode": ("2B", 20),
                        "errormsg": (serializeme.NULL_TERMINATE, "Illegal operation specified")
                    }
                    logger.error("illegal operation specified")
                    packet = serializeme.Serialize(pkt_format)
                    client_dedicated_sock.sendto(packet.packetize(), addr)

                # listen for a client response for 10 seconds
                # close everything and terminate if no response
                try:
                    pkt, addr = client_dedicated_sock.recvfrom(
                        self.BUFFER_SIZE)

                except:
                    logger.error("Socket Timed Out")
                    client_dedicated_sock.close()
                    logger.error('closed socket')
                    break
        except FileNotFoundError:
            # send an error packet to the requesting host
            # error_opcode = pack("!H", TFTPServer.ERROR_OPCODE)
            # error_code = pack("!H", 17)
            # error_message = b"No such file within the directory\0"
            pkt_format = {
                "opcode": ("2B", TFTPServer.ERROR_OPCODE),
                "errorcode": ("2B", 17),
                "errormsg": (serializeme.NULL_TERMINATE, "No such file within the directory")
            }
            logger.error("No such file within the directory")
            packet = serializeme.Serialize(pkt_format)
            client_dedicated_sock.sendto(packet.packetize(), addr)
            client_dedicated_sock.close()
Ejemplo n.º 10
0
def construct_packet(inter, dmac, sip, dip, bootp):

    # BOOTP Payload
    bootp = bootp.to_bytes()
    # udp   = bytearray(UDP)
    # ip    = bytearray(IP)
    # ether = bytearray(ETHER)

    udp_pack = serializeme.Serialize({
        'source': ('2B', sip),
        'destination': ('2B', dip),
        'length': ('2B', len(bootp) + 8),
        'checksum': ('2B', udp_checksum(sip, dip, bootp))
    })

    # # UDP Packet
    # udp_length = len(bootp) + 8
    # udp[4:6] = (udp_length).to_bytes(2, 'big')
    # udp[6:8] = udp_checksum(sip, dip, bootp)

    ip_header = serializeme.Serialize({
        'version': ('4b', 4),
        'IHL': (4, 5),
        'tos': (8, 0),
        'total_length':
        ('2B', (udp_pack.packetize().length + 20).to_bytes(2, 'big')),
        'identification': ('2B', (randrange(0, 65535)).to_bytes(2, 'big')),
        'flags': (3, 2),
        'fragment_offset':
        13
    })

    #           |V IHL     | TOS     | TOTLEN     | ID           |  F OFF | TTL + PR |
    # IP    = b'\x45       \x00      \x00\x00     \x00\x00       \x40\x00 \x40\x11  \   x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
    ip_pack = serializeme.Serialize({
        'ttl': (8, 64),
        'protocol': (4, 17),
        'checksum': ('2B', IP_checksum(ip_header.packetize())),
        'source': ('4B', inet_aton(sip)),
        'destination': ('4B', inet_aton(dip))
    })
    # # IP Packet
    # version & IHL & type of service      ip[ 0: 2]
    # total length                         ip[ 2: 4] = (udp_length + 20).to_bytes(2, 'big')
    # indentification                      ip[ 4: 6] = (randrange(0, 65535)).to_bytes(2, 'big')
    # flags+fragmentoffset                 ip[ 6:10] = we dont know ;)
    # checksum                             ip[10:12] = IP_checksum(ip)
    # source address                       ip[12:16] = inet_aton(sip)
    # destination                          ip[16:20] = inet_aton(dip)

    try:
        mac = open('/sys/class/net/' + inter + '/address').readline()
    except:
        print("Failed to get mac adress for ", inter)

    ether_pack = serializeme.Serialize({
        'mac_address': ('6B', macpack(dmac)),
        'destination': ('6B', macpack(mac[0:17])),
    })

    # # Ethernet Frame
    # ether[0: 6] = macpack(dmac)
    # ether[6:12] = macpack(mac[0:17])
    # packet = b''.join([bytes(ether), bytes(ip), bytes(udp), bootp])

    return ether_pack.packetize() + ip_header.packetize() + ip_pack.packetize(
    ) + udp_pack.packetize() + bootp
Ejemplo n.º 11
0
def resolve():
    print("Hello")

    PORT = 1080
    HOST = 'localhost'
    sd = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sd.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    sd.bind((HOST, PORT))
    sd.listen(1)

    #print(sd)

    while True:
        print('Waiting for a client connection')

        connection, client_address = sd.accept()
        with connection:
            print("Connected by", client_address)
            rsp = connection.recv(1024)

            #section 3
            decode_client_greeting = serializeme.Deserialize(
                rsp, {
                    "VER": ("1B"),
                    "NAUTH": ("1B", "", "AUTH"),
                    "AUTH": {
                        "Name": "1B"
                    }
                })

            server_choice = serializeme.Serialize({
                "VER": ("1B", 5),
                "METHOD": ("1B", 2)
            })
            connection.sendall(server_choice.packetize())

            #subsequent authentication
            rsp = connection.recv(1024)
            decode_request = serializeme.Deserialize(rsp, {
                "VER": "1B",
                "IDLEN": "1B",
                "ID": "1B",
                "PWLEN": "1B",
                "PW": "1B"
            })

            #if success => status is 0 and return True, if not =>status is 0xFF and return False
            server_response = serializeme.Serialize({
                "VER": ("1B", 1),
                "STATUS": ("1B", 0)
            })
            connection.sendall(server_response.packetize())

            #Section 4
            #Client request
            rsp = connection.recv(1024)

            #Decode first 4 bytes
            decode_client_connection = serializeme.Deserialize(
                rsp[0:4], {
                    "VER": ("1B"),
                    "CMD": ("1B"),
                    "RSV": ("1B"),
                    "ATYP": ("1B")
                })
            atyp = decode_client_connection.get_value("ATYP")

            #Decode rest of bytes
            if atyp == 1:
                decode = serializeme.Deserialize(rsp[4:], {
                    "DEST_ADDR": serializeme.IPv4,
                    "DEST_PORT": "4B"
                })
            elif atyp == 3:
                decode = serializeme.Deserialize(rsp[4:], {
                    "DEST_ADDR": serializeme.PREFIX_LENGTH,
                    "DEST_PORT": "2B"
                })
            dest_addr = decode.get_value("DEST_ADDR")
            dest_port = decode.get_value("DEST_PORT")

            #connection to dest_port (google.com in here)
            new_sd = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            new_sd.connect((dest_addr, dest_port))

            #section 6
            response_packet = serializeme.Serialize({
                "VER": ("1B", 5),
                "STATUS": ("1B", 0),
                "RSV": ("1B", 0),
                "ATYP": ("1B", atyp),
                "BND_ADDR": (serializeme.PREFIX_LENGTH, dest_addr),
                "BND_PORT": ("2B", dest_port)
            })

            #connection.sendall(response_packet.packetize())
            connection.sendall(response_packet.packetize())

            #listen from client
            rsp = connection.recv(1024)

            #Send packet to server
            new_sd.sendall(rsp)

            #listen from destination address
            rsp = new_sd.recv(4096)
            """
            message = b''
            i = 1
            #print(message)
            while (True):
                rsp = new_sd.recv(4096)
                print(i, rsp)
                if not rsp:
                    break
                #print(i, rsp)
                i = i + 1
                #message += rsp
                message.append(rsp)
            print(message)
            """
            connection.sendall(rsp)
            print("Done")
Ejemplo n.º 12
0
def resolve():
    print("Hello")

    PORT = 1080
    HOST = 'localhost'
    sd = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sd.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    sd.bind((HOST, PORT))
    #print("Server IP {} Listening on Port {}".format(HOST, PORT))
    sd.listen(1)

    #print(sd)

    while True:
        # Wait for a connection
        print('Waiting for a client connection')
        # connection established
        connection, client_address = sd.accept()
        with connection:
            print("Connected by", client_address)
            rsp = connection.recv(1024)
            #print("clinet_greeting data: ", rsp)

            #section 3
            decode_client_greeting = serializeme.Deserialize(
                rsp, {
                    "VER": ("1B"),
                    "NAUTH": ("1B", "", "AUTH"),
                    "AUTH": {
                        "Name": "1B"
                    }
                })
            #print("VER is: ", decode_client_greeting.get_value("VER"))
            #print("NAUTH is: ", decode_client_greeting.get_value("NAUTH"))
            #print("AUTH is: ", decode_client_greeting.get_value("AUTH"))

            server_choice = serializeme.Serialize({
                "VER": ("1B", 5),
                "METHOD": ("1B", 2)
            })
            #print("server choice: ", server_choice.packetize())
            connection.sendall(server_choice.packetize())

            #subsequent authentication
            rsp = connection.recv(1024)
            #print("Client quthentication request): ", rsp)
            decode_request = serializeme.Deserialize(rsp, {
                "VER": "1B",
                "IDLEN": "1B",
                "ID": "1B",
                "PWLEN": "1B",
                "PW": "1B"
            })
            #print("VER is: ", decode_request.get_value("VER"))
            #print("IDLEN is: ", decode_request.get_value("IDLEN"))
            #print("ID is: ", decode_request.get_value("ID"))
            #print("PWLEN is: ", decode_request.get_value("PWLEN"))
            #print("PW is: ", decode_request.get_value("PW"))

            #if success => status is 0 and return True, if not =>status is 0xFF and return False
            server_response = serializeme.Serialize({
                "VER": ("1B", 1),
                "STATUS": ("1B", 0)
            })
            #print("server response: ", server_response.packetize())
            connection.sendall(server_response.packetize())
            print("server response is sent")

            #Section 4
            rsp = connection.recv(1024)
            #print("Client request message: ", rsp)
            #print("First 4 bytes: ", rsp[0:4])

            decode_client_connection = serializeme.Deserialize(
                rsp[0:4], {
                    "VER": ("1B"),
                    "CMD": ("1B"),
                    "RSV": ("1B"),
                    "ATYP": ("1B")
                })
            #print("ATYP is: ", decode_client_connection.get_value("ATYP"))
            #print("Rest of bytes: ", rsp[4:])
            atyp = decode_client_connection.get_value("ATYP")

            if atyp == 1:
                decode = serializeme.Deserialize(rsp[4:], {
                    "DEST_ADDR": serializeme.IPv4,
                    "DEST_PORT": "4B"
                })
            elif atyp == 3:
                decode = serializeme.Deserialize(rsp[4:], {
                    "DEST_ADDR": serializeme.PREFIX_LENGTH,
                    "DEST_PORT": "2B"
                })
            dest_addr = decode.get_value("DEST_ADDR")
            #print(dest_addr)
            dest_port = decode.get_value("DEST_PORT")
            #print(dest_port)

            #print("VER is: ", decode_client_connection.get_value("VER"))
            #print("CMD is: ", decode_client_connection.get_value("CMD"))
            #print("RSV is: ", decode_client_connection.get_value("RSV"))
            #print("ATYP is: ", decode_client_connection.get_value("ATYP"))
            #print("DEST_ADDR is: ", decode.get_value("DEST_ADDR"))
            #print("DEST_PORT is: ", decode.get_value("DEST_PORT"))

            #connection to dest_port (google.com in here)
            new_sd = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            new_sd.connect((dest_addr, dest_port))
            #res = new_sd.recv(1024)
            #print(res)

            #section 6
            response_packet = serializeme.Serialize({
                "VER": ("1B", 5),
                "STATUS": ("1B", 0),
                "RSV": ("1B", 0),
                "ATYP": ("1B", atyp),
                "BND_ADDR": (serializeme.PREFIX_LENGTH, dest_addr),
                "BND_PORT": ("2B", dest_port)
            })
            #print("response packet from server", response_packet.packetize())
            #connection.sendall(response_packet.packetize())
            connection.sendall(response_packet.packetize())
            print("response packet is sent to client!")

            #listen from client
            rsp = connection.recv(1024)
            #print(rsp)

            new_sd.sendall(rsp)
            print("User request is sent to desination address!")

            #listen from destination address
            #rsp = new_sd.recv(4096)

            message = b''
            i = 1
            #print(message)
            while (True):
                rsp = new_sd.recv(4096)
                print(i, rsp)
                if not rsp:
                    break
                #print(i, rsp)
                i = i + 1
                #message += rsp
                message.append(rsp)
            print(message)

            connection.sendall(rsp)
            print("Sent reply back from google to clinet")