def test_prepare_unsigned_certificate(self): identityStorage = MemoryIdentityStorage() privateKeyStorage = MemoryPrivateKeyStorage() identityManager = IdentityManager(identityStorage, privateKeyStorage) keyName = Name("/test/ksk-1457560485494") identityStorage.addKey(keyName, KeyType.RSA, Blob(PUBLIC_KEY)) subjectDescriptions = [] subjectDescriptions.append( CertificateSubjectDescription(TEST_OID, "TEST NAME")) newCertificate = identityManager.prepareUnsignedIdentityCertificate( keyName, keyName.getPrefix(1), self.toyCertNotBefore, self.toyCertNotAfter, subjectDescriptions) # Update the generated certificate version to equal the one in toyCert. newCertificate.setName( Name(newCertificate.getName().getPrefix(-1).append( self.toyCert.getName().get(-1)))) # Make a copy to test encoding. certificateCopy = IdentityCertificate(newCertificate) self.assertEqual( str(self.toyCert), str(certificateCopy), "Prepared unsigned certificate dump does not have the expected format" )
def setUp(self): # set up the keychain so we can sign data self.identityStorage = MemoryIdentityStorage() self.privateKeyStorage = MemoryPrivateKeyStorage() self.keyChain = KeyChain( IdentityManager(self.identityStorage, self.privateKeyStorage)) self.privateKeyStorage = MemoryPrivateKeyStorage() # not using keychain for verification so we don't need to set the # policy manager self.keyChain = KeyChain( IdentityManager(self.identityStorage, self.privateKeyStorage)) self.identityName = Name('/SecurityTestSecRule/Basic/Longer') keyName = Name(self.identityName).append('ksk-2439872') self.defaultCertName = self._certNameFromKeyName(keyName) self.identityStorage.addKey(keyName, KeyType.RSA, Blob(DEFAULT_RSA_PUBLIC_KEY_DER)) self.privateKeyStorage.setKeyPairForKeyName( keyName, KeyType.RSA, DEFAULT_RSA_PUBLIC_KEY_DER, DEFAULT_RSA_PRIVATE_KEY_DER) keyName = Name('/SecurityTestSecRule/Basic/ksk-0923489') self.identityStorage.addKey(keyName, KeyType.RSA, Blob(DEFAULT_RSA_PUBLIC_KEY_DER)) self.privateKeyStorage.setKeyPairForKeyName( keyName, KeyType.RSA, DEFAULT_RSA_PUBLIC_KEY_DER, DEFAULT_RSA_PRIVATE_KEY_DER) self.shortCertName = self._certNameFromKeyName(keyName, -2)
def test_prepare_unsigned_certificate(self): identityStorage = MemoryIdentityStorage() privateKeyStorage = MemoryPrivateKeyStorage() identityManager = IdentityManager(identityStorage, privateKeyStorage) keyName = Name("/test/ksk-1457560485494") identityStorage.addKey(keyName, KeyType.RSA, Blob(PUBLIC_KEY)) subjectDescriptions = [] subjectDescriptions.append(CertificateSubjectDescription( TEST_OID, "TEST NAME")) newCertificate = identityManager.prepareUnsignedIdentityCertificate( keyName, keyName.getPrefix(1), self.toyCertNotBefore, self.toyCertNotAfter, subjectDescriptions) # Update the generated certificate version to equal the one in toyCert. newCertificate.setName( Name(newCertificate.getName().getPrefix(-1).append (self.toyCert.getName().get(-1)))) # Make a copy to test encoding. certificateCopy = IdentityCertificate(newCertificate) self.assertEqual( str(self.toyCert), str(certificateCopy), "Prepared unsigned certificate dump does not have the expected format")
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. identityStorage = MemoryIdentityStorage() privateKeyStorage = MemoryPrivateKeyStorage() keyChain = KeyChain(IdentityManager(identityStorage, privateKeyStorage), SelfVerifyPolicyManager(identityStorage)) keyName = Name("/testname/DSK-123") identityStorage.addKey( keyName, keyType, Blob( DEFAULT_EC_PUBLIC_KEY_DER if keyType == KeyType.ECDSA else DEFAULT_RSA_PUBLIC_KEY_DER)) 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 __init__(self, face): self._defaultIdentity = None self._defaultCertificateName = None self._controllerName = None self._controllerCertificate = None self._applicationName = "" self._identityManager = IdentityManager(BasicIdentityStorage(), FilePrivateKeyStorage()) self._policyManager = ConfigPolicyManager() self._policyManager.config.read("validator \n \ { \n \ rule \n \ { \n \ id \"initial rule\" \n \ for data \n \ checker \n \ { \n \ type hierarchical \n \ } \n \ } \n \ }", "initial-schema") # keyChain is what we return to the application after successful setup # TODO: should we separate keyChain from internal KeyChain used to verify trust schemas? self._keyChain = KeyChain(self._identityManager, self._policyManager) self._face = face # setFace for keyChain or else it won't be able to express interests for certs self._keyChain.setFace(self._face) self._certificateContentCache = MemoryContentCache(face) self._trustSchemas = dict()
def createKeyChain(): """ Create an in-memory KeyChain with default keys. :return: A tuple with the new KeyChain and certificate name. :rtype: (KeyChain,Name) """ identityStorage = MemoryIdentityStorage() privateKeyStorage = MemoryPrivateKeyStorage() keyChain = KeyChain(IdentityManager(identityStorage, privateKeyStorage), NoVerifyPolicyManager()) # Initialize the storage. keyName = Name("/testname/DSK-123") certificateName = keyName.getSubName( 0, keyName.size() - 1).append("KEY").append( keyName.get(-1)).append("ID-CERT").append("0") identityStorage.addKey(keyName, KeyType.RSA, Blob(DEFAULT_RSA_PUBLIC_KEY_DER, False)) privateKeyStorage.setKeyPairForKeyName(keyName, KeyType.RSA, DEFAULT_RSA_PUBLIC_KEY_DER, DEFAULT_RSA_PRIVATE_KEY_DER) return keyChain, certificateName
def __init__(self, face, encryptResult, link = None): # Set up face self.face = face self._encryptResult = encryptResult self._link = link self.databaseFilePath = "policy_config/test_consumer_dpu.db" try: os.remove(self.databaseFilePath) except OSError: # no such file pass self.groupName = Name("/org/openmhealth/haitao") # Set up the keyChain. identityStorage = BasicIdentityStorage() privateKeyStorage = FilePrivateKeyStorage() self.keyChain = KeyChain( IdentityManager(identityStorage, privateKeyStorage), NoVerifyPolicyManager()) # Authorized identity identityName = Name("/ndn/edu/basel/dpu") # Function name: the function that this DPU provides self._functionName = "bounding_box" self._identityName = identityName self.certificateName = self.keyChain.createIdentityAndCertificate(identityName) # TODO: if using BasicIdentityStorage and FilePrivateKeyStorage # For some reason this newly generated cert is not installed by default, calling keyChain sign later would result in error #self.keyChain.installIdentityCertificate() self.face.setCommandSigningInfo(self.keyChain, self.certificateName) consumerKeyName = IdentityCertificate.certificateNameToPublicKeyName(self.certificateName) consumerCertificate = identityStorage.getCertificate(self.certificateName) self.consumer = Consumer( face, self.keyChain, self.groupName, identityName, Sqlite3ConsumerDb(self.databaseFilePath)) # TODO: Read the private key to decrypt d-key...this may or may not be ideal base64Content = None with open(privateKeyStorage.nameTransform(consumerKeyName.toUri(), ".pri")) as keyFile: print privateKeyStorage.nameTransform(consumerKeyName.toUri(), ".pri") base64Content = keyFile.read() #print base64Content der = Blob(base64.b64decode(base64Content), False) self.consumer.addDecryptionKey(consumerKeyName, der) self.memoryContentCache = MemoryContentCache(self.face) self.memoryContentCache.registerPrefix(identityName, self.onRegisterFailed, self.onDataNotFound) self.memoryContentCache.add(consumerCertificate) accessRequestInterest = Interest(Name(self.groupName).append("read_access_request").append(self.certificateName).appendVersion(int(time.time()))) self.face.expressInterest(accessRequestInterest, self.onAccessRequestData, self.onAccessRequestTimeout) print "Access request interest name: " + accessRequestInterest.getName().toUri() self._tasks = dict() return
def main(): # The default Face will connect using a Unix socket, or to "localhost". face = Face() identityStorage = MemoryIdentityStorage() privateKeyStorage = MemoryPrivateKeyStorage() keyChain = KeyChain(IdentityManager(identityStorage, privateKeyStorage), None) keyChain.setFace(face) # Initialize the storage. keyName = Name("/testname/DSK-123") certificateName = keyName.getSubName( 0, keyName.size() - 1).append("KEY").append( keyName[-1]).append("ID-CERT").append("0") identityStorage.addKey(keyName, KeyType.RSA, Blob(DEFAULT_RSA_PUBLIC_KEY_DER)) privateKeyStorage.setKeyPairForKeyName(keyName, KeyType.RSA, DEFAULT_RSA_PUBLIC_KEY_DER, DEFAULT_RSA_PRIVATE_KEY_DER) echo = Echo(keyChain, certificateName) prefix = Name("/testecho") dump("Register prefix", prefix.toUri()) face.registerPrefix(prefix, echo.onInterest, echo.onRegisterFailed) while echo._responseCount < 1: face.processEvents() # We need to sleep for a few milliseconds so we don't use 100% of the CPU. time.sleep(0.01) face.shutdown()
def benchmarkDecodeDataSeconds(nIterations, useCrypto, 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 Blob encoding: The wire encoding to decode. """ # Initialize the private key storage in case useCrypto is true. identityStorage = MemoryIdentityStorage() privateKeyStorage = MemoryPrivateKeyStorage() keyChain = KeyChain(IdentityManager(identityStorage, privateKeyStorage), SelfVerifyPolicyManager(identityStorage)) keyName = Name("/testname/DSK-123") certificateName = keyName.getSubName( 0, keyName.size() - 1).append("KEY").append( keyName[-1]).append("ID-CERT").append("0") identityStorage.addKey(keyName, KeyType.RSA, Blob(DEFAULT_RSA_PUBLIC_KEY_DER)) start = getNowSeconds() for i in range(nIterations): data = Data() data.wireDecode(encoding) if useCrypto: keyChain.verifyData(data, onVerified, onVerifyFailed) finish = getNowSeconds() return finish - start
def __init__(self, face, groupManagerName, dataType, dKeyDatabaseFilePath): # Set up face self.face = face #self.loop = eventLoop # Set up the keyChain. identityStorage = MemoryIdentityStorage() privateKeyStorage = MemoryPrivateKeyStorage() self.keyChain = KeyChain( IdentityManager(identityStorage, privateKeyStorage), NoVerifyPolicyManager()) self.certificateName = self.keyChain.createIdentityAndCertificate( groupManagerName) self.dKeyDatabaseFilePath = dKeyDatabaseFilePath self.manager = GroupManager( groupManagerName, dataType, Sqlite3GroupManagerDb(self.dKeyDatabaseFilePath), 2048, 1, self.keyChain) self.memoryContentCache = MemoryContentCache(self.face) self.memoryContentCache.registerPrefix(groupManagerName, self.onRegisterFailed, self.onDataNotFound) self.needToPublishGroupKeys = False return
def main(): # The default Face will connect using a Unix socket, or to "localhost". face = Face() # Use the system default key chain and certificate name to sign commands. #print("key1") #keyChain = KeyChain() #print("key2") identityStorage = MemoryIdentityStorage() privateKeyStorage = MemoryPrivateKeyStorage() keyChain = KeyChain(IdentityManager(identityStorage, privateKeyStorage), NoVerifyPolicyManager()) identityName = Name("TestProducer") certificateName = keyChain.createIdentityAndCertificate(identityName) keyChain.getIdentityManager().setDefaultIdentity(identityName) face.setCommandSigningInfo(keyChain, keyChain.getDefaultCertificateName()) # Also use the default certificate name to sign data packets. ubicdn = UbiCDN(keyChain, certificateName) prefix = Name("/ubicdn/video") dump("Register prefix", prefix.toUri()) face.registerPrefix(prefix, ubicdn.onInterest, ubicdn.onRegisterFailed) while 1: #while ubicdn._responseCount < 1: face.processEvents() # We need to sleep for a few milliseconds so we don't use 100% of the CPU. time.sleep(0.01) face.shutdown()
def main(): # COMMAND LINE ARGS parser = argparse.ArgumentParser( description='Parse or follow Cascade Datahub log and publish to NDN.') parser.add_argument('filename', help='datahub log file') parser.add_argument('-f', dest='follow', action='store_true', help='follow (tail -f) the log file') parser.add_argument('--namespace', default='/ndn/edu/ucla/remap/bms', help='root ndn name, no trailing slash') args = parser.parse_args() # NDN global face, keychain loop = asyncio.get_event_loop() face = ThreadsafeFace(loop, "localhost") keychain = KeyChain( IdentityManager( BasicIdentityStorage(), FilePrivateKeyStorage())) # override default even for MacOS cache = MemoryContentCache(face) # READ THE FILE (MAIN LOOP) if args.follow: loop.run_until_complete( followfile(args.filename, args.namespace, cache)) else: loop.run_until_complete(readfile(args.filename, args.namespace, cache)) face.shutdown()
def __init__(self): self.identityStorage = MemoryIdentityStorage() self.privateKeyStorage = MemoryPrivateKeyStorage() self.keyChain = KeyChain( IdentityManager(self.identityStorage, self.privateKeyStorage), SelfVerifyPolicyManager(self.identityStorage)) keyName = Name("/testname/DSK-123") self.defaultCertName = keyName[:-1].append("KEY").append( keyName[-1]).append("ID-CERT").append("0") ecdsaKeyName = Name("/testEcdsa/DSK-123") self.ecdsaCertName = ecdsaKeyName[:-1].append("KEY").append( ecdsaKeyName[-1]).append("ID-CERT").append("0") self.identityStorage.addKey(keyName, KeyType.RSA, Blob(DEFAULT_RSA_PUBLIC_KEY_DER)) self.privateKeyStorage.setKeyPairForKeyName( keyName, KeyType.RSA, DEFAULT_RSA_PUBLIC_KEY_DER, DEFAULT_RSA_PRIVATE_KEY_DER) self.identityStorage.addKey(ecdsaKeyName, KeyType.ECDSA, Blob(DEFAULT_EC_PUBLIC_KEY_DER)) self.privateKeyStorage.setKeyPairForKeyName( ecdsaKeyName, KeyType.ECDSA, DEFAULT_EC_PUBLIC_KEY_DER, DEFAULT_EC_PRIVATE_KEY_DER)
def setUp(self): self.decryptionKeys = {} # key: Name, value: Blob self.encryptionKeys = {} # key: Name, value: Data # Reuse the policy_config subdirectory for the temporary SQLite files. self.databaseFilePath = "policy_config/test.db" try: os.remove(self.databaseFilePath) except OSError: # no such file pass self.groupName = Name("/Prefix/READ") self.contentName = Name("/Prefix/SAMPLE/Content") self.cKeyName = Name("/Prefix/SAMPLE/Content/C-KEY/1") self.eKeyName = Name("/Prefix/READ/E-KEY/1/2") self.dKeyName = Name("/Prefix/READ/D-KEY/1/2") self.uKeyName = Name("/U/Key") self.uName = Name("/U") # Generate the E-KEY and D-KEY. params = RsaKeyParams() self.fixtureDKeyBlob = RsaAlgorithm.generateKey(params).getKeyBits() self.fixtureEKeyBlob = RsaAlgorithm.deriveEncryptKey( self.fixtureDKeyBlob).getKeyBits() # Generate the user key. self.fixtureUDKeyBlob = RsaAlgorithm.generateKey(params).getKeyBits() self.fixtureUEKeyBlob = RsaAlgorithm.deriveEncryptKey( self.fixtureUDKeyBlob).getKeyBits() # Load the C-KEY. self.fixtureCKeyBlob = Blob(AES_KEY, False) # Set up the keyChain. identityStorage = MemoryIdentityStorage() privateKeyStorage = MemoryPrivateKeyStorage() self.keyChain = KeyChain( IdentityManager(identityStorage, privateKeyStorage), NoVerifyPolicyManager()) # Initialize the storage. keyName = Name("/testname/DSK-123") self.certificateName = keyName.getSubName( 0, keyName.size() - 1).append("KEY").append( keyName.get(-1)).append("ID-CERT").append("0") identityStorage.addKey(keyName, KeyType.RSA, Blob(DEFAULT_RSA_PUBLIC_KEY_DER, False)) privateKeyStorage.setKeyPairForKeyName(keyName, KeyType.RSA, DEFAULT_RSA_PUBLIC_KEY_DER, DEFAULT_RSA_PRIVATE_KEY_DER)
def __init__(self, face, username, memoryContentCache): # Set up face self.face = face # Set up the keyChain. identityStorage = MemoryIdentityStorage() privateKeyStorage = MemoryPrivateKeyStorage() self.keyChain = KeyChain( IdentityManager(identityStorage, privateKeyStorage), NoVerifyPolicyManager()) identityName = Name(username) self.certificateName = self.keyChain.createIdentityAndCertificate( identityName) self.keyChain.getIdentityManager().setDefaultIdentity(identityName) self.face.setCommandSigningInfo(self.keyChain, self.certificateName) self.databaseFilePath = "../policy_config/test_producer.db" self.catalogDatabaseFilePath = "../policy_config/test_producer_catalog.db" try: os.remove(self.databaseFilePath) except OSError: # no such file pass try: os.remove(self.catalogDatabaseFilePath) except OSError: # no such file pass self.testDb = Sqlite3ProducerDb(self.databaseFilePath) self.catalogDb = Sqlite3ProducerDb(self.catalogDatabaseFilePath) # TODO: as of right now, catalog has a different suffix, so need another instance of producer; that producer cannot share # the same DB with the first producer, otherwise there won't be a self.onEncryptedKeys call; as the catalog producer uses # its own C-key, and that key won't be encrypted by an E-key as no interest goes out # This sounds like something problematic from the library prefix = Name(username) suffix = Name("fitness/physical_activity/time_location") self.producer = Producer(Name(prefix), suffix, self.face, self.keyChain, self.testDb) catalogSuffix = Name(suffix).append("catalog") self.catalogProducer = Producer(Name(prefix), catalogSuffix, self.face, self.keyChain, self.catalogDb) self.memoryContentCache = memoryContentCache return
def __init__(self, face): # Set up face self.face = face identityStorage = BasicIdentityStorage() privateKeyStorage = FilePrivateKeyStorage() self.keyChain = KeyChain( IdentityManager(identityStorage, privateKeyStorage), NoVerifyPolicyManager()) self.face.setCommandSigningInfo( self.keyChain, Name( "/org/openmhealth/KEY/ksk-1490231565751/ID-CERT/%FD%00%00%01Z%F8%B9%1Et" )) self.face.registerPrefix(Name("/org/openmhealth"), self.onInterest, self.onRegisterFailed)
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) identityStorage = MemoryIdentityStorage() privateKeyStorage = MemoryPrivateKeyStorage() keyChain = KeyChain(IdentityManager(identityStorage, privateKeyStorage), SelfVerifyPolicyManager(identityStorage)) # Initialize the storage. keyName = Name("/testname/DSK-123") certificateName = keyName.getSubName( 0, keyName.size() - 1).append("KEY").append( keyName[-1]).append("ID-CERT").append("0") identityStorage.addKey(keyName, KeyType.RSA, Blob(DEFAULT_RSA_PUBLIC_KEY_DER)) privateKeyStorage.setKeyPairForKeyName(keyName, KeyType.RSA, DEFAULT_RSA_PUBLIC_KEY_DER, DEFAULT_RSA_PRIVATE_KEY_DER) keyChain.verifyData(reDecodedData, makeOnVerified("Re-decoded Data"), makeOnVerifyFailed("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, certificateName) dump("") dump("Freshly-signed Data:") dumpData(freshData) keyChain.verifyData(freshData, makeOnVerified("Freshly-signed Data"), makeOnVerifyFailed("Freshly-signed Data"))
def test_verify_digest_sha256(self): # Create a KeyChain but we don't need to add keys. identityStorage = MemoryIdentityStorage() keyChain = KeyChain( IdentityManager(identityStorage, MemoryPrivateKeyStorage()), SelfVerifyPolicyManager(identityStorage)) interest = Interest(Name("/test/signed-interest")) keyChain.signWithSha256(interest) # We create 'mock' objects to replace callbacks since we're not # interested in the effect of the callbacks themselves. failedCallback = Mock() verifiedCallback = Mock() keyChain.verifyInterest(interest, verifiedCallback, failedCallback) self.assertEqual(failedCallback.call_count, 0, 'Signature verification failed') self.assertEqual(verifiedCallback.call_count, 1, 'Verification callback was not used.')
def createVerifyKeyChain(): """ Create an in-memory KeyChain with a default public key for verifying. :return: A new KeyChain. :rtype: KeyChain """ identityStorage = MemoryIdentityStorage() keyChain = KeyChain( IdentityManager(identityStorage, MemoryPrivateKeyStorage()), SelfVerifyPolicyManager(identityStorage)) # Initialize the storage. keyName = Name("/testname/DSK-123") identityStorage.addKey(keyName, KeyType.RSA, Blob(DEFAULT_RSA_PUBLIC_KEY_DER, False)) return keyChain
def __init__(self, name=None): # PLC Simulation self.slaveid = 0x00 self.name = name if not name: self.name = socket.gethostname() self.plcrpcclient = PLCRPCClient(rpc_server="0.0.0.0", rpc_port=8000, plc=self.name) self.registered = False self.speed = 0.2 self.db = {} # NDN self._callbackCount = 0 self.primary_prefix = "/example" self.names = [] self.freshnessPeriod = 2000 # in milliseconds (2000 = 2s). self.identify_manager = IdentityManager() self.keyChain = KeyChain(self.identify_manager)
def __init__(self, transport = None, conn = None): """ Initialize the network and security classes for the node """ super(BaseNode, self).__init__() self.faceTransport = transport self.faceConn = conn self._identityStorage = BasicIdentityStorage() self._identityManager = IdentityManager(self._identityStorage, FilePrivateKeyStorage()) self._policyManager = IotPolicyManager(self._identityStorage) # hopefully there is some private/public key pair available self._keyChain = KeyChain(self._identityManager, self._policyManager) self._registrationFailures = 0 self._prepareLogging() self._setupComplete = False
def setUp(self): self.decryptionKeys = {} # key: Name, value: Blob self.encryptionKeys = {} # key: Name, value: Data # Reuse the policy_config subdirectory for the temporary SQLite files. self.databaseFilePath = "policy_config/test.db" try: os.remove(self.databaseFilePath) except OSError: # no such file pass # Set up the keyChain. identityStorage = MemoryIdentityStorage() privateKeyStorage = MemoryPrivateKeyStorage() self.keyChain = KeyChain( IdentityManager(identityStorage, privateKeyStorage), NoVerifyPolicyManager()) identityName = Name("TestProducer") self.certificateName = self.keyChain.createIdentityAndCertificate(identityName) self.keyChain.getIdentityManager().setDefaultIdentity(identityName)
def __init__(self, face, groupManagerName, dataType, readAccessName, dKeyDatabaseFilePath): # Set up face self.face = face #self.loop = eventLoop # Set up the keyChain. identityStorage = MemoryIdentityStorage() privateKeyStorage = MemoryPrivateKeyStorage() self.keyChain = KeyChain( IdentityManager(identityStorage, privateKeyStorage), NoVerifyPolicyManager()) self.certificateName = self.keyChain.createIdentityAndCertificate( groupManagerName) self.face.setCommandSigningInfo(self.keyChain, self.certificateName) self.dKeyDatabaseFilePath = dKeyDatabaseFilePath try: os.remove(self.dKeyDatabaseFilePath) except OSError: # no such file pass self.manager = GroupManager( groupManagerName, dataType, Sqlite3GroupManagerDb(self.dKeyDatabaseFilePath), 2048, 1, self.keyChain) self.memoryContentCache = MemoryContentCache(self.face) self.memoryContentCache.registerPrefix( Name(groupManagerName).append("READ"), self.onRegisterFailed, self.onDataNotFound) self.face.registerPrefix(readAccessName, self.onAccessInterest, self.onAccessTimeout) self.updateGroupKeys = False return
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() dump(freshInterest.toUri()) identityStorage = MemoryIdentityStorage() privateKeyStorage = MemoryPrivateKeyStorage() keyChain = KeyChain(IdentityManager(identityStorage, privateKeyStorage), SelfVerifyPolicyManager(identityStorage)) # Initialize the storage. keyName = Name("/testname/DSK-123") certificateName = keyName.getSubName( 0, keyName.size() - 1).append("KEY").append( keyName[-1]).append("ID-CERT").append("0") identityStorage.addKey(keyName, KeyType.RSA, Blob(DEFAULT_RSA_PUBLIC_KEY_DER)) privateKeyStorage.setKeyPairForKeyName(keyName, KeyType.RSA, DEFAULT_RSA_PUBLIC_KEY_DER, DEFAULT_RSA_PRIVATE_KEY_DER) # Make a Face just so that we can sign the interest. face = Face("localhost") face.setCommandSigningInfo(keyChain, certificateName) face.makeCommandInterest(freshInterest) reDecodedFreshInterest = Interest() reDecodedFreshInterest.wireDecode(freshInterest.wireEncode()) dump("") dump("Re-decoded fresh Interest:") dumpInterest(reDecodedFreshInterest) keyChain.verifyInterest(reDecodedFreshInterest, makeOnVerified("Freshly-signed Interest"), makeOnVerifyFailed("Freshly-signed Interest"))
def startFileSync(): global EXIT screenName = promptAndInput("Enter your name: ") defaultHubPrefix = "ndn/no/ntnu" hubPrefix = promptAndInput("Enter your hub prefix [" + defaultHubPrefix + "]: ") if hubPrefix == "": hubPrefix = defaultHubPrefix defaultpkList = "pklist" pkListName = promptAndInput("Sync with public key list [" + defaultpkList + "]: ") if pkListName == "": pkListName = defaultpkList host = "localhost" # host = "129.241.208.115" logging.info("Connecting to " + host + ", public Key List: " + pkListName + ", Name: " + screenName) # Set up the key chain. face = Face(host) identityStorage = MemoryIdentityStorage() privateKeyStorage = MemoryPrivateKeyStorage() # privateKeyStorage = OSXPrivateKeyStorage() identityManager = IdentityManager(identityStorage, privateKeyStorage) # identityManager.createIdentity(Name("/name/")) keyChain = KeyChain(identityManager, NoVerifyPolicyManager()) keyChain.setFace(face) keyName = Name("/testname/DSK-123") certificateName = keyName.getSubName(0, keyName.size() - 1).append("KEY").append(keyName[-1]).append("ID-CERT").append("0") identityStorage.addKey(keyName, KeyType.RSA, Blob(DEFAULT_RSA_PUBLIC_KEY_DER)) privateKeyStorage.setKeyPairForKeyName(keyName, KeyType.RSA, DEFAULT_RSA_PUBLIC_KEY_DER, DEFAULT_RSA_PRIVATE_KEY_DER) face.setCommandSigningInfo(keyChain, certificateName) # keyName = Name("/ndn/no/ntnu/stud/haakonmo/ksk-1426537450856") # certificateName = Name("/ndn/no/ntnu/KEY/stud/haakonmo/ksk-1426537450856/ID-CERT/%FD%00%00%01L%26%D9E%92") # publicKey = privateKeyStorage.getPublicKey(keyName) # identityStorage.addKey(keyName, publicKey.getKeyType(), publicKey.getKeyDer()) # face.setCommandSigningInfo(keyChain, certificateName) # print(identityStorage.getCertificate(certificateName)) # print(identityStorage.getKey(keyName)) path = './files/' fileSyncer = FileSync(screenName, pkListName, Name(hubPrefix), face, keyChain, certificateName, path) fileSyncer.initial() fileWatcher = FileWatch(fileSyncer, path) # TODO: # 1. Generate new public key or use existing? # 2. Watch new public key # 3. sendUpdatedPublicKey if key is changed # 4. Download and store other keys # 5. Verify data packet while not EXIT: isReady, _, _ = select.select([sys.stdin], [], [], 0) if len(isReady) != 0: input = promptAndInput("") if input == "leave" or input == "exit": EXIT = True break #fileSyncer.onFileUpdate(input) fileSyncer.face.processEvents() # We need to sleep for a few milliseconds so we don't use 100% of the CPU. time.sleep(0.01) fileSyncer.unsubscribe() startTime = FileSync.getNowMilliseconds() while True: if FileSync.getNowMilliseconds() - startTime >= 1000.0: break face.processEvents() time.sleep(0.01) # Shutdown all services fileSyncer.face.shutdown() fileWatcher.stopFileWatch()
def main(): # Uncomment these lines to print ChronoSync debug messages. # logging.getLogger('').addHandler(logging.StreamHandler(sys.stdout)) # logging.getLogger('').setLevel(logging.INFO) defaultUserPrefix = "com/newspaper/USER/bob" userPrefix = promptAndInput("Enter user prefix: [" + defaultUserPrefix + "]") if userPrefix == "": userPrefix = defaultUserPrefix defaultNamespacePrefix = "/ndn/hackathon/cnl-demo/slides" #"com/newspaper" namespacePrefix = promptAndInput("Enter namespace prefix [" + defaultNamespacePrefix + "]: ") if namespacePrefix == "": namespacePrefix = defaultNamespacePrefix host = "localhost" #"memoria.ndn.ucla.edu" print("Connecting to " + host) print("") # Set up the key chain. face = Face(host) identityStorage = MemoryIdentityStorage() privateKeyStorage = MemoryPrivateKeyStorage() keyChain = KeyChain(IdentityManager(identityStorage, privateKeyStorage), NoVerifyPolicyManager()) keyChain.setFace(face) keyName = Name("/testname/DSK-123") certificateName = keyName.getSubName(0, keyName.size() - 1).append( "KEY").append(keyName[-1]).append("ID-CERT").append("0") identityStorage.addKey(keyName, KeyType.RSA, Blob(DEFAULT_RSA_PUBLIC_KEY_DER)) privateKeyStorage.setKeyPairForKeyName( keyName, KeyType.RSA, DEFAULT_RSA_PUBLIC_KEY_DER, DEFAULT_RSA_PRIVATE_KEY_DER) face.setCommandSigningInfo(keyChain, certificateName) newspaper = Namespace(namespacePrefix) def onContentSet(namespace, contentNamespace, callbackId): global currentSlideName if contentNamespace == namespace: print("content size "+str(contentNamespace.content.size())) currentSlideName = contentNamespace.getName() displayImage(contentNamespace.content.toRawStr(), contentNamespace.getName().toUri()) # dump("Got segmented content ", contentNamespace.content.toRawStr()) def onNewName(namespace, addedNamespace, callbackId): print("namespace ("+addedNamespace.getName().toUri()+") added to "+namespace.getName().toUri()) if addedNamespace.getName().get(-1).isSegment() and addedNamespace.getName().get(-1).toSegment() == 0: addedNamespace.getParent().addOnContentSet(onContentSet) SegmentedContent(addedNamespace.getParent()).start() newspaper.addOnNameAdded(onNewName) newspaper.setFace(face) namesync = NameSyncHandler(newspaper, userPrefix, keyChain, certificateName) # The main loop to process Chat while checking stdin to send a message. print("Enter your namespace update. To quit, enter \"exit\".") def process(): # while True: # Set timeout to 0 for an immediate check. isReady, _, _ = select.select([sys.stdin], [], [], 0) if len(isReady) != 0: input = promptAndInput("") if input == "exit": stopGui() # We will send the leave message below. # break # before producer has namespace.publish call, we manually call onNameAdded as a hack to publish namesync.onNameAdded(None, Namespace(Name(input)), 0, True) face.processEvents() if root: root.after(100, process) def leftKey(event): global currentSlideName allVersions = newspaper.getChildComponents() currentVersion = currentSlideName[-1] selected = allVersions[0] for c in allVersions: print(str(c.toVersion())) if c.toVersion() == currentVersion.toVersion(): break selected = c currentSlideName = Name(newspaper.getName()).append(selected) displayImage(newspaper.getChild(selected).content.toRawStr(), currentSlideName.toUri()) def rightKey(event): global currentSlideName allVersions = newspaper.getChildComponents() currentVersion = currentSlideName[-1] selected = None for c in allVersions[::-1]: if c.toVersion() == currentVersion.toVersion(): break selected = c if selected: currentSlideName = Name(newspaper.getName()).append(selected) displayImage(newspaper.getChild(selected).content.toRawStr(), currentSlideName.toUri()) else: print("no slides to show") runGui(process, leftKey, rightKey)
def setUp(self): # Reuse the policy_config subdirectory for the temporary SQLite files. self.dKeyDatabaseFilePath = "policy_config/manager-d-key-test.db" try: os.remove(self.dKeyDatabaseFilePath) except OSError: # no such file pass self.eKeyDatabaseFilePath = "policy_config/manager-e-key-test.db" try: os.remove(self.eKeyDatabaseFilePath) except OSError: # no such file pass self.intervalDatabaseFilePath = "policy_config/manager-interval-test.db" try: os.remove(self.intervalDatabaseFilePath) except OSError: # no such file pass self.groupKeyDatabaseFilePath = "policy_config/manager-group-key-test.db" try: os.remove(self.groupKeyDatabaseFilePath) except OSError: # no such file pass params = RsaKeyParams() memberDecryptKey = RsaAlgorithm.generateKey(params) self.decryptKeyBlob = memberDecryptKey.getKeyBits() memberEncryptKey = RsaAlgorithm.deriveEncryptKey(self.decryptKeyBlob) self.encryptKeyBlob = memberEncryptKey.getKeyBits() # Generate the certificate. self.certificate = IdentityCertificate() self.certificate.setName(Name("/ndn/memberA/KEY/ksk-123/ID-CERT/123")) contentPublicKey = PublicKey(self.encryptKeyBlob) self.certificate.setPublicKeyInfo(contentPublicKey) self.certificate.setNotBefore(0) self.certificate.setNotAfter(0) self.certificate.encode() signatureInfoBlob = Blob(SIG_INFO, False) signatureValueBlob = Blob(SIG_VALUE, False) signature = TlvWireFormat.get().decodeSignatureInfoAndValue( signatureInfoBlob.buf(), signatureValueBlob.buf()) self.certificate.setSignature(signature) self.certificate.wireEncode() # Set up the keyChain. identityStorage = MemoryIdentityStorage() privateKeyStorage = MemoryPrivateKeyStorage() self.keyChain = KeyChain( IdentityManager(identityStorage, privateKeyStorage), NoVerifyPolicyManager()) identityName = Name("TestGroupManager") self.keyChain.createIdentityAndCertificate(identityName) self.keyChain.getIdentityManager().setDefaultIdentity(identityName)
def main(): """ Call startRepoWatch and register a prefix so that SendSegments will answer interests from the repo to send data packets for the watched prefix. When all the data is sent (or an error), call startRepoWatch. """ repoCommandPrefix = Name("/ndn/edu/ucla/remap/bms-repo/1") repoDataPrefix = Name("/ndn/edu/ucla/remap/bms") nowMilliseconds = int(time.time() * 1000.0) watchPrefix = Name(repoDataPrefix).append("testwatch").appendVersion( nowMilliseconds) # The default Face will connect using a Unix socket, or to "localhost". face = Face() # Use the system default key chain and certificate name to sign commands. from pyndn.security.identity import IdentityManager, FilePrivateKeyStorage, BasicIdentityStorage keyChain = KeyChain( IdentityManager(BasicIdentityStorage(), FilePrivateKeyStorage())) face.setCommandSigningInfo(keyChain, keyChain.getDefaultCertificateName()) # Register the prefix and start the repo watch at the same time. enabled = [True] sendSegments = SendSegments(keyChain, keyChain.getDefaultCertificateName(), enabled) dump("Register prefix", watchPrefix.toUri()) face.registerPrefix(watchPrefix, sendSegments.onInterest, sendSegments.onRegisterFailed) print("Here") def onRepoWatchStarted(): dump("Watch started for", watchPrefix.toUri()) def onFailed(): enabled[0] = False startRepoWatch(face, repoCommandPrefix, watchPrefix, onRepoWatchStarted, onFailed) # Run until all the data is sent. while enabled[0]: face.processEvents() # We need to sleep for a few milliseconds so we don't use 100% of the CPU. time.sleep(0.01) def onRepoWatchStopped(): dump("Watch stopped for", watchPrefix.toUri()) enabled[0] = False stopRepoWatch(face, repoCommandPrefix, watchPrefix, onRepoWatchStopped, onFailed) # Run until stopRepoWatch finishes. enabled[0] = True while enabled[0]: face.processEvents() # We need to sleep for a few milliseconds so we don't use 100% of the CPU. time.sleep(0.01) face.shutdown()
def __init__(self, face): # Set up face self.face = face self.databaseFilePath = "policy_config/test_consumer.db" try: os.remove(self.databaseFilePath) except OSError: # no such file pass self.groupName = Name("/org/openmhealth/haitao") # Set up the keyChain. identityStorage = BasicIdentityStorage() privateKeyStorage = FilePrivateKeyStorage() self.keyChain = KeyChain( IdentityManager(identityStorage, privateKeyStorage), NoVerifyPolicyManager()) # Authorized identity identityName = Name("/org/openmhealth/dvu-python-3") # Unauthorized identity #identityName = Name("/org/openmhealth/dvu-python-1") self.certificateName = self.keyChain.createIdentityAndCertificate( identityName) self.face.setCommandSigningInfo(self.keyChain, self.certificateName) consumerKeyName = IdentityCertificate.certificateNameToPublicKeyName( self.certificateName) consumerCertificate = identityStorage.getCertificate( self.certificateName) self.consumer = Consumer(face, self.keyChain, self.groupName, identityName, Sqlite3ConsumerDb(self.databaseFilePath)) # TODO: Read the private key to decrypt d-key...this may or may not be ideal base64Content = None with open( privateKeyStorage.nameTransform(consumerKeyName.toUri(), ".pri")) as keyFile: print privateKeyStorage.nameTransform(consumerKeyName.toUri(), ".pri") base64Content = keyFile.read() #print base64Content der = Blob(base64.b64decode(base64Content), False) self.consumer.addDecryptionKey(consumerKeyName, der) self.memoryContentCache = MemoryContentCache(self.face) self.memoryContentCache.registerPrefix(identityName, self.onRegisterFailed, self.onDataNotFound) self.memoryContentCache.add(consumerCertificate) accessRequestInterest = Interest( Name(self.groupName).append("read_access_request").append( self.certificateName).appendVersion(int(time.time()))) self.face.expressInterest(accessRequestInterest, self.onAccessRequestData, self.onAccessRequestTimeout) print "Access request interest name: " + accessRequestInterest.getName( ).toUri() self.consumeCatalog = True return
def benchmarkEncodeDataSeconds(nIterations, useComplex, useCrypto): """ 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. :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. identityStorage = MemoryIdentityStorage() privateKeyStorage = MemoryPrivateKeyStorage() keyChain = KeyChain(IdentityManager(identityStorage, privateKeyStorage), SelfVerifyPolicyManager(identityStorage)) keyName = Name("/testname/DSK-123") certificateName = keyName.getSubName( 0, keyName.size() - 1).append("KEY").append( keyName[-1]).append("ID-CERT").append("0") identityStorage.addKey(keyName, KeyType.RSA, Blob(DEFAULT_RSA_PUBLIC_KEY_DER)) privateKeyStorage.setKeyPairForKeyName(keyName, KeyType.RSA, DEFAULT_RSA_PUBLIC_KEY_DER, DEFAULT_RSA_PRIVATE_KEY_DER) # Set up signatureBits in case useCrypto is false. signatureBits = Blob(bytearray(256)) emptyBlob = Blob([]) 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, certificateName) 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)
def main(): # Uncomment these lines to print ChronoSync debug messages. # logging.getLogger('').addHandler(logging.StreamHandler(sys.stdout)) # logging.getLogger('').setLevel(logging.INFO) screenName = promptAndInput("Enter your chat username: "******"ndn/edu/ucla/remap" hubPrefix = promptAndInput("Enter your hub prefix [" + defaultHubPrefix + "]: ") if hubPrefix == "": hubPrefix = defaultHubPrefix defaultChatRoom = "ndnchat" chatRoom = promptAndInput("Enter the chatroom name [" + defaultChatRoom + "]: ") if chatRoom == "": chatRoom = defaultChatRoom host = "localhost" print("Connecting to " + host + ", Chatroom: " + chatRoom + ", Username: "******"") # Set up the key chain. face = Face(host) identityStorage = MemoryIdentityStorage() privateKeyStorage = MemoryPrivateKeyStorage() keyChain = KeyChain(IdentityManager(identityStorage, privateKeyStorage), NoVerifyPolicyManager()) keyChain.setFace(face) keyName = Name("/testname/DSK-123") certificateName = keyName.getSubName( 0, keyName.size() - 1).append("KEY").append( keyName[-1]).append("ID-CERT").append("0") identityStorage.addKey(keyName, KeyType.RSA, Blob(DEFAULT_RSA_PUBLIC_KEY_DER)) privateKeyStorage.setKeyPairForKeyName(keyName, KeyType.RSA, DEFAULT_RSA_PUBLIC_KEY_DER, DEFAULT_RSA_PRIVATE_KEY_DER) face.setCommandSigningInfo(keyChain, certificateName) chat = Chat(screenName, chatRoom, Name(hubPrefix), face, keyChain, certificateName) # The main loop to process Chat while checking stdin to send a message. print("Enter your chat message. To quit, enter \"leave\" or \"exit\".") while True: # Set timeout to 0 for an immediate check. isReady, _, _ = select.select([sys.stdin], [], [], 0) if len(isReady) != 0: input = promptAndInput("") if input == "leave" or input == "exit": # We will send the leave message below. break chat.sendMessage(input) face.processEvents() # We need to sleep for a few milliseconds so we don't use 100% of the CPU. time.sleep(0.01) # The user entered the command to leave. chat.leave() # Wait a little bit to allow other applications to fetch the leave message. startTime = Chat.getNowMilliseconds() while True: if Chat.getNowMilliseconds() - startTime >= 1000.0: break face.processEvents() time.sleep(0.01)
class Bootstrap(object): """ Create a Bootstrap object. Bootstrap object provides interface for setting up KeyChain, default certificate name; (as a producer) requesting publishing authorization from controller; and (as a consumer) keeping track of changes :param face: the face for communicating with a local / remote forwarder :type face: ThreadsafeFace TODO: support Face as well as ThreadsafeFace """ def __init__(self, face): self._defaultIdentity = None self._defaultCertificateName = None self._controllerName = None self._controllerCertificate = None self._applicationName = "" self._identityManager = IdentityManager(BasicIdentityStorage(), FilePrivateKeyStorage()) self._policyManager = ConfigPolicyManager() self._policyManager.config.read("validator \n \ { \n \ rule \n \ { \n \ id \"initial rule\" \n \ for data \n \ checker \n \ { \n \ type hierarchical \n \ } \n \ } \n \ }", "initial-schema") # keyChain is what we return to the application after successful setup # TODO: should we separate keyChain from internal KeyChain used to verify trust schemas? self._keyChain = KeyChain(self._identityManager, self._policyManager) self._face = face # setFace for keyChain or else it won't be able to express interests for certs self._keyChain.setFace(self._face) self._certificateContentCache = MemoryContentCache(face) self._trustSchemas = dict() ############################################### # Initial keyChain and defaultCertificate setup ############################################### def setupDefaultIdentityAndRoot(self, defaultIdentityOrFileName, signerName = None, onSetupComplete = None, onSetupFailed = None): """ Sets up the keyChain, default key name and certificate name according to given configuration. If successful, this KeyChain and default certificate name will be returned to the application, which can be passed to instances like Consumer, Discovery, etc :param defaultIdentityOrFileName: if str, the name of the configuration file; if Name, the default identity name of this IoT node. The node will use the default keys and certificate of that identity name. :type defaultIdentityOrFileName: Name or str :param signerName: (optional) the expected signing identity of the certificate :type signerName: Name :param onSetupComplete: (optional) onSetupComplete(Name, KeyChain) will be called if set up's successful :type onSetupComplete: function object :param onSetupFailed: (optional) onSetupFailed(msg) will be called if setup fails :type onSetupFailed: function object """ def helper(identityName, signerName): try: self._defaultIdentity = identityName self._defaultCertificateName = self._identityManager.getDefaultCertificateNameForIdentity(self._defaultIdentity) self._defaultKeyName = self._identityManager.getDefaultKeyNameForIdentity(identityName) except SecurityException: msg = "Identity " + identityName.toUri() + " in configuration does not exist. Please configure the device with this identity first." if onSetupFailed: onSetupFailed(msg) return if not self._defaultCertificateName: msg = "Unable to get default certificate name for identity " + identityName.toUri() + ". Please configure the device with this identity first." if onSetupFailed: onSetupFailed(msg) return if not self._defaultKeyName: msg = "Unable to get default key name for identity " + identityName.toUri() + ". Please configure the device with this identity first." if onSetupFailed: onSetupFailed(msg) return # Note we'll not be able to issue face commands before this point self._face.setCommandSigningInfo(self._keyChain, self._defaultCertificateName) # Serve our own certificate self._certificateContentCache.registerPrefix(Name(self._defaultCertificateName).getPrefix(-1), self.onRegisterFailed) self._certificateContentCache.add(self._keyChain.getCertificate(self._defaultCertificateName)) actualSignerName = self._keyChain.getCertificate(self._defaultCertificateName).getSignature().getKeyLocator().getKeyName() if not signerName: print "Deriving from " + actualSignerName.toUri() + " for controller name" else: if signerName and actualSignerName.toUri() != signerName.toUri(): msg = "Configuration signer names mismatch: expected " + signerName.toUri() + "; got " + actualSignerName.toUri() print msg if onSetupFailed: onSetupFailed(msg) self._controllerName = self.getIdentityNameFromCertName(actualSignerName) print "Controller name: " + self._controllerName.toUri() try: self._controllerCertificate = self._keyChain.getCertificate(self._identityManager.getDefaultCertificateNameForIdentity(self._controllerName)) # TODO: this does not seem a good approach, implementation-wise and security implication self._policyManager._certificateCache.insertCertificate(self._controllerCertificate) if onSetupComplete: onSetupComplete(Name(self._defaultCertificateName), self._keyChain) except SecurityException as e: print "don't have controller certificate " + actualSignerName.toUri() + " yet" controllerCertInterest = Interest(Name(actualSignerName)) controllerCertInterest.setInterestLifetimeMilliseconds(4000) controllerCertRetries = 3 self._face.expressInterest(controllerCertInterest, lambda interest, data: self.onControllerCertData(interest, data, onSetupComplete, onSetupFailed), lambda interest: self.onControllerCertTimeout(interest, onSetupComplete, onSetupFailed, controllerCertRetries)) return if isinstance(defaultIdentityOrFileName, basestring): confObj = self.processConfiguration(defaultIdentityOrFileName) if "identity" in confObj: if confObj["identity"] == "default": # TODO: handling the case where no default identity is present defaultIdentity = self._keyChain.getDefaultIdentity() else: defaultIdentity = Name(confObj["identity"]) else: defaultIdentity = self._keyChain.getDefaultIdentity() # TODO: handling signature with direct bits instead of keylocator keyname if "signer" in confObj: if confObj["signer"] == "default": signerName = None else: signerName = Name(confObj["signer"]) else: signerName = None print "Deriving from " + signerName.toUri() + " for controller name" helper(defaultIdentity, signerName) else: if isinstance(defaultIdentityOrFileName, Name): helper(defaultIdentityOrFileName, signerName) else: raise RuntimeError("Please call setupDefaultIdentityAndRoot with identity name and root key name") return def onControllerCertData(self, interest, data, onSetupComplete, onSetupFailed): # TODO: verification rule for received self-signed cert. # So, if a controller comes masquerading in at this point with the right name, it is problematic. Similar with ndn-pi's implementation self._controllerCertificate = IdentityCertificate(data) # insert root certificate so that we could verify initial trust schemas # TODO: this does not seem a good approach, implementation-wise and security implication self._keyChain.getPolicyManager()._certificateCache.insertCertificate(self._controllerCertificate) try: self._identityManager.addCertificate(self._controllerCertificate) except SecurityException as e: print str(e) for schema in self._trustSchemas: # TODO: remove the concept of pending-schema if "pending-schema" in self._trustSchemas[schema]: self._keyChain.verifyData(self._trustSchemas[schema]["pending-schema"], self.onSchemaVerified, self.onSchemaVerificationFailed) if onSetupComplete: onSetupComplete(Name(self._defaultCertificateName), self._keyChain) return def onControllerCertTimeout(self, interest, onSetupComplete, onSetupFailed, controllerCertRetries): print "Controller certificate interest times out" newInterest = Interest(interest) newInterest.refreshNonce() if controllerCertRetries == 0: if onSetupFailed: onSetupFailed("Controller certificate interest times out") else: print "Set up failed: controller certificate interest times out" else: self._face.expressInterest(newInterest, lambda interest, data: self.onControllerCertData(interest, data, onSetupComplete, onSetupFailed), lambda interest: self.onControllerCertTimeout(interest, onSetupComplete, onSetupFailed, controllerCertRetries - 1)) return ######################################################### # Handling application consumption (trust schema updates) ######################################################### # TODO: if trust schema gets over packet size limit, segmentation def startTrustSchemaUpdate(self, appPrefix, onUpdateSuccess = None, onUpdateFailed = None): """ Starts trust schema update for under an application prefix: initial interest asks for the rightMostChild, and later interests are sent with previous version excluded. Each verified trust schema will trigger onUpdateSuccess and update the ConfigPolicyManager for the keyChain in this instance, and unverified ones will trigger onUpdateFailed. The keyChain and trust anchor should be set up using setupDefaultIdentityAndRoot before calling this method. :param appPrefix: the prefix to ask trust schema for. (interest name: /<prefix>/_schema) :type appPrefix: Name :param onUpdateSuccess: (optional) onUpdateSuccess(trustSchemaStr, isInitial) is called when update succeeds :type onUpdateSuccess: function object :param onUpdateFailed: (optional) onUpdateFailed(msg) is called when update fails :type onUpdateFailed: function object """ namespace = appPrefix.toUri() if namespace in self._trustSchemas: if self._trustSchemas[namespace]["following"] == True: print "Already following trust schema under this namespace!" return self._trustSchemas[namespace]["following"] = True else: self._trustSchemas[namespace] = {"following": True, "version": 0, "is-initial": True} initialInterest = Interest(Name(namespace).append("_schema")) initialInterest.setChildSelector(1) self._face.expressInterest(initialInterest, lambda interest, data: self.onTrustSchemaData(interest, data, onUpdateSuccess, onUpdateFailed), lambda interest: self.onTrustSchemaTimeout(interest, onUpdateSuccess, onUpdateFailed)) return def stopTrustSchemaUpdate(self): print "stopTrustSchemaUpdate not implemented" return def onSchemaVerified(self, data, onUpdateSuccess, onUpdateFailed): print "trust schema verified: " + data.getName().toUri() version = data.getName().get(-1) namespace = data.getName().getPrefix(-2).toUri() if not (namespace in self._trustSchemas): print "unexpected: received trust schema for application namespace that's not being followed; malformed data name?" return if version.toVersion() <= self._trustSchemas[namespace]["version"]: msg = "Got out-of-date trust schema" print msg if onUpdateFailed: onUpdateFailed(msg) return self._trustSchemas[namespace]["version"] = version.toVersion() if "pending-schema" in self._trustSchemas[namespace] and self._trustSchemas[namespace]["pending-schema"].getName().toUri() == data.getName().toUri(): # we verified a pending trust schema, don't need to keep that any more del self._trustSchemas[namespace]["pending-schema"] self._trustSchemas[namespace]["trust-schema"] = data.getContent().toRawStr() print self._trustSchemas[namespace]["trust-schema"] # TODO: what about trust schema for discovery, is discovery its own application? newInterest = Interest(Name(data.getName()).getPrefix(-1)) newInterest.setChildSelector(1) exclude = Exclude() exclude.appendAny() exclude.appendComponent(version) newInterest.setExclude(exclude) self._face.expressInterest(newInterest, lambda interest, data: self.onTrustSchemaData(interest, data, onUpdateSuccess, onUpdateFailed), lambda interest: self.onTrustSchemaTimeout(interest, onUpdateSuccess, onUpdateFailed)) # Note: this changes the verification rules for root cert, future trust schemas as well; ideally from the outside this doesn't have an impact, but do we want to avoid this? # Per reset function in ConfigPolicyManager; For now we don't call reset as we still want root cert in our certCache, instead of asking for it again (when we want to verify) each time we update the trust schema self._policyManager.config = BoostInfoParser() self._policyManager.config.read(self._trustSchemas[namespace]["trust-schema"], "updated-schema") if onUpdateSuccess: onUpdateSuccess(data.getContent().toRawStr(), self._trustSchemas[namespace]["is-initial"]) self._trustSchemas[namespace]["is-initial"] = False return def onSchemaVerificationFailed(self, data, reason, onUpdateSuccess, onUpdateFailed): print "trust schema verification failed: " + reason namespace = data.getName().getPrefix(-2).toUri() if not (namespace in self._trustSchemas): print "unexpected: received trust schema for application namespace that's not being followed; malformed data name?" return newInterest = Interest(Name(data.getName()).getPrefix(-1)) newInterest.setChildSelector(1) exclude = Exclude() exclude.appendAny() exclude.appendComponent(Name.Component.fromVersion(self._trustSchemas[namespace]["version"])) newInterest.setExclude(exclude) # Don't immediately ask for potentially the same content again if verification fails self._face.callLater(4000, lambda : self._face.expressInterest(newInterest, lambda interest, data: self.onTrustSchemaData(interest, data, onUpdateSuccess, onUpdateFailed), lambda interest: self.onTrustSchemaTimeout(interest, onUpdateSuccess, onUpdateFailed))) return def onTrustSchemaData(self, interest, data, onUpdateSuccess, onUpdateFailed): print("Trust schema received: " + data.getName().toUri()) namespace = data.getName().getPrefix(-2).toUri() # Process newly received trust schema if not self._controllerCertificate: # we don't yet have the root certificate fetched, so we store this cert for now print "Controller certificate not yet present, verify once it's in place" self._trustSchemas[namespace]["pending-schema"] = data else: # we veriy the received trust schema, should we use an internal KeyChain instead? self._keyChain.verifyData(data, lambda data: self.onSchemaVerified(data, onUpdateSuccess, onUpdateFailed), lambda data, reason: self.onSchemaVerificationFailed(data, reason, onUpdateSuccess, onUpdateFailed)) return def onTrustSchemaTimeout(self, interest, onUpdateSuccess, onUpdateFailed): print("Trust schema interest times out: " + interest.getName().toUri()) newInterest = Interest(interest) newInterest.refreshNonce() self._face.expressInterest(newInterest, lambda interest, data: self.onTrustSchemaData(interest, data, onUpdateSuccess, onUpdateFailed), lambda interest: self.onTrustSchemaTimeout(interest, onUpdateSuccess, onUpdateFailed)) return ############################################### # Handling application producing authorizations ############################################### # Wrapper for sendAppRequest, fills in already configured defaultCertificateName def requestProducerAuthorization(self, dataPrefix, appName, onRequestSuccess = None, onRequestFailed = None): """ Requests producing authorization for a data prefix: commandInterest is sent out to the controller, using /<controller identity>/requests/<encoded-application-parameters>/<signed-interest-suffix> where encoded-application-parameters is a ProtobufTlv encoding of {appPrefix, certificateName, appName} The keyChain, trust anchor and controller name should be set up using setupDefaultIdentityAndRoot before calling this method. :param dataPrefix: the prefix to request publishing for :type dataPrefix: Name :param appName: the application name to request publishing for :type appName: str :param onRequestSuccess: (optional) onRequestSuccess() is called when a valid response if received for the request :type onRequestSuccess: function object :param onRequestFailed: (optional) onRequestFailed(msg) is called when request fails :type onRequestFailed: function object """ # TODO: update logic on this part, should the presence of default certificate name be mandatory? # And allow application developer to send app request to a configured root/controller? if not self._defaultCertificateName: raise RuntimeError("Default certificate is missing! Try setupDefaultIdentityAndRoot first?") return self.sendAppRequest(self._defaultCertificateName, dataPrefix, appName, onRequestSuccess, onRequestFailed) def sendAppRequest(self, certificateName, dataPrefix, applicationName, onRequestSuccess, onRequestFailed): message = AppRequestMessage() for component in range(certificateName.size()): message.command.idName.components.append(certificateName.get(component).toEscapedString()) for component in range(dataPrefix.size()): message.command.dataPrefix.components.append(dataPrefix.get(component).toEscapedString()) message.command.appName = applicationName paramComponent = ProtobufTlv.encode(message) requestInterest = Interest(Name(self._controllerName).append("requests").append(paramComponent)) requestInterest.setInterestLifetimeMilliseconds(4000) self._face.makeCommandInterest(requestInterest) appRequestTimeoutCnt = 3 self._face.expressInterest(requestInterest, lambda interest, data : self.onAppRequestData(interest, data, onRequestSuccess, onRequestFailed), lambda interest : self.onAppRequestTimeout(interest, onRequestSuccess, onRequestFailed, appRequestTimeoutCnt)) print "Application publish request sent: " + requestInterest.getName().toUri() return def onAppRequestData(self, interest, data, onRequestSuccess, onRequestFailed): print "Got application publishing request data" def onVerified(data): responseObj = json.loads(data.getContent().toRawStr()) if responseObj["status"] == "200": if onRequestSuccess: onRequestSuccess() else: print "onSetupComplete" else: print "Verified content: " + data.getContent().toRawStr() if onRequestFailed: onRequestFailed(data.getContent().toRawStr()) def onVerifyFailed(data, reason): msg = "Application request response verification failed: " + reason print msg if onRequestFailed: onRequestFailed(msg) self._keyChain.verifyData(data, onVerified, onVerifyFailed) return def onAppRequestTimeout(self, interest, onSetupComplete, onSetupFailed, appRequestTimeoutCnt): print "Application publishing request times out" newInterest = Interest(interest) newInterest.refreshNonce() if appRequestTimeoutCnt == 0: if onSetupFailed: onSetupFailed("Application publishing request times out") else: print "Setup failed: application publishing request times out" else: self._face.expressInterest(newInterest, lambda interest, data : self.onAppRequestData(interest, data, onSetupComplete, onSetupFailed), lambda interest : self.onAppRequestTimeout(interest, onSetupComplete, onSetupFailed, appRequestTimeoutCnt - 1)) return ############################################### # Helper functions ############################################### def onRegisterFailed(self, prefix): print("register failed for prefix " + prefix.getName().toUri()) return def processConfiguration(self, confFile): config = BoostInfoParser() config.read(confFile) # TODO: handle missing configuration, refactor dict representation confObj = dict() try: confObj["identity"] = config["application/identity"][0].value confObj["signer"] = config["application/signer"][0].value except KeyError as e: msg = "Missing key in configuration: " + str(e) print msg return None return confObj def getIdentityNameFromCertName(self, certName): i = certName.size() - 1 idString = "KEY" while i >= 0: if certName.get(i).toEscapedString() == idString: break i -= 1 if i < 0: print "Error: unexpected certName " + certName.toUri() return None return Name(certName.getPrefix(i)) ################################# # Getters and setters ################################# def getKeyChain(self): return self._keyChain
def __init__(self, face, identityName, groupName, catalogPrefix, rawDataPrefix, producerDbFilePath, consumerDbFilePath, encrypted=False): self.face = face # Set up the keyChain. identityStorage = BasicIdentityStorage() privateKeyStorage = FilePrivateKeyStorage() self.keyChain = KeyChain( IdentityManager(identityStorage, privateKeyStorage), NoVerifyPolicyManager()) self.identityName = Name(identityName) self.groupName = Name(groupName) self.rawDataPrefix = rawDataPrefix self.catalogPrefix = catalogPrefix self.certificateName = self.keyChain.createIdentityAndCertificate( self.identityName) self.face.setCommandSigningInfo(self.keyChain, self.certificateName) # Set up the memoryContentCache self.memoryContentCache = MemoryContentCache(self.face) self.memoryContentCache.registerPrefix(self.identityName, self.onRegisterFailed, self.onDataNotFound) self.producerPrefix = Name(identityName) self.producerSuffix = Name() self.producer = DPUProducer(face, self.memoryContentCache, self.producerPrefix, self.producerSuffix, self.keyChain, self.certificateName, producerDbFilePath) # Put own (consumer) certificate in memoryContentCache consumerKeyName = IdentityCertificate.certificateNameToPublicKeyName( self.certificateName) consumerCertificate = identityStorage.getCertificate( self.certificateName, True) # TODO: request that this DPU be added as a trusted group member self.remainingTasks = dict() try: os.remove(consumerDbFilePath) except OSError: # no such file pass self.consumer = Consumer(face, self.keyChain, self.groupName, consumerKeyName, Sqlite3ConsumerDb(consumerDbFilePath)) # TODO: Read the private key to decrypt d-key...this may or may not be ideal base64Content = None with open( privateKeyStorage.nameTransform(consumerKeyName.toUri(), ".pri")) as keyFile: base64Content = keyFile.read() der = Blob(base64.b64decode(base64Content), False) self.consumer.addDecryptionKey(consumerKeyName, der) self.memoryContentCache.add(consumerCertificate) self.encrypted = encrypted self.rawData = [] self.catalogFetchFinished = False self.remainingData = 0 return