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 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"))
def _makeSelfSignedCertificate(keyName, privateKeyBag, publicKeyEncoding, password, digestAlgorithm, wireFormat): certificate = CertificateV2() # Set the name. now = Common.getNowMilliseconds() certificateName = Name(keyName) certificateName.append("self").appendVersion(int(now)) certificate.setName(certificateName) # Set the MetaInfo. certificate.getMetaInfo().setType(ContentType.KEY) # Set a one-hour freshness period. certificate.getMetaInfo().setFreshnessPeriod(3600 * 1000.0) # Set the content. publicKey = PublicKey(publicKeyEncoding) certificate.setContent(publicKey.getKeyDer()) # Create a temporary in-memory Tpm and import the private key. tpm = Tpm("", "", TpmBackEndMemory()) tpm._importPrivateKey(keyName, privateKeyBag.toBytes(), password) # Set the signature info. if publicKey.getKeyType() == KeyType.RSA: certificate.setSignature(Sha256WithRsaSignature()) elif publicKey.getKeyType() == KeyType.EC: certificate.setSignature(Sha256WithEcdsaSignature()) else: raise ValueError("Unsupported key type") signatureInfo = certificate.getSignature() KeyLocator.getFromSignature(signatureInfo).setType( KeyLocatorType.KEYNAME) KeyLocator.getFromSignature(signatureInfo).setKeyName(keyName) # Set a 20-year validity period. ValidityPeriod.getFromSignature(signatureInfo).setPeriod( now, now + 20 * 365 * 24 * 3600 * 1000.0) # Encode once to get the signed portion. encoding = certificate.wireEncode(wireFormat) signatureBytes = tpm.sign(encoding.toSignedBytes(), keyName, digestAlgorithm) signatureInfo.setSignature(signatureBytes) # Encode again to include the signature. certificate.wireEncode(wireFormat) return certificate
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
def setUp(self): self.backEndMemory = TpmBackEndMemory() locationPath = os.path.abspath("policy_config/ndnsec-key-file") if os.path.exists(locationPath): # Delete files from a previous test. for fileName in os.listdir(locationPath): filePath = os.path.join(locationPath, fileName) if os.path.isfile(filePath): os.remove(filePath) self.backEndFile = TpmBackEndFile(locationPath) self.backEndOsx = TpmBackEndOsx() self.backEndList = [None, None, None] self.backEndList[0] = self.backEndMemory self.backEndList[1] = self.backEndFile self.backEndList[2] = self.backEndOsx
def setUp(self): self.backEndMemory = TpmBackEndMemory() locationPath = os.path.abspath("policy_config/ndnsec-key-file") if os.path.exists(locationPath): # Delete files from a previous test. for fileName in os.listdir(locationPath): filePath = os.path.join(locationPath, fileName) if os.path.isfile(filePath): os.remove(filePath) self.backEndFile = TpmBackEndFile(locationPath) self.backEndOsx = TpmBackEndOsx() self.backEndList = [] self.backEndList.append(self.backEndMemory) self.backEndList.append(self.backEndFile) if sys.platform == 'darwin': self.backEndList.append(self.backEndOsx)
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)
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")
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)
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")