def getCertificatesOfKey(self, keyName): """ Get a list of certificate names of the key with id keyName. The returned certificate names can be used to create a PibCertificateContainer. With a certificate name and a backend implementation, one can obtain the certificate. :param Name keyName: The name of the key. :return: The set of certificate names. The Name objects are fresh copies. If the key does not exist, return an empty set. :rtype: set of Name """ certNames = set() try: cursor = self._database.cursor() cursor.execute( "SELECT certificate_name " + "FROM certificates JOIN keys ON certificates.key_id=keys.id " + "WHERE keys.key_name=?", (sqlite3.Binary(bytearray(keyName.wireEncode().buf())), )) rows = cursor.fetchall() for (encoding, ) in rows: name = Name() name.wireDecode(bytearray(encoding)) certNames.add(name) cursor.close() except Exception as ex: raise PibImpl.Error("PibSqlite3: SQLite error: " + str(ex)) return certNames
def getScheduleMembers(self, name): """ For each member using the given schedule, get the name and public key DER of the member's key. :param str name: The name of the schedule. :return: a new dictionary where the dictionary's key is the Name of the public key and the value is the Blob of the public key DER. Note that the member's identity name is keyName.getPrefix(-1). If the schedule name is not found, the dictionary is empty. :rtype: dictionary<Name, Blob> :raises GroupManagerDb.Error: For a database error. """ dictionary = {} try: cursor = self._database.cursor() cursor.execute( "SELECT key_name, pubkey " + "FROM members JOIN schedules ON members.schedule_id=schedules.schedule_id " + "WHERE schedule_name=?", (name,), ) results = cursor.fetchall() for (keyNameEncoding, keyEncoding) in results: keyName = Name() keyName.wireDecode(bytearray(keyNameEncoding), TlvWireFormat.get()) dictionary[keyName] = Blob(bytearray(keyEncoding), False) cursor.close() return dictionary except Exception as ex: raise GroupManagerDb.Error("Sqlite3GroupManagerDb.getScheduleMembers: SQLite error: " + str(ex))
def getDefaultIdentity(self): """ Get the default identity. :return: The name of the default identity, as a fresh copy. :rtype: Name :raises Pib.Error: For no default identity. """ encoding = None try: cursor = self._database.cursor() cursor.execute("SELECT identity FROM identities WHERE is_default=1") row = cursor.fetchone() if row != None: (encoding,) = row cursor.close() except Exception as ex: raise PibImpl.Error("PibSqlite3: SQLite error: " + str(ex)) if encoding != None: name = Name() name.wireDecode(bytearray(encoding)) return name else: raise Pib.Error("No default identity")
def _createDKeyData(self, startTimeStamp, endTimeStamp, keyName, privateKeyBlob, certificateKey): """ Create a D-KEY Data packet with an EncryptedContent for the given private key, encrypted with the certificate key. :param str startTimeStamp: The start time stamp string to put in the name. :param str endTimeStamp: The end time stamp string to put in the name. :param Name keyName The key name to put in the data packet name and the EncryptedContent key locator. :param Blob privateKeyBlob: A Blob of the encoded private key. :param Blob certificateKey: The certificate key encoding, used to encrypt the private key. :return: The Data packet. :rtype: Data """ name = Name(self._namespace) name.append(Encryptor.NAME_COMPONENT_D_KEY) name.append(startTimeStamp).append(endTimeStamp) data = Data(name) data.getMetaInfo().setFreshnessPeriod( self._freshnessHours * GroupManager.MILLISECONDS_IN_HOUR) encryptParams = EncryptParams(EncryptAlgorithmType.RsaOaep) Encryptor.encryptData( data, privateKeyBlob, keyName, certificateKey, encryptParams) self._keyChain.sign(data) return data
def produce(self, data, timeSlot, content, onError=defaultOnError): """ Encrypt the given content with the content key that covers timeSlot, and update the data packet with the encrypted content and an appropriate data name. :param Data data: An empty Data object which is updated. :param float timeSlot: The time slot as milliseconds since Jan 1, 1970 UTC. :param Blob content: The content to encrypt. :param onError: (optional) This calls onError(errorCode, message) for an error, where errorCode is from EncryptError.ErrorCode and message is a str. If omitted, use a default callback which does nothing. NOTE: The library will log any exceptions raised by this callback, but for better error handling the callback should catch and properly handle any exceptions. :type onError: function object """ # Get a content key. contentKeyName = self.createContentKey(timeSlot, None, onError) contentKey = self._database.getContentKey(timeSlot) # Produce data. dataName = Name(self._namespace) dataName.append(Schedule.toIsoString(timeSlot)) data.setName(dataName) params = EncryptParams(EncryptAlgorithmType.AesCbc, 16) Encryptor.encryptData(data, content, contentKeyName, contentKey, params) self._keyChain.sign(data)
def getKeysOfIdentity(self, identityName): """ Get all the key names of the identity with the name identityName. The returned key names can be used to create a KeyContainer. With a key name and a backend implementation, one can create a Key front end instance. :param Name identityName: The name of the identity. :return: The set of key names. The Name objects are fresh copies. If the identity does not exist, return an empty set. :rtype: set of Name """ keyNames = set() try: cursor = self._database.cursor() cursor.execute( "SELECT key_name " + "FROM keys JOIN identities ON keys.identity_id=identities.id " + "WHERE identities.identity=?", (sqlite3.Binary(bytearray(identityName.wireEncode().buf())), )) rows = cursor.fetchall() for (encoding, ) in rows: name = Name() name.wireDecode(bytearray(encoding)) keyNames.add(name) cursor.close() except Exception as ex: raise PibImpl.Error("PibSqlite3: SQLite error: " + str(ex)) return keyNames
def _initialTimeOut(self, interest): """ Initial sync interest timeout, which means there are no other publishers yet. """ if not self._enabled: # Ignore callbacks after the application calls shutdown(). return logging.getLogger(__name__).info("initial sync timeout") logging.getLogger(__name__).info("no other people") self._sequenceNo += 1 if self._sequenceNo != 0: # Since there were no other users, we expect sequence no 0. raise RuntimeError( "ChronoSync: sequenceNo_ is not the expected value of 0 for first use.") tempContent = sync_state_pb2.SyncStateMsg() content = getattr(tempContent, "ss").add() content.name = self._applicationDataPrefixUri content.type = SyncState_UPDATE content.seqno.seq = self._sequenceNo content.seqno.session = self._sessionNo self._update(getattr(tempContent, "ss")) self._onInitialized() name = Name(self._applicationBroadcastPrefix) name.append(self._digestTree.getRoot()) retryInterest = Interest(name) retryInterest.setInterestLifetimeMilliseconds(self._syncLifetime) self._face.expressInterest(retryInterest, self._onData, self._syncTimeout) logging.getLogger(__name__).info("Syncinterest expressed:") logging.getLogger(__name__).info("%s", name.toUri())
def _onData(self, interest, data): """ Process Sync Data. """ if not self._enabled: # Ignore callbacks after the application calls shutdown(). return logging.getLogger(__name__).info( "Sync ContentObject received in callback") logging.getLogger(__name__).info( "name: %s", data.getName().toUri()) # TODO: Check if this works in Python 3. tempContent = SyncStateMsg() #pylint: disable=E1103 tempContent.ParseFromString(data.getContent().toBytes()) #pylint: enable=E1103 content = getattr(tempContent, "ss") if self._digestTree.getRoot() == "00": isRecovery = True #processing initial sync data self._initialOndata(content) else: self._update(content) if (interest.getName().size() == self._applicationBroadcastPrefix.size() + 2): # Assume this is a recovery interest. isRecovery = True else: isRecovery = False # Send the interests to fetch the application data. syncStates = [] for i in range(len(content)): syncState = content[i] # Only report UPDATE sync states. if syncState.type == SyncState_UPDATE: if len(syncState.application_info) > 0: applicationInfo = Blob(syncState.application_info, True) else: applicationInfo = Blob() syncStates.append(self.SyncState( syncState.name, syncState.seqno.session, syncState.seqno.seq, applicationInfo)) try: self._onReceivedSyncState(syncStates, isRecovery) except: logging.exception("Error in onReceivedSyncState") name = Name(self._applicationBroadcastPrefix) name.append(self._digestTree.getRoot()) syncInterest = Interest(name) syncInterest.setInterestLifetimeMilliseconds(self._syncLifetime) self._face.expressInterest(syncInterest, self._onData, self._syncTimeout) logging.getLogger(__name__).info("Syncinterest expressed:") logging.getLogger(__name__).info("%s", name.toUri())
def signByIdentity(self, target, identityName = None, wireFormat = None): """ Sign the target. If it is a Data object, set its signature. If it is an array, return a signature object. :param target: If this is a Data object, wire encode for signing, update its signature and key locator field and wireEncoding. If it is an array, sign it and return a Signature object. :type target: Data or an array which implements the buffer protocol :param Name identityName: (optional) The identity name for the key to use for signing. If omitted, infer the signing identity from the data packet name. :param wireFormat: (optional) A WireFormat object used to encode the input. If omitted, use WireFormat.getDefaultWireFormat(). :type wireFormat: A subclass of WireFormat :return: The Signature object (only if the target is an array). :rtype: An object of a subclass of Signature """ if identityName == None: identityName = Name() if isinstance(target, Data): if identityName.size() == 0: inferredIdentity = self._policyManager.inferSigningIdentity( target.getName()) if inferredIdentity.size() == 0: signingCertificateName = self._identityManager.getDefaultCertificateName() else: signingCertificateName = \ self._identityManager.getDefaultCertificateNameForIdentity(inferredIdentity) else: signingCertificateName = \ self._identityManager.getDefaultCertificateNameForIdentity(identityName) if signingCertificateName.size() == 0: raise SecurityException("No qualified certificate name found!") if not self._policyManager.checkSigningPolicy( target.getName(), signingCertificateName): raise SecurityException( "Signing Cert name does not comply with signing policy") self._identityManager.signByCertificate( target, signingCertificateName, wireFormat) else: signingCertificateName = \ self._identityManager.getDefaultCertificateNameForIdentity(identityName) if signingCertificateName.size() == 0: raise SecurityException("No qualified certificate name found!") return self._identityManager.signByCertificate( target, signingCertificateName)
def _sendRecovery(self, syncDigest): """ Send Recovery Interest. """ logging.getLogger(__name__).info("unknown digest: ") name = Name(self._applicationBroadcastPrefix) name.append("recovery").append(syncDigest) interest = Interest(name) interest.setInterestLifetimeMilliseconds(self._syncLifetime) self._face.expressInterest(interest, self._onData, self._syncTimeout) logging.getLogger(__name__).info("Recovery Syncinterest expressed:") logging.getLogger(__name__).info("%s", name.toUri())
def constructKeyName(identityName, keyId): """ Construct a key name based on the appropriate naming conventions. :param Name identityName: The name of the identity. :param Name.Component keyId: The key ID name component. :return: The constructed name as a new Name. :rtype: Name """ keyName = Name(identityName) keyName.append(CertificateV2.KEY_COMPONENT).append(keyId) return keyName
def __init__(self, prefix, regexFilter = None): if type(prefix) is InterestFilter: interestFilter = prefix # The copy constructor. self._prefix = Name(interestFilter._prefix) self._regexFilter = interestFilter._regexFilter self._regexFilterPattern = interestFilter._regexFilterPattern else: self._prefix = Name(prefix) self._regexFilter = regexFilter if regexFilter != None: self._regexFilterPattern = self.makePattern(regexFilter) else: self._regexFilterPattern = None
def _makeSelfSignedCertificate( keyName, privateKeyBag, publicKeyEncoding, password, digestAlgorithm, wireFormat): certificate = CertificateV2() # Set the name. now = Common.getNowMilliseconds() certificateName = Name(keyName) certificateName.append("self").appendVersion(int(now)) certificate.setName(certificateName) # Set the MetaInfo. certificate.getMetaInfo().setType(ContentType.KEY) # Set a one-hour freshness period. certificate.getMetaInfo().setFreshnessPeriod(3600 * 1000.0) # Set the content. publicKey = PublicKey(publicKeyEncoding) certificate.setContent(publicKey.getKeyDer()) # Create a temporary in-memory Tpm and import the private key. tpm = Tpm("", "", TpmBackEndMemory()) tpm._importPrivateKey(keyName, privateKeyBag.toBytes(), password) # Set the signature info. if publicKey.getKeyType() == KeyType.RSA: certificate.setSignature(Sha256WithRsaSignature()) elif publicKey.getKeyType() == KeyType.EC: certificate.setSignature(Sha256WithEcdsaSignature()) else: raise ValueError("Unsupported key type") signatureInfo = certificate.getSignature() KeyLocator.getFromSignature(signatureInfo).setType(KeyLocatorType.KEYNAME) KeyLocator.getFromSignature(signatureInfo).setKeyName(keyName) # Set a 20-year validity period. ValidityPeriod.getFromSignature(signatureInfo).setPeriod( now, now + 20 * 365 * 24 * 3600 * 1000.0) # Encode once to get the signed portion. encoding = certificate.wireEncode(wireFormat) signatureBytes = tpm.sign(encoding.toSignedBytes(), keyName, digestAlgorithm) signatureInfo.setSignature(signatureBytes) # Encode again to include the signature. certificate.wireEncode(wireFormat) return certificate
def __init__(self, expectedNEntries, face, syncPrefix, onNamesUpdate, keyChain, syncInterestLifetime = DEFAULT_SYNC_INTEREST_LIFETIME, syncReplyFreshnessPeriod = DEFAULT_SYNC_REPLY_FRESHNESS_PERIOD, signingInfo = SigningInfo(), canAddToSyncData = None, canAddReceivedName = None): super(FullPSync2017, self).__init__( expectedNEntries, syncPrefix, syncReplyFreshnessPeriod) self._face = face self._keyChain = keyChain self._syncInterestLifetime = syncInterestLifetime self._signingInfo = SigningInfo(signingInfo) self._onNamesUpdate = onNamesUpdate self._canAddToSyncData = canAddToSyncData self._canAddReceivedName = canAddReceivedName self._segmentPublisher = PSyncSegmentPublisher(self._face, self._keyChain) # The key is the Name. The values is a _PendingEntryInfoFull. self._pendingEntries = {} self._outstandingInterestName = Name() self._registeredPrefix = self._face.registerPrefix( self._syncPrefix, self._onSyncInterest, PSyncProducerBase.onRegisterFailed) # TODO: Should we do this after the registerPrefix onSuccess callback? self._sendSyncInterest()
def __init__(self, onReceivedSyncState, onInitialized, applicationDataPrefix, applicationBroadcastPrefix, sessionNo, face, keyChain, certificateName, syncLifetime, onRegisterFailed): self._onReceivedSyncState = onReceivedSyncState self._onInitialized = onInitialized self._applicationDataPrefixUri = applicationDataPrefix.toUri() self._applicationBroadcastPrefix = Name(applicationBroadcastPrefix) self._sessionNo = sessionNo self._face = face self._keyChain = keyChain self._certificateName = Name(certificateName) self._syncLifetime = syncLifetime self._contentCache = MemoryContentCache(face) self._digestLog = [] # of _DigestLogEntry self._digestTree = DigestTree() self._sequenceNo = -1 self._enabled = True emptyContent = SyncStateMsg() # Use getattr to avoid pylint errors. self._digestLog.append(self._DigestLogEntry("00", getattr(emptyContent, "ss"))) # Register the prefix with the contentCache_ and use our own onInterest # as the onDataNotFound fallback. self._contentCache.registerPrefix( self._applicationBroadcastPrefix, onRegisterFailed, self._onInterest) interest = Interest(self._applicationBroadcastPrefix) interest.getName().append("00") interest.setInterestLifetimeMilliseconds(1000) interest.setMustBeFresh(True) face.expressInterest(interest, self._onData, self._initialTimeOut) logging.getLogger(__name__).info("initial sync expressed") logging.getLogger(__name__).info("%s", interest.getName().toUri())
def toUri(self): """ Encode the name according to the "NDN URI Scheme". If there are interest selectors, append "?" and add the selectors as a query string. For example "/test/name?ndn.ChildSelector=1". :note: This is an experimental feature. See the API docs for more detail at http://named-data.net/doc/ndn-ccl-api/interest.html#interest-touri-method . :return: The URI string. :rtype: string """ selectors = "" if self._minSuffixComponents != None: selectors += "&ndn.MinSuffixComponents=" + repr(self._minSuffixComponents) if self._maxSuffixComponents != None: selectors += "&ndn.MaxSuffixComponents=" + repr(self._maxSuffixComponents) if self._childSelector != None: selectors += "&ndn.ChildSelector=" + repr(self._childSelector) if self._mustBeFresh: selectors += "&ndn.MustBeFresh=true" if self._scope != None: selectors += "&ndn.Scope=" + repr(self._scope) if self._interestLifetimeMilliseconds != None: selectors += "&ndn.InterestLifetime=" + repr(int(round(self._interestLifetimeMilliseconds))) if self.getNonce().size() > 0: selectors += "&ndn.Nonce=" + Name.toEscapedString(self.getNonce().buf()) if self.getExclude().size() > 0: selectors += "&ndn.Exclude=" + self.getExclude().toUri() result = self.getName().toUri() if selectors != "": # Replace the first & with ?. result += "?" + selectors[1:] return result
def _encryptContentKey(self, encryptionKey, eKeyName, timeSlot, onEncryptedKeys, onError): """ Get the content key from the database_ and encrypt it for the timeSlot using encryptionKey. :param Blob encryptionKey: The encryption key value. :param Name eKeyName: The key name for the EncryptedContent. :param float timeSlot: The time slot as milliseconds since Jan 1, 1970 UTC. :param onEncryptedKeys: When there are no more interests to process, this calls onEncryptedKeys(keys) where keys is a list of encrypted content key Data packets. If onEncryptedKeys is None, this does not use it. :type onEncryptedKeys: function object :param onError: This calls onError(errorCode, message) for an error. :type onError: function object :return: True if encryption succeeds, otherwise False. :rtype: bool """ timeCount = round(timeSlot) keyRequest = self._keyRequests[timeCount] keyName = Name(self._namespace) keyName.append(Encryptor.NAME_COMPONENT_C_KEY) keyName.append( Schedule.toIsoString(Producer._getRoundedTimeSlot(timeSlot))) contentKey = self._database.getContentKey(timeSlot) cKeyData = Data() cKeyData.setName(keyName) params = EncryptParams(EncryptAlgorithmType.RsaOaep) try: Encryptor.encryptData( cKeyData, contentKey, eKeyName, encryptionKey, params) except Exception as ex: try: onError(EncryptError.ErrorCode.EncryptionFailure, "encryptData error: " + repr(ex)) except: logging.exception("Error in onError") return False self._keyChain.sign(cKeyData) keyRequest.encryptedKeys.append(cKeyData) self._updateKeyRequest(keyRequest, timeCount, onEncryptedKeys) return True
def _decryptCKey(self, cKeyData, onPlainText, onError): """ Decrypt cKeyData. :param Data cKeyData: The C-KEY data packet. :param onPlainText: When the data packet is decrypted, this calls onPlainText(decryptedBlob) with the decrypted blob. :type onPlainText: function object :param onError: This calls onError(errorCode, message) for an error, where errorCode is from EncryptError.ErrorCode and message is a str. :type onError: function object """ # Get the encrypted content. cKeyContent = cKeyData.getContent() cKeyEncryptedContent = EncryptedContent() try: cKeyEncryptedContent.wireDecode(cKeyContent) except Exception as ex: try: onError(EncryptError.ErrorCode.InvalidEncryptedFormat, repr(ex)) except: logging.exception("Error in onError") return eKeyName = cKeyEncryptedContent.getKeyLocator().getKeyName() dKeyName = eKeyName.getPrefix(-3) dKeyName.append(Encryptor.NAME_COMPONENT_D_KEY).append( eKeyName.getSubName(-2)) # Check if the decryption key is already in the store. if dKeyName in self._dKeyMap: dKey = self._dKeyMap[dKeyName] Consumer._decrypt(cKeyEncryptedContent, dKey, onPlainText, onError) else: # Get the D-Key Data. interestName = Name(dKeyName) interestName.append(Encryptor.NAME_COMPONENT_FOR).append( self._consumerName) interest = Interest(interestName) def onVerified(validDKeyData): def localOnPlainText(dKeyBits): # dKeyName is already a local copy. self._dKeyMap[dKeyName] = dKeyBits Consumer._decrypt( cKeyEncryptedContent, dKeyBits, onPlainText, onError) self._decryptDKey(validDKeyData, localOnPlainText, onError) self._sendInterest(interest, 1, self._dKeyLink, onVerified, onError)
def _sendSyncData(self, name, content): """ Send the sync Data. Check if the data will satisfy our own pending Interest. If it does, then remove it and then renew the sync interest. Otherwise, just send the Data. :param Name name: The basis to use for the Data name. :param Blob content: The content of the Data. """ logging.getLogger(__name__).debug( "Checking if the Data will satisfy our own pending interest") nameWithIblt = Name() nameWithIblt.append(self._iblt.encode()) # Append the hash of our IBLT so that the Data name should be different # for each node. Use abs() since hash() can return negative. dataName = Name(name).appendNumber(abs(hash(nameWithIblt))) # Check if our own Interest got satisfied. if self._outstandingInterestName.equals(name): logging.getLogger(__name__).debug("Satisfies our own pending Interest") # Remove the outstanding interest. # Debug: Implement stopping an ongoing fetch. #if self._fetcher != None: # logging.getLogger(__name__).debug( # "Removing our pending interest from the Face (stopping fetcher)") # self._fetcher.stop() # self._outstandingInterestName = Name() self._outstandingInterestName = Name() logging.getLogger(__name__).debug("Sending sync Data") # Send Data after removing the pending sync interest on the Face. self._segmentPublisher.publish( name, dataName, content, self._syncReplyFreshnessPeriod, self._signingInfo) logging.getLogger(__name__).info("sendSyncData: Renewing sync interest") self._sendSyncInterest() else: logging.getLogger(__name__).debug( "Sending Sync Data for not our own Interest") self._segmentPublisher.publish( name, dataName, content, self._syncReplyFreshnessPeriod, self._signingInfo)
def _createEKeyData(self, startTimeStamp, endTimeStamp, publicKeyBlob): """ Create an E-KEY Data packet for the given public key. :param str startTimeStamp: The start time stamp string to put in the name. :param str endTimeStamp: The end time stamp string to put in the name. :param Blob publicKeyBlob: A Blob of the public key DER. :return: The Data packet. :rtype: Data """ name = Name(self._namespace) name.append(Encryptor.NAME_COMPONENT_E_KEY).append(startTimeStamp).append(endTimeStamp) data = Data(name) data.getMetaInfo().setFreshnessPeriod(self._freshnessHours * GroupManager.MILLISECONDS_IN_HOUR) data.setContent(publicKeyBlob) self._keyChain.sign(data) return data
def toName(componentArray): """ Return a Name made from the component array in a Protobuf message object, assuming that it was defined with "repeated bytes". For example: message Name { repeated bytes component = 8; } :param Array componentArray: The array from the Protobuf message object representing the "repeated bytes" component array. :return: A new Name. :rtype: Name """ name = Name() for component in componentArray: name.append(Blob(component, True)) return name
def _sendSyncInterest(self): """ Send the sync interest for full synchronization. This forms the interest name: /<sync-prefix>/<own-IBLT>. This cancels any pending sync interest we sent earlier on the face. """ # Debug: Implement stopping an ongoing fetch. ## If we send two sync interest one after the other ## since there is no new data in the network yet, ## when data is available it may satisfy both of them #if self._fetcher != None: # self._fetcher.stop() # Sync Interest format for full sync: /<sync-prefix>/<ourLatestIBF> syncInterestName = Name(self._syncPrefix) # Append our latest IBLT. syncInterestName.append(self._iblt.encode()) self._outstandingInterestName = syncInterestName # random1 is from 0.0 to 1.0. random1 = self._systemRandom.random() # Get a jitter of +/- syncInterestLifetime_ * 0.2 . jitter = (random1 - 0.5) * (self._syncInterestLifetime * 0.2) self._face.callLater(self._syncInterestLifetime / 2 + jitter, self._sendSyncInterest) syncInterest = Interest(syncInterestName) syncInterest.setInterestLifetimeMilliseconds( self._syncInterestLifetime) syncInterest.refreshNonce() SegmentFetcher.fetch( self._face, syncInterest, None, lambda content: self._onSyncData(content, syncInterest), FullPSync2017._onError) logging.getLogger(__name__).debug("sendFullSyncInterest, nonce: " + syncInterest.getNonce().toHex() + ", hash: " + str(abs(hash(syncInterestName))))
def setCommandCertificateName(self, certificateName): """ Set the certificate name used to sign command interest (e.g. for registerPrefix), using the KeyChain that was set with setCommandSigningInfo. :param Name certificateName: The certificate name for signing interest. This makes a copy of the Name. """ self._commandCertificateName = Name(certificateName)
def clear(self): """ Clear fields and reset to default values. """ self._type = ContentType.BLOB self._otherTypeCode = -1 self._freshnessPeriod = None self._finalBlockId = Name.Component() self._changeCount += 1
def __init__(self): self._name = Name() self._faceId = None # TODO: Add "Uri" string. self._localControlFeature = None self._origin = None self._cost = None self._forwardingFlags = ForwardingFlags() # TODO: Add "Strategy" name. self._expirationPeriod = None
def clear(self): self._name = None self._faceId = None self._uri = "" self._localControlFeature = None self._origin = None self._cost = None self._flags = RegistrationOptions() self._strategy = Name() self._expirationPeriod = None
def setKeyName(self, keyName): """ Set key name to a copy of the given Name. This is the name if getType() is KeyLocatorType.KEYNAME. :param Name keyName: The key name which is copied. """ self._keyName.set( keyName if isinstance(keyName, Name) else Name(keyName)) self._changeCount += 1
def clear(self): self._name = None self._faceId = None self._uri = "" self._localControlFeature = None self._origin = None self._cost = None self._forwardingFlags = ForwardingFlags() self._strategy = Name() self._expirationPeriod = None
def main(filepath=None, maxSuccess=None): with open('attacker2.csv', 'rb') as f: dataArray = [] readdata = f.read(8*1024) dataArray.append(readdata) manifestData = {} count = 0 seq = 0 while readdata: digest = hashes.Hash(hashes.SHA256(), backend=default_backend()) digest.update(readdata) manifestData[(seq+count)]=(str(digest.finalize())) #c = sys.getsizeof(manifestData) count = count + 1 if count == 100: #print(manifestData) s=json.dumps(manifestData).encode('utf-8') manifest_packet = Manifest(Name("prefix/data/"+str(seq))) manifest_packet.setContent(s) k = json.loads(Blob(manifest_packet.getContent()).toBytes().decode('utf-8')) print(sys.getsizeof(Blob(s))) #print(seq) if seq == 15150: print(manifestData[15150]) print(k["15150"]) #print(Blob(s).toBytes().decode('utf-8')) #print(json.loads(s.decode('utf-8'))) #print(manifest_packet.getName()) while count > 0: seq = seq + 1 datapacket = Data(Name("prefix/data/"+str(seq))) datapacket.setContent(dataArray[10-count]) print(datapacket.getContent()) count = count - 1 seq = seq + 1 manifestData = {} dataArray = [] readdata = f.read(8*1024) dataArray.append(readdata)
def __init__(self, face, keyChain, groupName, consumerName, database): self._database = database self._keyChain = keyChain self._face = face self._groupName = Name(groupName) self._consumerName = Name(consumerName) # The dictionary key is the C-KEY name. The value is the encoded key Blob. self._cKeyMap = {} # The dictionary key is the D-KEY name. The value is the encoded key Blob. self._dKeyMap = {}
def __init__(self): if not WireFormat.ENABLE_NDNX: raise RuntimeError( "ForwardingEntry is for NDNx and is deprecated. To enable while you upgrade your code to use NFD, set WireFormat.ENABLE_NDNX = True" ) self._action = None self._prefix = Name() self._faceId = None self._forwardingFlags = ForwardingFlags() self._freshnessPeriod = None
def __init__(self, value=None): if isinstance(value, Data): # Copy the values. self._name = ChangeCounter(Name(value.getName())) self._metaInfo = ChangeCounter(MetaInfo(value.getMetaInfo())) self._signature = ChangeCounter(value.getSignature().clone()) self._content = value._content self._defaultWireEncoding = value.getDefaultWireEncoding() self._defaultWireEncodingFormat = value._defaultWireEncodingFormat else: self._name = ChangeCounter( Name(value) if type(value) is Name else Name()) self._metaInfo = ChangeCounter(MetaInfo()) self._signature = ChangeCounter(Sha256WithRsaSignature()) self._content = Blob() self._defaultWireEncoding = SignedBlob() self._defaultWireEncodingFormat = None self._getDefaultWireEncodingChangeCount = 0 self._changeCount = 0
def registerPrefix( self, prefix, onInterest, onRegisterFailed, onRegisterSuccess = None, registrationOptions = None, wireFormat = None): """ Register prefix with the connected NDN hub and call onInterest when a matching interest is received. To register a prefix with NFD, you must first call setCommandSigningInfo. :param Name prefix: The Name for the prefix to register. This copies the Name. :param onInterest: If not None, this creates an interest filter from prefix so that when an Interest is received which matches the filter, this calls onInterest(prefix, interest, face, interestFilterId, filter). NOTE: You must not change the prefix or filter objects - if you need to change them then make a copy. If onInterest is None, it is ignored and you must call setInterestFilter. NOTE: The library will log any exceptions raised by this callback, but for better error handling the callback should catch and properly handle any exceptions. :type onInterest: function object :param onRegisterFailed: If register prefix fails for any reason, this calls onRegisterFailed(prefix). NOTE: The library will log any exceptions raised by this callback, but for better error handling the callback should catch and properly handle any exceptions. :type onRegisterFailed: function object :param onRegisterSuccess: (optional) This calls onRegisterSuccess(prefix, registeredPrefixId) when this receives a success message from the forwarder. If onRegisterSuccess is None or omitted, this does not use it. (The onRegisterSuccess parameter comes after onRegisterFailed because it can be None or omitted, unlike onRegisterFailed.) NOTE: The library will log any exceptions raised by this callback, but for better error handling the callback should catch and properly handle any exceptions. :type onRegisterSuccess: function object :param RegistrationOptions registrationOptions: (optional) The registration options for finer control of how to forward an interest and other options. :param wireFormat: (optional) A WireFormat object used to encode this ControlParameters. If omitted, use WireFormat.getDefaultWireFormat(). :type wireFormat: A subclass of WireFormat :raises: This raises an exception if setCommandSigningInfo has not been called to set the KeyChain, etc. for signing the command interest. """ registeredPrefixId = self._node.getNextEntryId() # Node.registerPrefix requires a copy of the prefix. self._registerPrefixHelper( registeredPrefixId, Name(prefix), onInterest, onRegisterFailed, onRegisterSuccess, registrationOptions, wireFormat) return registeredPrefixId
def setDefaultKeyForIdentity(self, keyName, identityName = None): """ Set a key as the default key of an identity. :param Name keyName: The name of the key. :param Name identityName: (optional) the name of the identity. If not specified, the identity name is inferred from the keyName. """ if identityName == None: identityName = Name() self._identityStorage.setDefaultKeyNameForIdentity(keyName, identityName)
def _createEKeyData(self, startTimeStamp, endTimeStamp, publicKeyBlob): """ Create an E-KEY Data packet for the given public key. :param str startTimeStamp: The start time stamp string to put in the name. :param str endTimeStamp: The end time stamp string to put in the name. :param Blob publicKeyBlob: A Blob of the public key DER. :return: The Data packet. :rtype: Data """ name = Name(self._namespace) name.append(Encryptor.NAME_COMPONENT_E_KEY).append( startTimeStamp).append(endTimeStamp) data = Data(name) data.getMetaInfo().setFreshnessPeriod( self._freshnessHours * GroupManager.MILLISECONDS_IN_HOUR) data.setContent(publicKeyBlob) self._keyChain.sign(data) return data
def setName(self, name): """ Set name to a copy of the given Name. :param Name name: The Name which is copied. :return: This Data so that you can chain calls to update values. :rtype: Data """ self._name.set(name if type(name) is Name else Name(name)) self._changeCount += 1 return self
def setDefaultIdentity(self, identityName): """ Set the identity with the identityName as the default identity. If the identity with identityName does not exist, then it will be created. :param Name identityName: The name for the default identity. This copies the name. """ self.addIdentity(identityName) # Copy the name. self._defaultIdentityName = Name(identityName)
def _sendSyncInterest(self): """ Send the sync interest for full synchronization. This forms the interest name: /<sync-prefix>/<own-IBLT>. This cancels any pending sync interest we sent earlier on the face. """ # Debug: Implement stopping an ongoing fetch. ## If we send two sync interest one after the other ## since there is no new data in the network yet, ## when data is available it may satisfy both of them #if self._fetcher != None: # self._fetcher.stop() # Sync Interest format for full sync: /<sync-prefix>/<ourLatestIBF> syncInterestName = Name(self._syncPrefix) # Append our latest IBLT. syncInterestName.append(self._iblt.encode()) self._outstandingInterestName = syncInterestName # random1 is from 0.0 to 1.0. random1 = self._systemRandom.random() # Get a jitter of +/- syncInterestLifetime_ * 0.2 . jitter = (random1 - 0.5) * (self._syncInterestLifetime * 0.2) self._face.callLater( self._syncInterestLifetime / 2 + jitter, self._sendSyncInterest) syncInterest = Interest(syncInterestName) syncInterest.setInterestLifetimeMilliseconds(self._syncInterestLifetime) syncInterest.refreshNonce() SegmentFetcher.fetch( self._face, syncInterest, None, lambda content: self._onSyncData(content, syncInterest), FullPSync2017._onError) logging.getLogger(__name__).debug("sendFullSyncInterest, nonce: " + syncInterest.getNonce().toHex() + ", hash: " + str(abs(hash(syncInterestName))))
def getKeyLocatorName(dataOrInterest, state): """ Extract the KeyLocator Name from a Data or signed Interest packet. The SignatureInfo in the packet must contain a KeyLocator of type KEYNAME. Otherwise, state.fail is invoked with INVALID_KEY_LOCATOR. :param dataOrInterest: The Data or Interest packet with the KeyLocator. :type dataOrInterest: Data or Interest :param ValidationState state: On error, this calls state.fail and returns an empty Name. :return: The KeyLocator name, or an empty Name for failure. :rtype: Name """ if isinstance(dataOrInterest, Data): data = dataOrInterest return ValidationPolicy._getKeyLocatorNameFromSignature( data.getSignature(), state) else: interest = dataOrInterest name = interest.getName() if name.size() < 2: state.fail( ValidationError(ValidationError.INVALID_KEY_LOCATOR, "Invalid signed Interest: name too short")) return Name() try: # TODO: Generalize the WireFormat. signatureInfo = WireFormat.getDefaultWireFormat( ).decodeSignatureInfoAndValue( interest.getName().get(-2).getValue().buf(), interest.getName().get(-1).getValue().buf()) except Exception as ex: state.fail( ValidationError(ValidationError.INVALID_KEY_LOCATOR, "Invalid signed Interest: " + repr(ex))) return Name() return ValidationPolicy._getKeyLocatorNameFromSignature( signatureInfo, state)
def _decryptContent(self, data, onPlainText, onError): """ Decrypt the data packet. :param Data data: The data packet. This does not verify the packet. :param onPlainText: When the data packet is decrypted, this calls onPlainText(decryptedBlob) with the decrypted blob. :type onPlainText: function object :param onError: This calls onError(errorCode, message) for an error, where errorCode is from EncryptError.ErrorCode and message is a str. :type onError: function object """ # Get the encrypted content. dataEncryptedContent = EncryptedContent() try: dataEncryptedContent.wireDecode(data.getContent()) except Exception as ex: Consumer._callOnError(onError, EncryptError.ErrorCode.InvalidEncryptedFormat, repr(ex)) return cKeyName = dataEncryptedContent.getKeyLocator().getKeyName() # Check if the content key is already in the store. if cKeyName in self._cKeyMap: cKey = self._cKeyMap[cKeyName] self._decrypt(dataEncryptedContent, cKey, onPlainText, onError) else: # Retrieve the C-KEY Data from the network. interestName = Name(cKeyName) interestName.append(Encryptor.NAME_COMPONENT_FOR).append(self._groupName) interest = Interest(interestName) def onVerified(validCKeyData): def localOnPlainText(cKeyBits): # cKeyName is already a copy inside the local # dataEncryptedContent. self._cKeyMap[cKeyName] = cKeyBits Consumer._decrypt( dataEncryptedContent, cKeyBits, onPlainText, onError) self._decryptCKey(validCKeyData, localOnPlainText, onError) self._sendInterest(interest, 1, self._cKeyLink, onVerified, onError)
def __init__(self, accessPrefix, ckPrefix, ckDataSigningInfo, onError, validator, keyChain, face): # Copy the Name. self._accessPrefix = Name(accessPrefix) self._ckPrefix = Name(ckPrefix) self._ckBits = bytearray(EncryptorV2.AES_KEY_SIZE) self._ckDataSigningInfo = SigningInfo(ckDataSigningInfo) self._isKekRetrievalInProgress = False self._onError = onError self._keyChain = keyChain self._face = face self._kekData = None # Storage for encrypted CKs. self._storage = InMemoryStorageRetaining() self._kekPendingInterestId = 0 self.regenerateCk() def onInterest(prefix, interest, face, interestFilterId, filter): data = self._storage.find(interest) if data != None: logging.getLogger(__name__).info("Serving " + data.getName().toUri() + " from InMemoryStorage") try: face.putData(data) except: logging.exception("Error in Face.putData") else: logging.getLogger(__name__).info("Didn't find CK data for " + interest.getName().toUri()) # TODO: Send NACK? def onRegisterFailed(prefix): logging.getLogger(__name__).error("Failed to register prefix " + prefix.toUri()) self._ckRegisteredPrefixId = self._face.registerPrefix( Name(ckPrefix).append(EncryptorV2.NAME_COMPONENT_CK), onInterest, onRegisterFailed)
def setDefaultCertificateNameForKey(self, keyName, certificateName): """ Set the default key name for the specified identity. :param Name keyName: The key name. :param Name certificateName: The certificate name. """ keyNameUri = keyName.toUri() if keyNameUri in self._keyStore: # Replace the third element. self._keyStore[keyNameUri] = (self._keyStore[keyNameUri][0:2] + (Name(certificateName), ))
def _syncTimeout(self, interest): """ Sync interest time out. If the interest is the static one send again. """ if not self._enabled: # Ignore callbacks after the application calls shutdown(). return logging.getLogger(__name__).info("Sync Interest time out.") logging.getLogger(__name__).info("Sync Interest name: %s", interest.getName().toUri()) component = interest.getName().get(4).toEscapedString() if component == self._digestTree.getRoot(): name = Name(interest.getName()) retryInterest = Interest(interest.getName()) retryInterest.setInterestLifetimeMilliseconds(self._syncLifetime) self._face.expressInterest(retryInterest, self._onData, self._syncTimeout) logging.getLogger(__name__).info("Syncinterest expressed:") logging.getLogger(__name__).info("%s", name.toUri())
def setName(self, name): """ Set the interest name. :note: You can also call getName and change the name values directly. :param Name name: The interest name. This makes a copy of the name. :return: This Interest so that you can chain calls to update values. :rtype: Interest """ self._name.set(name if type(name) is Name else Name(name)) self._changeCount += 1 return self
def removeUserNode(self, prefix): """ Remove the user node from the synchronization. This erases the prefix from the IBLT and other tables. :param Name prefix: The prefix Name of the user node to be removed. If there is no user node with this prefix, do nothing. """ if self._prefixes.isUserNode(prefix): sequenceNo = self._prefixes._prefixes[prefix] self._prefixes.removeUserNode(prefix) self._fullPSync.removeName(Name(prefix).appendNumber(sequenceNo))
def _syncTimeout(self, interest): """ Sync interest time out. If the interest is the static one send again. """ if not self._enabled: # Ignore callbacks after the application calls shutdown(). return logging.getLogger(__name__).info("Sync Interest time out.") logging.getLogger(__name__).info( "Sync Interest name: %s", interest.getName().toUri()) component = interest.getName().get(4).toEscapedString() if component == self._digestTree.getRoot(): name = Name(interest.getName()) retryInterest = Interest(interest.getName()) retryInterest.setInterestLifetimeMilliseconds(self._syncLifetime) self._face.expressInterest( retryInterest, self._onData, self._syncTimeout) logging.getLogger(__name__).info("Syncinterest expressed:") logging.getLogger(__name__).info("%s", name.toUri())
def __init__(self, identityName, pibImpl): # Cache of loaded PibKeyImpl objects. Name => PibKeyImpl. self._keys = {} # Copy the Name. self._identityName = Name(identityName) self._pibImpl = pibImpl if pibImpl == None: raise ValueError("The pibImpl is None") self._keyNames = self._pibImpl.getKeysOfIdentity(identityName)
def setSigningIdentity(self, identityName): """ Set this to type SignerType.ID and an identity with name identityName. This does not change the digest algorithm. :param Name identityName: The name of the identity. This copies the Name. :return: This SigningInfo. :rtype: SigningInfo """ self.reset(SigningInfo.SignerType.ID) self._name = Name(identityName) return self
def __init__(self, transport, connectionInfo): self._transport = transport self._connectionInfo = connectionInfo # An array of PendintInterest self._pendingInterestTable = [] # An array of RegisteredPrefix self._registeredPrefixTable = [] self._ndndIdFetcherInterest = Interest( Name("/%C1.M.S.localhost/%C1.M.SRV/ndnd/KEY")) self._ndndIdFetcherInterest.setInterestLifetimeMilliseconds(4000.0) self._ndndId = None self._commandInterestGenerator = CommandInterestGenerator()
def setSigningKeyName(self, keyName): """ Set this to type SignerType.KEY and a key with name keyName. This does not change the digest algorithm. :param Name keyName: The name of the key. This copies the Name. :return: This SigningInfo. :rtype: SigningInfo """ self.reset(SigningInfo.SignerType.KEY) self._name = Name(keyName) return self
def _createDKeyData(self, startTimeStamp, endTimeStamp, keyName, privateKeyBlob, certificateKey): """ Create a D-KEY Data packet with an EncryptedContent for the given private key, encrypted with the certificate key. :param str startTimeStamp: The start time stamp string to put in the name. :param str endTimeStamp: The end time stamp string to put in the name. :param Name keyName The key name to put in the data packet name and the EncryptedContent key locator. :param Blob privateKeyBlob: A Blob of the encoded private key. :param Blob certificateKey: The certificate key encoding, used to encrypt the private key. :return: The Data packet. :rtype: Data """ name = Name(self._namespace) name.append(Encryptor.NAME_COMPONENT_D_KEY) name.append(startTimeStamp).append(endTimeStamp) data = Data(name) data.getMetaInfo().setFreshnessPeriod( self._freshnessHours * GroupManager.MILLISECONDS_IN_HOUR) encryptParams = EncryptParams(EncryptAlgorithmType.RsaOaep) Encryptor.encryptData(data, privateKeyBlob, keyName, certificateKey, encryptParams) self._keyChain.sign(data) return data
def setSigningCertificateName(self, certificateName): """ Set this to type SignerType.CERT and a certificate with name certificateName. This does not change the digest algorithm. :param Name certificateName: The name of the certificate. This copies the Name. :return: This SigningInfo. :rtype: SigningInfo """ self.reset(SigningInfo.SignerType.CERT) self._name = Name(certificateName) return self
def __init__(self, transport, connectionInfo): self._transport = transport self._connectionInfo = connectionInfo # An array of PendintInterest self._pendingInterestTable = [] # An array of RegisteredPrefix self._registeredPrefixTable = [] self._ndndIdFetcherInterest = Interest( Name("/%C1.M.S.localhost/%C1.M.SRV/ndnd/KEY")) self._ndndIdFetcherInterest.setInterestLifetimeMilliseconds(4000.0) self._ndndId = None self._commandInterestGenerator = CommandInterestGenerator() self._timeoutPrefix = Name("/local/timeout")
def __init__(self, value=None): if type(value) is ControlParameters: # Make a deep copy. self._name = None if value._name == None else Name(value._name) self._faceId = value._faceId self._uri = value._uri self._localControlFeature = value._localControlFeature self._origin = value._origin self._cost = value._cost self._forwardingFlags = ForwardingFlags(value._forwardingFlags) self._strategy = Name(value._strategy) self._expirationPeriod = value._expirationPeriod else: self._name = None self._faceId = None self._uri = "" self._localControlFeature = None self._origin = None self._cost = None self._forwardingFlags = ForwardingFlags() self._strategy = Name() self._expirationPeriod = None
def addIdentity(self, identityName): """ Add the identity. If the identity already exists, do nothing. If no default identity has been set, set the added identity as the default. :param Name identityName: The name of the identity to add. This copies the name. """ identityNameCopy = Name(identityName) self._identityNames.add(identityNameCopy) if self._defaultIdentityName == None: self._defaultIdentityName = identityNameCopy
def addKey(self, identityName, keyName, key): """ Add the key. If a key with the same name already exists, overwrite the key. If the identity does not exist, it will be created. If no default key for the identity has been set, then set the added key as the default for the identity. If no default identity has been set, identity becomes the default. :param Name identityName: The name of the identity that the key belongs to. This copies the name. :param Name keyName: The name of the key. This copies the name. :param key: The public key bits. This copies the array. :type key: an array which implements the buffer protocol """ self.addIdentity(identityName) keyNameCopy = Name(keyName) self._keys[keyNameCopy] = Blob(key, True) if not identityName in self._defaultKeyNames: # Copy the identityName. self._defaultKeyNames[Name(identityName)] = keyNameCopy
def getDefaultIdentity(self): """ Get the default identity. :return: The name of the default identity, as a fresh copy. :rtype: Name :raises Pib.Error: For no default identity. """ if self._defaultIdentityName != None: # Copy the name. return Name(self._defaultIdentityName) raise Pib.Error("No default identity")
def getIdentities(self): """ Get the names of all the identities. :return: The a fresh set of identity names. The Name objects are fresh copies. :rtype: set of Name """ identities = set() try: cursor = self._database.cursor() cursor.execute("SELECT identity FROM identities") rows = cursor.fetchall() for (encoding, ) in rows: name = Name() name.wireDecode(bytearray(encoding)) identities.add(name) cursor.close() except Exception as ex: raise PibImpl.Error("PibSqlite3: SQLite error: " + str(ex)) return identities
def __init__(self, transport, connectionInfo): self._transport = transport self._connectionInfo = connectionInfo self._pendingInterestTable = PendingInterestTable() self._interestFilterTable = InterestFilterTable() self._registeredPrefixTable = RegisteredPrefixTable(self._interestFilterTable) self._delayedCallTable = DelayedCallTable() # An array of function objects self._onConnectedCallbacks = [] self._commandInterestGenerator = CommandInterestGenerator() self._timeoutPrefix = Name("/local/timeout") self._lastEntryId = 0 self._lastEntryIdLock = threading.Lock() self._connectStatus = Node._ConnectStatus.UNCONNECTED
def listAllMembers(self): """ List all the members. :return: A new List of Name with the names of all members. :rtype: Array<Name> :raises GroupManagerDb.Error: For a database error. """ list = [] try: cursor = self._database.cursor() cursor.execute("SELECT member_name FROM members", ()) results = cursor.fetchall() for (nameEncoding,) in results: identity = Name() identity.wireDecode(bytearray(nameEncoding), TlvWireFormat.get()) list.append(identity) cursor.close() return list except Exception as ex: raise GroupManagerDb.Error("Sqlite3GroupManagerDb.listAllMembers: SQLite error: " + str(ex))