Exemplo n.º 1
0
 def importServerCerts(self):
     rawCerts = getServerCerts()
     self.certs = [
         CipherUtil.getCertFromBytes(c.encode("utf-8")) for c in rawCerts
     ]
     self.publicKey = self.certs[0].public_key()
     self.rootCert = CipherUtil.getCertFromBytes(
         getRootCert().encode("utf-8"))
Exemplo n.º 2
0
    def importKeys(self):
        addr = self.transport.get_extra_info('sockname')[0]
        self.privateKey = serialization.load_pem_private_key(
            str.encode(getPrivateKeyForAddr(addr)),
            password=None,
            backend=default_backend())

        rawCerts = getCertsForAddr(addr)
        self.certs = [
            CipherUtil.getCertFromBytes(c.encode("utf-8")) for c in rawCerts
        ]
        self.publicKey = self.certs[0].public_key()

        self.rootCert = CipherUtil.getCertFromBytes(
            getRootCert().encode("utf-8"))
Exemplo n.º 3
0
 def GetCommonName(cls, certBytes):
     cert = CipherUtil.getCertFromBytes(certBytes)
     commonNameList = cert.subject.get_attributes_for_oid(
         NameOID.COMMON_NAME)
     if len(commonNameList) != 1:
         return None
     commonNameAttr = commonNameList[0]
     return commonNameAttr.value
Exemplo n.º 4
0
	def sendPlsKeyExchange(self,pc):
		#print("************ TIME FOR SERVER TO SEND KEY EXCHANGE PACKET ********************")
		ServerKX = PlsKeyExchange()
		ServerKX.NoncePlusOne = self.NCc + 1
		#print("1")
		self.PKs = (CipherUtil.getCertFromBytes(self.Received_Certificates[0])).public_key()
		#print("1")
		ServerKX.PreKey = self.PKs.encrypt(os.urandom(16),padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()),algorithm=hashes.SHA256(),label=None))
		self.serverprekey = ServerKX.PreKey
		#print("1")		
		skeyexchange = ServerKX.__serialize__()
		self.m.update(skeyexchange)
		self.transport.write(skeyexchange)
Exemplo n.º 5
0
 def sendPlsKeyExchange(self, pc):
     #print("************ TIME FOR CLIENT TO SEND KEY EXCHANGE PACKET ********************")
     ClientKX = PlsKeyExchange()
     ClientKX.NoncePlusOne = pc.Nonce + 1
     self.PKs = (CipherUtil.getCertFromBytes(pc.Certs[0])).public_key()
     ClientKX.PreKey = self.PKs.encrypt(
         os.urandom(16),
         padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()),
                      algorithm=hashes.SHA256(),
                      label=None))
     self.clientprekey = ClientKX.PreKey
     ckeyexchange = ClientKX.__serialize__()
     self.m.update(ckeyexchange)
     self.transport.write(ckeyexchange)
Exemplo n.º 6
0
    def data_received(self, data):
        self.deserializer.update(data)
        for packet in self.deserializer.nextPackets():
            if isinstance(packet, PlsHello):
                self.incoming_cert.append(
                    CipherUtil.getCertFromBytes(packet.Certs[0]))
                self.incoming_cert.append(
                    CipherUtil.getCertFromBytes(packet.Certs[1]))
                self.incoming_cert.append(
                    CipherUtil.getCertFromBytes(packet.Certs[2]))
                print("\nReceived Server Hello. Beginning Validation.")
                if self.validate(self.incoming_cert):
                    self.m.update(packet.__serialize__())
                    print(
                        " Server Certificate Validated. Sending Client Key Exchange!\n"
                    )
                    clientkey = PlsKeyExchange()
                    randomvalue = os.urandom(
                        16)  # Example bytes:- b'1234567887654321'
                    self.pkc = int.from_bytes(randomvalue, byteorder='big')
                    clientkey.NoncePlusOne = packet.Nonce + 1
                    self.ns = packet.Nonce
                    pub_key = self.incoming_cert[0].public_key()
                    encrypted1 = pub_key.encrypt(
                        randomvalue,
                        padding.OAEP(
                            mgf=padding.MGF1(algorithm=hashes.SHA256()),
                            algorithm=hashes.SHA256(),
                            label=None))
                    #print ("Encrypted String is: ",encrypted1)
                    clientkey.PreKey = encrypted1
                    clkey = clientkey.__serialize__()
                    print("Sent the Prekey to Server.")
                    self.m.update(clkey)
                    self.transport.write(clkey)

            if isinstance(packet, PlsKeyExchange):
                print("Received Server Key Exchange.")
                self.m.update(packet.__serialize__())
                myprivatekey = getPrivateKeyForAddr(
                    "20174.1.666.46"
                )  #This hardcoded IP address must the peerAddress
                serverpriv = CipherUtil.getPrivateKeyFromPemBytes(myprivatekey)
                decrypted = serverpriv.decrypt(
                    packet.PreKey,
                    padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()),
                                 algorithm=hashes.SHA256(),
                                 label=None))
                #print("Decrypted Pre-Master Secret: ", decrypted)
                self.pks = int.from_bytes(decrypted, byteorder='big')
                #====================================
                #sending digest
                self.clientdigest = self.m.digest()
                #print("Hash digest is: ", self.clientdigest)
                hdone = PlsHandshakeDone()
                hdone.ValidationHash = self.clientdigest
                hdone_s = hdone.__serialize__()
                print("Sent the PLS Handshake Done to server.")
                self.transport.write(hdone_s)

            if isinstance(packet, PlsHandshakeDone):
                print("\n\nReceived Server Handshake done message.")
                if (self.clientdigest == packet.ValidationHash):
                    print("Digest verification done!")
                    self.key_generator()
                    plstransport = PLSStackingTransport(self, self.transport)
                    higherTransport = StackingTransport(plstransport)
                    self.higherProtocol().connection_made(higherTransport)

            if isinstance(packet, PlsData):
                print(
                    "#######################Recieved Data Packet from PLSServer ############################"
                )
                self.ctr = 0
                if self.mac_verification_engine(packet.Ciphertext, packet.Mac):
                    DecryptedPacket = self.decryption_engine(packet.Ciphertext)
                    self.higherProtocol().data_received(DecryptedPacket)

                    self.ctr = 0

                else:
                    self.ctr += 1

                    if self.ctr != 5:
                        print("Verification Failed. Try Again. Failed {}"
                              ).format(self.ctr)

                    else:
                        print(
                            "Verification failed 5 times. Killing Connection and Sending PlsClose."
                        )
                        # Creating and Sending PlsClose
                        self.ctr = 0
                        Close = PlsClose()
                        #Close.Error = "Closing Connection due to 5 Verification failures. Aggressive Close."
                        serializeClose = Close.__serialize__()
                        self.transport.write(serializeClose)
                        self.transport.close()

            if isinstance(packet, PlsClose):
                print(
                    "#####################Received PlsClose from Server###########################"
                )
                self.transport.close()
Exemplo n.º 7
0
    def validate(self, certificate):

        serverissuer = CipherUtil.getCertIssuer(certificate[0])
        intermediatesubject = CipherUtil.getCertSubject(certificate[1])
        intermediateissuer = CipherUtil.getCertIssuer(certificate[1])

        encodedrootcert = getRootCert()
        rootcert = CipherUtil.getCertFromBytes(encodedrootcert)
        print("Type of RootCert: ", type(rootcert))
        rootsubject = CipherUtil.getCertSubject(rootcert)

        print(" Server PeerAddress is:- ", self.address)

        receivedIDCommonName = self.GetCommonName(certificate[0])
        intermediateCommonName = self.GetCommonName(certificate[1])
        rootCommonName = self.GetCommonName(rootcert)

        if self.peerAddress == receivedIDCommonName:
            splitlist = re.split('(.*)\.(.*)\.(.*)\.(.*)',
                                 receivedIDCommonName)[1:4]
            FirstThreeOctets = '.'.join(splitlist)

            if serverissuer == intermediatesubject and FirstThreeOctets == intermediateCommonName:
                print(
                    "Chain 1 verification succeeded! Going to Check Signature now"
                )
                # checking signature first stage

                signature = certificate[0].signature
                intermediate_pubkey = certificate[1].public_key()
                cert_bytes = certificate[0].tbs_certificate_bytes
                try:
                    intermediate_pubkey.verify(signature, cert_bytes,
                                               padding.PKCS1v15(),
                                               hashes.SHA256())

                    print("Signature check stage 1 successful!")

                    splitlist = re.split('(.*)\.(.*)\.(.*)',
                                         intermediateCommonName)[1:3]
                    FirstTwoOctets = '.'.join(splitlist)

                    if intermediateissuer == rootsubject and FirstTwoOctets == rootCommonName:
                        print(
                            "Chain 2 verification succeeded! Going to check signature now"
                        )
                        # checking signature second stage

                        signature = certificate[1].signature
                        cert_bytes = certificate[1].tbs_certificate_bytes
                        root_pubkey = rootcert.public_key()

                        try:
                            root_pubkey.verify(signature, cert_bytes,
                                               padding.PKCS1v15(),
                                               hashes.SHA256())

                            print("Signature check stage 2 successful!")

                            print("FULLY VALIDATED! AWESOME!")

                            return True

                        except Exception:
                            print("Signature check stage 2 failed")
                            raise

                    else:
                        print(
                            "Chain 2 verification failed! Check the chain please."
                        )

                except Exception:
                    print("Signature check stage 1 failed")
                    raise

            else:
                print("Chain 1 verification failed! Check the chain please.")

        else:
            print(
                "Peer Address and the address received in the certificate is incorrect! Please check the Identity Certificate"
            )
        '''
Exemplo n.º 8
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.')
Exemplo n.º 9
0
    def data_received(self, data):
        self.deserializer.update(data)
        for pkt in self.deserializer.nextPackets():
            if isinstance(pkt, PlsHello) and self.state == self.STATE_SERVER_HELLO:
                # Deserialize certs in packet, attach root cert
                peerCerts = [CipherUtil.getCertFromBytes(c) for c in pkt.Certs]
                if self.verifyCerts(peerCerts):
                    self.dbgPrint("Server: PlsHello received!")
                    self.messages["M1"] = pkt.__serialize__()
                    self.peerPublicKey = peerCerts[0].public_key()
                    self.clientNonce = pkt.Nonce

                    # Make PlsHello and send back
                    self.serverNonce = self.generateNonce()
                    # Serialize certs to pack into PlsHello
                    certBytes = [CipherUtil.serializeCert(c) for c in self.certs]
                    self.dbgPrint("Server: sending PlsHello back to client... Current state: {!r}, nonce Number: {!r}"
                                  .format(self.STATE_DESC[self.state], self.serverNonce))
                    helloPkt = PlsHello.makeHelloPacket(self.serverNonce, certBytes)
                    self.messages["M2"] = helloPkt.__serialize__()
                    self.transport.write(helloPkt.__serialize__())
                    self.state = self.STATE_SERVER_KEY_EXCHANGE
                else:
                    self.handleError("Error: certificate verification failure.")
            elif isinstance(pkt, PlsKeyExchange) and self.state == self.STATE_SERVER_KEY_EXCHANGE:
                if self.serverNonce + 1 == pkt.NoncePlusOne:
                    self.dbgPrint("Server: received PlsKeyExchange packet from client")
                    self.messages["M3"] = pkt.__serialize__()
                    self.clientPreKey = self.privateKey.decrypt(
                        pkt.PreKey,
                        padding.OAEP(
                            mgf=padding.MGF1(algorithm=hashes.SHA1()),
                            algorithm=hashes.SHA1(),
                            label=None
                        )
                    )
                    if len(self.clientPreKey) != self.PRE_KEY_LENGTH_BYTES:
                        self.handleError("Error: Bad client pre-key with length = " + str(len(self.clientPreKey) * 8)
                                         + " bits, wrong RSA decryption?")
                    else:
                        self.dbgPrint("Server: client prekey received: " + self.clientPreKey.hex())

                        # Make PlsKeyExchange and send back
                        self.serverPreKey = self.generatePreKey()
                        self.dbgPrint(
                            "Server: sending plsKeyExchange packet, prekey: {!r}".format(self.serverPreKey.hex()))
                        encryptedPreKey = self.peerPublicKey.encrypt(
                            self.serverPreKey,
                            padding.OAEP(
                                mgf=padding.MGF1(algorithm=hashes.SHA1()),
                                algorithm=hashes.SHA1(),
                                label=None
                            )
                        )
                        plsKeyExchangePkt = PlsKeyExchange.makePlsKeyExchange(encryptedPreKey, self.clientNonce + 1)
                        self.messages["M4"] = plsKeyExchangePkt.__serialize__()
                        self.transport.write(plsKeyExchangePkt.__serialize__())
                        self.state = self.STATE_SERVER_PLS_HANDSHAKE_DONE

                        # Enough info to generate keys and initialize ciphers
                        self.setKeys(self.generateDerivationHash())
                        self.setEngines()
                else:
                    self.handleError("Error: bad nonce in key exchange.")
            elif isinstance(pkt, PlsHandshakeDone) and self.state == self.STATE_SERVER_PLS_HANDSHAKE_DONE:
                if self.verifyValidationHash(pkt.ValidationHash):
                    self.dbgPrint("Server: plsHandshakeDone packet received from client.")
                    self.dbgPrint(
                        "Server: sending plsHandshakeDone to client and notifying upper layer connection_made")
                    hashText = self.generateValidationHash()
                    handshakeDonePkt = PlsHandshakeDone.makePlsHandshakeDone(hashText)
                    self.transport.write(handshakeDonePkt.__serialize__())

                    # Enter transmission
                    self.state = self.STATE_SERVER_TRANSFER
                    higherTransport = PLSTransport(self.transport, self)
                    self.higherProtocol().connection_made(higherTransport)
                else:
                    self.handleError("Error: validation hash verification failure.")
            elif isinstance(pkt, PlsData) and self.state == self.STATE_SERVER_TRANSFER:
                self.dbgPrint("Server: received application data from client, decrypt and notify upper layer")
                if self.verifyPlsData(pkt.Ciphertext, pkt.Mac):
                    self.dbgPrint("Verification succeeded, sending data to upper layer...")
                    self.higherProtocol().data_received(self.decrypt(pkt.Ciphertext))
                else:
                    # self.handleError("Error: data verification failure.")
                    self.dbgPrint("Data MAC verification error, discarded.")
            elif isinstance(pkt, PlsClose):
                self.dbgPrint("PlsClose received, closing...")
                self.transport.close()
            else:
                self.handleError("Error: wrong packet type " + pkt.DEFINITION_IDENTIFIER + ", current state "
                                 + self.STATE_DESC[self.state])
Exemplo n.º 10
0
    def data_received(self, data):
        self.deserializer.update(data)
        for packet in self.deserializer.nextPackets():
            if isinstance(packet, PlsHello):
                self.incoming_cert.append(
                    CipherUtil.getCertFromBytes(str.encode(packet.Certs[0])))
                self.incoming_cert.append(
                    CipherUtil.getCertFromBytes(str.encode(packet.Certs[1])))
                self.incoming_cert.append(
                    CipherUtil.getCertFromBytes(str.encode(packet.Certs[2])))
                print("\nReceived Server Hello. Trying to verify issuer...")
                if self.validate(self.incoming_cert):
                    self.m.update(packet.__serialize__())
                    print(
                        " Server Certificate Validated. Sending Client Key Exchange!\n"
                    )
                    clientkey = PlsKeyExchange()
                    randomvalue = b'1234567887654321'
                    print(type(randomvalue))
                    self.pkc = randomvalue.decode()
                    clientkey.NoncePlusOne = packet.Nonce + 1
                    self.ns = packet.Nonce
                    pub_key = self.incoming_cert[0].public_key()
                    encrypted1 = pub_key.encrypt(
                        randomvalue,
                        padding.OAEP(
                            mgf=padding.MGF1(algorithm=hashes.SHA256()),
                            algorithm=hashes.SHA256(),
                            label=None))
                    print("Encrypted String is: ", encrypted1)
                    clientkey.PreKey = encrypted1
                    clkey = clientkey.__serialize__()
                    print("Sent the Prekey to Server.")
                    self.m.update(clkey)
                    self.transport.write(clkey)

            if isinstance(packet, PlsKeyExchange):
                print("Received Server Key Exchange.")
                self.m.update(packet.__serialize__())
                serverpriv = CipherUtil.loadPrivateKeyFromPemFile(
                    "/root/keys/client/sagar-client.key")
                decrypted = serverpriv.decrypt(
                    packet.PreKey,
                    padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()),
                                 algorithm=hashes.SHA256(),
                                 label=None))
                print("Decrypted Pre-Master Secret: ", decrypted)
                self.pks = decrypted.decode()
                #====================================
                #sending digest
                self.clientdigest = self.m.digest()
                print("Hash digest is: ", self.clientdigest)
                hdone = PlsHandshakeDone()
                hdone.ValidationHash = self.clientdigest
                hdone_s = hdone.__serialize__()
                print("Sent the PLS Handshake Done to server.")
                self.transport.write(hdone_s)

            if isinstance(packet, PlsHandshakeDone):
                print("\n\nReceived Server Handshake done message.")
                if (self.clientdigest == packet.ValidationHash):
                    print("Digest verification done!")
                    self.key_generator()
Exemplo n.º 11
0
    def data_received(self, data):
        self.deserializer.update(data)
        for pkt in self.deserializer.nextPackets():
            if isinstance(
                    pkt, SITHPacket
            ):  # judge if this packet is an instance of RIPPPacket
                if (pkt.Type == "HELLO") and (
                        self.state
                        == self.STATE_SERVER_HELLO):  #receive client hello pkt
                    # Deserialize certs in packet, attach root cert
                    self.peerCerts = [
                        CipherUtil.getCertFromBytes(c) for c in pkt.Certificate
                    ]

                    if self.verifyCerts(self.peerCerts):
                        self.log("Server: SithHello received!")
                        self.messages["M1"] = pkt.__serialize__(
                        )  #turn the client's hello pkt into bytes
                        self.peerPublicKey = self.peerCerts[0].public_key()

                        # Serialize certs to pack into SithHello
                        self.certBytes = [
                            CipherUtil.serializeCert(c) for c in self.certs
                        ]
                        self.log(
                            "Server: sending SithHello back to client... Current state: {!r}, random: {!r}"
                            .format(self.STATE_DESC[self.state], self.random))
                        helloPkt = SITHPacket.makeHelloPacket(
                            self.random, self.certBytes, self.public_key)
                        self.messages["M2"] = helloPkt.__serialize__(
                        )  #turn the server's hello pkt into bytes

                        self.transport.write(
                            helloPkt.__serialize__()
                        )  #send the server hello pkt and enter 'server_key_exchange' stage
                        self.state = self.STATE_SERVER_KEY_EXCHANGE

                        #key derivation
                        self.client_public_key = x25519.X25519PublicKey.from_public_bytes(
                            pkt.PublicValue
                        )  #load client's public key from bytes
                        shared_secret = self.private_key.exchange(
                            self.client_public_key)
                        hasher = hashes.Hash(hashes.SHA256(),
                                             backend=default_backend())
                        hasher.update(self.messages["M1"] +
                                      self.messages["M2"])
                        self.hash_msg = hasher.finalize()  #get the hash result
                        derived_key = HKDF(
                            algorithm=hashes.SHA256(),
                            length=32,
                            salt=None,
                            info=self.hash_msg,
                            backend=default_backend()).derive(
                                shared_secret)  #get the derived key

                        self.iv_dec = derived_key[:12]
                        self.iv_enc = derived_key[12:24]

                        self.server_write = derived_key[:16]
                        self.server_read = derived_key[16:]

                        self.setEngines()

                        self.state = self.STATE_SERVER_SITH_HANDSHAKE_DONE

                    else:
                        self.log("Error: certificate verification failure.")
                        self.sendSithClose(1)

                elif (pkt.Type == "FINISH") and (
                        self.state == self.STATE_SERVER_SITH_HANDSHAKE_DONE):

                    self.log(
                        "Server: received handshake_finish packet from client")
                    #verify client's signature
                    client_public_key = self.peerCerts[0].public_key()
                    client_signature = pkt.Signature

                    verify_result = self.verify_signature(
                        client_public_key, client_signature, self.hash_msg)

                    if not verify_result:
                        self.log("Server: wrong signature of client!")
                        self.log("Server is closing...")
                        self.sendSithClose(1)
                    else:

                        # generate handshake finish pkt
                        self.cert_private_key = getServerPrivateKey(
                        )  # read private of server's certificate
                        finishPkt = SITHPacket.makeFinishPacket(
                            self.messages["M1"], self.messages["M2"],
                            self.cert_private_key)
                        self.transport.write(
                            finishPkt.__serialize__()
                        )  # send the server hello pkt and enter 'server_key_exchange' stage

                        #enter the data transmission state
                        self.state = self.STATE_SERVER_TRANSFER
                        higherTransport = SITHTransport(self.transport, self)
                        self.higherProtocol().connection_made(higherTransport)

                        # Enter transmission
                        higherTransport = SITHTransport(self.transport, self)
                        self.higherProtocol().connection_made(higherTransport)

                elif (pkt.Type
                      == "DATA") and self.state == self.STATE_SERVER_TRANSFER:
                    self.log(
                        "Server: received application data from client, decrypt and notify upper layer"
                    )
                    self.log(
                        "Verification succeeded, sending data to upper layer..."
                    )
                    self.higherProtocol().data_received(
                        self.decrypt(self.iv_dec, pkt.Ciphertext, None))
                elif (pkt.Type == "CLOSE"):
                    self.transport.close()

                else:
                    self.log("Error: wrong packet type " +
                             pkt.DEFINITION_IDENTIFIER + ", current state " +
                             self.STATE_DESC[self.state])
                    self.sendSithClose(1)

            else:
                self.log("Wrong packet class type: {!r}".format(str(
                    type(pkt))))
                self.sendSithClose(1)
Exemplo n.º 12
0
    def data_received(self, data):
        self.deserializer.update(data)
        for packet in self.deserializer.nextPackets():
            if isinstance(packet, PlsHello):
                self.incoming_cert.append(
                    CipherUtil.getCertFromBytes(str.encode(packet.Certs[0])))
                self.incoming_cert.append(
                    CipherUtil.getCertFromBytes(str.encode(packet.Certs[1])))
                self.incoming_cert.append(
                    CipherUtil.getCertFromBytes(str.encode(packet.Certs[2])))
                print("\nReceived Server Hello. Trying to verify issuer...")
                if self.validate(self.incoming_cert):
                    self.m.update(packet.__serialize__())
                    print(
                        " Server Certificate Validated. Sending Client Key Exchange!\n"
                    )
                    clientkey = PlsKeyExchange()
                    randomvalue = b'1234567887654321'
                    print(type(randomvalue))
                    self.pkc = randomvalue.decode()
                    clientkey.NoncePlusOne = packet.Nonce + 1
                    self.ns = packet.Nonce
                    pub_key = self.incoming_cert[0].public_key()
                    encrypted1 = pub_key.encrypt(
                        randomvalue,
                        padding.OAEP(
                            mgf=padding.MGF1(algorithm=hashes.SHA256()),
                            algorithm=hashes.SHA256(),
                            label=None))
                    print("Encrypted String is: ", encrypted1)
                    clientkey.PreKey = encrypted1
                    clkey = clientkey.__serialize__()
                    print("Sent the Prekey to Server.")
                    self.m.update(clkey)
                    self.transport.write(clkey)

            if isinstance(packet, PlsKeyExchange):
                print("Received Server Key Exchange.")
                self.m.update(packet.__serialize__())
                serverpriv = CipherUtil.loadPrivateKeyFromPemFile(
                    "/home/prashanth/netsec/prashanth-client.key")
                decrypted = serverpriv.decrypt(
                    packet.PreKey,
                    padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()),
                                 algorithm=hashes.SHA256(),
                                 label=None))
                print("Decrypted Pre-Master Secret: ", decrypted)
                self.pks = decrypted.decode()
                #====================================
                #sending digest
                self.clientdigest = self.m.digest()
                print("Hash digest is: ", self.clientdigest)
                hdone = PlsHandshakeDone()
                hdone.ValidationHash = self.clientdigest
                hdone_s = hdone.__serialize__()
                print("Sent the PLS Handshake Done to server.")
                self.transport.write(hdone_s)

            if isinstance(packet, PlsHandshakeDone):
                print("\n\nReceived Server Handshake done message.")
                if (self.clientdigest == packet.ValidationHash):
                    print("Digest verification done!")
                    self.key_generator()

            if isinstance(packet, PlsData):
                print(
                    "=====================Recieved Data Packet from PLSServer ======================"
                )
                self.ctr = 0
                if self.mac_verification_engine(packet.Ciphertext, packet.Mac):
                    print(
                        "=====================Pls Client Verification Successful. Decrypting============="
                    )
                    DecryptedPacket = self.decryption_engine(packet.Ciphertext)
                    print(
                        "=======================Decryption DONE! =======Sending to HigherLayer==========="
                    )
                    self.higherProtocol().data_received(DecryptedPacket)

                    self.ctr = 0

                else:
                    self.ctr += 1

                    if self.ctr != 5:
                        print("Verification Failed. Try Again. Failed {}"
                              ).format(self.ctr)

                    else:
                        print(
                            "Verification failed 5 times. Killing Connection and Sending PlsClose."
                        )
                        #Creating and Sending PlsClose
                        self.ctr = 0
                        Close = PlsClose()
                        Close.Error = "Closing Connection due to 5 Verification failures. Aggressive Close."
                        serializeClose = Close.__serialize__()
                        self.transport.write(serializeClose)
                        self.transport.close()

            if isinstance(packet, PlsClose):
                print(
                    "==================Received PlsClose from Server======================== "
                )
                self.connection_lost(packet.Error)
                self.transport.close()
Exemplo n.º 13
0
    def data_received(self, data):
        print(
            "####################SSL layer data received called!#####################"
        )
        self.deserializer.update(data)
        for packet in self.deserializer.nextPackets():
            if isinstance(packet, PlsHello):
                self.incoming_cert.append(
                    CipherUtil.getCertFromBytes(packet.Certs[0]))
                self.incoming_cert.append(
                    CipherUtil.getCertFromBytes(packet.Certs[1]))
                self.incoming_cert.append(
                    CipherUtil.getCertFromBytes(packet.Certs[2]))
                print("\nReceived Client Hello packet. Beginning Validation.")
                if self.validate(self.incoming_cert):
                    self.nc = packet.Nonce
                    self.m = hashlib.sha1()
                    self.m.update(packet.__serialize__())
                    print("Certificate Validated. Sending Server hello!\n")
                    self.clientnonce = packet.Nonce
                    serverhello = PlsHello()
                    serverhello.Nonce = int.from_bytes(
                        os.urandom(8), byteorder='big')  #12345678
                    self.ns = serverhello.Nonce
                    idcert = getCertsForAddr(self.address)
                    pubkey = getCertsForAddr(self.splitaddr)
                    root = getRootCert()
                    serverhello.Certs = []
                    serverhello.Certs.append(idcert)
                    serverhello.Certs.append(pubkey)
                    serverhello.Certs.append(root)
                    srvhello = serverhello.__serialize__()
                    print("Sent Server Hello!\n")
                    self.m.update(srvhello)
                    self.transport.write(srvhello)

            if isinstance(packet, PlsKeyExchange):
                print("Received Client Key Exchange. Server Server Keys\n\n")
                self.m.update(packet.__serialize__())
                myprivatekey = getPrivateKeyForAddr(self.address)
                serverpriv = CipherUtil.getPrivateKeyFromPemBytes(myprivatekey)
                decrypted = serverpriv.decrypt(
                    packet.PreKey,
                    padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()),
                                 algorithm=hashes.SHA256(),
                                 label=None))
                #print("Decrypted Pre-Master Secret: ", decrypted)
                self.pkc = int.from_bytes(decrypted, byteorder='big')
                #====================================
                #Creating Server Pre-Master
                serverkey = PlsKeyExchange()
                randomvalue = os.urandom(16)  #b'1234567887654321'
                self.pks = int.from_bytes(randomvalue, byteorder='big')
                serverkey.NoncePlusOne = self.clientnonce + 1
                pub_key = self.incoming_cert[0].public_key()
                encrypted = pub_key.encrypt(
                    randomvalue,
                    padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()),
                                 algorithm=hashes.SHA256(),
                                 label=None))
                #print("Encrypted String is: ", encrypted)
                serverkey.PreKey = encrypted
                skey = serverkey.__serialize__()
                print("Sent the Prekey to Client.\n\n")
                self.m.update(skey)
                self.transport.write(skey)

            if isinstance(packet, PlsHandshakeDone):
                print("Received Client Handshake done message.")
                clientdigest = packet.ValidationHash
                serverdigest = self.m.digest()
                #print("Hash digest is: ", serverdigest)
                hdone = PlsHandshakeDone()
                hdone.ValidationHash = serverdigest
                if (serverdigest == clientdigest):
                    print("Digest verification done!")
                    # calling higher connection made since we have received the ACK
                    self.key_generator()
                    plstransport = PLSStackingTransport(self, self.transport)
                    higherTransport = StackingTransport(plstransport)
                    self.higherProtocol().connection_made(higherTransport)
                hdone_s = hdone.__serialize__()
                self.transport.write(hdone_s)

            if isinstance(packet, PlsData):
                print(
                    "##################Recieved Data Packet from PLSClient###########################"
                )
                self.ctr = 0
                if self.mac_verification_engine(packet.Ciphertext, packet.Mac):
                    DecryptedPacket = self.decryption_engine(packet.Ciphertext)
                    self.higherProtocol().data_received(DecryptedPacket)

                    self.ctr = 0

                else:
                    self.ctr += 1

                    if self.ctr != 5:
                        print("Verification Failed. Try Again. Failed {}"
                              ).format(self.ctr)

                    else:
                        print(
                            "Verification failed 5 times. Killing Connection and Sending PlsClose."
                        )
                        self.ctr = 0
                        #Creating and Sending PlsClose
                        Close = PlsClose()
                        #Close.Error = "Closing Connection due to 5 Verification failures. Aggrresive Close"
                        serializeClose = Close.__serialize__()
                        self.transport.write(serializeClose)
                        self.transport.close()

            if isinstance(packet, PlsClose):
                print(
                    "######################Received PlsClose from Client######################### "
                )
                #self.connection_lost(self)
                self.transport.close()
Exemplo n.º 14
0
    def data_received(self, data):
        self.deserializer.update(data)
        for pkt in self.deserializer.nextPackets():
            if isinstance(
                    pkt, SITHPacket
            ):  #judge if this packet is an instance of RIPPPacket

                if (pkt.Type
                        == "HELLO") and (self.state == self.STATE_CLIENT_HELLO
                                         ):  #receive server's hello pkt
                    # Deserialize certs in packet, attach root cert
                    self.peerCerts = [
                        CipherUtil.getCertFromBytes(c) for c in pkt.Certificate
                    ]  #deserialize certificate from byte format
                    if self.verifyCerts(self.peerCerts):
                        self.dbgPrint(
                            "Client: received SithHello packet from server, current state: {!r}"
                            .format(self.STATE_DESC[self.state]))
                        self.messages["M2"] = pkt.__serialize__()
                        self.state = self.STATE_CLIENT_KEY_EXCHANGE  #after receiving server's hello pkt, enter 'client_key_exchange' stage

                        #key derivation
                        self.server_public_key = x25519.X25519PublicKey.from_public_bytes(
                            pkt.PublicValue
                        )  #load server's public key from bytes
                        shared_secret = self.private_key.exchange(
                            self.server_public_key)
                        hasher = hashes.Hash(hashes.SHA256(),
                                             backend=default_backend())
                        hasher.update(self.messages["M1"] +
                                      self.messages["M2"])
                        self.hash_msg = hasher.finalize()  #get the hash result
                        derived_key = HKDF(
                            algorithm=hashes.SHA256(),
                            length=32,
                            salt=None,
                            info=self.hash_msg,
                            backend=default_backend()).derive(
                                shared_secret)  #get the derived key

                        self.iv_enc = derived_key[:12]
                        self.iv_dec = derived_key[12:24]

                        self.client_read = derived_key[:16]
                        self.client_write = derived_key[16:]

                        self.setEngines()

                        self.state = self.STATE_CLIENT_SITH_HANDSHAKE_DONE

                        #generate handshake finish pkt
                        self.cert_private_key = getClientPrivateKey()
                        finishPkt = SITHPacket.makeFinishPacket(
                            self.messages["M1"], self.messages["M2"],
                            self.cert_private_key)
                        self.transport.write(
                            finishPkt.__serialize__()
                        )  #send the server hello pkt and enter 'server_key_exchange' state
                        #send the client finish pkt to server and enter handshake done state

                    else:
                        self.dbgPrint(
                            "Error: certificate verification failure.")
                        self.state = self.STATE_CLIENT_CLOSED
                        self.sendSithClose(1)

                elif (
                        pkt.Type == "FINISH"
                ) and self.state == self.STATE_CLIENT_SITH_HANDSHAKE_DONE:
                    self.dbgPrint(
                        "Client: received handshake_finish packet from server")

                    #verify server's signature
                    server_public_key = self.peerCerts[0].public_key()
                    server_signature = pkt.Signature

                    verify_result = self.verify_signature(
                        server_public_key, server_signature, self.hash_msg)

                    if not verify_result:
                        self.dbgPrint("Client: wrong signature of client!")
                        self.dbgPrint("Client is closing...")
                        self.state = self.STATE_CLIENT_CLOSED
                        self.sendSithClose(1)
                    else:
                        #enter data transmission state
                        self.state = self.STATE_CLIENT_TRANSFER

                        higherTransport = SITHTransport(self.transport, self)
                        self.higherProtocol().connection_made(higherTransport)

                elif (pkt.Type
                      == "DATA") and self.state == self.STATE_CLIENT_TRANSFER:
                    self.dbgPrint(
                        "Client: received application data from server")

                    self.higherProtocol().data_received(
                        self.decrypt(self.iv_dec, pkt.Ciphertext, None))
                elif (pkt.Type == "CLOSE"):
                    self.state = self.STATE_CLIENT_CLOSED
                    self.transport.close()

                else:
                    self.dbgPrint("Error: wrong packet type " +
                                  pkt.DEFINITION_IDENTIFIER +
                                  ", current state " +
                                  self.STATE_DESC[self.state])
                    self.sendSithClose(1)

            else:
                self.dbgPrint("Wrong packet class type: {!r}".format(
                    str(type(pkt))))
                self.sendSithClose(1)
Exemplo n.º 15
0
    def data_received(self, data):
        print("###SSL layer data received called!###")
        self.deserializer.update(data)
        for packet in self.deserializer.nextPackets():
            #print(packet.Certs[0], packet.Certs[1], packet.Certs[2])
            if isinstance(packet, PlsHello):
                self.incoming_cert.append(
                    CipherUtil.getCertFromBytes(str.encode(packet.Certs[0])))
                self.incoming_cert.append(
                    CipherUtil.getCertFromBytes(str.encode(packet.Certs[1])))
                self.incoming_cert.append(
                    CipherUtil.getCertFromBytes(str.encode(packet.Certs[2])))
                print(
                    "\nReceived Client Hello packet. Trying to verify issuer..."
                )
                #print(packet.Certs)
                if self.validate(self.incoming_cert):
                    self.nc = packet.Nonce
                    self.m = hashlib.sha1()
                    self.m.update(packet.__serialize__())
                    print("Certificate Validated. Sending Server hello!\n")
                    self.clientnonce = packet.Nonce
                    serverhello = PlsHello()
                    serverhello.Nonce = 12345678
                    self.ns = serverhello.Nonce
                    idcert = getServerIDCertsForAddr()
                    pubkey = getCertsForAddr()
                    root = getRootCertsForAddr()
                    serverhello.Certs = []
                    serverhello.Certs.append(idcert)
                    serverhello.Certs.append(pubkey)
                    serverhello.Certs.append(root)
                    srvhello = serverhello.__serialize__()
                    print("Sent Server Hello!\n")
                    self.m.update(srvhello)
                    self.transport.write(srvhello)

            if isinstance(packet, PlsKeyExchange):
                print("Received Client Key Exchange. Server Server Keys\n\n")
                self.m.update(packet.__serialize__())
                serverpriv = CipherUtil.loadPrivateKeyFromPemFile(
                    "/home/prashanth/netsec/prashanth.key")
                decrypted = serverpriv.decrypt(
                    packet.PreKey,
                    padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()),
                                 algorithm=hashes.SHA256(),
                                 label=None))
                print("Decrypted Pre-Master Secret: ", decrypted)
                self.pkc = decrypted.decode()
                #====================================
                #Creating Server Pre-Master
                serverkey = PlsKeyExchange()
                randomvalue = b'1234567887654321'
                self.pks = randomvalue.decode()
                serverkey.NoncePlusOne = self.clientnonce + 1
                pub_key = self.incoming_cert[0].public_key()
                encrypted1 = pub_key.encrypt(
                    randomvalue,
                    padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()),
                                 algorithm=hashes.SHA256(),
                                 label=None))
                print("Encrypted String is: ", encrypted1)
                serverkey.PreKey = encrypted1
                skey = serverkey.__serialize__()
                print("Sent the Prekey to Client.\n\n")
                self.m.update(skey)
                self.transport.write(skey)

            if isinstance(packet, PlsHandshakeDone):
                print("Received Client Handshake done message.")
                clientdigest = packet.ValidationHash
                serverdigest = self.m.digest()
                print("Hash digest is: ", serverdigest)
                hdone = PlsHandshakeDone()
                hdone.ValidationHash = serverdigest
                if (serverdigest == clientdigest):
                    print("Digest verification done!")
                    self.key_generator()
                hdone_s = hdone.__serialize__()
                self.transport.write(hdone_s)

            if isinstance(packet, PlsData):
                print(
                    "=====================Recieved Data Packet from PLSClient======================"
                )
                self.ctr = 0
                if self.mac_verification_engine(packet.Ciphertext, packet.Mac):
                    print(
                        "=====================Pls Client Verification Successful. Decrypting============="
                    )
                    DecryptedPacket = self.decryption_engine(packet.Ciphertext)
                    print(
                        "=======================Decryption DONE! =======Sending to HigherLayer==========="
                    )
                    self.higherProtocol().data_received(DecryptedPacket)

                    self.ctr = 0

                else:
                    self.ctr += 1

                    if self.ctr != 5:
                        print("Verification Failed. Try Again. Failed {}"
                              ).format(self.ctr)

                    else:
                        print(
                            "Verification failed 5 times. Killing Connection and Sending PlsClose."
                        )
                        self.ctr = 0
                        # Creating and Sending PlsClose
                        Close = PlsClose()
                        Close.Error = "Closing Connection due to 5 Verification failures. Aggrresive Close"
                        serializeClose = Close.__serialize__()
                        self.transport.write(serializeClose)
                        self.transport.close()

            if isinstance(packet, PlsClose):
                print(
                    "==================Received PlsClose from Client======================== "
                )
                self.connection_lost(packet.Error)
                self.transport.close()
Exemplo n.º 16
0
    def data_received(self, data):
        print("###SSL layer data received called!###")
        self.deserializer.update(data)
        for packet in self.deserializer.nextPackets():
            #print(packet.Certs[0], packet.Certs[1], packet.Certs[2])
            if isinstance(packet, PlsHello):
                self.incoming_cert.append(CipherUtil.getCertFromBytes(str.encode(packet.Certs[0])))
                self.incoming_cert.append(CipherUtil.getCertFromBytes(str.encode(packet.Certs[1])))
                self.incoming_cert.append(CipherUtil.getCertFromBytes(str.encode(packet.Certs[2])))
                print("\nReceived Client Hello packet. Trying to verify issuer...")
                #print(packet.Certs)
                if self.validate(self.incoming_cert):
                    self.nc = packet.Nonce
                    self.m = hashlib.sha1()
                    self.m.update(packet.__serialize__())
                    print("Certificate Validated. Sending Server hello!\n")
                    self.clientnonce = packet.Nonce
                    serverhello = PlsHello()
                    serverhello.Nonce = 12345678
                    self.ns = serverhello.Nonce
                    idcert = getIDCertsForAddr()
                    pubkey = getCertsForAddr()
                    root = getRootCertsForAddr()
                    serverhello.Certs = []
                    serverhello.Certs.append(idcert)
                    serverhello.Certs.append(pubkey)
                    serverhello.Certs.append(root)
                    srvhello = serverhello.__serialize__()
                    print("Sent Server Hello!\n")
                    self.m.update(srvhello)
                    self.transport.write(srvhello)

            if isinstance(packet, PlsKeyExchange):
                print("Received Client Key Exchange. Server Server Keys\n\n")
                self.m.update(packet.__serialize__())
                serverpriv = CipherUtil.loadPrivateKeyFromPemFile("/root/keys/server/sagar-server.key")
                decrypted = serverpriv.decrypt(packet.PreKey, padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()),algorithm=hashes.SHA256(), label=None))
                print("Decrypted Pre-Master Secret: ", decrypted)
                self.pkc = decrypted.decode()
                #====================================
                #Creating Server Pre-Master
                serverkey = PlsKeyExchange()
                randomvalue = b'1234567887654321'
                self.pks = randomvalue.decode()
                serverkey.NoncePlusOne = self.clientnonce + 1
                pub_key = self.incoming_cert[0].public_key()
                encrypted1 = pub_key.encrypt(randomvalue, padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()),algorithm=hashes.SHA256(), label=None))
                print("Encrypted String is: ", encrypted1)
                serverkey.PreKey = encrypted1
                skey = serverkey.__serialize__()
                print("Sent the Prekey to Client.\n\n")
                self.m.update(skey)
                self.transport.write(skey)

            if isinstance(packet, PlsHandshakeDone):
                print("Received Client Handshake done message.")
                clientdigest = packet.ValidationHash
                serverdigest = self.m.digest()
                print("Hash digest is: ", serverdigest)
                hdone = PlsHandshakeDone()
                hdone.ValidationHash = serverdigest
                if (serverdigest == clientdigest):
                    print("Digest verification done!")
                    self.key_generator()
                hdone_s = hdone.__serialize__()
                self.transport.write(hdone_s)