Exemple #1
0
class RevTLSClient:
    def __init__(self, address, credentials):
        self.address = address
        self.__creds = credentials
        self.conn = None
        self.connect()

    def __enter__(self):
        return self

    def __exit__(self, type, value, traceback):
        self.close()

    def connect(self):
        if self.conn:
            return

        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.connect(self.address)

        self.conn = TLSConnection(sock)
        self.conn.handshakeClientCert(self.__creds.cert,
                                      self.__creds.pkey,
                                      checker=self.__creds.checker)
        self.fconn = self.conn.makefile()

    def sendall(self, data):
        _write_with_length(self.fconn, data)

    def recvall(self):
        return _read_with_length(self.fconn)

    def close(self):
        self.fconn.close()
        self.fconn = None
        self.conn.close()
        self.conn = None
Exemple #2
0
class WAVEGRPCClient:
    def __init__(self,
                 address_tuple,
                 namespace,
                 entityfile,
                 grpcservice,
                 proof_file='clientproof.pem',
                 waved='localhost:410'):
        self.address_tuple = address_tuple
        self.ns = namespace
        self.grpcservice = grpcservice
        self.nsbytes = base64.urlsafe_b64decode(self.ns)
        self.entityfile = open(entityfile, 'rb').read()
        self.perspective = eapi_pb2.Perspective(
            entitySecret=eapi_pb2.EntitySecret(DER=self.entityfile))
        self._listen_address = None
        self._ready = threading.Event()

        self.wave_channel = grpc.insecure_channel(waved)
        self.wave_client = eapi_pb2_grpc.WAVEStub(self.wave_channel)
        resp = self.wave_client.Inspect(
            eapi_pb2.InspectParams(content=self.entityfile, ))
        self.entityhash = resp.entity.hash

        self.proof_file = open('clientproof.pem', 'rb').read()
        resp = self.wave_client.VerifyProof(
            eapi_pb2.VerifyProofParams(proofDER=self.proof_file, ))
        self.sigresp = self.wave_client.Sign(
            eapi_pb2.SignParams(
                perspective=self.perspective,
                content=self.proof_file,
            ))

        # setup server
        self._server_thread = threading.Thread(
            target=self.get_client_connection, daemon=True)
        self._server_thread.start()

    def setup_connection(self):
        hdr = self.generate_peer_header()

        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        #sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        sock.connect(self.address_tuple)
        self.upstream_connection = TLSConnection(sock)
        hs = self.upstream_connection.handshakeClientCert()
        self.upstream_connection.write(self.nsbytes)
        self.upstream_connection.write(hdr)
        invalid = self.read_peer_header(self.upstream_connection)
        if invalid.message != '':
            raise Exception(
                "GRPC Server sent invalid header or proof {0}".format(invalid))

    @property
    def listen_address(self):
        self._ready.wait()
        return "{0}:{1}".format(*self._listen_address)

    def get_client_connection(self):
        listen_port = 5005
        while True:
            listen_address = ('localhost', listen_port)
            server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            try:
                server.bind(listen_address)
                self._listen_address = listen_address
                self._ready.set()
                break
            except Exception as e:
                print("Failed to listen on {0}".format(listen_address), e)
                time.sleep(1)
                listen_port += 1
        print("Listening on {0}".format(listen_address))
        server.listen(10)

        while True:
            client_socket, addr = server.accept()
            # reconnect to the GRPC server on each call
            self.setup_connection()

            # start a thread to talk to the remote host
            proxy_thread = threading.Thread(target=self.handle_client,
                                            args=(client_socket, ),
                                            daemon=True)
            proxy_thread.start()

    def handle_client(self, client_socket):
        while True:
            try:
                local_buffer = receive_from(client_socket)
                if len(local_buffer):
                    self.upstream_connection.send(local_buffer)
                # receive back the response
                remote_buffer = receive_from(self.upstream_connection)
                if len(remote_buffer):
                    # send the response to the local socket
                    client_socket.send(remote_buffer)
                # if no more data on the either side, close the connections
                if not len(local_buffer) or not len(remote_buffer):
                    print("Done with call")
                    break
            finally:
                client_socket.close()
                self.upstream_connection.close()

    def generate_peer_header(self):
        buf = bytes()
        buf += self.entityhash
        buf += struct.pack('<H', len(self.sigresp.signature))
        buf += self.sigresp.signature
        buf += struct.pack('<I', len(self.proof_file))
        buf += self.proof_file
        return buf

    def read_peer_header(self, conn):
        entityhash = conn.read(max=34, min=34)
        sigsize = struct.unpack('<H', conn.read(max=2, min=2))[0]
        signature = conn.read(max=sigsize, min=sigsize)
        proofsize = struct.unpack('<I', conn.read(max=4, min=4))[0]
        proof = conn.read(max=proofsize, min=proofsize)
        #TODO verify this
        # TODO: need peer certificate
        cert = self.upstream_connection.session.serverCertChain.x509List[
            0].bytes

        c = x509.load_der_x509_certificate(cert, default_backend())

        vresp = self.wave_client.VerifySignature(
            eapi_pb2.VerifySignatureParams(
                signer=entityhash,
                signature=signature,
                content=c.signature,
            ))
        if vresp.error.message != "":
            return vresp.error

        proofresp = self.wave_client.VerifyProof(
            eapi_pb2.VerifyProofParams(
                proofDER=proof,
                subject=entityhash,
                requiredRTreePolicy=eapi_pb2.RTreePolicy(
                    namespace=self.nsbytes,
                    statements=[
                        eapi_pb2.RTreePolicyStatement(
                            permissionSet=XBOS_PERMSET,
                            permissions=["serve_grpc"],
                            resource=self.grpcservice,
                        ),
                    ],
                )))
        if proofresp.result == None:
            return "no proof"
        return proofresp.error
Exemple #3
0
                  (_SID, msg2.SID, msg2.BODY))
        print('***INCOMING FROM [%s]:%s***' % (msg2.SID, msg2.BODY))


recv_thread = threading.Thread(target=loop)
recv_thread.setDaemon(True)
recv_thread.start()

while True:
    _ = raw_input('RID> ')
    if not _:
        break
    msg.RID = _
    msg.TYPE = 0
    _ = raw_input('MSG> ')
    if not _:
        break
    if _.startswith('group'):
        _1, action, data = _.split()
        msg.TYPE = setBit(msgType, 5)
        msg.BODY = '{"action":"%s", "data":"%s"}' % (action, data)
        print(msg.BODY)
    else:
        msg.BODY = _

    data = Packet.Pack(msg)

    data = connection.write(data)  # You must implement your own tcp receiver

connection.close()
Exemple #4
0
            buf = ''
        if msg2.SID == "":
            print('***ok')
            continue
        os.system('TITLE CLIENT %s INCOMING FROM [%s]:%s' % (_SID, msg2.SID, (msg2.BODY[:13]+"...") if len(msg2.BODY)>16 else msg2.BODY))
        for k,v in json.loads(msg2.BODY).iteritems():
            print("%s: %s" % (k,v))
        print('=====================================')
        #print('***INCOMING FROM [%s]:%s***' % (msg2.SID, msg2.BODY))
        last_mid = msg2.MID
        
recv_thread = threading.Thread(target = loop)
recv_thread.setDaemon(True)
recv_thread.start()

while True:
    _ = raw_input('CONFIRM?> ') or 'y'
    print(last_mid)
    if _ == 'n':
        break
    msg.SID = _SID
    msg.MID = ''
    msg.RID = "00000001"
    msg.TYPE = 1
    msg.BODY = '{"type":"receipt", "status":"ok", "mid":"'+last_mid+'"}'
    data = Packet.Pack(msg)
    data = connection.write(data) # You must implement your own tcp receiver


connection.close()
Exemple #5
0
        print("------------------------------")
        if tackExt.activation_flags != 0:
            usingTACK = True

    # if no active TACKs in TLS-Connection
    if not usingTACK:
        if haveActivePin:
            raise Error("Active PIN, but no active TACK. Connection might be compromised!")
        elif havePin:
            del store[sockString]  # del inactive pin
            print("deleting inactive pin")
        else:
            print(sockString + " doesn't seem to you use TACK.")

        store.close()
        conn.close()
        exit(0)

    if not tackExt.verifySignatures():
        raise SyntaxError("TACK doesn't belong to Cert!")
    # from here exist only one or two valid TACKs

    # check tack generations
    '''If a tack has matching pins in the pin store and a generation
       less than the stored min_generation, then that tack is revoked and
       the client SHALL send a fatal "certificate_revoked" error alert.'''
    for tack in tackExt.tacks:
        if tack.min_generation < min_generation:
            raise Error("Certificate revoked")

    if tackExt.activation_flags == 3: