コード例 #1
0
ファイル: client.py プロジェクト: dsoneira7/TheOgreProtocol
def run_client(hoplist, destination):

    next_s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    next_host = (hoplist[len(hoplist) - 1][0], hoplist[len(hoplist) - 1][1])
    next_s.connect(next_host)
    # Generate wrapped message
    wrapped_message, aes_key_list = utils.wrap_all_messages(
        hoplist, destination)

    utils.send_message_with_length_prefix(next_s, wrapped_message)

    while True:
        print colored("CLIENT: Type some text to send through the network.",
                      'yellow')
        message = raw_input()
        message = utils.add_all_layers(aes_key_list, message)
        try:
            utils.send_message_with_length_prefix(next_s, message)
        except socket.error, e:
            print "client detected node closing, finished!"
            return
        try:
            response = utils.recv_message_with_length_prefix(next_s)
        except socket.error, e:
            print "client detected node closing, finished!"
            return
コード例 #2
0
def proxy_thread(conn, client_addr, hoplist):
    #print "thread launched"
    request = conn.recv(
        2048
    )  #FIXME: handle closed socket on other side of connection, also why 2048?
    # print request
    first_line = request.split('\n')[0]
    splitlist = first_line.split(' ')
    if len(splitlist) < 2:
        conn.close()
        return  #This is a fix for the 'index out of range' error we've seen
    url = first_line.split(' ')[1]

    http_pos = url.find("://")
    if http_pos == -1:
        temp = url
    else:
        temp = url[(http_pos + 3):]

    port_pos = temp.find(":")

    webserver_pos = temp.find("/")
    if webserver_pos == -1:
        webserver_pos = len(temp)

    webserver = ""
    port = -1
    if port_pos == -1 or webserver_pos < port_pos:
        port = 80
        webserver = temp[:webserver_pos]
    else:
        port = int((temp[(port_pos + 1):])[:webserver_pos - port_pos - 1])
        webserver = temp[:port_pos]

    request = re.sub(r"http:\/\/.*?(?=\/)", "", request)

    webserver = socket.gethostbyname(
        webserver
    )  #FIXME: what happens if i type a random url that doesn't resolve?
    destination = utils.packHostPort(webserver, port)
    next_s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    next_host = (hoplist[len(hoplist) - 1][0], hoplist[len(hoplist) - 1][1])
    next_s.connect(next_host)
    # Generate wrapped message
    wrapped_message, aes_key_list = utils.wrap_all_messages(
        hoplist, destination)
    # print "AES key list length" + str(len(aes_key_list))
    # print "hoplist length " + str(len(hoplist))

    sendret = 0
    try:
        sendret = utils.send_message_with_length_prefix(
            next_s, wrapped_message)
    except socket.error, e:
        sendret = 0
コード例 #3
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("dir_auth_ip",
                        help="the ip address of the directory authority")
    parser.add_argument("dir_auth_port",
                        help="the port number of the directory authority")
    parser.add_argument("client_ip", help="the ip address of the proxy client")
    parser.add_argument("client_port",
                        help="the port number of the proxy client")
    args = parser.parse_args()

    DA_IP = args.dir_auth_ip
    DA_PORT = args.dir_auth_port
    CLI_ADDR = args.client_ip
    CLI_PORT = args.client_port

    da_file = open('dir_auth_pub_key.pem', 'r')
    da_pub_key = da_file.read()
    da_pub_key = RSA.importKey(da_pub_key)

    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect((DA_IP, int(DA_PORT)))
    s.send('r')  # specify request type (route)

    # construct and send an aes key
    randfile = Random.new()
    aes_key = randfile.read(32)
    aes_obj = aes_obj = AES.new(aes_key, AES.MODE_CBC, "0" * 16)
    aes_msg = da_pub_key.encrypt(aes_key, 0)[0]
    succ = utils.send_message_with_length_prefix(s, aes_msg)
    if not succ:
        s.close()
        print colored("Proxy Client: Directory authority connection failed",
                      'yellow')
        quit()

    # Receive
    data = utils.recv_message_with_length_prefix(
        s)  # All info from directory authority
    if data == "":
        s.close()
        print colored("Proxy Client: Directory authority connection failed",
                      'yellow')
        quit()

    hop_data = aes_obj.decrypt(data)

    # hoplist format (ip, port, public_key)
    # Replace this with processed route and key data
    hoplist = utils.process_route(hop_data)
    hoplist = list(reversed(hoplist))

    # Send keys and establish link
    run_client(hoplist, (CLI_ADDR, int(CLI_PORT)))
コード例 #4
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("dir_auth_port", help="the port number of the directory authority")
    args = parser.parse_args()

    RSA_KEY_SIZE = 212
    NUM_NODES = 3

    relay_nodes = {}

    exit_nodes = {}

    randfile = Random.new()

    #get the DA private key from a file
    da_file = open('dir_auth_priv_key.pem','r')
    da_private = da_file.read()
    da_mykey = RSA.importKey(da_private)

    #read in Port from command line args
    da_IP = "127.0.0.1"
    da_port = args.dir_auth_port



    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.bind((da_IP, int(da_port)))
    s.listen(1)

    while True:
        #listen for connections and serve requests:
            #Register relay nodes with IP, Port, PublicKey in NodeDict
            #Register exit nodes with IP, Port PublicKey in ExitDict
            #Provide route of N nodes and 1 exit node, with IP, Port, PublicKey for every node
        
        (clientsocket, addr) = s.accept()

        request_type = clientsocket.recv(1);
        if request_type == "":
            clientsocket.close()
            continue

        if request_type == 'n': #relay node
            msg = utils.recvn(clientsocket,RSA_KEY_SIZE+8)
            if msg == "":
                clientsocket.close()
                continue
            node_addr = msg[:8]
            key = msg[8:]
            relay_nodes[node_addr] = key
            print colored("DA["+da_port+"]: registered a relay node on port " + str(utils.unpackHostPort(node_addr)[1]), 'green')

        elif request_type == 'e': #exit node
            msg = utils.recvn(clientsocket,RSA_KEY_SIZE+8)
            if msg == "":
                clientsocket.close()
                continue
            node_addr = msg[:8]
            key = msg[8:]
            exit_nodes[node_addr] = key
            print colored("DA["+da_port+"]: registered an exit node on port " + str(utils.unpackHostPort(node_addr)[1]), 'green')

        elif request_type == 'r': #route

            #recieve encrypted aes key from client
            aes_enc = utils.recv_message_with_length_prefix(clientsocket)
            if aes_enc == "":
                clientsocket.close()
                continue
            aes_key = da_mykey.decrypt(aes_enc)
            
            relay_list = random.sample(relay_nodes.items(),NUM_NODES-1)
            exit = random.sample(exit_nodes.items(),1)
            route_message = construct_route(relay_list,exit)
            
            aes_obj = AES.new(aes_key, AES.MODE_CBC, "0"*16)
            blob = aes_obj.encrypt(utils.pad_message(route_message))
            utils.send_message_with_length_prefix(clientsocket,blob)
            print colored("DA["+da_port+"]: sent a route to a client", 'green')

        clientsocket.close()
コード例 #5
0
signal.signal(signal.SIGINT, utils.signal_handler)

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
myip = '127.0.0.1'  #loopback only for now
s.bind((myip, int(sys.argv[1])))
s.listen(1)
print colored("Waiting for a connection...", "red")
(clientsocket, addr) = s.accept()
print colored("Accepted a connection!", "red")
while True:
    message = utils.recv_message_with_length_prefix(clientsocket)
    if message == "":
        sys.exit(0)
    print colored("Anonymous Message:\n" + message, 'yellow')
    print colored("Please type a reponse.", "red")
    revmessage = raw_input()
    if revmessage == "QUIT":
        try:
            clientsocket.shutdown(socket.SHUT_RDWR)
            s.shutdown(socket.SHUT_RDWR)
        except socket.error, e:
            pass
        sys.exit(0)
    bytessent = utils.send_message_with_length_prefix(clientsocket, revmessage)
    if bytessent == 0:
        try:
            clientsocket.shutdown(socket.SHUT_RDWR)
            s.shutdown(socket.SHUT_RDWR)
        except socket.error, e:
            pass
        print "\n\nLost connection to client. Closing...\n"
コード例 #6
0
    sendret = 0
    try:
        sendret = utils.send_message_with_length_prefix(
            next_s, wrapped_message)
    except socket.error, e:
        sendret = 0
    if sendret == 0:
        conn.close()
        try:
            next_s.shutdown(socket.SHUT_RDWR)
        except socket.error:
            return
        return

    request = utils.add_all_layers(aes_key_list, request)
    sendret = utils.send_message_with_length_prefix(next_s, request)
    if sendret == 0:
        conn.close()
        next_s.shutdown(socket.SHUT_RDWR)
        return
    try:
        data = utils.recv_message_with_length_prefix(next_s)
    except socket.error, e:
        data = ""
    if data == "":
        conn.close()
        next_s.shutdown(socket.SHUT_RDWR)
        return
    conn.send(utils.peel_all_layers(
        aes_key_list,
        data))  #FIXME: handle closed socket on other side of connection
コード例 #7
0
        routemessage = utils.recv_message_with_length_prefix(prevhop)
    except socket.error, e:
        routemessage = ""
    if routemessage == "":
        #kill this thread
        return
    try:
        aeskey, hostport, nextmessage = peelRoute(routemessage, mykey)
    except ValueError:
        prevhop.shutdown(socket.SHUT_RDWR)
        return
    nexthost, nextport = utils.unpackHostPort(hostport)
    nexthop = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    nexthop.connect((nexthost, nextport))
    if nextmessage != "":
        utils.send_message_with_length_prefix(nexthop, nextmessage)
    #spawn forwarding and backwarding threads here
    fwd = threading.Thread(target=forwardingLoop, args=(prevhop, nexthop, aeskey, is_exit))
    bwd = threading.Thread(target=backwardingLoop, args=(prevhop, nexthop, aeskey, is_exit))
    fwd.start()
    bwd.start()
    fwd.join()
    bwd.join()
    return

def forwardingLoop(prevhop, nexthop, aeskey, is_exit):
    while True:
        try:
            message = utils.recv_message_with_length_prefix(prevhop)
        except socket.error, e:
            message = ""