Пример #1
0
    def test_constructor(self):
        certificate = CertificateV2()
        certificate.wireDecode(Blob(CERT, False))

        self.assertEqual(
          Name("/ndn/site1/KEY/ksk-1416425377094/0123/%FD%00%00%01I%C9%8B"),
          certificate.getName())
        self.assertEqual(Name("/ndn/site1/KEY/ksk-1416425377094"),
          certificate.getKeyName())
        self.assertEqual(Name("/ndn/site1"), certificate.getIdentity())
        self.assertEqual(Name.Component("0123"), certificate.getIssuerId())
        self.assertEqual(Name.Component("ksk-1416425377094"),
          certificate.getKeyId())
        self.assertEqual(Name("/ndn/site1/KEY/ksk-2516425377094"),
          KeyLocator.getFromSignature(certificate.getSignature()).getKeyName())
        self.assertEqual(fromIsoString("20150814T223739"),
          certificate.getValidityPeriod().getNotBefore(), 0)
        self.assertEqual(fromIsoString("20150818T223738"),
          certificate.getValidityPeriod().getNotAfter(), 0)

        try:
          certificate.getPublicKey()
        except:
          self.fail("Error in getPublicKey");

        data = Data()
        data.wireDecode(Blob(CERT, False))
        certificate2 = CertificateV2(data)
        self.assertEqual(certificate.getName(), certificate2.getName())
        self.assertTrue(certificate.getPublicKey().equals(certificate2.getPublicKey()))
Пример #2
0
    def test_setters(self):
        certificate = CertificateV2()
        certificate.setName(
          Name("/ndn/site1/KEY/ksk-1416425377094/0123/%FD%00%00%01I%C9%8B"))
        certificate.getMetaInfo().setFreshnessPeriod(3600 * 1000.0)
        certificate.setContent(Blob(PUBLIC_KEY, False))
        certificate.setSignature(self.generateFakeSignature())

        self.assertEqual(
          Name("/ndn/site1/KEY/ksk-1416425377094/0123/%FD%00%00%01I%C9%8B"),
          certificate.getName())
        self.assertEqual(Name("/ndn/site1/KEY/ksk-1416425377094"),
          certificate.getKeyName())
        self.assertEqual(Name("/ndn/site1"), certificate.getIdentity())
        self.assertEqual(Name.Component("0123"), certificate.getIssuerId())
        self.assertEqual(Name.Component("ksk-1416425377094"),
          certificate.getKeyId())
        self.assertEqual(Name("/ndn/site1/KEY/ksk-2516425377094"),
          KeyLocator.getFromSignature(certificate.getSignature()).getKeyName())
        self.assertEqual(fromIsoString("20141111T050000"),
          certificate.getValidityPeriod().getNotBefore(), 0)
        self.assertEqual(fromIsoString("20141111T060000"),
          certificate.getValidityPeriod().getNotAfter(), 0)

        try:
          certificate.getPublicKey()
        except:
          self.fail("Error in getPublicKey");
Пример #3
0
def prepareData(ckPrefix, keyChain, face):
    """
    Create the encrypted CK Data and KDK, and add to the Namespace object.
    For the meaning of "CK data", etc. see:
    https://github.com/named-data/name-based-access-control/blob/new/docs/spec.rst

    :return: The EncryptorV2 for encrypting the content.
    :rtype: EncryptorV2
    """
    # Imitate TestEncryptorV2 and TestAccessManagerV2 from the integration tests.
    accessIdentity = keyChain.createIdentityV2(Name("/access/policy/identity"),
                                               RsaKeyParams())
    # This matches memberKeyName in test_nac_consumer.
    memberKeyName = Name("/first/user/KEY/%0C%87%EB%E6U%27B%D6")

    # The member certificate only needs to have a name and public key.
    memberCertificate = CertificateV2()
    memberCertificate.setName(Name(memberKeyName).append("self").append("1"))
    memberCertificate.setContent(Blob(MEMBER_PUBLIC_KEY, False))

    dataset = Name("/dataset")
    accessManager = AccessManagerV2(accessIdentity, dataset, keyChain, face)
    # The face now has callbacks to the AccessManagerV2 and will keep it alive.
    accessManager.addMember(memberCertificate)

    def onError(code, message):
        print("onError: " + message)

    # TODO: Sign with better than SHA256?
    return EncryptorV2(
        Name(accessIdentity.getName()).append("NAC").append(dataset), ckPrefix,
        SigningInfo(SigningInfo.SignerType.SHA256), onError, ValidatorNull(),
        keyChain, face)
Пример #4
0
        def processInterest(interest, onData, onTimeout, onNetworkNack):
            try:
                # Create another key for the same identity and sign it properly.
                parentKey = self._fixture._keyChain.createKey(
                    self._fixture._subIdentity)
                requestedKey = self._fixture._subIdentity.getKey(
                    interest.getName())

                # Copy the Name.
                certificateName = Name(requestedKey.getName())
                certificateName.append("looper").appendVersion(1)
                certificate = CertificateV2()
                certificate.setName(certificateName)

                # Set the MetaInfo.
                certificate.getMetaInfo().setType(ContentType.KEY)
                # Set the freshness period to one hour.
                certificate.getMetaInfo().setFreshnessPeriod(3600 * 1000.0)

                # Set the content.
                certificate.setContent(requestedKey.getPublicKey())

                # Set SigningInfo.
                params = SigningInfo(parentKey)
                # Validity period from 10 days before to 10 days after now.
                now = Common.getNowMilliseconds()
                params.setValidityPeriod(
                    ValidityPeriod(now - 10 * 24 * 3600 * 1000.0,
                                   now + 10 * 24 * 3600 * 1000.0))

                self._fixture._keyChain.sign(certificate, params)
                onData(interest, certificate)
            except Exception as ex:
                self.fail("Error in InfiniteCertificateChain: " + repr(ex))
    def addCertificate(self, key, issuerId):
        """
        Add a self-signed certificate made from the key and issuer ID.

        :param PibKey key: The key for the certificate.
        :param str issuerId: The issuer ID name component for the certificate
          name.
        :return: The new certificate.
        :rtype: CertificateV2
        """
        certificateName = Name(key.getName())
        certificateName.append(issuerId).appendVersion(3)
        certificate = CertificateV2()
        certificate.setName(certificateName)

        # Set the MetaInfo.
        certificate.getMetaInfo().setType(ContentType.KEY)
        # One hour.
        certificate.getMetaInfo().setFreshnessPeriod(3600 * 1000.0)

        # Set the content.
        certificate.setContent(key.getPublicKey())

        params = SigningInfo(key)
        # Validity period of 10 days.
        now = Common.getNowMilliseconds()
        params.setValidityPeriod(
          ValidityPeriod(now, now + 10 * 24 * 3600 * 1000.0))

        self._keyChain.sign(certificate, params)
        return certificate
Пример #6
0
    def test_malformed_certificate(self):
        # Copy the default certificate.
        malformedCertificate = Data(
            self._fixture._subIdentity.getDefaultKey().getDefaultCertificate())
        malformedCertificate.getMetaInfo().setType(ContentType.BLOB)
        self._fixture._keyChain.sign(malformedCertificate,
                                     SigningInfo(self._fixture._identity))
        # It has the wrong content type and a missing ValidityPeriod.
        try:
            CertificateV2(malformedCertificate).wireEncode()
            self.fail("Did not throw the expected exception")
        except CertificateV2.Error:
            pass
        else:
            self.fail("Did not throw the expected exception")

        originalProcessInterest = self._fixture._face._processInterest

        def processInterest(interest, onData, onTimeout, onNetworkNack):
            if interest.getName().isPrefixOf(malformedCertificate.getName()):
                onData(interest, malformedCertificate)
            else:
                originalProcessInterest.processInterest(
                    interest, onData, onTimeout, onNetworkNack)

        self._fixture._face._processInterest = processInterest

        data = Data(Name("/Security/V2/ValidatorFixture/Sub1/Sub2/Data"))
        self._fixture._keyChain.sign(data,
                                     SigningInfo(self._fixture._subIdentity))

        self.validateExpectFailure(data, "Signed by a malformed certificate")
        self.assertEqual(1, len(self._fixture._face._sentInterests))
Пример #7
0
    def test_expired_certificate(self):
        # Copy the default certificate.
        expiredCertificate = Data(
            self._fixture._subIdentity.getDefaultKey().getDefaultCertificate())
        info = SigningInfo(self._fixture._identity)
        # Validity period from 2 hours ago do 1 hour ago.
        now = Common.getNowMilliseconds()
        info.setValidityPeriod(
            ValidityPeriod(now - 2 * 3600 * 1000, now - 3600 * 1000.0))
        self._fixture._keyChain.sign(expiredCertificate, info)
        try:
            CertificateV2(expiredCertificate).wireEncode()
        except Exception as ex:
            self.fail("Unexpected exception: " + str(ex))

        originalProcessInterest = self._fixture._face._processInterest

        def processInterest(interest, onData, onTimeout, onNetworkNack):
            if interest.getName().isPrefixOf(expiredCertificate.getName()):
                onData(interest, expiredCertificate)
            else:
                originalProcessInterest.processInterest(
                    interest, onData, onTimeout, onNetworkNack)

        self._fixture._face._processInterest = processInterest

        data = Data(Name("/Security/V2/ValidatorFixture/Sub1/Sub2/Data"))
        self._fixture._keyChain.sign(data,
                                     SigningInfo(self._fixture._subIdentity))

        self.validateExpectFailure(data, "Signed by an expired certificate")
        self.assertEqual(1, len(self._fixture._face._sentInterests))
Пример #8
0
    def generateKeyAndSendNewInterest(self, probeTokenData):
        """
        """
        pib = self.keyChain.getPib()
        try:
            identity = pib.getIdentity(self.identityName)
            self.key = self.keyChain.createKey(identity)
        except Exception as e:
            identity = self.keyChain.createIdentityV2(self.identityName)
            self.key = identity.getDefaultKey()

        cert = CertificateV2()
        cert.setName(
            Name(self.key.getName()).append("cert-request").appendVersion(
                int(time.time())))
        cert.getMetaInfo().setType(ContentType.KEY)
        cert.getMetaInfo().setFreshnessPeriod(24 * 3600)
        cert.setContent(self.key.getPublicKey())

        signingInfo = SigningInfo(self.key)
        now = Common.getNowMilliseconds()
        signingInfo.setValidityPeriod(
            ValidityPeriod(now, now + 24 * 3600 * 1000.0))
        self.keyChain.sign(cert, signingInfo)
        #cert = self.keyChain.selfSign(self.key) # Does not work because validity period is greater than certserver default

        interestName = Name(self.caPrefix).append("CA").append("_NEW")
        newInterest = Interest(interestName)
        newInterest.setMustBeFresh(True)
        newInterest.setCanBePrefix(False)

        ecdhPub = "{}\n".format(self.ecdh.getBase64PubKey())
        ecdhCertReq = "{}\n".format(
            b64encode(cert.wireEncode().toBytes()).decode('utf-8'))
        probeToken = "{}\n".format(
            b64encode(probeTokenData.wireEncode().toBytes()).decode('utf-8'))

        jsonDump = json.dumps(
            {
                "ecdh-pub": ecdhPub,
                "cert-request": ecdhCertReq,
                "probe-token": probeToken
            },
            indent=4)
        print(jsonDump)
        newInterest.setApplicationParameters(jsonDump)
        newInterest.appendParametersDigestToName()

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

        print(newInterest.getName())

        self.face.expressInterest(newInterest, self.onNewData, self.onTimeout)
Пример #9
0
    def test_validity_period_checking(self):
        certificate = CertificateV2()
        certificate.setName(
          Name("/ndn/site1/KEY/ksk-1416425377094/0123/%FD%00%00%01I%C9%8B"))
        certificate.getMetaInfo().setFreshnessPeriod(3600 * 1000.0)
        certificate.setContent(PUBLIC_KEY)
        certificate.setSignature(self.generateFakeSignature())

        self.assertEqual(True,  certificate.isValid
          (fromIsoString("20141111T050000")))
        self.assertEqual(True,  certificate.isValid
          (fromIsoString("20141111T060000")))
        self.assertEqual(False, certificate.isValid
          (fromIsoString("20141111T045959")))
        self.assertEqual(False, certificate.isValid
          (fromIsoString("20141111T060001")))
Пример #10
0
 def __init__(self, caPrefix):
     self.ecdh = ECDHState()
     self.face = Face()
     self.keyChain = KeyChain()
     self.key = None
     self.caPrefix = caPrefix
     self.anchor = CertificateV2()
     self.anchor.wireDecode(
         Blob(
             b64decode(
                 "Bv0DgQc7CANuZG4IA2VkdQgHbWVtcGhpcwgIYWdhd2FuZGUIA0tFWQgIo6cuGT4GVKEIAk5BCAn9AAABbQxT3hEUCRgBAhkEADbugBX9ASYwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDII1sLOE7cCQVTKoGjeM5o/mxWqhMx0siLHJ81Ee/eUCNAMxA0w1oxAoTGQ8HbNP3vShZfvMJ/11Jiqus2wAWlNjRWvQShNv5MueU8kYtOGTbiqr/I1EpSRQ2aJX3s49CoskoWMzf6knK4ELleH3/EBUPGJK0cpHHdFOjwlzO3Y3Rtc/DhHVTVsBWvPS1wKgnzBFO36k73gAQJi4bOc0ggPPcK3UfVzpz8XTe+IcS2N9jew+kDqoZaL+HHz26PIAwQvXQFXPhE6y/nH/4yes24DlK3u+vHTQHXRKcLNSpYvmS6KrHvt2t01Fk0hXxeFkbh4XaE73eXB9AzNw+AccovAgMBAAEW/QEHGwEBHCQHIggDbmRuCANlZHUIB21lbXBoaXMIA0tFWQgI9bIQPIJIGTf9AP0m/QD+DzIwMTkwOTA2VDE1MjQ0Nf0A/w8yMDIwMDkwNlQxNTI0NDX9AQKw/QIAD/0CAQdhZHZpc29y/QICAP0CACH9AgEFZW1haWz9AgIUYWdhd2FuZGVAbWVtcGhpcy5lZHX9AgAf/QIBCGZ1bGxuYW1l/QICD0FzaGxlc2ggR2F3YW5kZf0CAA39AgEFZ3JvdXD9AgIA/QIAD/0CAQdob21ldXJs/QICAP0CAC39AgEMb3JnYW5pemF0aW9u/QICGVRoZSBVbml2ZXJzaXR5IG9mIE1lbXBoaXMX/QEAMZ4XLBqFjABr/k58Gq6GrNfaDMb+NLyJYF5X2mDwKnUgp1is83eg/90LqO8AVGYdyirKfr23HP4565iJXhOmFgRbP+faN++0oUTXdUSvDm43Rp+OCHr9uGPPYjUjUeNhrD7Fxfq5m3EHNMxQqnVJOODpVrF3D0EYJ4Q4IETmxrSmuDpH9I92fs7rU/51aNAZbU7DewPmcq/IrY4RO5G9pfYR+gu/gyO/L8gN39EhBbsOYWOh3EYOdAJlSktP1evL/5yRdQq7bVLyG6dZSsYQ1x4XDJ9epUesZ+TbCK/lXfRrmFG9uk8TI/rZNAYfUiQifnsNvRu34PcyELiFJ/h2xA=="
             )))
     self.identityName = ""
     self.status = None
     self.requestId = None
     self.challenges = None
    def __init__(self, policy):
        super(HierarchicalValidatorFixture, self).__init__(policy)

        self._identity = self.addIdentity(Name("/Security/V2/ValidatorFixture"))
        self._subIdentity = self.addSubCertificate(
          Name("/Security/V2/ValidatorFixture/Sub1"), self._identity)
        self._subSelfSignedIdentity = self.addIdentity(
          Name("/Security/V2/ValidatorFixture/Sub1/Sub2"))
        self._otherIdentity = self.addIdentity(Name("/Security/V2/OtherIdentity"))

        self._validator.loadAnchor(
          "", CertificateV2(self._identity.getDefaultKey().getDefaultCertificate()))

        self._cache.insert(self._identity.getDefaultKey().getDefaultCertificate())
        self._cache.insert(self._subIdentity.getDefaultKey().getDefaultCertificate())
        self._cache.insert(
          self._subSelfSignedIdentity.getDefaultKey().getDefaultCertificate())
        self._cache.insert(
          self._otherIdentity.getDefaultKey().getDefaultCertificate())
Пример #12
0
    def test_print_certificate_info(self):
        expectedCertificateInfo = (
            "Certificate name:\n" +
            "  /ndn/site1/KEY/ksk-1416425377094/0123/%FD%00%00%01I%C9%8B\n" +
            "Validity:\n" + "  NotBefore: 20150814T223739\n" +
            "  NotAfter: 20150818T223738\n" + "Public key bits:\n" +
            "MIGdMA0GCSqGSIb3DQEBAQUAA4GLADCBhwKBgQCeBj5HhbI0N6qFR6wDJIO1nKgF\n"
            +
            "OiQe64kBu+mbssMirGjj8GwCzmimxNCnBpCcqhsIHYtDmjNnRG0hoxuImpdeWcQV\n"
            +
            "C9ksvVEHYYKtwbjXv5vPfSTCY/OXF+v+YiW6W02Kwnq9Q4qPuPLxxWow01CMyJrf\n"
            + "7+0153pi6nZ8uwgmxwIBEQ==\n" + "Signature Information:\n" +
            "  Signature Type: SignatureSha256WithRsa\n" +
            "  Key Locator: Name=/ndn/site1/KEY/ksk-2516425377094\n")

        certificate = CertificateV2()
        certificate.wireDecode(Blob(CERT, False))

        actual = str(certificate)
        self.assertEqual(expectedCertificateInfo, actual)
Пример #13
0
    def makeCertificate(self, key, signer):
        """
        Make a certificate and put it in the _fixture._cache .

        :type key: PibKey
        :type signer: PibKey
        """
        # Copy the default certificate.
        request = CertificateV2(key.getDefaultCertificate())
        request.setName(Name(key.getName()).append("looper").appendVersion(1))

        # Set SigningInfo.
        params = SigningInfo(signer)
        # Validity period from 100 days before to 100 days after now.
        now = Common.getNowMilliseconds()
        params.setValidityPeriod(ValidityPeriod
          (now - 100 * 24 * 3600 * 1000.0, now + 100 * 24 * 3600 * 1000.0))
        self._fixture._keyChain.sign(request, params)
        self._fixture._keyChain.addCertificate(key, request)

        self._fixture._cache.insert(request)
Пример #14
0
    def test_management(self):
        identityName = Name("/test/id")
        identity2Name = Name("/test/id2")

        self.assertEqual(0,
                         self._fixture._keyChain.getPib()._identities.size())
        try:
            self._fixture._keyChain.getPib().getDefaultIdentity()
            self.fail("Did not throw the expected exception")
        except Pib.Error:
            pass
        else:
            self.fail("Did not throw the expected exception")

        # Create an identity.
        id = self._fixture._keyChain.createIdentityV2(identityName)
        self.assertTrue(id != None)
        self.assertTrue(identityName in self._fixture._keyChain.getPib().
                        _identities._identities)

        # The first added identity becomes the default identity.
        try:
            self._fixture._keyChain.getPib().getDefaultIdentity()
        except Exception as ex:
            self.fail("Unexpected exception: " + str(ex))

        # The default key of the added identity must exist.
        try:
            key = id.getDefaultKey()
        except Exception as ex:
            self.fail("Unexpected exception: " + str(ex))

        # The default certificate of the default key must exist.
        try:
            key.getDefaultCertificate()
        except Exception as ex:
            self.fail("Unexpected exception: " + str(ex))

        # Delete the key.
        key1Name = key.getName()
        try:
            id.getKey(key1Name)
        except Exception as ex:
            self.fail("Unexpected exception: " + str(ex))

        self.assertEqual(1, id._getKeys().size())
        self._fixture._keyChain.deleteKey(id, key)
        # TODO: Implement key validity.
        #        # The key instance should not be valid anymore.
        #        self.assertTrue(!key)

        try:
            id.getKey(key1Name)
            self.fail("Did not throw the expected exception")
        except Pib.Error:
            pass
        else:
            self.fail("Did not throw the expected exception")

        self.assertEqual(0, id._getKeys().size())

        # Create another key.
        self._fixture._keyChain.createKey(id)
        # The added key becomes the default key.
        try:
            id.getDefaultKey()
        except Exception as ex:
            self.fail("Unexpected exception: " + str(ex))

        key2 = id.getDefaultKey()
        self.assertTrue(key2 != None)
        self.assertTrue(not key2.getName().equals(key1Name))
        self.assertEqual(1, id._getKeys().size())
        try:
            key2.getDefaultCertificate()
        except Exception as ex:
            self.fail("Unexpected exception: " + str(ex))

        # Create a third key.
        key3 = self._fixture._keyChain.createKey(id)
        self.assertTrue(not key3.getName().equals(key2.getName()))
        # The added key will not be the default key, because the default key already exists.
        self.assertTrue(id.getDefaultKey().getName().equals(key2.getName()))
        self.assertEqual(2, id._getKeys().size())
        try:
            key3.getDefaultCertificate()
        except Exception as ex:
            self.fail("Unexpected exception: " + str(ex))

        # Delete the certificate.
        self.assertEqual(1, key3._getCertificates().size())
        key3Cert1 = list(key3._getCertificates()._certificates.values())[0]
        key3CertName = key3Cert1.getName()
        self._fixture._keyChain.deleteCertificate(key3, key3CertName)
        self.assertEqual(0, key3._getCertificates().size())
        try:
            key3.getDefaultCertificate()
            self.fail("Did not throw the expected exception")
        except Pib.Error:
            pass
        else:
            self.fail("Did not throw the expected exception")

        # Add a certificate.
        self._fixture._keyChain.addCertificate(key3, key3Cert1)
        self.assertEqual(1, key3._getCertificates().size())
        try:
            key3.getDefaultCertificate()
        except Exception as ex:
            self.fail("Unexpected exception: " + str(ex))

        # Overwriting the certificate should work.
        self._fixture._keyChain.addCertificate(key3, key3Cert1)
        self.assertEqual(1, key3._getCertificates().size())
        # Add another certificate.
        key3Cert2 = CertificateV2(key3Cert1)
        key3Cert2Name = Name(key3.getName())
        key3Cert2Name.append("Self")
        key3Cert2Name.appendVersion(1)
        key3Cert2.setName(key3Cert2Name)
        self._fixture._keyChain.addCertificate(key3, key3Cert2)
        self.assertEqual(2, key3._getCertificates().size())

        # Set the default certificate.
        self.assertTrue(
            key3.getDefaultCertificate().getName().equals(key3CertName))
        self._fixture._keyChain.setDefaultCertificate(key3, key3Cert2)
        self.assertTrue(
            key3.getDefaultCertificate().getName().equals(key3Cert2Name))

        # Set the default key.
        self.assertTrue(id.getDefaultKey().getName().equals(key2.getName()))
        self._fixture._keyChain.setDefaultKey(id, key3)
        self.assertTrue(id.getDefaultKey().getName().equals(key3.getName()))

        # Set the default identity.
        id2 = self._fixture._keyChain.createIdentityV2(identity2Name)
        self.assertTrue(self._fixture._keyChain.getPib().getDefaultIdentity().
                        getName().equals(id.getName()))
        self._fixture._keyChain.setDefaultIdentity(id2)
        self.assertTrue(self._fixture._keyChain.getPib().getDefaultIdentity().
                        getName().equals(id2.getName()))

        # Delete an identity.
        self._fixture._keyChain.deleteIdentity(id)
        # TODO: Implement identity validity.
        #        # The identity instance should not be valid anymore.
        #        BOOST_CHECK(!id)
        try:
            self._fixture._keyChain.getPib().getIdentity(identityName)
            self.fail("Did not throw the expected exception")
        except Pib.Error:
            pass
        else:
            self.fail("Did not throw the expected exception")

        self.assertTrue(not (identityName in self._fixture._keyChain.getPib().
                             _identities._identities))