Ejemplo n.º 1
0
    def verifySignature(signature, signedBlob, publicKeyDer):
        """
        Check the type of signature and use the publicKeyDer to verify the
        signedBlob using the appropriate signature algorithm.

        :param Signature signature: An object of a subclass of Signature, e.g.
          Sha256WithRsaSignature.
        :param SignedBlob signedBlob: the SignedBlob with the signed portion to
          verify.
        :param Blob publicKeyDer: The DER-encoded public key used to verify the
          signature. This is ignored if the signature type does not require a
          public key.
        :return: True if the signature verifies, False if not.
        :rtype: bool
        :raises: SecurityException if the signature type is not recognized or if
          publicKeyDer can't be decoded.
        """
        if (isinstance(signature, Sha256WithRsaSignature)
                or isinstance(signature, Sha256WithEcdsaSignature)):
            if publicKeyDer.isNull():
                return False
            return VerificationHelpers.verifySignature(
                signedBlob.toSignedBytes(), signature.getSignature(),
                PublicKey(publicKeyDer), DigestAlgorithm.SHA256)
        elif isinstance(signature, DigestSha256Signature):
            return VerificationHelpers.verifyDigest(signedBlob.toSignedBytes(),
                                                    signature.getSignature(),
                                                    DigestAlgorithm.SHA256)
        else:
            raise SecurityException(
                "PolicyManager.verify: Signature type is unknown")
Ejemplo n.º 2
0
    def verifySignature(signature, signedBlob, publicKeyDer):
        """
        Check the type of signature and use the publicKeyDer to verify the
        signedBlob using the appropriate signature algorithm.

        :param Signature signature: An object of a subclass of Signature, e.g.
          Sha256WithRsaSignature.
        :param SignedBlob signedBlob: the SignedBlob with the signed portion to
          verify.
        :param Blob publicKeyDer: The DER-encoded public key used to verify the
          signature. This is ignored if the signature type does not require a
          public key.
        :return: True if the signature verifies, False if not.
        :rtype: bool
        :raises: SecurityException if the signature type is not recognized or if
          publicKeyDer can't be decoded.
        """
        if (isinstance(signature, Sha256WithRsaSignature) or
            isinstance(signature, Sha256WithEcdsaSignature)):
            if publicKeyDer.isNull():
                return False
            return VerificationHelpers.verifySignature(
              signedBlob.toSignedBytes(), signature.getSignature(),
              PublicKey(publicKeyDer), DigestAlgorithm.SHA256)
        elif isinstance(signature, DigestSha256Signature):
            return VerificationHelpers.verifyDigest(
              signedBlob.toSignedBytes(), signature.getSignature(),
              DigestAlgorithm.SHA256)
        else:
            raise SecurityException(
              "PolicyManager.verify: Signature type is unknown")
Ejemplo n.º 3
0
    def _verifyOriginalPacket(self, trustedCertificate):
        """
        Verify the signature of the original packet. This is only called by the
        Validator class.

        :param CertificateV2 trustedCertificate: The certificate that signs the
          original packet.
        """
        if VerificationHelpers.verifyInterestSignature(self._interest,
                                                       trustedCertificate):
            logging.getLogger(__name__).info("OK signature for interest `" +
                                             self._interest.getName().toUri() +
                                             "`")
            for i in range(len(self._successCallbacks)):
                try:
                    self._successCallbacks[i](self._interest)
                except:
                    logging.exception("Error in successCallback")

            self.setOutcome(True)
        else:
            self.fail(
                ValidationError(
                    ValidationError.INVALID_SIGNATURE,
                    "Invalid signature of interest `" +
                    self._interest.getName().toUri() + "`"))
Ejemplo n.º 4
0
    def onProbeData(self, interest, data):
        """ Content:
          {
              "email": "*****@*****.**",
              "UID": "",
              "name: "\/ndn\/edu\/memphis\/agawande\/6046888920342781294"
          }
          1) Verify signature
          2) Extract name component from the json to use as identity
        """
        if not VerificationHelpers.verifyDataSignature(data, self.anchor):
            print("Cannot verify signature from: {}".format(self.caPrefix))
        else:
            print("Successfully verified data with hard-coded certificate")

        try:
            self.identityName = Name(
                json.loads(data.getContent().__str__())['name'])
            if self.identityName == "":
                print("Name received from server is empty")
                sys.exit(0)
        except Exception as e:
            print(e)

        print("Got namespace {} from server".format(self.identityName))
        self.generateKeyAndSendNewInterest(data)
Ejemplo n.º 5
0
    def test_generate_key(self):
        for dataSet in self.keyTestData:
            key = TpmPrivateKey.generatePrivateKey(dataSet.keyParams)
            publicKeyBits = key.derivePublicKey()
            publicKey = PublicKey(publicKeyBits)

            data = Blob([0x01, 0x02, 0x03, 0x04])

            # Sign and verify.
            signature = key.sign(data.toBytes(), DigestAlgorithm.SHA256)

            result = VerificationHelpers.verifySignature(
                data, signature, publicKey)
            self.assertTrue(result)

            # Check that another generated private key is different.
            key2 = TpmPrivateKey.generatePrivateKey(dataSet.keyParams)
            self.assertTrue(not key.toPkcs8().equals(key2.toPkcs8()))
Ejemplo n.º 6
0
    def test_generate_key(self):
        for dataSet in self.keyTestData:
            key = TpmPrivateKey.generatePrivateKey(dataSet.keyParams)
            publicKeyBits = key.derivePublicKey()
            publicKey = PublicKey(publicKeyBits)

            data = Blob([0x01, 0x02, 0x03, 0x04])

            # Sign and verify.
            signature = key.sign(data.toBytes(), DigestAlgorithm.SHA256)

            result = VerificationHelpers.verifySignature(
              data, signature, publicKey)
            self.assertTrue(result)

            # Check that another generated private key is different.
            key2 = TpmPrivateKey.generatePrivateKey(dataSet.keyParams)
            self.assertTrue(not key.toPkcs8().equals(key2.toPkcs8()))
Ejemplo n.º 7
0
    def test_rsa_signing(self):
        for tpm in self.backEndList:
            # Create an RSA key.
            identityName = Name("/Test/KeyName")

            key = tpm.createKey(identityName, RsaKeyParams())
            keyName = key.getKeyName()

            content = Blob([0x01, 0x02, 0x03, 0x04])
            signature = key.sign(DigestAlgorithm.SHA256, content.toBytes())

            publicKey = key.derivePublicKey()

            result = VerificationHelpers.verifySignature(
              content, signature, publicKey)
            self.assertEquals(True, result)

            tpm.deleteKey(keyName)
            self.assertEquals(False, tpm.hasKey(keyName))
Ejemplo n.º 8
0
    def test_rsa_signing(self):
        for tpm in self.backEndList:
            # Create an RSA key.
            identityName = Name("/Test/KeyName")

            key = tpm.createKey(identityName, RsaKeyParams())
            keyName = key.getKeyName()

            content = Blob([0x01, 0x02, 0x03, 0x04])
            signature = key.sign(DigestAlgorithm.SHA256, content.toBytes())

            publicKey = key.derivePublicKey()

            result = VerificationHelpers.verifySignature(
              content, signature, publicKey)
            self.assertEqual(True, result)

            tpm.deleteKey(keyName)
            self.assertEqual(False, tpm.hasKey(keyName))
Ejemplo n.º 9
0
    def _verifyOriginalPacket(self, trustedCertificate):
        """
        Verify the signature of the original packet. This is only called by the
        Validator class.

        :param CertificateV2 trustedCertificate: The certificate that signs the
          original packet.
        """
        if VerificationHelpers.verifyDataSignature(self._data, trustedCertificate):
            logging.getLogger(__name__).info("OK signature for data `" +
              self._data.getName().toUri() + "`")
            try:
                self._successCallback(self._data)
            except:
                logging.exception("Error in successCallback")

            self.setOutcome(True)
        else:
          self.fail(ValidationError(ValidationError.INVALID_SIGNATURE,
            "Invalid signature of data `" + self._data.getName().toUri() + "`"))
Ejemplo n.º 10
0
    def _verifyCertificateChain(self, trustedCertificate):
        """
        Verify signatures of certificates in the certificate chain. On return,
        the certificate chain contains a list of certificates successfully
        verified by trustedCertificate.
        When the certificate chain cannot be verified, this method will call
        fail() with the INVALID_SIGNATURE error code and the appropriate message.
        This is only called by the Validator class.

        :return: The certificate to validate the original data packet, either
          the last entry in the certificate chain or trustedCertificate if the
          certificate chain is empty. However, return None if the signature of
          at least one certificate in the chain is invalid, in which case all
          unverified certificates have been removed from the certificate chain.
        :rtype: CertificateV2
        """
        validatedCertificate = trustedCertificate
        for i in range(len(self._certificateChain)):
            certificateToValidate = self._certificateChain[i]

            if not VerificationHelpers.verifyDataSignature(
                    certificateToValidate, validatedCertificate):
                self.fail(
                    ValidationError(
                        ValidationError.INVALID_SIGNATURE,
                        "Invalid signature of certificate `" +
                        certificateToValidate.getName().toUri() + "`"))
                # Remove this and remaining certificates in the chain.
                while len(self._certificateChain) > i:
                    self._certificateChain.pop(i)

                return None
            else:
                logging.getLogger(__name__).info(
                    "OK signature for certificate `" +
                    certificateToValidate.getName().toUri() + "`")
                validatedCertificate = certificateToValidate

        return validatedCertificate
Ejemplo n.º 11
0
    def _verifyCertificateChain(self, trustedCertificate):
        """
        Verify signatures of certificates in the certificate chain. On return,
        the certificate chain contains a list of certificates successfully
        verified by trustedCertificate.
        When the certificate chain cannot be verified, this method will call
        fail() with the INVALID_SIGNATURE error code and the appropriate message.
        This is only called by the Validator class.

        :return: The certificate to validate the original data packet, either
          the last entry in the certificate chain or trustedCertificate if the
          certificate chain is empty. However, return None if the signature of
          at least one certificate in the chain is invalid, in which case all
          unverified certificates have been removed from the certificate chain.
        :rtype: CertificateV2
        """
        validatedCertificate = trustedCertificate
        for i in range(len(self._certificateChain)):
            certificateToValidate = self._certificateChain[i]

            if not VerificationHelpers.verifyDataSignature(
                  certificateToValidate, validatedCertificate):
                self.fail(ValidationError(ValidationError.INVALID_SIGNATURE,
                  "Invalid signature of certificate `" +
                  certificateToValidate.getName().toUri() + "`"))
                # Remove this and remaining certificates in the chain.
                while len(self._certificateChain) > i:
                    self._certificateChain.pop(i)

                return None
            else:
                logging.getLogger(__name__).info(
                  "OK signature for certificate `" +
                  certificateToValidate.getName().toUri() + "`")
                validatedCertificate = certificateToValidate

        return validatedCertificate
Ejemplo n.º 12
0
    def onNewData(self, interest, data):
        """
        !! Again \n in public key??
        Got data:  {
            "ecdh-pub": "Aqxofe3QdsAfgbtS8TMxv31oudNKoSV307ci5gNXm88h\n",
            "salt": "12935684137560555161",
            "request-id": "14275252044236690531",
            "status": "0",
            "challenges": [
                {
                    "challenge-id": "Email"
                }
            ]
        }
        1. Verify data
        2. Derive shared secret
        """
        content = data.getContent()
        print("Got data: ", content)
        if not VerificationHelpers.verifyDataSignature(data, self.anchor):
            print("Cannot verify signature from: {}".format(self.caPrefix))
        else:
            print("Successfully verified data with hard-coded certificate")

        contentJson = json.loads(content.__str__())
        peerKeyBase64 = contentJson['ecdh-pub']
        self.status = contentJson['status']
        self.requestId = contentJson['request-id']
        self.challenges = contentJson['challenges']

        print(peerKeyBase64)

        serverPubKey = ec.EllipticCurvePublicKey.from_encoded_point(
            ec.SECP256R1(), b64decode(peerKeyBase64))

        shared_key = self.ecdh.private_key.exchange(ec.ECDH(), serverPubKey)
        derived_key = HKDF(algorithm=hashes.SHA256(),
                           length=32,
                           salt=contentJson['salt'].encode(),
                           info=b'handshake data',
                           backend=default_backend()).derive(shared_key)

        self.ecdh.derived_key = derived_key
        print(shared_key)
        for t in shared_key:
            print(t)

        challengeInterestName = Name(
            self.caPrefix).append("CA").append("_CHALLENGE").append(
                self.requestId)
        challengeInterest = Interest(challengeInterestName)
        challengeInterest.setMustBeFresh(True)
        challengeInterest.setCanBePrefix(False)

        # Encrypt the interest parameters
        challengeJson = json.dumps(
            {
                "selected-challenge": "Email",
                "email": "*****@*****.**"
            },
            indent=4)
        raw = self.pad(challengeJson, 16)
        print("raw", raw)
        iv = Random.new().read(AES.block_size)
        #cipher = AES.new(self.ecdh.derived_key, AES.MODE_CBC, iv)
        cipher = AES.new(shared_key, AES.MODE_CBC, iv)
        print(iv)
        xx = cipher.encrypt(raw)

        print(cipher.decrypt(xx))

        print("Printing iv:")
        for t in iv:
            print(t)

        encoder = TlvEncoder(256)
        saveLength = len(encoder)
        encoder.writeBlobTlv(632, iv)
        encoder.writeBlobTlv(630, cipher.encrypt(raw))
        #encoder.writeTypeAndLength(36, len(encoder) - saveLength)

        challengeInterest.setApplicationParameters(Blob(encoder.getOutput()))
        challengeInterest.appendParametersDigestToName()

        self.keyChain.sign(challengeInterest, SigningInfo(self.key))

        with open('foobar.tlv', 'wb') as f:
            f.write(challengeInterest.wireEncode().buf())
        self.face.expressInterest(challengeInterest, self.onChallengeData,
                                  self.onTimeout)