def addCertificate(self, key, issuerId): """ Add a self-signed certificate made from the key and issuer ID. :param PibKey key: The key for the certificate. :param str issuerId: The issuer ID name component for the certificate name. :return: The new certificate. :rtype: CertificateV2 """ certificateName = Name(key.getName()) certificateName.append(issuerId).appendVersion(3) certificate = CertificateV2() certificate.setName(certificateName) # Set the MetaInfo. certificate.getMetaInfo().setType(ContentType.KEY) # One hour. certificate.getMetaInfo().setFreshnessPeriod(3600 * 1000.0) # Set the content. certificate.setContent(key.getPublicKey()) params = SigningInfo(key) # Validity period of 10 days. now = Common.getNowMilliseconds() params.setValidityPeriod( ValidityPeriod(now, now + 10 * 24 * 3600 * 1000.0)) self._keyChain.sign(certificate, params) return certificate
def generateData(self, baseName): ''' This appends the segment number to the data name, since repo-ng tends to expect it ''' # just make up some data and return it ts = (time.time()) segmentId = 0 # compatible with repo-ng test: may change to test segmented data versionStr = baseName.get(-1).toEscapedString() dataName = Name(baseName) dataName.appendSegment(segmentId) d = Data(dataName) content = "(" + str(ts) + ") Data named " + dataName.toUri() d.setContent(content) d.getMetaInfo().setFinalBlockID(segmentId) d.getMetaInfo().setFreshnessPeriod(-1) if shouldSign: self.keychain.sign(d, self.certificateName) else: d.setSignature(self.fakeSignature) stats.insertDataForVersion(versionStr, {'publish_time':time.time()}) logger.debug('Publishing: '+d.getName().toUri()) return d
def onPublishInterest(self, prefix, interest, transport, pxID): ''' For publishing face ''' # just make up some data and return it interestName = interest.getName() logger.info("Interest for " + interestName.toUri()) ## CURRENTLY ASSUMES THERE'S A VERSION+SEGMENT SUFFIX! dataName = Name(interestName) ts = (time.time()) segmentId = 0 #try: # segmentId = interestName.get(-1).toSegment() #except: #logger.debug("Could not find segment id!") #dataName.appendSegment(segmentId) versionStr = str(interestName.get(-2).getValue()) logger.debug('Publishing ' + versionStr + ' @ ' + str(ts)) d = Data(dataName) content = "(" + str(ts) + ") Data named " + dataName.toUri() d.setContent(content) d.getMetaInfo().setFinalBlockID(segmentId) d.getMetaInfo().setFreshnessPeriod(1000) self.keychain.sign(d, self.certificateName) encodedData = d.wireEncode() stats.insertDataForVersion(versionStr, {'publish_time': time.time()}) transport.send(encodedData.toBuffer())
def test_compare(self): c7f = Name("/%7F").get(0) c80 = Name("/%80").get(0) c81 = Name("/%81").get(0) self.assertTrue(c81.compare(c80) > 0, "%81 should be greater than %80") self.assertTrue(c80.compare(c7f) > 0, "%80 should be greater than %7f")
def apply_exclude(self, last_node, exclude): """ @param last_node - the node to start search from @param exlucde - exclude filter the interest contains @returns all nodes that fullfil the selector """ _id = last_node._id query = 'START s=node(%s)\n' % _id + \ 'MATCH (s)-[:%s]->(m)\n' % (RELATION_C2C) + \ 'RETURN (m)' records = neo4j.CypherQuery(self.db_handler, query).execute() _nodes = [record.values[0] for record in records.data] if not exclude: return _nodes nodes = [] for node in _nodes: name = Name() name.set(node.get_properties()[PROPERTY_COMPONENT]) comp = name.get(0) if not exclude.matches(comp): nodes.append(node) return nodes
def _createCertificateFromRequest(self, message): """ Generate an IdentityCertificate from the public key information given. """ # TODO: Verify the certificate was actually signed with the private key # matching the public key we are issuing a cert for!! keyComponents = message.command.keyName.components keyName = Name("/".join(keyComponents)) self.log.debug("Key name: " + keyName.toUri()) if not self._policyManager.getEnvironmentPrefix().match(keyName): # we do not issue certs for keys outside of our network return None keyDer = Blob(message.command.keyBits) keyType = message.command.keyType try: self._identityStorage.addKey(keyName, keyType, keyDer) except SecurityException: # assume this is due to already existing? pass certificate = self._identityManager.generateCertificateForKey(keyName) self._keyChain.sign(certificate, self.getDefaultCertificateName()) # store it for later use + verification self._identityStorage.addCertificate(certificate) self._policyManager._certificateCache.insertCertificate(certificate) return certificate
def onInterest(self, prefix, interest, transport, registeredPrefixId): print "received interest" initInterest = Name(interest.getName()) print "interest name:",initInterest.toUri() d = Data(interest.getName().append(self.deviceComponent)) try: print "start to set data's content" currentString = ','.join(currentList) d.setContent("songList of " +self.device+":"+currentString+ "\n") self.face.registerPrefix(self.changePrefix,self.onInterest,self.onRegisterFailed) except KeyboardInterrupt: print "key interrupt" sys.exit(1) except Exception as e: print e d.setContent("Bad command\n") finally: self.keychain.sign(d,self.certificateName) encodedData = d.wireEncode() transport.send(encodedData.toBuffer()) print d.getName().toUri() print d.getContent() self.loop.close() self.face.shutdown() self.face = None
def wrap_content(self, name, content, key=None, key_locator=None): """ @param name - name of the data @param content - data to be wrapped @param key - key used to sign the data @return the content object created wraps the given name and content into a content object """ co = Data(Name(name)) co.setContent(content) co.getMetaInfo().setFreshnessPeriod(5000) co.getMetaInfo().setFinalBlockID(Name("/%00%09")[0]) identityStorage = MemoryIdentityStorage() privateKeyStorage = MemoryPrivateKeyStorage() identityManager = IdentityManager(identityStorage, privateKeyStorage) keyChain = KeyChain(identityManager, None) # Initialize the storage. keyName = Name("/ndn/bms/DSK-default") certificateName = keyName.getSubName(0, keyName.size() - 1).append( "KEY").append(keyName[-1]).append("ID-CERT").append("0") identityStorage.addKey(keyName, KeyType.RSA, Blob(DEFAULT_PUBLIC_KEY_DER)) privateKeyStorage.setKeyPairForKeyName(keyName, DEFAULT_PUBLIC_KEY_DER, DEFAULT_PRIVATE_KEY_DER) keyChain.sign(co, certificateName) _data = co.wireEncode() return _data.toRawStr()
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, prefix, maxCount=1): self.keyChain = KeyChain() self.prefix = Name(prefix) self.isDone = False # Initialize list for Data packet storage. # We'll treat the indices as equivalent to the sequence # number requested by Interests. self.data = [] finalBlock = Name.Component.fromNumberWithMarker(maxCount - 1, 0x00) hourMilliseconds = 3600 * 1000 # Pre-generate and sign all of Data we can serve. # We can also set the FinalBlockID in each packet # ahead of time because we know the entire sequence. for i in range(maxCount): dataName = Name(prefix).appendSegment(i) data = Data(dataName) data.setContent("Hello, " + dataName.toUri()) data.getMetaInfo().setFinalBlockID(finalBlock) data.getMetaInfo().setFreshnessPeriod(hourMilliseconds) self.keyChain.sign(data, self.keyChain.getDefaultCertificateName()) self.data.append(data)
def processInterest(interest, onData, onTimeout, onNetworkNack): try: # Create another key for the same identity and sign it properly. parentKey = self._fixture._keyChain.createKey( self._fixture._subIdentity) requestedKey = self._fixture._subIdentity.getKey(interest.getName()) # Copy the Name. certificateName = Name(requestedKey.getName()) certificateName.append("looper").appendVersion(1) certificate = CertificateV2() certificate.setName(certificateName) # Set the MetaInfo. certificate.getMetaInfo().setType(ContentType.KEY) # Set the freshness period to one hour. certificate.getMetaInfo().setFreshnessPeriod(3600 * 1000.0) # Set the content. certificate.setContent(requestedKey.getPublicKey()) # Set SigningInfo. params = SigningInfo(parentKey) # Validity period from 10 days before to 10 days after now. now = Common.getNowMilliseconds() params.setValidityPeriod(ValidityPeriod( now - 10 * 24 * 3600 * 1000.0, now + 10 * 24 * 3600 * 1000.0)) self._fixture._keyChain.sign(certificate, params) onData(interest, certificate) except Exception as ex: self.fail("Error in InfiniteCertificateChain: " + repr(ex))
def generateData(baseName): ''' This appends the segment number to the data name ''' # just make up some data and return it ts = (time.time()) segmentId = 0 # compatible with repo-ng test: may change to test segmented data versionComponent = baseName.get(-1) # should have a ts dataName = Name(baseName) dataName.appendSegment(segmentId) d = Data(dataName) content = "(" + str(ts) + ") Data named " + dataName.toUri() d.setContent(content) d.getMetaInfo().setFinalBlockID(segmentId) d.getMetaInfo().setFreshnessPeriod(-1) if shouldSign: keychain.sign(d, certName) else: d.setSignature(fakeSignature) if shouldCollectStats: info = getInfoForVersion(versionComponent.toEscapedString()) if info is not None: info['publish_time'] = ts return d
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 generateVersionedName(self): fullName = Name(self.dataName) # currently we need to provide the version ourselves when we # poke the repo ts = int(time.time()*1000) fullName.appendVersion(int(ts)) return fullName
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 testTimestamp(self): expected = Name("/%FC%00%04%7BE%E3%1B%00%00") self.assertTrue(expected.get(0).isTimestamp()) # 40 years (not counting leap years) in microseconds. number = 40 * 365 * 24 * 3600 * 1000000 self.assertEqual(Name().appendTimestamp(number), expected, "appendTimestamp did not create the expected component") self.assertEqual(expected[0].toTimestamp(), number, "toTimestamp did not return the expected value")
def onDataInterest(prefix, interest, transport, pxID): ''' For publishing face ''' # just make up some data and return it interestName = interest.getName() logger.info("Interest for " + interestName.toUri()) ## CURRENTLY ASSUMES THERE'S A VERSION/SEGMENT SUFFIX! dataName = Name(interestName.getPrefix(-1)) ts = (time.time()) segmentId = 0 try: segmentId = interestName().get(-1).toSegment() except: logger.debug("Could not find segment id!") dataName.appendSegment(segmentId) versionStr = interestName.get(-2).getValue().toRawStr() logger.debug('publishing ' + versionStr) info = getInfoForVersion(versionStr) d = Data(dataName) content = "(" + str(ts) + ") Data named " + dataName.toUri() d.setContent(content) d.getMetaInfo().setFinalBlockID(segmentId) keychain.sign(d, certName) encodedData = d.wireEncode() now = time.time() if info is not None: info['publish_time'] = now transport.send(encodedData.toBuffer())
def main(): face = Face("localhost") identityStorage = MemoryIdentityStorage() privateKeyStorage = MemoryPrivateKeyStorage() keyChain = KeyChain( IdentityManager(identityStorage, privateKeyStorage), None) keyChain.setFace(face) # Initialize the storage. keyName = Name("/testname/DSK-reposerver") certificateName = keyName.getSubName(0, keyName.size() - 1).append( "KEY").append(keyName[-1]).append("ID-CERT").append("0") identityStorage.addKey(keyName, KeyType.RSA, Blob(DEFAULT_PUBLIC_KEY_DER)) privateKeyStorage.setKeyPairForKeyName( keyName, DEFAULT_PUBLIC_KEY_DER, DEFAULT_PRIVATE_KEY_DER) echo = RepoServer(keyChain, certificateName) prefix = Name("/ndn/ucla.edu/bms") dump("Register prefix", prefix.toUri()) face.registerPrefix(prefix, echo.onInterest, echo.onRegisterFailed) while True: 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(): # Silence the warning from Interest wire encode. Interest.setDefaultCanBePrefix(True) # The default Face will connect using a Unix socket, or to "localhost". face = Face() counter = Counter() if sys.version_info[0] <= 2: word = raw_input("Enter a word to echo: ") else: word = input("Enter a word to echo: ") name = Name("/testecho") name.append(word) dump("Express name ", name.toUri()) face.expressInterest(name, counter.onData, counter.onTimeout) while counter._callbackCount < 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(): 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")) freshInterest.setMustBeFresh(False) dump(freshInterest.toUri()) freshInterest.setMinSuffixComponents(4) freshInterest.setMaxSuffixComponents(6) 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.setInterestLifetimeMilliseconds(30000) freshInterest.setChildSelector(1) freshInterest.setMustBeFresh(True); freshInterest.setScope(2) 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 onBootstrapData(self, interest, data): dump("Bootstrap data received.") if (self._accessControlManager.verifyDataWithHMACKey(data, self._bootstrapKey)): dump("Verified") content = json.loads(data.getContent().toRawStr(), encoding="latin-1") deviceNewIdentity = Name(content["deviceNewIdentity"]) controllerIdentity = Name(content["controllerIdentity"]) controllerPublicKeyInfo = content["controllerPublicKey"] #add prefix to device profile self._deviceProfile.setPrefix(deviceNewIdentity.toUri()) seed = HMACKey(content["seedSequence"], 0, str(content["seed"]), "seedName") self._seed = seed configurationTokenSequence = content["configurationTokenSequence"] #generate configuration token configurationTokenName = controllerIdentity.toUri()+"/"+str(configurationTokenSequence) configurationTokenKey = hmac.new(seed.getKey(), configurationTokenName, sha256).digest() self._configurationToken = HMACKey(configurationTokenSequence, 0, configurationTokenKey, configurationTokenName) #register new identity dump("Registered new prefix: ", deviceNewIdentity.toUri()) self.face.registerPrefix(content["deviceNewIdentity"],self.onInterest,self.onRegisterFailed) #set new identity as default and generate default key-pair with KSK Certificate self._identityStorage.addIdentity(deviceNewIdentity) self._identityManager.setDefaultIdentity(deviceNewIdentity) try: self._identityManager.getDefaultKeyNameForIdentity(deviceNewIdentity) dump("device identity already exists") except SecurityException: #generate new key-pair and certificate for new identity dump("Install new identity as default\nGenerate new key-pair and self signed certificate") newKey = self._identityManager.generateRSAKeyPairAsDefault(Name(deviceNewIdentity), isKsk=True) newCert = self._identityManager.selfSign(newKey) self._identityManager.addCertificateAsIdentityDefault(newCert) #add controller's identity and public key keyType = controllerPublicKeyInfo["keyType"] keyName = Name(controllerPublicKeyInfo["keyName"]) keyDer = Blob().fromRawStr(controllerPublicKeyInfo["publicKeyDer"]) self._identityStorage.addIdentity(controllerIdentity) try: self._identityStorage.addKey(keyName, keyType, keyDer) dump("Controller's identity, key and certificate installled") except SecurityException: dump("Controller's identity, key, certificate already exists.") #express an certificate request interest #defaultKeyName = self._identityManager.getDefaultKeyNameForIdentity(self._keyChain.getDefaultIdentity() ) #self.requestCertificate(defaultKeyName) else: dump("Not verified")
def handleExpressInterest(interest, onData, onTimeout): expressInterestCallCount[0] += 1 interestName = Name(interest.getName()) interestName.append(timeMarker) self.assertTrue(interestName in self.encryptionKeys) onData(interest, self.encryptionKeys[interestName]) return 0
def sendData(self, prefix, interest, face, registeredPrefixId, content): #onInterest #transport.send(encodedData.toBuffer()) #print(prefix) # Publish segments dataSize = len(content) print("Dat size: ",dataSize) segmentBegin = 0 segmentNo = 0 print "Start" while segmentBegin < dataSize: segmentEnd = segmentBegin + 2000 #Common.MAX_NDN_PACKET_SIZE if segmentEnd > dataSize: segmentEnd = dataSize # Make and sign a Data packet. print("Prefix: ") print(prefix) if not "%" in str(prefix)[-7:]: segmentName = prefix #print("NO % in name: ", segmentName) segmentName.appendSegment(segmentNo) else: segmentName = str(prefix)[:-1] #print("% in name: ",segmentName) segmentName += str(segmentNo) segmentName = Name(segmentName) print("Segment Name: ") print(segmentName) print("Segment Name appended: ", segmentName) print "Segmenting data from %d to %d" % (segmentBegin, segmentEnd) print("COntent: ") print(content[segmentBegin:segmentEnd]) data = Data(segmentName) data.setContent(content[segmentBegin:segmentEnd]) data.getMetaInfo().setFreshnessPeriod(2000) self._keyChain.sign(data, self._certificateName) if segmentEnd >= dataSize: print("yes") data.getMetaInfo().setFinalBlockId(segmentName[-1]) #encodedData = data.wireEncode() segmentBegin = segmentEnd print "Sending data " + segmentName.toUri() #transport.send(encodedData.toBuffer()) face.putData(data) segmentNo += 1 time.sleep(0.5) print "Finish"
def test_match(self): name = Name("/edu/cmu/andrew/user/3498478") name2 = Name(name) self.assertTrue(name.match(name2), 'Name does not match deep copy of itself') name2 = name[:2] self.assertTrue(name2.match(name), 'Name did not match prefix') self.assertFalse(name.match(name2), 'Name should not match shorter name') self.assertTrue(Name().match(name), 'Empty name should always match another')
def test_prefix(self): name = Name("/edu/cmu/andrew/user/3498478") prefix1 = name.getPrefix(2) self.assertEqual(len(prefix1), 2, 'Name prefix has ' + str(len(prefix1)) + ' components instead of 2') for i in range(2): self.assertTrue(name[i].getValue() == prefix1[i].getValue()) prefix2 = name.getPrefix(100) self.assertEqual(prefix2, name, 'Prefix with more components than original should stop at end of original name')
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.getSubName(0, keyName.size() - 1).append( "KEY").append(keyName[-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)
def createEncryptionKey(self, eKeyName, timeMarker): params = RsaKeyParams() eKeyName = Name(eKeyName) eKeyName.append(timeMarker) dKeyBlob = RsaAlgorithm.generateKey(params).getKeyBits() eKeyBlob = RsaAlgorithm.deriveEncryptKey(dKeyBlob).getKeyBits() self.decryptionKeys[eKeyName] = dKeyBlob keyData = Data(eKeyName) keyData.setContent(eKeyBlob) self.keyChain.sign(keyData, self.certificateName) self.encryptionKeys[eKeyName] = keyData
def createCheckInterest(self, fullName, checkNum): insertionName = Name(self.repoPrefix).append('insert check') commandParams = RepoCommandParameterMessage() interestName = Name(fullName) commandParams.repo_command_parameter.process_id = checkNum for i in range(interestName.size()): commandParams.repo_command_parameter.name.component.append(str(interestName.get(i).getValue())) commandName = insertionName.append(ProtobufTlv.encode(commandParams)) interest = Interest(commandName) return interest
def createCheckInterest(fullName, checkNum): insertionName = Name("/repotest/repo/insert check") commandParams = RepoCommandParameterMessage() interestName = Name(fullName) commandParams.repo_command_parameter.process_id = checkNum for i in range(interestName.size()): commandParams.repo_command_parameter.name.component.append(interestName.get(i).toEscapedString()) commandName = insertionName.append(ProtobufTlv.encode(commandParams)) interest = Interest(commandName) return interest
def test_02_device_methods(self): #create device prefixStr = '/home/sensor/LED/1' name = Name(prefixStr) profile = DeviceProfile(prefix = name) location = 'living_room' profile.setLocation(location) serviceProfileList = ['/standard/sensor/simple-camera-control/v0', '/standard/sensor/simple-motionsensor-control/v0'] profile.setServiceProfile(serviceProfileList) keyContent = 'this is key content' seedName = 'led1' seed = HMACKey( 0, 0 ,keyContent, seedName) configurationToken = HMACKey(0, 0, keyContent) commandName1 = 'turn_on' commandName2 = 'turn_off' commandList = [commandName1, commandName2] result = self.manager.createDevice(profile, seed, configurationToken, commandList) self.assertTrue(result, 'fail to create device') #getDeviceProfile() deviceProfile = self.manager.getDeviceProfile(name) self.assertTrue(deviceProfile.getLocation() == location, 'wrong location in device profile ') self.assertTrue(deviceProfile.getServiceProfileList() == serviceProfileList, 'wrong service profile list in device profile' ) #getSeed() seed = self.manager.getSeed(name) self.assertTrue(seed.getName() == seedName, 'wrong seed name') #getConfigurationToken() configurationToken = self.manager.getConfigurationToken(name) self.assertTrue(configurationToken.getKey()== keyContent, 'wrong configration token') #getCommandToken() commandToken1 = self.manager.getCommandToken(name, commandName1) commandToken2 = self.manager.getCommandToken(name, commandName2) commandTokenName1 = name.toUri()+"/"+ commandName1 +"/token/0" commandTokenName2 = name.toUri()+"/"+ commandName2 +"/token/0" self.assertTrue(commandToken1.getName() == commandTokenName1, 'wrong commandToken') self.assertTrue(commandToken2.getName() == commandTokenName2, 'wrong commandToken') #getCommandsOfDevice() commandNameList = self.manager.getCommandsOfDevice(name) self.assertTrue(commandName1 in commandNameList, 'command:' + commandName1 + ' not found') self.assertTrue(commandName2 in commandNameList, 'command:' + commandName2 + ' not found') #getServiceProfilesOfDevice() serviceProfileListReturned = self.manager.getServiceProfilesOfDevice(name) self.assertTrue(serviceProfileList[0] in serviceProfileListReturned, 'service profile:' + serviceProfileList[0] + ' not found') self.assertTrue(serviceProfileList[1] in serviceProfileListReturned, 'service profile:' + serviceProfileList[1] + ' not found')
def onInterest(self, prefix, interest, face, interestFilterId, filter): print "Got interest for device ID list." file = open("%s" % (deviceIDListName), "r") deviceIDList = file.read() data = Data(interest.getName()) signature = HmacWithSha256Signature() signature.getKeyLocator().setType(KeyLocatorType.KEYNAME) signature.getKeyLocator().setKeyName(Name("key1")) data.setSignature(signature) data.setContent(deviceIDList) dump("Signing device ID List data packet", data.getName().toUri()) KeyChain.signWithHmacWithSha256(data, key) face.putData(data)
def test_key_create_delete(self): identityName = Name('/TestIdentityStorage/Identity').appendVersion( int(time.time())) keyName1 = self.keyChain.generateRSAKeyPair(identityName, True) self.keyChain.getIdentityManager().setDefaultKeyForIdentity(keyName1) keyName2 = self.keyChain.generateRSAKeyPair(identityName, False) self.assertEqual(self.identityManager.getDefaultKeyNameForIdentity(identityName), keyName1, "Default key name was changed without explicit request") self.assertNotEqual(self.identityManager.getDefaultKeyNameForIdentity(identityName), keyName2, "Newly created key replaced default key without explicit request") self.identityStorage.deletePublicKeyInfo(keyName2) self.assertFalse(self.identityStorage.doesKeyExist(keyName2)) self.keyChain.deleteIdentity(identityName)
def run(self): try: # send Interest message to retrieve data #self.sendNextInterest(self.prefix_serviceMigration) print 'Select Service ' print ' (1) umobilestore' print ' (2) cloudrone' print ' (3) kebapp' service = raw_input( 'Choose service to be deployed (type number, e.g., 1): ') if service == '1': print 'Start migrating umobilestore' service_name = 'umobilestore' elif service == '2': print 'Start migrating cloudrone' service_name = 'cloudrone' elif service == '3': print 'Start migrating kebapp' service_name = 'kebapp' else: print 'Chosen service is not available' print 'Select Migration Method' print ' (a) push @Service Manager' print ' (b) pull @SEG' method = raw_input( 'Choose method to migrate service (type code, e.g., a): ') if method == 'a': print 'Migrate by PUSH' input_node = raw_input( 'Select node to migrate service (e.g., SEG_1): ') name_prefix = self.prefix_DE + service_name + '.tar.xz' + '/' + input_node elif method == 'b': print 'Migrate by PULL' name_prefix = self.prefix_pushService + service_name + '.tar.xz' else: print 'Chosen type is not available' print 'name prefix: %s' % name_prefix self.sendInterest(Name(name_prefix)) except RuntimeError as e: print "ERROR: %s" % e
def processFaceStatus(encodedFaceStatus, prefix, uri, face, enabled): """ This is called when all the segments are received to decode the encodedFaceStatus as a TLV FaceStatus message. If the face ID exists for the face URL, use it to call registerRoute(), otherwise send a /localhost/nfd/faces/create command to create the face. :param Blob encodedFaceStatus: The TLV-encoded FaceStatus. :param Name prefix: The prefix name to register. :param str uri: The remote URI in case we need to tell NFD to create a face. :param Face face: The Face which is used to sign the command interest and call expressInterest. :param enabled: On success or error, set enabled[0] = False. :type enabled: An array with one bool element """ if encodedFaceStatus.size() == 0: # No result, so we need to tell NFD to create the face. # Encode the ControlParameters. message = \ control_parameters_pb2.ControlParametersTypes.ControlParametersMessage() message.control_parameters.uri = uri encodedControlParameters = ProtobufTlv.encode(message) interest = Interest(Name("/localhost/nfd/faces/create")) interest.getName().append(encodedControlParameters) interest.setInterestLifetimeMilliseconds(10000) def onData(localInterest, data): processCreateFaceResponse(data.getContent(), prefix, face, enabled) def onTimeout(localInterest): enabled[0] = False dump("Face create command timed out.") # Sign and express the interest. face.makeCommandInterest(interest) face.expressInterest(interest, onData, onTimeout) else: decodedFaceStatus = face_status_pb2.FaceStatusMessage() ProtobufTlv.decode(decodedFaceStatus, encodedFaceStatus) faceId = decodedFaceStatus.face_status[0].face_id dump("Found face ID ", faceId) registerRoute(prefix, faceId, face, enabled)
def register_prefix(prefix: Union[str, Name]): self.face.registerPrefix(prefix, None, self.on_register_failed) self.face.setInterestFilter( Name(prefix).append("push"), self.on_push) self.face.setInterestFilter( Name(prefix).append("create-branch"), self.on_create_branch) self.face.setInterestFilter( Name(prefix).append("track-repo"), self.on_track_repo) self.face.setInterestFilter( Name(prefix).append("mount"), self.on_mount) self.face.setInterestFilter( Name(prefix).append("update"), self.on_update) self.face.setInterestFilter( Name(prefix).append("unmount"), self.on_unmount) self.face.setInterestFilter( Name(prefix).append("commit"), self.on_commit)
def test_registration_callbacks(self): onRegisterFailed = Mock() onRegisterSuccess = Mock() self.face.registerPrefix( Name("/test/register/callbacks"), None, onRegisterFailed, onRegisterSuccess) while True: self.face.processEvents() time.sleep(0.01) if (onRegisterSuccess.call_count > 0 or onRegisterFailed.call_count > 0): break self.assertEqual( onRegisterSuccess.call_count, 1, "Expected 1 onRegisterSuccess callback, got " + str(onRegisterSuccess.call_count))
def __init__(self): super(PirPublisher, self).__init__() # find the pins to set up from the config pinList = [18, 25] self._pirs = {} for pin in pinList: readCommand = Name('read').append(str(pin)) self.addCommand(readCommand, self.onReadPir, ['pir'], False) pir = Pir(pin) self._pirs[pin] = { "device": pir, "lastVal": pir.read(), "lastTime": int(time.time() * 1000) } self._count = 0
def update_branch(self, branch: str, timestamp: int, commit: str, head_data: bytes): # Update database self.branches[branch].timestamp = timestamp self.branches[branch].head = commit self.branches[branch].head_data = head_data self.repo_db.put(branch, pickle.dumps(self.branches[branch])) # Release Data in memory self.branches[branch].head_data = b"" # Send notification Data notif = Data(Name(LOCAL_CMD_PREFIX) .append("notif") .append(self.repo_name) .append(branch) .appendTimestamp(Sync.timestamp())) notif.metaInfo.freshnessPeriod = 10 notif.content = commit.encode() self.face.putData(notif)
def on_command(self, _prefix, interest, _face, _interest_filter_id, _filter_obj): # type: (Name, Interest, Face, int, InterestFilter) -> None parameter_msg = SegmentParameterMessage() try: ProtobufTlv.decode(parameter_msg, interest.name[-1].getValue()) except ValueError: self.nodata_reply(interest.name, RET_MALFORMED_COMMAND) return parameter = parameter_msg.segment_parameter prefix = Name() for compo in parameter.name.component: prefix.append(compo.decode("utf-8")) # Check operations for op in parameter.operations.components: model_name = op.model.decode("utf-8") if model_name not in self.operations_set: self.nodata_reply(interest.name, RET_NOT_SUPPORTED) return # Fetch frames for frame_id in range(parameter.start_frame, parameter.end_frame + 1): frame_name = Name(prefix).append(str(frame_id)) for op in parameter.operations.components: model_name = op.model.decode("utf-8") data_name = Name(frame_name).append(model_name) logging.info("Request processed: %s", data_name) status = ResultStatus(prefix.toUri(), model_name, Common.getNowMilliseconds()) status.status = STATUS_FETCHING status.estimated_time = status.proecess_start_time + 10.0 self.save_status(data_name, status) # Check data existence and trigger fetching process for frame_id in range(parameter.start_frame, parameter.end_frame + 1): frame_name = Name(prefix).append(str(frame_id)) if self.storage.exists(frame_name): self.on_payload(frame_name) else: self.fetcher.fetch_data(frame_name) self.nodata_reply(interest.name, RET_OK, 10.0)
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 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 generateFakeSignature(): signatureInfo = Sha256WithRsaSignature() keyLocatorName = Name("/ndn/site1/KEY/ksk-2516425377094") keyLocator = KeyLocator() keyLocator.setType(KeyLocatorType.KEYNAME) keyLocator.setKeyName(keyLocatorName) signatureInfo.setKeyLocator(keyLocator) period = ValidityPeriod() period.setPeriod(fromIsoString("20141111T050000"), fromIsoString("20141111T060000")) signatureInfo.setValidityPeriod(period) block2 = Blob(SIG_VALUE, False) signatureInfo.setSignature(block2) return signatureInfo
def ctrl_info_run(self): ControllerPrefixString = '/ndn/ie/tcd/controller01/ofndn/--/n1.0/36/0/0/' ControllerPrefix = Name(ControllerPrefixString) self.face.setCommandSigningInfo(self.keyChain, \ self.keyChain.getDefaultCertificateName()) self.face.registerPrefix(ControllerPrefix, self.onInterest_CtrlInfo, self.onRegisterFailed) # run prefix # # # filters: # CtrlInfo_msg_prefix = Name('/ndn/ie/tcd/controller01/ofndn/--/n1.0/36/0/0/') # self.face.setInterestFilter(CtrlInfo_msg_prefix, self.onInterest_CtrlInfo) # for CtrlInfo msg # Run the event loop forever. Use a short sleep to # prevent the Producer from using 100% of the CPU. while not self.isDone: # listen hello cannot stop self.face.processEvents() time.sleep(0.01)
def __init__(self, data=None): """ Create a new identity certificate. :param data: (optional) A Data object to copy the contents of :type data: Data :throws: SecurityException if the name of this Data object is not a valid identity certificate name. """ super(IdentityCertificate, self).__init__(data) if isinstance(data, IdentityCertificate): # The copy constructor. self._publicKeyName = Name(data._publicKeyName) elif isinstance(data, Data): if not self._isCorrectName(data.getName()): raise SecurityException("Wrong Identity Certificate Name!") self._setPublicKeyName()
def run(self, namespace): # Create a connection to the local forwarder over a Unix socket face = Face() prefix = Name(namespace) # Use the system default key chain and certificate name to sign commands. face.setCommandSigningInfo(self.keyChain, \ self.keyChain.getDefaultCertificateName()) # Also use the default certificate name to sign Data packets. face.registerPrefix(prefix, self.onInterest, self.onRegisterFailed) # Run the event loop forever. Use a short sleep to # prevent the Producer from using 100% of the CPU. while not self.isDone: face.processEvents() time.sleep(0.01)
def test_max_ndn_packet_size(self): # Construct an interest whose encoding is one byte larger than getMaxNdnPacketSize. targetSize = Face.getMaxNdnPacketSize() + 1 # Start with an interest which is almost the right size. interest = Interest() interest.getName().append(bytearray(targetSize)) initialSize = interest.wireEncode().size() # Now replace the component with the desired size which trims off the extra encoding. interest.setName( (Name().append(bytearray(targetSize - (initialSize - targetSize))))) interestSize = interest.wireEncode().size() self.assertEqual(targetSize, interestSize, "Wrong interest size for MaxNdnPacketSize") with self.assertRaises(RuntimeError): # If no error is raised, then expressInterest didn't throw an # exception when the interest size exceeds getMaxNdnPacketSize() self.face.expressInterest(interest, Mock(), Mock())
def pointNameToNDNName(self, point, isAggregation=True): name = point.lower().split(":")[1] # We expect failures in name transformation to be as little as possible; for our current historical data, 3 out of ~800 sensor names cannot be found if (name in self._sensorNDNDict): if isAggregation: return self._sensorNDNDict[name]._aggregationName else: return self._sensorNDNDict[name]._instName else: print( "Sensor name " + name + " not found in dict, aggregation calculation skipped; raw publishing with assumed name" ) if isAggregation: return None else: return Name(name.replace('.', '/'))
def list_key_tree(): """ Return the id-key-cert tree in a JSON like dict object. """ pib = KeyChain().getPib() identities = pib._identities._identityNames ret = {} try: default_id = pib.getDefaultIdentity().getName() except Pib.Error: default_id = Name('/') for id_name in identities: id_obj = pib.getIdentity(Name(id_name)) cur_id = {'default': '*' if id_name == default_id else ' '} try: default_key = id_obj.getDefaultKey().getName() except Pib.Error: default_key = Name('/') keys = id_obj._getKeys()._keyNames cur_id['keys'] = {} for key_name in keys: key_obj = id_obj.getKey(Name(key_name)) cur_key = {'default': '*' if key_name == default_key else ' '} try: default_cert = key_obj.getDefaultCertificate().getName() except Pib.Error: default_cert = Name('/') key_type = key_obj.getKeyType() if key_type <= 4: cur_key['key_type'] = ['NONE', 'RSA', 'EC', 'AES', 'HMAC'][key_type] else: cur_key['key_type'] = 'unknown' certs = key_obj._getCertificates()._certificateNames cur_key['certs'] = {} for cert_name in certs: cert_obj = key_obj.getCertificate(Name(cert_name)) signature = cert_obj.getSignature() cur_cert = { 'default': '*' if cert_name == default_cert else ' ', 'not_before': str(cert_obj.getValidityPeriod().getNotBefore()), 'not_after': str(cert_obj.getValidityPeriod().getNotAfter()), 'issuer_id': cert_obj.getIssuerId().toEscapedString(), 'key_locator': signature.getKeyLocator().getKeyName().toUri(), 'signature_type': cert_obj.getSignature().__class__.__name__, } cur_key['certs'][cert_name.toUri()] = cur_cert cur_id['keys'][key_name.toUri()] = cur_key ret[id_name.toUri()] = cur_id return ret
def test_specific_interest(self): uri = "/ndn/edu/ucla/remap/ndn-js-test/howdy.txt/%FD%052%A1%DF%5E%A4" (dataCallback, timeoutCallback) = self.run_express_name_test(uri) self.assertTrue(timeoutCallback.call_count == 0, 'Unexpected timeout on expressed interest') # check that the callback was correct self.assertEqual( dataCallback.call_count, 1, 'Expected 1 onData callback, got ' + str(dataCallback.call_count)) onDataArgs = dataCallback.call_args[ 0] # the args are returned as ([ordered arguments], [keyword arguments]) #just check that the interest was returned correctly? callbackInterest = onDataArgs[0] self.assertTrue(callbackInterest.getName().equals(Name(uri)), 'Interest returned on callback had different name')
def test_any_interest(self): uri = "/" (dataCallback, timeoutCallback) = self.run_express_name_test(uri) self.assertTrue(timeoutCallback.call_count == 0, 'Timeout on expressed interest') # check that the callback was correct self.assertEqual( dataCallback.call_count, 1, 'Expected 1 onData callback, got ' + str(dataCallback.call_count)) onDataArgs = dataCallback.call_args[ 0] # the args are returned as ([ordered arguments], [keyword arguments]) #just check that the interest was returned correctly? callbackInterest = onDataArgs[0] self.assertTrue(callbackInterest.getName().equals(Name(uri)), 'Interest returned on callback had different name')
def __init__(self, contentPrefix, userKeyName, keyChain, certificateName): self._enabled = True self._responseCount = 0 # Imitate test_consumer from the PyNDN integration tests. contentName0 = Name(contentPrefix).append("Content").appendSegment(0) contentName1 = Name(contentPrefix).append("Content").appendSegment(1) cKeyName = Name("/Prefix/SAMPLE/Content/C-KEY/1") dKeyName = Name("/Prefix/READ/D-KEY/1/2") # Generate the E-KEY and D-KEY. params = RsaKeyParams() fixtureDKeyBlob = RsaAlgorithm.generateKey(params).getKeyBits() fixtureEKeyBlob = RsaAlgorithm.deriveEncryptKey( fixtureDKeyBlob).getKeyBits() # The user key. fixtureUserEKeyBlob = Blob(FIXTURE_USER_E_KEY) # Load the C-KEY. fixtureCKeyBlob = Blob(AES_KEY, False) # Imitate createEncryptedContent. Make two segments. encryptParams = EncryptParams(EncryptAlgorithmType.AesCbc) encryptParams.setInitialVector(Blob(INITIAL_VECTOR, False)) self._contentData0 = Data(contentName0) Encryptor.encryptData(self._contentData0, Blob(DATA0_CONTENT, False), cKeyName, fixtureCKeyBlob, encryptParams) self._contentData0.getMetaInfo().setFinalBlockId( Name().appendSegment(1)[0]) keyChain.sign(self._contentData0, certificateName) self._contentData1 = Data(contentName1) Encryptor.encryptData(self._contentData1, Blob(DATA1_CONTENT, False), cKeyName, fixtureCKeyBlob, encryptParams) self._contentData1.getMetaInfo().setFinalBlockId( Name().appendSegment(1)[0]) keyChain.sign(self._contentData1, certificateName) # Imitate createEncryptedCKey. self._cKeyData = Data(cKeyName) encryptParams = EncryptParams(EncryptAlgorithmType.RsaOaep) Encryptor.encryptData(self._cKeyData, fixtureCKeyBlob, dKeyName, fixtureEKeyBlob, encryptParams) keyChain.sign(self._cKeyData, certificateName) # Imitate createEncryptedDKey. self._dKeyData = Data(dKeyName) encryptParams = EncryptParams(EncryptAlgorithmType.RsaOaep) Encryptor.encryptData(self._dKeyData, fixtureDKeyBlob, userKeyName, fixtureUserEKeyBlob, encryptParams) keyChain.sign(self._dKeyData, certificateName)
def test_content_symmetric_encrypt(self): for input in encryptorAesTestInputs: data = Data() Encryptor.encryptData( data, input.plainText, input.keyName, input.key, input.encryptParams) self.assertTrue(data.getName().equals(Name("/FOR").append(input.keyName)), input.testName) self.assertTrue(input.encryptedContent.equals(data.getContent()), input.testName) content = EncryptedContent() content.wireDecode(data.getContent()) decryptedOutput = AesAlgorithm.decrypt( input.key, content.getPayload(), input.encryptParams) self.assertTrue(input.plainText.equals(decryptedOutput), input.testName)
def _heartbeat(self, interest): """ This repeatedly calls itself after a timeout to send a heartbeat message (chat message type HELLO). This method has an "interest" argument because we use it as the onTimeout for Face.expressInterest. """ if len(self._messageCache) == 0: self._messageCacheAppend(chatbuf_pb2.ChatMessage.JOIN, "xxx") self._sync.publishNextSequenceNo() self._messageCacheAppend(chatbuf_pb2.ChatMessage.HELLO, "xxx") # Call again. # TODO: Are we sure using a "/local/timeout" interest is the best future call # approach? timeout = Interest(Name("/local/timeout")) timeout.setInterestLifetimeMilliseconds(60000) self._face.expressInterest(timeout, self._dummyOnData, self._heartbeat)
def main(): #Interest.setDefaultCanBePrefix(True) with open("shared/system-info.json") as f: user_data = json.load(f) face = Face() counter = Counter() name = Name("/test") """ req_name = "/example/test" sym_key = base64.b64decode(user_data['austin']['sym_key']) iv,ct,tag = sym_encrypt(sym_key,req_name) enc_req_name = base64.b64encode(iv).decode('ascii') name.append(enc_req_name) enc_req_name = base64.b64encode(ct).decode('ascii') name.append(enc_req_name) enc_req_name = base64.b64encode(tag).decode('ascii') name.append(enc_req_name) priv_key = user_data['austin']['priv_key'] priv_key = base64.b64decode(priv_key) priv_key = load_priv_key(priv_key) #sig = base64.b64encode(priv_key.sign(bytes(enc_req_name,'utf-8'))) sig =\ base64.b64encode(priv_key.sign(bytes("austin",'utf-8'))).decode('ascii') name.append(sig) sig = base64.b64decode(sig) """ print(name) face.expressInterest(name,counter.onData,counter.onTimeout) while counter.rec == 1: face.processEvents() time.sleep(0.1)
def produce(self): # Produce the bounding box print "ready to produce" maxLong = -3600 minLong = 3600 maxLat = -3600 minLat = 3600 if len(self.rawData) == 0: print "No raw data as producer input" for item in self.rawData: print item if item["lng"] > maxLong: maxLong = item["lng"] if item["lng"] < minLong: minLong = item["lng"] if item["lat"] > maxLat: maxLat = item["lat"] if item["lat"] < minLat: minLat = item["lat"] result = json.dumps({ "maxlng": maxLong, "minlng": minLong, "maxlat": maxLat, "minlat": minLat, "size": len(self.rawData) }) if self.encrypted: # TODO: replace fixed timestamp for now for produced data, createContentKey as needed testTime1 = Schedule.fromIsoString("20160320T080000") self.producer.createContentKey(testTime1) self.producer.produce(testTime1, result) else: # Arbitrary produced data lifetime data = Data(Name(self.identityName).append("20160320T080000")) data.getMetaInfo().setFreshnessPeriod(400000) data.setContent(result) # If the interest's still within lifetime, this will satisfy the interest self.memoryContentCache.add(data) print "Produced data with name " + data.getName().toUri()
def main(self): log.debug("[PLC][%s] Initialized" % self.name) while not self.registered: log.debug( "[PLC][%s] Trying to register with scadasim rpc" % self.name) try: self._registerPLC() except KeyError: log.warn( """[PLC][%s] PLC not found within scadasim. Verify Docker Compose container names match list of plcs in scadasim config""") time.sleep(1) log.debug("[PLC][%s] Starting update service" % self.name) self.update() log.debug("[PLC][%s] Starting NDN Producer" % self.name) # TODO: Move this setup stuff into a function and make dynamic. log.info("Listening on: ") for n in self.db: # /ndn/plc2-site/plc2 name = Name("{0}/{1}-site/{1}/{2}".format(self.primary_prefix, self.name, n)) log.info("\t{}".format(name)) name_identiy = self.keyChain.createIdentityAndCertificate(name, self.keyChain.getDefaultKeyParams()) log.debug("Name Identify: {}".format(name_identiy)) self.face.setCommandSigningInfo(self.keyChain, name_identiy) self.face.registerPrefix(name, self.onInterest, self.onRegisterFailed) # log.debug("Registered Prefix: {} {}", str(self.primary_prefix), str(n)) # END LOOP # Keep Running unless error. while self._callbackCount < 1: self.face.processEvents() time.sleep(0.01) self.face.shutdown()
def registerRoute(prefix, faceId, face, enabled): """ Use /localhost/nfd/rib/register to register the prefix to the faceId. :param Name prefix: The prefix name to register. :param int faceId: The face ID. :param Face face: The Face which is used to sign the command interest and call expressInterest. :param enabled: On success or error, set enabled[0] = False. :type enabled: An array with one bool element """ # Use default values origin = 255 cost = 0 CHILD_INHERIT = 1 flags = CHILD_INHERIT message = control_parameters_pb2.ControlParametersTypes.ControlParametersMessage( ) for i in range(prefix.size()): message.control_parameters.name.component.append( prefix[i].getValue().toBytes()) message.control_parameters.face_id = faceId message.control_parameters.origin = origin message.control_parameters.cost = cost message.control_parameters.flags = flags encodedControlParameters = ProtobufTlv.encode(message) interest = Interest(Name("/localhost/nfd/rib/register")) interest.getName().append(encodedControlParameters) interest.setInterestLifetimeMilliseconds(10000) # Sign and express the interest. face.makeCommandInterest(interest) def onData(localInterest, data): enabled[0] = False processRegisterResponse(data.getContent()) def onTimeout(localInterest): enabled[0] = False dump("Register route command timed out.") face.expressInterest(interest, onData, onTimeout)
def on_interest_data(self, interest, data): if self.cim_timer is not None: self.cim_timer.cancel() content = data.getContent().toRawStr() redirectPrefix = "redirect:" if content.startswith(redirectPrefix): name = content[len(redirectPrefix):] self.redirect = Interest(Name(name)) Log.info("Received redirect for interest '{}' -> '{}':\n{}".format( Util.interest_to_string(interest), Util.interest_to_string(self.redirect), urllib.parse.unquote(content))) self.request_next_segments() else: Log.info("Received data for interest '{}':\n{}".format( Util.interest_to_string(interest), urllib.parse.unquote(content))) self.on_data(self, data)
def test_backref_matcher_advanced2(self): backRef = NdnRegexBackrefManager() cm = NdnRegexPatternListMatcher("(<a>(<b>))<c>", backRef) res = cm.match(Name("/a/b/c"), 0, 3) self.assertEquals(True, res) self.assertEquals(3, len(cm.getMatchResult())) self.assertEquals("a", cm.getMatchResult()[0].toEscapedString()) self.assertEquals("b", cm.getMatchResult()[1].toEscapedString()) self.assertEquals("c", cm.getMatchResult()[2].toEscapedString()) self.assertEquals(2, backRef.size()) self.assertEquals( "a", backRef.getBackref(0).getMatchResult()[0].toEscapedString()) self.assertEquals( "b", backRef.getBackref(0).getMatchResult()[1].toEscapedString()) self.assertEquals( "b", backRef.getBackref(1).getMatchResult()[0].toEscapedString())
def onInterest(self, prefix, interest, face, interestFilterId, filter): print "Got interest for latest device seq num." deviceID = str(interest.getName().getSubName(-1, 1).toUri()[1:]) file = open("../repo-ng/seq/%s.seq" % (deviceID), "r") deviceIDList = file.read() data = Data(interest.getName()) signature = HmacWithSha256Signature() signature.getKeyLocator().setType(KeyLocatorType.KEYNAME) signature.getKeyLocator().setKeyName(Name("key1")) data.setSignature(signature) data.setContent(deviceIDList) dump("Signing device ID List data packet", data.getName().toUri()) KeyChain.signWithHmacWithSha256(data, key) face.putData(data)