def setUp(self):
        testCertDirectory = 'policy_config/certs'
        self.testCertFile = os.path.join(testCertDirectory, 'test.cert')

        self.pibImpl = PibMemory()
        self.tpmBackEnd = TpmBackEndMemory()
        self.policyManager = ConfigPolicyManager(
            'policy_config/simple_rules.conf', CertificateCacheV2())

        self.identityName = Name('/TestConfigPolicyManager/temp')
        # to match the anchor cert
        self.keyName = Name(
            self.identityName).append("KEY").append("ksk-1416010123")
        self.pibImpl.addKey(self.identityName, self.keyName,
                            TEST_RSA_PUBLIC_KEY_DER)
        # Set the password to None since we have an unencrypted PKCS #8 private key.
        self.tpmBackEnd.importKey(self.keyName, TEST_RSA_PRIVATE_KEY_PKCS8,
                                  None)

        self.keyChain = KeyChain(self.pibImpl, self.tpmBackEnd,
                                 self.policyManager)

        pibKey = self.keyChain.getPib().getIdentity(self.identityName).getKey(
            self.keyName)
        # selfSign adds to the PIB.
        self.keyChain.selfSign(pibKey)
Beispiel #2
0
    def test_errors(self):
        fixture = self.fixture
        pibImpl = PibMemory()

        container = PibKeyContainer(fixture.id1, pibImpl)

        try:
            container.add(fixture.id2Key1.toBytes(), fixture.id2Key1Name)
            self.fail("Did not throw the expected exception")
        except ValueError:
            pass
        else:
            self.fail("Did not throw the expected exception")

        try:
            container.remove(fixture.id2Key1Name)
            self.fail("Did not throw the expected exception")
        except ValueError:
            pass
        else:
            self.fail("Did not throw the expected exception")

        try:
            container.get(fixture.id2Key1Name)
            self.fail("Did not throw the expected exception")
        except ValueError:
            pass
        else:
            self.fail("Did not throw the expected exception")
    def test_errors(self):
        fixture = self.fixture
        pibImpl = PibMemory()

        container = PibCertificateContainer(fixture.id1Key1Name, pibImpl)

        try:
            container.add(fixture.id1Key2Cert1)
            self.fail("Did not throw the expected exception")
        except ValueError:
            pass
        else:
            self.fail("Did not throw the expected exception")

        try:
            container.remove(fixture.id1Key2Cert1.getName())
            self.fail("Did not throw the expected exception")
        except ValueError:
            pass
        else:
            self.fail("Did not throw the expected exception")

        try:
            container.get(fixture.id1Key2Cert1.getName())
            self.fail("Did not throw the expected exception")
        except ValueError:
            pass
        else:
            self.fail("Did not throw the expected exception")
Beispiel #4
0
    def test_errors(self):
        fixture = self.fixture
        pibImpl = PibMemory()

        try:
            PibIdentityImpl(fixture.id1, pibImpl, False)
            self.fail("Did not throw the expected exception")
        except Pib.Error:
            pass
        else:
            self.fail("Did not throw the expected exception")

        identity1 = PibIdentityImpl(fixture.id1, pibImpl, True)

        identity1.addKey(fixture.id1Key1.buf(), fixture.id1Key1Name)
        try:
            identity1.addKey(fixture.id2Key1.buf(), fixture.id2Key1Name)
            self.fail("Did not throw the expected exception")
        except ValueError:
            pass
        else:
            self.fail("Did not throw the expected exception")

        identity1.addKey(fixture.id1Key1.buf(), fixture.id1Key1Name)
        try:
            identity1.removeKey(fixture.id2Key1Name)
            self.fail("Did not throw the expected exception")
        except ValueError:
            pass
        else:
            self.fail("Did not throw the expected exception")

        identity1.addKey(fixture.id1Key1.buf(), fixture.id1Key1Name)
        try:
            identity1.getKey(fixture.id2Key1Name)
            self.fail("Did not throw the expected exception")
        except ValueError:
            pass
        else:
            self.fail("Did not throw the expected exception")

        identity1.addKey(fixture.id1Key1.buf(), fixture.id1Key1Name)
        try:
            identity1.setDefaultKey(fixture.id2Key1.buf(), fixture.id2Key1Name)
            self.fail("Did not throw the expected exception")
        except ValueError:
            pass
        else:
            self.fail("Did not throw the expected exception")

        identity1.addKey(fixture.id1Key1.buf(), fixture.id1Key1Name)
        try:
            identity1.setDefaultKey(fixture.id2Key1Name)
            self.fail("Did not throw the expected exception")
        except ValueError:
            pass
        else:
            self.fail("Did not throw the expected exception")
def main():
    interest = Interest()
    interest.wireDecode(TlvInterest)
    dump("Interest:")
    dumpInterest(interest)

    # Set the name again to clear the cached encoding so we encode again.
    interest.setName(interest.getName())
    encoding = interest.wireEncode()
    dump("")
    dump("Re-encoded interest", encoding.toHex())

    reDecodedInterest = Interest()
    reDecodedInterest.wireDecode(encoding)
    dump("Re-decoded Interest:")
    dumpInterest(reDecodedInterest)

    freshInterest = (Interest(
        Name("/ndn/abc")).setMustBeFresh(False).setMinSuffixComponents(
            4).setMaxSuffixComponents(6).setInterestLifetimeMilliseconds(
                30000).setChildSelector(1).setMustBeFresh(True))
    freshInterest.getKeyLocator().setType(KeyLocatorType.KEY_LOCATOR_DIGEST)
    freshInterest.getKeyLocator().setKeyData(
        bytearray([
            0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A,
            0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15,
            0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F
        ]))
    freshInterest.getExclude().appendComponent(Name("abc")[0]).appendAny()
    freshInterest.getForwardingHint().add(1, Name("/A"))
    dump(freshInterest.toUri())

    # Set up the KeyChain.
    pibImpl = PibMemory()
    keyChain = KeyChain(pibImpl, TpmBackEndMemory(),
                        SelfVerifyPolicyManager(pibImpl))
    # This puts the public key in the pibImpl used by the SelfVerifyPolicyManager.
    keyChain.importSafeBag(
        SafeBag(Name("/testname/KEY/123"),
                Blob(DEFAULT_RSA_PRIVATE_KEY_DER, False),
                Blob(DEFAULT_RSA_PUBLIC_KEY_DER, False)))

    # Make a Face just so that we can sign the interest.
    face = Face("localhost")
    face.setCommandSigningInfo(keyChain, keyChain.getDefaultCertificateName())
    face.makeCommandInterest(freshInterest)

    reDecodedFreshInterest = Interest()
    reDecodedFreshInterest.wireDecode(freshInterest.wireEncode())
    dump("")
    dump("Re-decoded fresh Interest:")
    dumpInterest(reDecodedFreshInterest)

    keyChain.verifyInterest(reDecodedFreshInterest,
                            makeOnVerified("Freshly-signed Interest"),
                            makeOnValidationFailed("Freshly-signed Interest"))
Beispiel #6
0
    def test_overwrite(self):
        fixture = self.fixture
        pibImpl = PibMemory()
        identity1 = PibIdentityImpl(fixture.id1, pibImpl, True)

        identity1.addKey(fixture.id1Key1.toBytes(), fixture.id1Key1Name)
        self.assertTrue(identity1.getKey(fixture.id1Key1Name).getPublicKey()
          .equals(fixture.id1Key1))

        # Overwriting the key should work.
        identity1.addKey(fixture.id1Key2.toBytes(), fixture.id1Key1Name)
        self.assertTrue(identity1.getKey(fixture.id1Key1Name).getPublicKey()
          .equals(fixture.id1Key2))
Beispiel #7
0
    def test_overwrite(self):
        fixture = self.fixture
        pibImpl = PibMemory()

        try:
            PibKeyImpl(fixture.id1Key1Name, pibImpl)
            self.fail("Did not throw the expected exception")
        except Pib.Error:
            pass
        else:
            self.fail("Did not throw the expected exception")

        PibKeyImpl(fixture.id1Key1Name, fixture.id1Key1.buf(), pibImpl)
        key1 = PibKeyImpl(fixture.id1Key1Name, pibImpl)

        # Overwriting the key should work.
        PibKeyImpl(fixture.id1Key1Name, fixture.id1Key2.buf(), pibImpl)
        key2 = PibKeyImpl(fixture.id1Key1Name, pibImpl)

        # key1 should have cached the original public key.
        self.assertTrue(not key1.getPublicKey().equals(key2.getPublicKey()))
        self.assertTrue(key2.getPublicKey().equals(fixture.id1Key2))

        key1.addCertificate(fixture.id1Key1Cert1)
        # Use the wire encoding to check equivalence.
        self.assertTrue(
            key1.getCertificate(
                fixture.id1Key1Cert1.getName()).wireEncode().equals(
                    fixture.id1Key1Cert1.wireEncode()))

        otherCert = CertificateV2(fixture.id1Key1Cert1)
        otherCert.getSignature().getValidityPeriod().setPeriod(
            Common.getNowMilliseconds(),
            Common.getNowMilliseconds() + 1000)
        # Don't bother resigning so we don't have to load a private key.

        self.assertTrue(fixture.id1Key1Cert1.getName().equals(
            otherCert.getName()))
        self.assertTrue(otherCert.getContent().equals(
            fixture.id1Key1Cert1.getContent()))
        self.assertFalse(otherCert.wireEncode().equals(
            fixture.id1Key1Cert1.wireEncode()))

        key1.addCertificate(otherCert)

        self.assertTrue(
            key1.getCertificate(
                fixture.id1Key1Cert1.getName()).wireEncode().equals(
                    otherCert.wireEncode()))
Beispiel #8
0
    def test_basic(self):
        fixture = self.fixture
        pibImpl = PibMemory()
        key11 = PibKeyImpl(
          fixture.id1Key1Name, fixture.id1Key1.toBytes(), pibImpl)

        self.assertTrue(fixture.id1Key1Name.equals(key11.getName()))
        self.assertTrue(fixture.id1.equals(key11.getIdentityName()))
        self.assertEquals(KeyType.RSA, key11.getKeyType())
        self.assertTrue(key11.getPublicKey().equals(fixture.id1Key1))

        key11FromBackend = PibKeyImpl(fixture.id1Key1Name, pibImpl)
        self.assertTrue(fixture.id1Key1Name.equals(key11FromBackend.getName()))
        self.assertTrue(fixture.id1.equals(key11FromBackend.getIdentityName()))
        self.assertEquals(KeyType.RSA, key11FromBackend.getKeyType())
        self.assertTrue(key11FromBackend.getPublicKey().equals(fixture.id1Key1))
def main():

    backboneFace = Face()

    pibImpl = PibMemory()
    keyChain = KeyChain(pibImpl, TpmBackEndMemory(),
                        SelfVerifyPolicyManager(pibImpl))
    # This puts the public key in the pibImpl used by the SelfVerifyPolicyManager.
    keyChain.importSafeBag(
        SafeBag(Name("/testname/KEY/123"),
                Blob(DEFAULT_RSA_PRIVATE_KEY_DER, False),
                Blob(DEFAULT_RSA_PUBLIC_KEY_DER, False)))

    backboneFace.setCommandSigningInfo(keyChain,
                                       keyChain.getDefaultCertificateName())

    prefix = Name("/farm1")
    backboneFace.registerPrefix(prefix, onInterest, onRegisterFailed)
    print("Ready to go...")

    while 1:
        try:
            backboneFace.processEvents()

            e.acquire()
            frame = ieee.wait_read_frame(0.01)
            e.release()

            if frame is not None:
                if frame['rf_data'][0] == b'\x06' or frame['rf_data'][
                        0] == b'\x05':  #if Data or Interest
                    buffData[0] = frame['rf_data'][0]
                    buffData[1] = ord(frame['rf_data'][1]) + lCP
                    buffData[2] = frame['rf_data'][2]
                    buffData[3] = ord(frame['rf_data'][3]) + lCP
                    buffData[4:lCP + 4] = eCP
                    buffData[lCP + 4:] = frame['rf_data'][4:]
                    print(str(datetime.now().strftime('%X.%f')))
                    backboneFace.send(buffData)
                else:
                    print(frame['rf_data'][:])
            #time.sleep(0.1)
            gc.collect()
        except KeyboardInterrupt:
            backboneFace.shutdown()
            ser.close()
            break
Beispiel #10
0
def main():
    data = Data()
    data.wireDecode(TlvData)
    dump("Decoded Data:")
    dumpData(data)

    # Set the content again to clear the cached encoding so we encode again.
    data.setContent(data.getContent())
    encoding = data.wireEncode()

    reDecodedData = Data()
    reDecodedData.wireDecode(encoding)
    dump("")
    dump("Re-decoded Data:")
    dumpData(reDecodedData)

    # Set up the KeyChain.
    pibImpl = PibMemory()
    keyChain = KeyChain(
      pibImpl, TpmBackEndMemory(), SelfVerifyPolicyManager(pibImpl))
    # This puts the public key in the pibImpl used by the SelfVerifyPolicyManager.
    keyChain.importSafeBag(SafeBag
      (Name("/testname/KEY/123"),
       Blob(DEFAULT_RSA_PRIVATE_KEY_DER, False),
       Blob(DEFAULT_RSA_PUBLIC_KEY_DER, False)))

    keyChain.verifyData(reDecodedData, makeOnVerified("Re-decoded Data"),
                        makeOnValidationFailed("Re-decoded Data"))

    freshData = Data(Name("/ndn/abc"))
    freshData.setContent("SUCCESS!")
    freshData.getMetaInfo().setFreshnessPeriod(5000)
    freshData.getMetaInfo().setFinalBlockId(Name("/%00%09")[0])
    keyChain.sign(freshData)
    dump("")
    dump("Freshly-signed Data:")
    dumpData(freshData)

    keyChain.verifyData(freshData, makeOnVerified("Freshly-signed Data"),
                        makeOnValidationFailed("Freshly-signed Data"))
def benchmarkDecodeDataSeconds(nIterations, useCrypto, keyType, encoding):
    """
    Loop to decode a data packet nIterations times.

    :param int nIterations: The number of iterations.
    :param bool useCrypto: If true, verify the signature.  If false, don't
      verify.
    :param KeyType keyType: KeyType.RSA or EC, used if useCrypto is True.
    :param Blob encoding: The wire encoding to decode.
    :return: The number of seconds for all iterations.
    :rtype: float
    """
    # Initialize the private key storage in case useCrypto is true.
    pibImpl = PibMemory()
    keyChain = KeyChain(pibImpl, TpmBackEndMemory(),
                        SelfVerifyPolicyManager(pibImpl))
    # This puts the public key in the pibImpl used by the SelfVerifyPolicyManager.
    keyChain.importSafeBag(
        SafeBag(
            Name("/testname/KEY/123"),
            Blob(
                DEFAULT_EC_PRIVATE_KEY_DER if keyType == KeyType.ECDSA else
                DEFAULT_RSA_PRIVATE_KEY_DER, False),
            Blob(
                DEFAULT_EC_PUBLIC_KEY_DER if keyType == KeyType.ECDSA else
                DEFAULT_RSA_PUBLIC_KEY_DER, False)))

    start = getNowSeconds()
    for i in range(nIterations):
        data = Data()
        data.wireDecode(encoding)

        if useCrypto:
            keyChain.verifyData(data, onVerified, onValidationFailed)

    finish = getNowSeconds()

    return finish - start
    def setUp(self):
        testCertDirectory = 'policy_config/certs'
        self.testCertFile = os.path.join(testCertDirectory, 'test.cert')

        self.pibImpl = PibMemory()
        self.tpmBackEnd = TpmBackEndMemory()
        self.policyManager = ConfigPolicyManager(
          'policy_config/simple_rules.conf', CertificateCacheV2())

        self.identityName = Name('/TestConfigPolicyManager/temp')
        # to match the anchor cert
        self.keyName = Name(self.identityName).append("KEY").append("ksk-1416010123")
        self.pibImpl.addKey(self.identityName, self.keyName,
          TEST_RSA_PUBLIC_KEY_DER)
        # Set the password to None since we have an unencrypted PKCS #8 private key.
        self.tpmBackEnd.importKey(self.keyName, TEST_RSA_PRIVATE_KEY_PKCS8,
          None)

        self.keyChain = KeyChain(self.pibImpl, self.tpmBackEnd, self.policyManager)

        pibKey = self.keyChain.getPib().getIdentity(self.identityName).getKey(
          self.keyName)
        # selfSign adds to the PIB.
        self.keyChain.selfSign(pibKey)
Beispiel #13
0
    def test_basic(self):
        fixture = self.fixture
        pibImpl = PibMemory()

        # Start with an empty container.
        container = PibKeyContainer(fixture.id1, pibImpl)
        self.assertEqual(0, container.size())
        self.assertEqual(0, len(container._keys))

        # Add the first key.
        key11 = container.add(fixture.id1Key1.buf(), fixture.id1Key1Name)
        self.assertTrue(fixture.id1Key1Name.equals(key11.getName()))
        self.assertTrue(key11.getPublicKey().equals(fixture.id1Key1))
        self.assertEqual(1, container.size())
        self.assertEqual(1, len(container._keys))
        self.assertTrue(fixture.id1Key1Name in container._keys)

        # Add the same key again.
        key12 = container.add(fixture.id1Key1.buf(), fixture.id1Key1Name)
        self.assertTrue(fixture.id1Key1Name.equals(key12.getName()))
        self.assertTrue(key12.getPublicKey().equals(fixture.id1Key1))
        self.assertEqual(1, container.size())
        self.assertEqual(1, len(container._keys))
        self.assertTrue(fixture.id1Key1Name in container._keys)

        # Add the second key.
        key21 = container.add(fixture.id1Key2.buf(), fixture.id1Key2Name)
        self.assertTrue(fixture.id1Key2Name.equals(key21.getName()))
        self.assertTrue(key21.getPublicKey().equals(fixture.id1Key2))
        self.assertEqual(2, container.size())
        self.assertEqual(2, len(container._keys))
        self.assertTrue(fixture.id1Key1Name in container._keys)
        self.assertTrue(fixture.id1Key2Name in container._keys)

        # Get keys.
        try:
            container.get(fixture.id1Key1Name)
        except Exception as ex:
            self.fail("Unexpected exception: " + str(ex))
        try:
            container.get(fixture.id1Key2Name)
        except Exception as ex:
            self.fail("Unexpected exception: " + str(ex))
        id1Key3Name = PibKey.constructKeyName(
          fixture.id1, Name.Component("non-existing-id"))
        try:
            container.get(id1Key3Name)
            self.fail("Did not throw the expected exception")
        except Pib.Error:
            pass
        else:
            self.fail("Did not throw the expected exception")

        # Get and check keys.
        key1 = container.get(fixture.id1Key1Name)
        key2 = container.get(fixture.id1Key2Name)
        self.assertTrue(fixture.id1Key1Name.equals(key1.getName()))
        self.assertTrue(key1.getPublicKey().equals(fixture.id1Key1))
        self.assertEqual(fixture.id1Key2Name, key2.getName())
        self.assertTrue(key2.getPublicKey().equals(fixture.id1Key2))

        # Create another container using the same PibImpl. The cache should be empty.
        container2 = PibKeyContainer(fixture.id1, pibImpl)
        self.assertEqual(2, container2.size())
        self.assertEqual(0, len(container2._keys))

        # Get a key. The cache should be filled.
        try:
            container2.get(fixture.id1Key1Name)
        except Exception as ex:
            self.fail("Unexpected exception: " + str(ex))
        self.assertEqual(2, container2.size())
        self.assertEqual(1, len(container2._keys))

        try:
            container2.get(fixture.id1Key2Name)
        except Exception as ex:
            self.fail("Unexpected exception: " + str(ex))
        self.assertEqual(2, container2.size())
        self.assertEqual(2, len(container2._keys))

        # Remove a key.
        container2.remove(fixture.id1Key1Name)
        self.assertEqual(1, container2.size())
        self.assertEqual(1, len(container2._keys))
        self.assertTrue(not (fixture.id1Key1Name in container2._keys))
        self.assertTrue(fixture.id1Key2Name in container2._keys)

        # Remove another key.
        container2.remove(fixture.id1Key2Name)
        self.assertEqual(0, container2.size())
        self.assertEqual(0, len(container2._keys))
        self.assertTrue(not (fixture.id1Key2Name in container2._keys))
def benchmarkEncodeDataSeconds(nIterations, useComplex, useCrypto, keyType):
    """
    Loop to encode a data packet nIterations times.

    :param int nIterations: The number of iterations.
    :param bool useComplex: If true, use a large name, large content and all
      fields. If false, use a small name, small content and only required
      fields.
    :param bool useCrypto: If true, sign the data packet.  If false, use a blank
      signature.
    :param KeyType keyType: KeyType.RSA or EC, used if useCrypto is True.
    :return: A tuple (duration, encoding) where duration is the number of
      seconds for all iterations and encoding is the wire encoding.
    :rtype: (float, Blob)
    """
    if useComplex:
        # Use a large name and content.
        name = Name(
            "/ndn/ucla.edu/apps/lwndn-test/numbers.txt/%FD%05%05%E8%0C%CE%1D/%00"
        )

        contentString = ""
        count = 1
        contentString += "%d" % count
        count += 1
        while len(contentString) < 1115:
            contentString += " %d" % count
            count += 1
        content = Name.fromEscapedString(contentString)
    else:
        # Use a small name and content.
        name = Name("/test")
        content = Name.fromEscapedString("abc")
    finalBlockId = Name("/%00")[0]

    # Initialize the private key storage in case useCrypto is true.
    pibImpl = PibMemory()
    keyChain = KeyChain(pibImpl, TpmBackEndMemory(),
                        SelfVerifyPolicyManager(pibImpl))
    keyChain.importSafeBag(
        SafeBag(
            Name("/testname/KEY/123"),
            Blob(
                DEFAULT_EC_PRIVATE_KEY_DER if keyType == KeyType.ECDSA else
                DEFAULT_RSA_PRIVATE_KEY_DER, False),
            Blob(
                DEFAULT_EC_PUBLIC_KEY_DER if keyType == KeyType.ECDSA else
                DEFAULT_RSA_PUBLIC_KEY_DER, False)))
    certificateName = keyChain.getDefaultCertificateName()

    # Set up signatureBits in case useCrypto is false.
    signatureBits = Blob(bytearray(256))

    start = getNowSeconds()
    for i in range(nIterations):
        data = Data(name)
        data.setContent(content)
        if useComplex:
            data.getMetaInfo().setFreshnessPeriod(1000)
            data.getMetaInfo().setFinalBlockId(finalBlockId)

        if useCrypto:
            # This sets the signature fields.
            keyChain.sign(data)
        else:
            # Imitate IdentityManager.signByCertificate to set up the signature
            # fields, but don't sign.
            sha256Signature = data.getSignature()
            keyLocator = sha256Signature.getKeyLocator()
            keyLocator.setType(KeyLocatorType.KEYNAME)
            keyLocator.setKeyName(certificateName)
            sha256Signature.setSignature(signatureBits)

        encoding = data.wireEncode()

    finish = getNowSeconds()

    return (finish - start, encoding)
Beispiel #15
0
    def test_basic(self):
        fixture = self.fixture
        pibImpl = PibMemory()

        # Start with an empty container.
        container = PibIdentityContainer(pibImpl)
        self.assertEqual(0, container.size())
        self.assertEqual(0, len(container._identities))

        # Add the first identity.
        identity11 = container.add(fixture.id1)
        self.assertTrue(fixture.id1.equals(identity11.getName()))
        self.assertEqual(1, container.size())
        self.assertEqual(1, len(container._identities))
        self.assertTrue(fixture.id1 in container._identities)

        # Add the same identity again.
        identity12 = container.add(fixture.id1)
        self.assertTrue(fixture.id1.equals(identity12.getName()))
        self.assertEqual(1, container.size())
        self.assertEqual(1, len(container._identities))
        self.assertTrue(fixture.id1 in container._identities)

        # Add the second identity.
        identity21 = container.add(fixture.id2)
        self.assertTrue(fixture.id2.equals(identity21.getName()))
        self.assertEqual(2, container.size())
        self.assertEqual(2, len(container._identities))
        self.assertTrue(fixture.id1 in container._identities)
        self.assertTrue(fixture.id2 in container._identities)

        # Get identities.
        try:
            container.get(fixture.id1)
        except Exception as ex:
            self.fail("Unexpected exception: " + str(ex))
        try:
            container.get(fixture.id2)
        except Exception as ex:
            self.fail("Unexpected exception: " + str(ex))
        try:
            container.get(Name("/non-existing"))
            self.fail("Did not throw the expected exception")
        except Pib.Error:
            pass
        else:
            self.fail("Did not throw the expected exception")

        # Check the identity.
        identity1 = container.get(fixture.id1)
        identity2 = container.get(fixture.id2)
        self.assertTrue(fixture.id1.equals(identity1.getName()))
        self.assertTrue(fixture.id2.equals(identity2.getName()))

        # Create another container from the same PibImpl. The cache should be empty.
        container2 = PibIdentityContainer(pibImpl)
        self.assertEqual(2, container2.size())
        self.assertEqual(0, len(container2._identities))

        # Get keys. The cache should be filled.
        try:
            container2.get(fixture.id1)
        except Exception as ex:
            self.fail("Unexpected exception: " + str(ex))
        self.assertEqual(2, container2.size())
        self.assertEqual(1, len(container2._identities))

        try:
            container2.get(fixture.id2)
        except Exception as ex:
            self.fail("Unexpected exception: " + str(ex))
        self.assertEqual(2, container2.size())
        self.assertEqual(2, len(container2._identities))

        # Remove a key.
        container2.remove(fixture.id1)
        self.assertEqual(1, container2.size())
        self.assertEqual(1, len(container2._identities))
        self.assertTrue(not (fixture.id1 in container2._identities))
        self.assertTrue(fixture.id2 in container2._identities)

        # Remove another key.
        container2.remove(fixture.id2)
        self.assertEqual(0, container2.size())
        self.assertEqual(0, len(container2._identities))
        self.assertTrue(not (fixture.id2 in container2._identities))
    def test_basic(self):
        fixture = self.fixture
        pibImpl = PibMemory()

        # Start with an empty container.
        container = PibCertificateContainer(fixture.id1Key1Name, pibImpl)
        self.assertEqual(0, container.size())
        self.assertEqual(0, len(container._certificates))

        # Add a certificate.
        container.add(fixture.id1Key1Cert1)
        self.assertEqual(1, container.size())
        self.assertEqual(1, len(container._certificates))
        self.assertTrue(
            fixture.id1Key1Cert1.getName() in container._certificates)

        # Add the same certificate again.
        container.add(fixture.id1Key1Cert1)
        self.assertEqual(1, container.size())
        self.assertEqual(1, len(container._certificates))
        self.assertTrue(
            fixture.id1Key1Cert1.getName() in container._certificates)

        # Add another certificate.
        container.add(fixture.id1Key1Cert2)
        self.assertEqual(2, container.size())
        self.assertEqual(2, len(container._certificates))
        self.assertTrue(
            fixture.id1Key1Cert1.getName() in container._certificates)
        self.assertTrue(
            fixture.id1Key1Cert2.getName() in container._certificates)

        # Get the certificates.
        try:
            container.get(fixture.id1Key1Cert1.getName())
        except Exception as ex:
            self.fail("Unexpected exception: " + str(ex))
        try:
            container.get(fixture.id1Key1Cert2.getName())
        except Exception as ex:
            self.fail("Unexpected exception: " + str(ex))
        id1Key1Cert3Name = Name(fixture.id1Key1Name)
        id1Key1Cert3Name.append("issuer").appendVersion(3)
        try:
            container.get(id1Key1Cert3Name)
            self.fail("Did not throw the expected exception")
        except Pib.Error:
            pass
        else:
            self.fail("Did not throw the expected exception")

        # Check the certificates.
        cert1 = container.get(fixture.id1Key1Cert1.getName())
        cert2 = container.get(fixture.id1Key1Cert2.getName())
        # Use the wire encoding to check equivalence.
        self.assertTrue(cert1.wireEncode().equals(
            fixture.id1Key1Cert1.wireEncode()))
        self.assertTrue(cert2.wireEncode().equals(
            fixture.id1Key1Cert2.wireEncode()))

        # Create another container with the same PibImpl. The cache should be empty.
        container2 = PibCertificateContainer(fixture.id1Key1Name, pibImpl)
        self.assertEqual(2, container2.size())
        self.assertEqual(0, len(container2._certificates))

        # Get a certificate. The cache should be filled.
        try:
            container2.get(fixture.id1Key1Cert1.getName())
        except Exception as ex:
            self.fail("Unexpected exception: " + str(ex))
        self.assertEqual(2, container2.size())
        self.assertEqual(1, len(container2._certificates))

        try:
            container2.get(fixture.id1Key1Cert2.getName())
        except Exception as ex:
            self.fail("Unexpected exception: " + str(ex))
        self.assertEqual(2, container2.size())
        self.assertEqual(2, len(container2._certificates))

        # Remove a certificate.
        container2.remove(fixture.id1Key1Cert1.getName())
        self.assertEqual(1, container2.size())
        self.assertEqual(1, len(container2._certificates))
        self.assertTrue(not (
            fixture.id1Key1Cert1.getName() in container2._certificates))
        self.assertTrue(
            fixture.id1Key1Cert2.getName() in container2._certificates)

        # Remove another certificate.
        container2.remove(fixture.id1Key1Cert2.getName())
        self.assertEqual(0, container2.size())
        self.assertEqual(0, len(container2._certificates))
        self.assertTrue(not (
            fixture.id1Key1Cert2.getName() in container2._certificates))
Beispiel #17
0
    def test_certificate_operation(self):
        fixture = self.fixture
        pibImpl = PibMemory()
        key11 = PibKeyImpl(fixture.id1Key1Name, fixture.id1Key1.toBytes(),
                           pibImpl)
        try:
            PibKeyImpl(fixture.id1Key1Name, pibImpl)
        except Exception as ex:
            self.fail("Unexpected exception: " + str(ex))

        # The key should not have any certificates.
        self.assertEqual(0, key11._certificates.size())

        # Getting a non-existing certificate should throw Pib.Error.
        try:
            key11.getCertificate(fixture.id1Key1Cert1.getName())
            self.fail("Did not throw the expected exception")
        except Pib.Error:
            pass
        else:
            self.fail("Did not throw the expected exception")

        # Getting the non-existing default certificate should throw Pib.Error.
        try:
            key11.getDefaultCertificate()
            self.fail("Did not throw the expected exception")
        except Pib.Error:
            pass
        else:
            self.fail("Did not throw the expected exception")

        # Setting a non-existing certificate as the default should throw Pib.Error.
        try:
            key11.setDefaultCertificate(fixture.id1Key1Cert1.getName())
            self.fail("Did not throw the expected exception")
        except Pib.Error:
            pass
        else:
            self.fail("Did not throw the expected exception")

        # Add a certificate.
        key11.addCertificate(fixture.id1Key1Cert1)
        try:
            key11.getCertificate(fixture.id1Key1Cert1.getName())
        except Exception as ex:
            self.fail("Unexpected exception: " + str(ex))

        # The new certificate becomes the default when there was no default.
        try:
            key11.getDefaultCertificate()
        except Exception as ex:
            self.fail("Unexpected exception: " + str(ex))
        defaultCert0 = key11.getDefaultCertificate()
        self.assertTrue(fixture.id1Key1Cert1.getName().equals(
            defaultCert0.getName()))
        # Use the wire encoding to check equivalence.
        self.assertTrue(fixture.id1Key1Cert1.wireEncode().equals(
            defaultCert0.wireEncode()))

        # Remove the certificate.
        key11.removeCertificate(fixture.id1Key1Cert1.getName())
        try:
            key11.getCertificate(fixture.id1Key1Cert1.getName())
            self.fail("Did not throw the expected exception")
        except Pib.Error:
            pass
        else:
            self.fail("Did not throw the expected exception")

        try:
            key11.getDefaultCertificate()
            self.fail("Did not throw the expected exception")
        except Pib.Error:
            pass
        else:
            self.fail("Did not throw the expected exception")

        # Set the default certificate directly.
        try:
            key11.setDefaultCertificate(fixture.id1Key1Cert1)
        except Exception as ex:
            self.fail("Unexpected exception: " + str(ex))

        try:
            key11.getDefaultCertificate()
        except Exception as ex:
            self.fail("Unexpected exception: " + str(ex))

        try:
            key11.getCertificate(fixture.id1Key1Cert1.getName())
        except Exception as ex:
            self.fail("Unexpected exception: " + str(ex))

        # Check the default cert.
        defaultCert1 = key11.getDefaultCertificate()
        self.assertTrue(fixture.id1Key1Cert1.getName().equals(
            defaultCert1.getName()))
        self.assertTrue(defaultCert1.wireEncode().equals(
            fixture.id1Key1Cert1.wireEncode()))

        # Add another certificate.
        key11.addCertificate(fixture.id1Key1Cert2)
        self.assertEqual(2, key11._certificates.size())

        # Set the default certificate using a name.
        try:
            key11.setDefaultCertificate(fixture.id1Key1Cert2.getName())
        except Exception as ex:
            self.fail("Unexpected exception: " + str(ex))

        try:
            key11.getDefaultCertificate()
        except Exception as ex:
            self.fail("Unexpected exception: " + str(ex))

        defaultCert2 = key11.getDefaultCertificate()
        self.assertTrue(fixture.id1Key1Cert2.getName().equals(
            defaultCert2.getName()))
        self.assertTrue(defaultCert2.wireEncode().equals(
            fixture.id1Key1Cert2.wireEncode()))

        # Remove a certificate.
        key11.removeCertificate(fixture.id1Key1Cert1.getName())
        try:
            key11.getCertificate(fixture.id1Key1Cert1.getName())
            self.fail("Did not throw the expected exception")
        except Pib.Error:
            pass
        else:
            self.fail("Did not throw the expected exception")

        self.assertEqual(1, key11._certificates.size())

        # Set the default certificate directly again, which should change the default.
        try:
            key11.setDefaultCertificate(fixture.id1Key1Cert1)
        except Exception as ex:
            self.fail("Unexpected exception: " + str(ex))

        defaultCert3 = key11.getDefaultCertificate()
        self.assertTrue(fixture.id1Key1Cert1.getName().equals(
            defaultCert3.getName()))
        self.assertTrue(defaultCert3.wireEncode().equals(
            fixture.id1Key1Cert1.wireEncode()))
        self.assertEqual(2, key11._certificates.size())

        # Remove all certificates.
        key11.removeCertificate(fixture.id1Key1Cert1.getName())
        try:
            key11.getCertificate(fixture.id1Key1Cert1.getName())
            self.fail("Did not throw the expected exception")
        except Pib.Error:
            pass
        else:
            self.fail("Did not throw the expected exception")

        self.assertEqual(1, key11._certificates.size())
        key11.removeCertificate(fixture.id1Key1Cert2.getName())
        try:
            key11.getCertificate(fixture.id1Key1Cert2.getName())
            self.fail("Did not throw the expected exception")
        except Pib.Error:
            pass
        else:
            self.fail("Did not throw the expected exception")

        try:
            key11.getDefaultCertificate()
            self.fail("Did not throw the expected exception")
        except Pib.Error:
            pass
        else:
            self.fail("Did not throw the expected exception")

        self.assertEqual(0, key11._certificates.size())
Beispiel #18
0
    def test_errors(self):
        fixture = self.fixture
        pibImpl = PibMemory()

        try:
            PibKeyImpl(fixture.id1Key1Name, pibImpl)
            self.fail("Did not throw the expected exception")
        except Pib.Error:
            pass
        else:
            self.fail("Did not throw the expected exception")

        key11 = PibKeyImpl(fixture.id1Key1Name, fixture.id1Key1.buf(), pibImpl)

        try:
            PibKeyImpl(Name("/wrong"), pibImpl)
            self.fail("Did not throw the expected exception")
        except ValueError:
            pass
        else:
            self.fail("Did not throw the expected exception")

        try:
            PibKeyImpl(Name("/wrong"), fixture.id1Key1.buf(), pibImpl)
            self.fail("Did not throw the expected exception")
        except ValueError:
            pass
        else:
            self.fail("Did not throw the expected exception")

        wrongKey = Blob("")
        try:
            PibKeyImpl(fixture.id1Key2Name, wrongKey.toBytes(), pibImpl)
            self.fail("Did not throw the expected exception")
        except ValueError:
            pass
        else:
            self.fail("Did not throw the expected exception")

        key11.addCertificate(fixture.id1Key1Cert1)
        try:
            key11.addCertificate(fixture.id1Key2Cert1)
            self.fail("Did not throw the expected exception")
        except ValueError:
            pass
        else:
            self.fail("Did not throw the expected exception")

        try:
            key11.removeCertificate(fixture.id1Key2Cert1.getName())
            self.fail("Did not throw the expected exception")
        except ValueError:
            pass
        else:
            self.fail("Did not throw the expected exception")

        try:
            key11.getCertificate(fixture.id1Key2Cert1.getName())
            self.fail("Did not throw the expected exception")
        except ValueError:
            pass
        else:
            self.fail("Did not throw the expected exception")

        try:
            key11.setDefaultCertificate(fixture.id1Key2Cert1)
            self.fail("Did not throw the expected exception")
        except ValueError:
            pass
        else:
            self.fail("Did not throw the expected exception")

        try:
            key11.setDefaultCertificate(fixture.id1Key2Cert1.getName())
            self.fail("Did not throw the expected exception")
        except ValueError:
            pass
        else:
            self.fail("Did not throw the expected exception")
Beispiel #19
0
    def test_basic(self):
        fixture = self.fixture
        pibImpl = PibMemory()
        identity1 = PibIdentityImpl(fixture.id1, pibImpl, True)

        self.assertTrue(fixture.id1.equals(identity1.getName()))
class TestPolicyManagerV2(ut.TestCase):
    def setUp(self):
        testCertDirectory = 'policy_config/certs'
        self.testCertFile = os.path.join(testCertDirectory, 'test.cert')

        self.pibImpl = PibMemory()
        self.tpmBackEnd = TpmBackEndMemory()
        self.policyManager = ConfigPolicyManager(
            'policy_config/simple_rules.conf', CertificateCacheV2())

        self.identityName = Name('/TestConfigPolicyManager/temp')
        # to match the anchor cert
        self.keyName = Name(
            self.identityName).append("KEY").append("ksk-1416010123")
        self.pibImpl.addKey(self.identityName, self.keyName,
                            TEST_RSA_PUBLIC_KEY_DER)
        # Set the password to None since we have an unencrypted PKCS #8 private key.
        self.tpmBackEnd.importKey(self.keyName, TEST_RSA_PRIVATE_KEY_PKCS8,
                                  None)

        self.keyChain = KeyChain(self.pibImpl, self.tpmBackEnd,
                                 self.policyManager)

        pibKey = self.keyChain.getPib().getIdentity(self.identityName).getKey(
            self.keyName)
        # selfSign adds to the PIB.
        self.keyChain.selfSign(pibKey)

    def tearDown(self):
        try:
            os.remove(self.testCertFile)
        except OSError:
            pass

    def test_interest_timestamp(self):
        interestName = Name('/ndn/ucla/edu/something')
        certName = self.keyChain.getPib().getIdentity(
            self.identityName).getKey(
                self.keyName).getDefaultCertificate().getName()
        face = Face("localhost")
        face.setCommandSigningInfo(self.keyChain, certName)

        oldInterest = Interest(interestName)
        face.makeCommandInterest(oldInterest)

        time.sleep(0.1)  # make sure timestamps are different
        newInterest = Interest(interestName)
        face.makeCommandInterest(newInterest)

        vr = doVerify(self.policyManager, newInterest)

        self.assertFalse(
            vr.hasFurtherSteps,
            "ConfigPolicyManager returned ValidationRequest but certificate is known"
        )
        self.assertEqual(vr.failureCount, 0,
                         "Verification of valid interest failed")
        self.assertEqual(
            vr.successCount, 1,
            "Verification success called {} times instead of 1".format(
                vr.successCount))

        vr = doVerify(self.policyManager, oldInterest)

        self.assertFalse(
            vr.hasFurtherSteps,
            "ConfigPolicyManager returned ValidationRequest but certificate is known"
        )
        self.assertEqual(vr.successCount, 0,
                         "Verification of stale interest succeeded")
        self.assertEqual(
            vr.failureCount, 1,
            "Failure callback called {} times instead of 1".format(
                vr.failureCount))

    def test_refresh_10s(self):
        with open('policy_config/testData', 'r') as dataFile:
            encodedData = dataFile.read()
            data = Data()
            dataBlob = Blob(b64decode(encodedData))
            data.wireDecode(dataBlob)

        # This test is needed, since the KeyChain will express interests in
        # unknown certificates.
        vr = doVerify(self.policyManager, data)

        self.assertTrue(
            vr.hasFurtherSteps,
            "ConfigPolicyManager did not create ValidationRequest for unknown certificate"
        )
        self.assertEqual(
            vr.successCount, 0,
            "ConfigPolicyManager called success callback with pending ValidationRequest"
        )
        self.assertEqual(
            vr.failureCount, 0,
            "ConfigPolicyManager called failure callback with pending ValidationRequest"
        )

        # Now save the cert data to our anchor directory, and wait.
        # We have to sign it with the current identity or the policy manager
        # will create an interest for the signing certificate.

        cert = CertificateV2()
        certData = b64decode(CERT_DUMP)
        cert.wireDecode(Blob(certData, False))
        signingInfo = SigningInfo()
        signingInfo.setSigningIdentity(self.identityName)
        # Make sure the validity period is current for two years.
        now = Common.getNowMilliseconds()
        signingInfo.setValidityPeriod(
            ValidityPeriod(now, now + 2 * 365 * 24 * 3600 * 1000.0))

        self.keyChain.sign(cert, signingInfo)
        encodedCert = b64encode(cert.wireEncode().toBytes())
        with open(self.testCertFile, 'w') as certFile:
            certFile.write(Blob(encodedCert, False).toRawStr())

        # Still too early for refresh to pick it up.
        vr = doVerify(self.policyManager, data)

        self.assertTrue(
            vr.hasFurtherSteps,
            "ConfigPolicyManager refresh occured sooner than specified")
        self.assertEqual(
            vr.successCount, 0,
            "ConfigPolicyManager called success callback with pending ValidationRequest"
        )
        self.assertEqual(
            vr.failureCount, 0,
            "ConfigPolicyManager called failure callback with pending ValidationRequest"
        )
        time.sleep(6)

        # Now we should find it.
        vr = doVerify(self.policyManager, data)

        self.assertFalse(
            vr.hasFurtherSteps,
            "ConfigPolicyManager did not refresh certificate store")
        self.assertEqual(
            vr.successCount, 1,
            "Verification success called {} times instead of 1".format(
                vr.successCount))
        self.assertEqual(
            vr.failureCount, 0,
            "ConfigPolicyManager did not verify valid signed data")
Beispiel #21
0
    def test_key_operation(self):
        fixture = self.fixture
        pibImpl = PibMemory()
        identity1 = PibIdentityImpl(fixture.id1, pibImpl, True)
        try:
            PibIdentityImpl(fixture.id1, pibImpl, False)
        except Exception as ex:
            self.fail("Unexpected exception: " + str(ex))

        # The identity should not have any key.
        self.assertEquals(0, identity1._keys.size())

        # Getting non-existing key should throw Pib.Error.
        try:
            identity1.getKey(fixture.id1Key1Name)
            self.fail("Did not throw the expected exception")
        except Pib.Error:
            pass
        else:
            self.fail("Did not throw the expected exception")

        # Getting the default key should throw Pib.Error.
        try:
            identity1.getDefaultKey()
            self.fail("Did not throw the expected exception")
        except Pib.Error:
            pass
        else:
            self.fail("Did not throw the expected exception")

        # Setting a non-existing key as the default key should throw Pib.Error.
        try:
            identity1.setDefaultKey(fixture.id1Key1Name)
            self.fail("Did not throw the expected exception")
        except Pib.Error:
            pass
        else:
            self.fail("Did not throw the expected exception")

        # Add a key.
        identity1.addKey(fixture.id1Key1.toBytes(), fixture.id1Key1Name)
        try:
            identity1.getKey(fixture.id1Key1Name)
        except Exception as ex:
            self.fail("Unexpected exception: " + str(ex))

        # A new key should become the default key when there is no default.
        try:
            identity1.getDefaultKey()
        except Exception as ex:
            self.fail("Unexpected exception: " + str(ex))
        defaultKey0 = identity1.getDefaultKey()
        self.assertTrue(fixture.id1Key1Name.equals(defaultKey0.getName()))
        self.assertTrue(defaultKey0.getPublicKey().equals(fixture.id1Key1))

        # Remove a key.
        identity1.removeKey(fixture.id1Key1Name)
        try:
            identity1.setDefaultKey(fixture.id1Key1Name)
            self.fail("Did not throw the expected exception")
        except Pib.Error:
            pass
        else:
            self.fail("Did not throw the expected exception")

        try:
            identity1.getDefaultKey()
            self.fail("Did not throw the expected exception")
        except Pib.Error:
            pass
        else:
            self.fail("Did not throw the expected exception")

        # Set the default key directly.
        try:
            identity1.setDefaultKey(fixture.id1Key1.toBytes(),
                                    fixture.id1Key1Name)
        except Exception as ex:
            self.fail("Unexpected exception: " + str(ex))
        try:
            identity1.getDefaultKey()
        except Exception as ex:
            self.fail("Unexpected exception: " + str(ex))
        try:
            identity1.getKey(fixture.id1Key1Name)
        except Exception as ex:
            self.fail("Unexpected exception: " + str(ex))

        # Check for a default key.
        defaultKey1 = identity1.getDefaultKey()
        self.assertTrue(fixture.id1Key1Name.equals(defaultKey1.getName()))
        self.assertTrue(defaultKey1.getPublicKey().equals(fixture.id1Key1))

        # Add another key.
        identity1.addKey(fixture.id1Key2.toBytes(), fixture.id1Key2Name)
        self.assertEquals(2, identity1._keys.size())

        # Set the default key using a name.
        try:
            identity1.setDefaultKey(fixture.id1Key2Name)
        except Exception as ex:
            self.fail("Unexpected exception: " + str(ex))
        try:
            identity1.getDefaultKey()
        except Exception as ex:
            self.fail("Unexpected exception: " + str(ex))
        defaultKey2 = identity1.getDefaultKey()
        self.assertTrue(fixture.id1Key2Name.equals(defaultKey2.getName()))
        self.assertTrue(defaultKey2.getPublicKey().equals(fixture.id1Key2))

        # Remove a key.
        identity1.removeKey(fixture.id1Key1Name)
        try:
            identity1.getKey(fixture.id1Key1Name)
            self.fail("Did not throw the expected exception")
        except Pib.Error:
            pass
        else:
            self.fail("Did not throw the expected exception")

        self.assertEquals(1, identity1._keys.size())

        # Seting the default key directly again should change the default.
        try:
            identity1.setDefaultKey(fixture.id1Key1.toBytes(),
                                    fixture.id1Key1Name)
        except Exception as ex:
            self.fail("Unexpected exception: " + str(ex))
        defaultKey3 = identity1.getDefaultKey()
        self.assertTrue(fixture.id1Key1Name.equals(defaultKey3.getName()))
        self.assertTrue(defaultKey3.getPublicKey().equals(fixture.id1Key1))
        self.assertEquals(2, identity1._keys.size())

        # Remove all keys.
        identity1.removeKey(fixture.id1Key1Name)
        try:
            identity1.getKey(fixture.id1Key1Name)
            self.fail("Did not throw the expected exception")
        except Pib.Error:
            pass
        else:
            self.fail("Did not throw the expected exception")

        self.assertEquals(1, identity1._keys.size())
        identity1.removeKey(fixture.id1Key2Name)
        try:
            identity1.getKey(fixture.id1Key2Name)
            self.fail("Did not throw the expected exception")
        except Pib.Error:
            pass
        else:
            self.fail("Did not throw the expected exception")

        self.assertEquals(0, identity1._keys.size())
        try:
            identity1.getDefaultKey()
            self.fail("Did not throw the expected exception")
        except Pib.Error:
            pass
        else:
            self.fail("Did not throw the expected exception")
Beispiel #22
0
    def __init__(self):
        super(PibMemoryFixture, self).__init__()

        self._myPib = PibMemory()
        self.pib = self._myPib
class TestPolicyManagerV2(ut.TestCase):
    def setUp(self):
        testCertDirectory = 'policy_config/certs'
        self.testCertFile = os.path.join(testCertDirectory, 'test.cert')

        self.pibImpl = PibMemory()
        self.tpmBackEnd = TpmBackEndMemory()
        self.policyManager = ConfigPolicyManager(
          'policy_config/simple_rules.conf', CertificateCacheV2())

        self.identityName = Name('/TestConfigPolicyManager/temp')
        # to match the anchor cert
        self.keyName = Name(self.identityName).append("KEY").append("ksk-1416010123")
        self.pibImpl.addKey(self.identityName, self.keyName,
          TEST_RSA_PUBLIC_KEY_DER)
        # Set the password to None since we have an unencrypted PKCS #8 private key.
        self.tpmBackEnd.importKey(self.keyName, TEST_RSA_PRIVATE_KEY_PKCS8,
          None)

        self.keyChain = KeyChain(self.pibImpl, self.tpmBackEnd, self.policyManager)

        pibKey = self.keyChain.getPib().getIdentity(self.identityName).getKey(
          self.keyName)
        # selfSign adds to the PIB.
        self.keyChain.selfSign(pibKey)

    def tearDown(self):
        try:
            os.remove(self.testCertFile)
        except OSError:
            pass

    def test_interest_timestamp(self):
        interestName = Name('/ndn/ucla/edu/something')
        certName = self.keyChain.getPib().getIdentity(self.identityName).getKey(
          self.keyName).getDefaultCertificate().getName()
        face = Face("localhost")
        face.setCommandSigningInfo(self.keyChain, certName)

        oldInterest = Interest(interestName)
        face.makeCommandInterest(oldInterest)

        time.sleep(0.1) # make sure timestamps are different
        newInterest = Interest(interestName)
        face.makeCommandInterest(newInterest)

        vr  = doVerify(self.policyManager, newInterest)

        self.assertFalse(vr.hasFurtherSteps,
          "ConfigPolicyManager returned ValidationRequest but certificate is known")
        self.assertEqual(vr.failureCount, 0,
          "Verification of valid interest failed")
        self.assertEqual(vr.successCount, 1,
          "Verification success called {} times instead of 1".format(
            vr.successCount))

        vr  = doVerify(self.policyManager, oldInterest)

        self.assertFalse(vr.hasFurtherSteps,
          "ConfigPolicyManager returned ValidationRequest but certificate is known")
        self.assertEqual(vr.successCount, 0,
          "Verification of stale interest succeeded")
        self.assertEqual(vr.failureCount, 1,
          "Failure callback called {} times instead of 1".format(
            vr.failureCount))

    def test_refresh_10s(self):
        with open('policy_config/testData', 'r') as dataFile:
            encodedData = dataFile.read()
            data = Data()
            dataBlob = Blob(b64decode(encodedData))
            data.wireDecode(dataBlob)

        # This test is needed, since the KeyChain will express interests in
        # unknown certificates.
        vr = doVerify(self.policyManager, data)

        self.assertTrue(vr.hasFurtherSteps,
          "ConfigPolicyManager did not create ValidationRequest for unknown certificate")
        self.assertEqual(vr.successCount, 0,
          "ConfigPolicyManager called success callback with pending ValidationRequest")
        self.assertEqual(vr.failureCount, 0,
          "ConfigPolicyManager called failure callback with pending ValidationRequest")

        # Now save the cert data to our anchor directory, and wait.
        # We have to sign it with the current identity or the policy manager
        # will create an interest for the signing certificate.

        cert = CertificateV2()
        certData = b64decode(CERT_DUMP)
        cert.wireDecode(Blob(certData, False))
        signingInfo = SigningInfo()
        signingInfo.setSigningIdentity(self.identityName)
        # Make sure the validity period is current for two years.
        now = Common.getNowMilliseconds()
        signingInfo.setValidityPeriod(ValidityPeriod
          (now, now + 2 * 365 * 24 * 3600 * 1000.0))

        self.keyChain.sign(cert, signingInfo)
        encodedCert = b64encode(cert.wireEncode().toBytes())
        with open(self.testCertFile, 'w') as certFile:
            certFile.write(Blob(encodedCert, False).toRawStr())

        # Still too early for refresh to pick it up.
        vr = doVerify(self.policyManager, data)

        self.assertTrue(vr.hasFurtherSteps,
          "ConfigPolicyManager refresh occured sooner than specified")
        self.assertEqual(vr.successCount, 0,
          "ConfigPolicyManager called success callback with pending ValidationRequest")
        self.assertEqual(vr.failureCount, 0,
          "ConfigPolicyManager called failure callback with pending ValidationRequest")
        time.sleep(6)

        # Now we should find it.
        vr  = doVerify(self.policyManager, data)

        self.assertFalse(vr.hasFurtherSteps,
          "ConfigPolicyManager did not refresh certificate store")
        self.assertEqual(vr.successCount, 1,
          "Verification success called {} times instead of 1".format(
            vr.successCount))
        self.assertEqual(vr.failureCount, 0,
          "ConfigPolicyManager did not verify valid signed data")