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 main(): face = Face() keychain = KeyChain() face.setCommandSigningInfo(keychain, keychain.getDefaultCertificateName()) async def face_loop(): nonlocal face while True: face.processEvents() await asyncio.sleep(0.001) parser = argparse.ArgumentParser(description='segmented insert client') parser.add_argument('-r', '--repo_name', required=True, help='Name of repo') parser.add_argument('-p', '--process_id', required=True, help="Process ID") args = parser.parse_args() logging.basicConfig(format='[%(asctime)s]%(levelname)s:%(message)s', datefmt='%Y-%m-%d %H:%M:%S', level=logging.INFO) client = CommandChecker(face, keychain) event_loop = asyncio.get_event_loop() event_loop.create_task(face_loop()) event_loop.run_until_complete(client.check_delete(args.repo_name, int(args.process_id)))
def __init__(self, data_size, verbose=False): # create a KeyChain for signing data packets self._key_chain = KeyChain() self._is_done = False self._num_interests = 0 # self._keyChain.createIdentityV2(Name("/ndn/identity")) # host data at the local forwarder self._face = Face() # immutable byte array to use as data self._byte_array = bytes(data_size) # the number of bytes contained in each data packet self._data_size = data_size # the verbosity of diagnostic information self._verbose = verbose # keep track of if the first interest has been recieved (for timing) self._is_first_interst = True # keep track of various performance metrics: self._interests_satisfied = 0 self._interests_recieved = 0 self._data_sent = 0 self._elapsed_time = {} self._initial_time = {} self._final_time = {} print("Producer instance created.")
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, namePrefix): self.outstanding = dict() self.isDone = False self.keyChain = KeyChain() self.face = Face("127.0.0.1") self.configPrefix = Name(namePrefix) self.script_path = os.path.abspath( __file__) # i.e. /path/to/dir/foobar.py self.script_dir = os.path.split( self.script_path)[0] #i.e. /path/to/dir/ self.interestLifetime = 800000 #self.Datamessage_size = 1999000 self.Datamessage_size = 19990000 folder_name = "SC_repository/" rel_path = os.path.join(self.script_dir, folder_name) prefix_startDE = "/picasso/start_de/" self.prefix_startDE = Name(prefix_startDE) self.prefix_deployService = '/picasso/service_deployment_push/' self.json_server_Spec_default = { # This is only an skeleton 'par': { # service parameters 'serviceName': 'nameOfService', 'imageName': 'NameOfImageToIstantiateService', 'imageSize': 'sizeOfImage', 'maxConReq': 'maxNumConcurrentRequestsThatAnIntanceCanHandle', 'startUpTime': 'timeToInstatiateService' }, 'QoS': { #QoS parameters expected from the service 'responseTime': 'resposeTimeExpectedFromService', 'availability': 'availabilityExpectedFromService', 'numConReq': 'numConcurrentRequestsToBeHandledByService' } } if not os.path.exists(rel_path): os.makedirs(rel_path)
def main(): # Silence the warning from Interest wire encode. Interest.setDefaultCanBePrefix(True) if sys.version_info[0] <= 2: userPrefixUri = raw_input("Enter your user prefix (e.g. /a): ") else: userPrefixUri = input("Enter your user prefix (e.g. /a): ") if userPrefixUri == "": dump("You must enter a user prefix") return syncPrefixUri = "/sync" nUserPrefixes = 2 maxPublishedSequenceNo = 3 # The default Face will connect using a Unix socket, or to "localhost". face = Face() # Set up the KeyChain. keyChain = KeyChain("pib-memory:", "tpm-memory:") keyChain.importSafeBag( SafeBag(Name("/testname/KEY/123"), Blob(DEFAULT_RSA_PRIVATE_KEY_DER, False), Blob(DEFAULT_RSA_PUBLIC_KEY_DER, False))) face.setCommandSigningInfo(keyChain, keyChain.getDefaultCertificateName()) producer = Producer(face, keyChain, Name(syncPrefixUri), userPrefixUri, nUserPrefixes, maxPublishedSequenceNo) # The main event loop. 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)
def main(): if len(sys.argv) < 2: print("Usage:", sys.argv[0], "command-prefix", file=sys.stderr) return -1 else: command_prefix = sys.argv[1] logging.basicConfig(format='[%(asctime)s]%(levelname)s:%(message)s', datefmt='%Y-%m-%d %H:%M:%S', level=logging.INFO) event_loop = asyncio.get_event_loop() face = Face() keychain = KeyChain() face.setCommandSigningInfo(keychain, keychain.getDefaultCertificateName()) server = Server(face, command_prefix) async def face_loop(): nonlocal face, server while server.running: face.processEvents() await asyncio.sleep(0.01) try: event_loop.run_until_complete(face_loop()) finally: event_loop.close()
def main(): if len(argv) < 3: dump("Usage:", argv[0], "<repo-command-prefix> <fetch-prefix>") return repoCommandPrefix = Name(argv[1]) repoDataPrefix = Name(argv[2]) # 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. keyChain = KeyChain() face.setCommandSigningInfo(keyChain, keyChain.getDefaultCertificateName()) enabled = [True] def onInsertStarted(): # nonlocal enabled dump("Insert started for", repoDataPrefix.toUri()) enabled[0] = False def onFailed(): # nonlocal enabled enabled[0] = False requestInsert(face, repoCommandPrefix, repoDataPrefix, onInsertStarted, 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) face.shutdown()
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. keyChain = KeyChain() face.setCommandSigningInfo(keyChain, keyChain.getDefaultCertificateName()) objectPrefix = Namespace("/ndn/eb/run/28/description", keyChain) dump("Register prefix", objectPrefix.name) # Set the face and register to receive Interests. objectPrefix.setFace( face, lambda prefixName: dump("Register failed for prefix", prefixName)) dump("Preparing data for", objectPrefix.name) GeneralizedObjectHandler().setObject(objectPrefix, Blob("EB run #28. Ham and oats"), "text/html") 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)
def init_network(self, prefix): self.prefix = prefix self.face = Face() self.keychain = KeyChain() self.face.setCommandSigningInfo( self.keychain, self.keychain.getDefaultCertificateName()) self.face.registerPrefix(self.prefix, None, self.on_register_failed)
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 main(): async def face_loop(): nonlocal face, repo while repo.running: face.processEvents() await asyncio.sleep(0.001) config = get_yaml() logging.info(config) face = Face() keychain = KeyChain() face.setCommandSigningInfo(keychain, keychain.getDefaultCertificateName()) # storage = LevelDBStorage(config['db_config']['leveldb']['dir']) storage = MongoDBStorage(config['db_config']['mongodb']['db'], config['db_config']['mongodb']['collection']) read_handle = ReadHandle(face, keychain, storage) write_handle = WriteCommandHandle(face, keychain, storage, read_handle) delete_handle = DeleteCommandHandle(face, keychain, storage) tcp_bulk_insert_handle = TcpBulkInsertHandle( storage, read_handle, config['tcp_bulk_insert']['addr'], config['tcp_bulk_insert']['port']) repo = Repo(Name(config['repo_config']['repo_name']), face, storage, read_handle, write_handle, delete_handle, tcp_bulk_insert_handle) repo.listen() # my nfd is broken... event_loop = asyncio.get_event_loop() try: event_loop.run_until_complete(face_loop()) finally: event_loop.close()
def __init__(self, networkName, nodeName): super(IotConsole, self).__init__() self.deviceSuffix = Name(nodeName) self.networkPrefix = Name(networkName) self.prefix = Name(self.networkPrefix).append(self.deviceSuffix) self._identityStorage = IotIdentityStorage() self._policyManager = IotPolicyManager(self._identityStorage) self._identityManager = IotIdentityManager(self._identityStorage) self._keyChain = KeyChain(self._identityManager, self._policyManager) self._policyManager.setEnvironmentPrefix(self.networkPrefix) self._policyManager.setTrustRootIdentity(self.prefix) self._policyManager.setDeviceIdentity(self.prefix) self._policyManager.updateTrustRules() self.foundCommands = {} self.unconfiguredDevices = [] # TODO: use xDialog in XWindows self.ui = Dialog(backtitle='NDN IoT User Console', height=18, width=78) trolliusLogger = logging.getLogger('trollius') trolliusLogger.addHandler(logging.StreamHandler())
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 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 main(): face = Face() keychain = KeyChain() face.setCommandSigningInfo(keychain, keychain.getDefaultCertificateName()) running = True img = None interest = Interest(Name("/icear-server/result/example-data/2/deeplab")) interest.mustBeFresh = True def on_data(_, data): # type: (Interest, Data) -> None nonlocal running, img print(data.name.toUri()) print(data.content.toBytes()) running = False if data.metaInfo.type == ContentType.NACK: print("NACK") else: img = data.content.toBytes() face.expressInterest(interest, on_data) while running: face.processEvents() time.sleep(0.01) face.shutdown() if img: image = Image.open(io.BytesIO(img)) image.show()
def __init__(self, absPath, maxAttributes): self.keyChain = KeyChain("pib-memory:", "tpm-memory:") self.keyChain.createIdentityV2("/test/identity") self.validator = Validator( ValidationPolicyFromPib(self.keyChain.getPib())) # , filename, groupSize, nAttributes, absPath, keepData = False): # sys.stderr.write ("Using NDN-ABS authority, signer, and verifier database from %s\n" % absPath) self.db = ndnabs.PickleDb(absPath) self.signer = ndnabs.Signer(self.db) self.verifier = ndnabs.Verifier(self.db) try: info = self.signer.get_public_params_info() if info.getName().getPrefix( -2).toUri() != "/icn2019/test/authority": raise RuntimeError( 'NDN-ABS authority exists, but not setup for experiment. Use `ndnabs setup -f /icn2019/test/authority` to force-setup the authority' ) except: raise RuntimeError( "Public parameters are not properly installed for the signer/verifier" ) maxAttributes = [ b'attribute%d' % i for i in range(1, maxAttributes + 1) ] for attr in maxAttributes: if not attr in self.signer.get_attributes(): raise RuntimeError( "%s attribute missing. Generate attributes for the experiment using `ndnabs gen-secret %s | ndnabs install-secret`" % (str(attr, 'utf-8'), ' '.join( [str(i, 'utf-8') for i in maxAttributes])))
def create_identity(name): key_chain = KeyChain() try: cur_id = key_chain.getPib().getIdentity(Name(name)) key_chain.createKey(cur_id) except Pib.Error: key_chain.createIdentityV2(Name(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[:-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 __init__(self, prefix, transferfile): self.keyChain = KeyChain() self.prefix = Name(prefix) self.isDone = False self.transferfile = transferfile # Initialize list for Data packet storage. # We'll treat the indices as equivalent to the sequence # number requested by Interests. self.data = [] f = open(transferfile, 'rb') imgdata = f.read() chunks = list(chunkstring(imgdata, 8192)) print len(chunks) finalBlock = Name.Component.fromNumberWithMarker(len(chunks) - 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(0, len(chunks)): dataName = Name(prefix).appendSegment(i) print dataName data = Data(dataName) data.setContent(chunks[i]) data.getMetaInfo().setFinalBlockID(finalBlock) data.getMetaInfo().setFreshnessPeriod(hourMilliseconds) self.keyChain.sign(data, self.keyChain.getDefaultCertificateName()) self.data.append(data)
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() memberName = Name("/first/user") memberKeyName = Name(memberName).append(Name("/KEY/%0C%87%EB%E6U%27B%D6")) memberKeyChain = KeyChain("pib-memory:", "tpm-memory:") memberKeyChain.importSafeBag(SafeBag (memberKeyName, Blob(MEMBER_PRIVATE_KEY, False), Blob(MEMBER_PUBLIC_KEY, False))) # TODO: Use a real Validator. decryptor = DecryptorV2( memberKeyChain.getPib().getIdentity(memberName).getDefaultKey(), ValidatorNull(), memberKeyChain, face) contentPrefix = Name("/testname/content") contentNamespace = Namespace(contentPrefix) contentNamespace.setFace(face) contentNamespace.setDecryptor(decryptor) enabled = [True] def onSegmentedObject(objectNamespace): dump("Got segmented content", objectNamespace.obj.toRawStr()) enabled[0] = False SegmentedObjectHandler(contentNamespace, onSegmentedObject).objectNeeded() 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 setUp(self): testCertDirectory = 'policy_config/certs' self.testCertFile = os.path.join(testCertDirectory, 'test.cert') self.identityStorage = MemoryIdentityStorage() self.privateKeyStorage = MemoryPrivateKeyStorage() self.identityManager = IdentityManager(self.identityStorage, self.privateKeyStorage) self.policyManager = ConfigPolicyManager('policy_config/simple_rules.conf') self.identityName = Name('/TestConfigPolicyManager/temp') # to match the anchor cert keyName = Name(self.identityName).append('ksk-1416010123') self.privateKeyStorage.setKeyPairForKeyName( keyName, KeyType.RSA, TEST_RSA_PUBLIC_KEY_DER, TEST_RSA_PRIVATE_KEY_DER) self.identityStorage.addKey( keyName, KeyType.RSA, Blob(TEST_RSA_PUBLIC_KEY_DER)) cert = self.identityManager.selfSign(keyName) self.identityStorage.setDefaultKeyNameForIdentity(keyName) self.identityManager.addCertificateAsDefault(cert) self.keyChain = KeyChain(self.identityManager, self.policyManager) self.keyName = keyName self.face = Face()
def __init__(self, prefix="/ndn/edu/ucla/remap/music/list"): logging.basicConfig() '''#这些log是干嘛的myIP="192.168.1.1",lightIP="192.168.1.50", self.log = logging.getLogger("RegisterSongList") self.log.setLevel(logging.DEBUG) sh = logging.StreamHandler() sh.setLevel(logging.DEBUG) self.log.addHandler(sh) fh = logging.FileHandler("RegisterSongList.log") fh.setLevel(logging.INFO) self.log.addHandler(fh)''' self.device = "PC3" self.deviceComponent = Name.Component(self.device) self.excludeDevice = None #self.songList = originalList #security? self.prefix = Name(prefix) self.changePrefix = Name("/ndn/edu/ucla/remap/music/storage") self.keychain = KeyChain() self.certificateName = self.keychain.getDefaultCertificateName() self.address = "" self._isStopped = True
def test_self_verification(self): policyManager = SelfVerifyPolicyManager(self.identityStorage) keyChain = KeyChain(self.identityManager, policyManager) identityName = Name('TestValidator/RsaSignatureVerification') keyChain.createIdentityAndCertificate(identityName) data = Data(Name('/TestData/1')) keyChain.signByIdentity(data, identityName) vr = doVerify(policyManager, data) self.assertFalse(vr.hasFurtherSteps, "SelfVerifyPolicyManager returned a ValidationRequest") self.assertEqual(vr.failureCount, 0, "Verification of identity-signed data failed") self.assertEqual(vr.successCount, 1, "Verification success called {} times instead of 1".format( vr.successCount)) data2 = Data(Name('/TestData/2')) vr = doVerify(policyManager, data2) self.assertFalse(vr.hasFurtherSteps, "SelfVerifyPolicyManager returned a ValidationRequest") self.assertEqual(vr.successCount, 0, "Verification of unsigned data succeeded") self.assertEqual(vr.failureCount, 1, "Verification failure callback called {} times instead of 1".format( vr.failureCount))
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 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, producerName, namePrefix): self.configPrefix = Name(namePrefix) prefix_pullService = "/picasso/pull_Service/" self.prefix_pullService = Name(prefix_pullService) self.Datamessage_size = 2000000 #20MB --> Max Size from modified NDN self.window = 1 self.producerName = producerName self.outstanding = dict() self.isDone = False self.keyChain = KeyChain() self.face = Face("127.0.0.1") self.script_path = os.path.abspath( __file__) # i.e. /path/to/dir/foobar.py self.script_dir = os.path.split( self.script_path)[0] #i.e. /path/to/dir/ self.interestLifetime = 12000000 self.num_deployedContainer = 0 self.lastChunk_window = 0 self.lastChunk_sent = 0 folder_name = "SEG_repository/" self.repo_path = os.path.join(self.script_dir, folder_name) if not os.path.exists(self.repo_path): os.makedirs(self.repo_path) folder_name = "Migration_cost/" self.timestamp_path = os.path.join(self.script_dir, folder_name) if not os.path.exists(self.timestamp_path): os.makedirs(self.timestamp_path)
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 setUp(self): testCertDirectory = 'policy_config/certs' self.testCertFile = os.path.join(testCertDirectory, 'test.cert') self.pibImpl = PibMemory() self.tpmBackEnd = TpmBackEndMemory() self.policyManager = ConfigPolicyManager( 'policy_config/simple_rules.conf', CertificateCacheV2()) self.identityName = Name('/TestConfigPolicyManager/temp') # to match the anchor cert self.keyName = Name( self.identityName).append("KEY").append("ksk-1416010123") self.pibImpl.addKey(self.identityName, self.keyName, TEST_RSA_PUBLIC_KEY_DER) # Set the password to None since we have an unencrypted PKCS #8 private key. self.tpmBackEnd.importKey(self.keyName, TEST_RSA_PRIVATE_KEY_PKCS8, None) self.keyChain = KeyChain(self.pibImpl, self.tpmBackEnd, self.policyManager) pibKey = self.keyChain.getPib().getIdentity(self.identityName).getKey( self.keyName) # selfSign adds to the PIB. self.keyChain.selfSign(pibKey)
def __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