Ejemplo n.º 1
0
    def verifyCerts(self, certs):
        getCommonName = lambda cert: CipherUtil.getCertSubject(cert)[
            "commonName"]
        if getCommonName(certs[-1]) == getCommonName(self.rootCert):
            certs.pop()
        certs.append(self.rootCert)

        for i, cert in enumerate(certs):
            if i == len(certs) - 1:
                break
            nextCert = certs[i + 1]
            commonName = getCommonName(cert)
            nextCommonName = getCommonName(nextCert)
            if commonName.split(".")[:-1] != nextCommonName.split("."):
                self.dbgPrint("Error: cert common name mismatch: " +
                              commonName + ", " + nextCommonName)
                return False

        commonName = getCommonName(certs[0])
        peerAddressList = [str(i) for i in self.peerAddress[0].split(".")]
        peerAddress = ".".join(peerAddressList)

        if commonName != peerAddress:
            self.dbgPrint("Error: address mismatch: " + commonName + ", " +
                          peerAddress)
            return False
        else:
            return CipherUtil.ValidateCertChainSigs(certs)
Ejemplo n.º 2
0
 def validate(self, certificate):
     print("In Cert Validation")
     clientissuer = CipherUtil.getCertIssuer(certificate[0])
     clientsubject = CipherUtil.getCertSubject(certificate[0])
     IntermediateIssuer = {'emailAddress': '*****@*****.**', 'stateOrProvinceName': 'MD', 'countryName': 'US', 'commonName': '20174.1.666', 'organizationalUnitName': 'PETF', 'localityName': 'Baltimore', 'organizationName': 'JHUNetworkSecurityFall2017'}
     if clientissuer == IntermediateIssuer:
             print("Issuer verified.")
             Certificate_result = CipherUtil.ValidateCertChainSigs(certificate)
             if Certificate_result:
                 return True
             else:
                 print ("Certificate Validation Failed")
                 return False
Ejemplo n.º 3
0
    def data_received(self, data):
        self._deserializer.update(data)
        for packet in self._deserializer.nextPackets():
            if isinstance(packet, PlsData):
                cipher_text = packet.Ciphertext
                verification_code = packet.Mac

                if self._verification_engine.verifyMac(cipher_text,
                                                       verification_code):
                    plain_text = self._decryption_engine.decrypt(cipher_text)
                    self.higherProtocol().data_received(plain_text)
                else:
                    self.terminate_connection("validation error")

            elif isinstance(packet, PlsHello):
                '''
                1. store certs from the other side (?)
                2. get the other side's pubk from the certs
                3. store the other side's nonce
                4. store this message for SHA1
                '''
                self._certs_for_other_side = list(packet.Certs)
                self._nonce_for_other_side = packet.Nonce
                self._pubk_for_other_side = CertFactory.getPubkFromCert(
                    packet.Certs[0])
                self._messages_for_handshake.append(packet.__serialize__())
                '''
                verify certs
                '''
                tmp_cert_list = []
                for cert_for_other_side in self._certs_for_other_side:
                    tmp_cert_list.append(
                        CipherUtil.getCertFromBytes(cert_for_other_side))
                peer_name = self.transport.get_extra_info("peername")[0]
                common_name = CertFactory.GetCommonName(packet.Certs[0])

                root = CipherUtil.getCertFromBytes(CertFactory.getRootCert())
                issuer = CipherUtil.RSA_SIGNATURE_MAC(root.public_key())

                if str(peer_name).startswith(
                        common_name
                ) and CipherUtil.ValidateCertChainSigs(tmp_cert_list) and (
                        packet.Certs[-1] == CertFactory.getRootCert()
                        or issuer.verify(packet.Certs[-1], root.signature)):
                    if self._state == 0:
                        # start to send plshello
                        self._nonce = random.randint(0, 2**64)
                        pls_hello = PlsHello(Nonce=self._nonce,
                                             Certs=self._certs)
                        pls_hello_bytes = pls_hello.__serialize__()
                        self.transport.write(pls_hello_bytes)
                        self._state = 2
                        self._messages_for_handshake.append(pls_hello_bytes)
                    elif self._state == 1:
                        self._pre_key = CertFactory.getPreKey()
                        pls_key_exchange = PlsKeyExchange(
                            PreKey=CryptoUtil.RSAEncrypt(
                                self._pubk_for_other_side, self._pre_key),
                            NoncePlusOne=self._nonce_for_other_side + 1)
                        pls_key_exchange_bytes = pls_key_exchange.__serialize__(
                        )
                        self.transport.write(pls_key_exchange_bytes)
                        self._state = 3
                        self._messages_for_handshake.append(
                            (pls_key_exchange_bytes))
                    else:
                        # pass
                        self.terminate_connection("Status error")
                else:
                    # pass
                    self.terminate_connection("PlsHello error")

            elif isinstance(packet, PlsKeyExchange):
                if packet.NoncePlusOne == self._nonce + 1:
                    self._pre_key_for_other_side = CryptoUtil.RSADecrypt(
                        self._private_key, packet.PreKey)
                    self._messages_for_handshake.append(packet.__serialize__())
                    if self._state == 2:
                        self._pre_key = CertFactory.getPreKey()
                        pls_key_exchange = PlsKeyExchange(
                            PreKey=CryptoUtil.RSAEncrypt(
                                self._pubk_for_other_side, self._pre_key),
                            NoncePlusOne=self._nonce_for_other_side + 1)
                        pls_key_exchange_bytes = pls_key_exchange.__serialize__(
                        )
                        self.transport.write(pls_key_exchange_bytes)
                        self._state = 4
                        self._messages_for_handshake.append(
                            pls_key_exchange_bytes)
                    elif self._state == 3:
                        m = hashlib.sha1()
                        m.update(self._messages_for_handshake[0] +
                                 self._messages_for_handshake[1] +
                                 self._messages_for_handshake[2] +
                                 self._messages_for_handshake[3])
                        self._hash_for_handshake = m.digest()
                        pls_handshake_done = PlsHandshakeDone(
                            ValidationHash=self._hash_for_handshake)
                        self.transport.write(
                            pls_handshake_done.__serialize__())
                        self._state = 5
                    else:
                        # pass
                        self.terminate_connection("Status error")
                else:
                    # pass
                    self.terminate_connection("PlsKeyExchange error")

            elif isinstance(packet, PlsHandshakeDone):
                validation_hash = packet.ValidationHash
                if self._state == 4:
                    m = hashlib.sha1()
                    m.update(self._messages_for_handshake[0] +
                             self._messages_for_handshake[1] +
                             self._messages_for_handshake[2] +
                             self._messages_for_handshake[3])
                    self._hash_for_handshake = m.digest()
                    if self._hash_for_handshake == validation_hash:
                        pls_handshake_done = PlsHandshakeDone(
                            ValidationHash=self._hash_for_handshake)
                        self.transport.write(
                            pls_handshake_done.__serialize__())
                        self._state = 6
                        # ------------ set symmetric variables ------------
                        self.set_symmetric_variables(False)
                        # ------------ connect to higher protocol ------------
                        self.higherProtocol().connection_made(
                            PLSTransport(self.transport, self))
                    else:
                        # pass
                        self.terminate_connection(
                            "PlsHandshakeDone validation error")

                elif self._state == 5:
                    if self._hash_for_handshake == validation_hash:
                        self.set_symmetric_variables(True)
                        self.higherProtocol().connection_made(
                            PLSTransport(self.transport, self))
                        self._state = 6
                    else:
                        # pass
                        self.terminate_connection(
                            "PlsHandshakeDone validation error")
                else:
                    # pass
                    self.terminate_connection("status error")

            elif isinstance(packet, PlsClose):
                print("connection closed by the other side")
                self.transport.close()
            else:
                print('PLSP is waiting for a PLS packet.')