Exemple #1
0
def testMACValidation():
    """
    Tests whether the server properly rejects messages when their MAC is modified.
    """
    print("Testing validation of individual MAC bits...")
    failBits = []
    for maskBit in range(0, 96):
        rejected = False
        try:
            # formulate a bit mask based on the current mask bit index
            mask = bytearray([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
            maskIndex = int((maskBit - (maskBit % 8)) / 8)
            mask[maskIndex] = (0x80 >> (maskBit % 8))

            if args.verbose:
                maskBinString = ''.join(format(x, 'b').zfill(8) for x in mask)
                print("\tTesting bit %d, mask: %s" % (maskBit, maskBinString))
            else:
                print("+", end="")

            # connect to the server and do a handshake
            sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            sock.connect((args.host, args.port))
            tls = TLSConnection(sock)

            # assign mask as tweak
            tls.macTweak = bytearray(mask)

            tls.handshakeClientCert()

            # send a packet
            tls.send("GET / HTTP/1.0\n\n\n")

            # try to read some data back
            data = tls.read()
        except (TLSRemoteAlert, socket.error):
            rejected = True
            if args.verbose:
                print("\tBit %d rejected correctly!" % maskBit)
        except (TLSAbruptCloseError, socket.error):
            rejected = True
            if args.verbose:
                print("\tBit %d rejected correctly!" % maskBit)
        if not rejected:
            failBits.append(maskBit)

    if not args.verbose:
        print("")
    if len(failBits) > 0:
        macValidationIssue = getIssueTemplate("MAC_VALIDATION_ERROR")
        macValidationIssue.findings = ', '.join(str(b) for b in failBits)
        report.addIssue(macValidationIssue)
        print("The following modified MAC bits were incorrectly accepted: ",
              end='')
        print(', '.join(str(b) for b in failBits))
    else:
        print("All modified MAC bits were correctly rejected.")
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
        sock.sendall(request)

        # receive reply from socke 5 proxy
        failed_reply = b''
        failed_reply = failed_reply + b'\x05'  # version number
        failed_reply = failed_reply + b'\x01'  # general SOCKS server failure
        failed_reply = failed_reply + b'\x00'  # reserved
        failed_reply = failed_reply + b'\x01' + b'\x00' * 6

        reply = sock.recv(10)
        if len(reply) != 10:
            print 'reply length is not 10'
            print 'this should not happen'
        elif reply == failed_reply:
            print 'received failed reply'
        else:
            print 'received succeeded reply, socks 5 proxy established connection with the remote server'
            # now use sock to establish TLS 1.3 connection with the remote server
            connection = TLSConnection(sock)
            mb_utils.fake_handshakeClientCert(connection)
            # 2 \r\n
            connection.send("GET / HTTP/1.0\r\n\r\n")
            r = connection.recv(10240)
            if r in (0, 1):
                print 'received 0 or 1'
            elif isinstance(r, str):
                print 'received from server:'
                print r
            else:
                print 'f**k'
            #connection.close()