def test_malformed_certificate(self): # Copy the default certificate. malformedCertificate = Data( self._fixture._subIdentity.getDefaultKey().getDefaultCertificate()) malformedCertificate.getMetaInfo().setType(ContentType.BLOB) self._fixture._keyChain.sign(malformedCertificate, SigningInfo(self._fixture._identity)) # It has the wrong content type and a missing ValidityPeriod. try: CertificateV2(malformedCertificate).wireEncode() self.fail("Did not throw the expected exception") except CertificateV2.Error: pass else: self.fail("Did not throw the expected exception") originalProcessInterest = self._fixture._face._processInterest def processInterest(interest, onData, onTimeout, onNetworkNack): if interest.getName().isPrefixOf(malformedCertificate.getName()): onData(interest, malformedCertificate) else: originalProcessInterest.processInterest( interest, onData, onTimeout, onNetworkNack) self._fixture._face._processInterest = processInterest data = Data(Name("/Security/V2/ValidatorFixture/Sub1/Sub2/Data")) self._fixture._keyChain.sign(data, SigningInfo(self._fixture._subIdentity)) self.validateExpectFailure(data, "Signed by a malformed certificate") self.assertEqual(1, len(self._fixture._face._sentInterests))
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 test_expired_certificate(self): # Copy the default certificate. expiredCertificate = Data( self._fixture._subIdentity.getDefaultKey().getDefaultCertificate()) info = SigningInfo(self._fixture._identity) # Validity period from 2 hours ago do 1 hour ago. now = Common.getNowMilliseconds() info.setValidityPeriod( ValidityPeriod(now - 2 * 3600 * 1000, now - 3600 * 1000.0)) self._fixture._keyChain.sign(expiredCertificate, info) try: CertificateV2(expiredCertificate).wireEncode() except Exception as ex: self.fail("Unexpected exception: " + str(ex)) originalProcessInterest = self._fixture._face._processInterest def processInterest(interest, onData, onTimeout, onNetworkNack): if interest.getName().isPrefixOf(expiredCertificate.getName()): onData(interest, expiredCertificate) else: originalProcessInterest.processInterest( interest, onData, onTimeout, onNetworkNack) self._fixture._face._processInterest = processInterest data = Data(Name("/Security/V2/ValidatorFixture/Sub1/Sub2/Data")) self._fixture._keyChain.sign(data, SigningInfo(self._fixture._subIdentity)) self.validateExpectFailure(data, "Signed by an expired certificate") self.assertEqual(1, len(self._fixture._face._sentInterests))
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 addSubCertificate(self, subIdentityName, issuer, params = None): """ Issue a certificate for subIdentityName signed by issuer. If the identity does not exist, it is created. A new key is generated as the default key for the identity. A default certificate for the key is signed by the issuer using its default certificate. """ if params == None: params = KeyChain.getDefaultKeyParams() subIdentity = self.addIdentity(subIdentityName, params) request = subIdentity.getDefaultKey().getDefaultCertificate() request.setName(request.getKeyName().append("parent").appendVersion(1)) certificateParams = SigningInfo(issuer) # Validity period of 20 years. now = Common.getNowMilliseconds() certificateParams.setValidityPeriod( ValidityPeriod(now, now + 20 * 365 * 24 * 3600 * 1000.0)) # Skip the AdditionalDescription. self._keyChain.sign(request, certificateParams) self._keyChain.setDefaultCertificate(subIdentity.getDefaultKey(), request) return subIdentity
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 test_to_string(self): self.assertEquals("", str(SigningInfo())) self.assertEquals("id:/my-identity", str(SigningInfo(SigningInfo.SignerType.ID, Name("/my-identity")))) self.assertEquals("key:/my-key", str(SigningInfo(SigningInfo.SignerType.KEY, Name("/my-key")))) self.assertEquals("cert:/my-cert", str(SigningInfo(SigningInfo.SignerType.CERT, Name("/my-cert")))) self.assertEquals("id:/localhost/identity/digest-sha256", str(SigningInfo(SigningInfo.SignerType.SHA256)))
def __init__(self, screenName, chatRoom, hubPrefix, face, keyChain, certificateName): self._screenName = screenName self._chatRoom = chatRoom self._face = face self._keyChain = keyChain self._certificateName = certificateName self._messageCache = [] # of CachedMessage self._roster = [] # of str self._maxMessageCacheLength = 100 self._isRecoverySyncState = False self._syncLifetime = 5000.0 # milliseconds # This should only be called once, so get the random string here. self._chatPrefix = Name(hubPrefix).append(self._chatRoom).append( self._getRandomString()) session = 10000000000 self._userName = self._screenName + str(session) hmacKey = Blob( bytearray([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31 ])) self._sync = StateVectorSync2018( self._sendInterest, self._initial, self._chatPrefix, Name("/ndn/broadcast/SvsChat").append(self._chatRoom), face, keyChain, SigningInfo(), hmacKey, self._syncLifetime, onRegisterFailed) face.registerPrefix(self._chatPrefix, self._onInterest, onRegisterFailed)
def test_trusted_certificate_caching(self): data = Data(Name("/Security/V2/ValidatorFixture/Sub1/Sub2/Data")) self._fixture._keyChain.sign(data, SigningInfo(self._fixture._subIdentity)) self.validateExpectSuccess( data, "Should get accepted, as signed by the policy-compliant certificate" ) self.assertEqual(1, len(self._fixture._face._sentInterests)) self._fixture._face._sentInterests = [] # Disable responses from the simulated Face. self._fixture._face._processInterest = None self.validateExpectSuccess( data, "Should get accepted, based on the cached trusted certificate") self.assertEqual(0, len(self._fixture._face._sentInterests)) self._fixture._face._sentInterests = [] # Make the trusted cache simulate a time 2 hours later, after expiration. self._fixture._validator._setCacheNowOffsetMilliseconds(2 * 3600 * 1000.0) self.validateExpectFailure( data, "Should try and fail to retrieve certificates") # There should be multiple expressed interests due to retries. self.assertTrue(len(self._fixture._face._sentInterests) > 1) self._fixture._face._sentInterests = []
def makeCommandInterest(self, identity): """ :param PibIdentity identity: :rtype: Interest """ return self._signer.makeCommandInterest( Name(identity.getName()).append("CMD"), SigningInfo(identity))
def prepareData(ckPrefix, keyChain, face): """ Create the encrypted CK Data and KDK, and add to the Namespace object. For the meaning of "CK data", etc. see: https://github.com/named-data/name-based-access-control/blob/new/docs/spec.rst :return: The EncryptorV2 for encrypting the content. :rtype: EncryptorV2 """ # Imitate TestEncryptorV2 and TestAccessManagerV2 from the integration tests. accessIdentity = keyChain.createIdentityV2(Name("/access/policy/identity"), RsaKeyParams()) # This matches memberKeyName in test_nac_consumer. memberKeyName = Name("/first/user/KEY/%0C%87%EB%E6U%27B%D6") # The member certificate only needs to have a name and public key. memberCertificate = CertificateV2() memberCertificate.setName(Name(memberKeyName).append("self").append("1")) memberCertificate.setContent(Blob(MEMBER_PUBLIC_KEY, False)) dataset = Name("/dataset") accessManager = AccessManagerV2(accessIdentity, dataset, keyChain, face) # The face now has callbacks to the AccessManagerV2 and will keep it alive. accessManager.addMember(memberCertificate) def onError(code, message): print("onError: " + message) # TODO: Sign with better than SHA256? return EncryptorV2( Name(accessIdentity.getName()).append("NAC").append(dataset), ckPrefix, SigningInfo(SigningInfo.SignerType.SHA256), onError, ValidatorNull(), keyChain, face)
def test_reset_anchors(self): self._fixture._validator.resetAnchors() data = Data(Name("/Security/V2/ValidatorFixture/Sub1/Sub2/Data")) self._fixture._keyChain.sign(data, SigningInfo(self._fixture._subIdentity)) self.validateExpectFailure( data, "Should fail, as no anchors are configured")
def test_infinite_certificate_chain(self): 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)) self._fixture._face._processInterest = processInterest data = Data(Name("/Security/V2/ValidatorFixture/Sub1/Sub2/Data")) self._fixture._keyChain.sign(data, SigningInfo(self._fixture._subIdentity)) self._fixture._validator.setMaxDepth(40) self.assertEqual(40, self._fixture._validator.getMaxDepth()) self.validateExpectFailure( data, "Should fail since the certificate should be looped") self.assertEqual(40, len(self._fixture._face._sentInterests)) self._fixture._face._sentInterests = [] # Make the trusted cache simulate a time 5 hours later, after expiration. self._fixture._validator._setCacheNowOffsetMilliseconds(5 * 3600 * 1000.0) self._fixture._validator.setMaxDepth(30) self.assertEqual(30, self._fixture._validator.getMaxDepth()) self.validateExpectFailure( data, "Should fail since the certificate chain is infinite") self.assertEqual(30, len(self._fixture._face._sentInterests))
def test_chaining(self): info = (SigningInfo().setSigningIdentity( Name("/identity")).setSigningKeyName( Name("/key/name")).setSigningCertificateName( Name("/cert/name")).setPibIdentity(None).setPibKey( None).setSha256Signing().setDigestAlgorithm( DigestAlgorithm.SHA256)) self.assertEquals("id:/localhost/identity/digest-sha256", str(info))
def test_timeouts(self): # Disable responses from the simulated Face. self._fixture._face._processInterest = None data = Data(Name("/Security/V2/ValidatorFixture/Sub1/Sub2/Data")) self._fixture._keyChain.sign(data, SigningInfo(self._fixture._subIdentity)) self.validateExpectFailure(data, "Should fail to retrieve certificate") # There should be multiple expressed interests due to retries. self.assertTrue(len(self._fixture._face._sentInterests) > 1)
def makeCertificate(self, key, signer): """ Make a certificate and put it in the _fixture._cache . :type key: PibKey :type signer: PibKey """ # Copy the default certificate. request = CertificateV2(key.getDefaultCertificate()) request.setName(Name(key.getName()).append("looper").appendVersion(1)) # Set SigningInfo. params = SigningInfo(signer) # Validity period from 100 days before to 100 days after now. now = Common.getNowMilliseconds() params.setValidityPeriod(ValidityPeriod (now - 100 * 24 * 3600 * 1000.0, now + 100 * 24 * 3600 * 1000.0)) self._fixture._keyChain.sign(request, params) self._fixture._keyChain.addCertificate(key, request) self._fixture._cache.insert(request)
def test_refresh_10s(self): with open('policy_config/testData', 'r') as dataFile: encodedData = dataFile.read() data = Data() dataBlob = Blob(b64decode(encodedData)) data.wireDecode(dataBlob) # This test is needed, since the KeyChain will express interests in # unknown certificates. vr = doVerify(self.policyManager, data) self.assertTrue(vr.hasFurtherSteps, "ConfigPolicyManager did not create ValidationRequest for unknown certificate") self.assertEqual(vr.successCount, 0, "ConfigPolicyManager called success callback with pending ValidationRequest") self.assertEqual(vr.failureCount, 0, "ConfigPolicyManager called failure callback with pending ValidationRequest") # Now save the cert data to our anchor directory, and wait. # We have to sign it with the current identity or the policy manager # will create an interest for the signing certificate. cert = CertificateV2() certData = b64decode(CERT_DUMP) cert.wireDecode(Blob(certData, False)) signingInfo = SigningInfo() signingInfo.setSigningIdentity(self.identityName) # Make sure the validity period is current for two years. now = Common.getNowMilliseconds() signingInfo.setValidityPeriod(ValidityPeriod (now, now + 2 * 365 * 24 * 3600 * 1000.0)) self.keyChain.sign(cert, signingInfo) encodedCert = b64encode(cert.wireEncode().toBytes()) with open(self.testCertFile, 'w') as certFile: certFile.write(Blob(encodedCert, False).toRawStr()) # Still too early for refresh to pick it up. vr = doVerify(self.policyManager, data) self.assertTrue(vr.hasFurtherSteps, "ConfigPolicyManager refresh occured sooner than specified") self.assertEqual(vr.successCount, 0, "ConfigPolicyManager called success callback with pending ValidationRequest") self.assertEqual(vr.failureCount, 0, "ConfigPolicyManager called failure callback with pending ValidationRequest") time.sleep(6) # Now we should find it. vr = doVerify(self.policyManager, data) self.assertFalse(vr.hasFurtherSteps, "ConfigPolicyManager did not refresh certificate store") self.assertEqual(vr.successCount, 1, "Verification success called {} times instead of 1".format( vr.successCount)) self.assertEqual(vr.failureCount, 0, "ConfigPolicyManager did not verify valid signed data")
def test_nacked_interests(self): def processInterest(interest, onData, onTimeout, onNetworkNack): networkNack = NetworkNack() networkNack.setReason(NetworkNack.Reason.NO_ROUTE) onNetworkNack(interest, networkNack) self._fixture._face._processInterest = processInterest data = Data(Name("/Security/V2/ValidatorFixture/Sub1/Sub2/Data")) self._fixture._keyChain.sign(data, SigningInfo(self._fixture._subIdentity)) self.validateExpectFailure(data, "All interests should get NACKed") # There should be multiple expressed interests due to retries. self.assertTrue(len(self._fixture._face._sentInterests) > 1)
def __init__(self, shouldPublishData, onError): super(EncryptorFixture, self).__init__() # Include the code here from the NAC unit-tests class # EncryptorStaticDataEnvironment instead of making it a base class. self._storage = InMemoryStorageRetaining() if shouldPublishData: self.publishData() self._face = InMemoryStorageFace(self._storage) self._validator = ValidatorNull() self._encryptor = EncryptorV2( Name("/access/policy/identity/NAC/dataset"), Name("/some/ck/prefix"), SigningInfo(SigningInfo.SignerType.SHA256), onError, self._validator, self._keyChain, self._face)
def test_looped_certificate_chain(self): identity1 = self._fixture.addIdentity(Name("/loop")) key1 = self._fixture._keyChain.createKey( identity1, RsaKeyParams(Name.Component("key1"))) key2 = self._fixture._keyChain.createKey( identity1, RsaKeyParams(Name.Component("key2"))) key3 = self._fixture._keyChain.createKey( identity1, RsaKeyParams(Name.Component("key3"))) self.makeCertificate(key1, key2) self.makeCertificate(key2, key3) self.makeCertificate(key3, key1) data = Data(Name("/loop/Data")) self._fixture._keyChain.sign(data, SigningInfo(key1)) self.validateExpectFailure( data, "Should fail since the certificate chain loops") self.assertEqual(3, len(self._fixture._face._sentInterests))
def test_validate_interest(self): identity = self._fixture.addIdentity(Name("/TestValidator/Null")) interest = Interest(Name("/Some/Other/Interest/Name")) self._fixture._keyChain.sign(interest, SigningInfo(identity)) validator = ValidatorNull() successCount = [0] failureCount = [0] def successCallback(interest): successCount[0] += 1 def failureCallback(interest, error): failureCount[0] += 1 validator.validate(interest, successCallback, failureCallback) self.assertTrue(successCount[0] == 1 and failureCount[0] == 0, "Validation should not have failed")
def main(): # Uncomment these lines to print StateVectorSync debug messages. logging.getLogger('').addHandler(logging.StreamHandler(sys.stdout)) logging.getLogger('').setLevel(logging.INFO) face = Face("localhost") # Set up the key chain. 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()) screenName = promptAndInput("Enter your user name: ") hubPrefix = "ndn/edu/ucla/remap" chatRoom = "ndnchat" notificationInterestLifetime = 5000.0 sessionNumber = int(round(Common.getNowMilliseconds() / 1000.0)) hmacKey = Blob(bytearray([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31 ])) memberDataPrefix = Name(hubPrefix).append(screenName).append(chatRoom) def onInitialized(): stateVectorSync.publishNextSequenceNo() stateVectorSync = StateVectorSync2018(onReceivedSyncState, onInitialized, memberDataPrefix, Name("/ndn/broadcast/SvsChat").append(chatRoom), face, keyChain, SigningInfo(), hmacKey, notificationInterestLifetime, 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)
def test_from_string(self): infoDefault = SigningInfo("") self.assertEquals(SigningInfo.SignerType.NULL, infoDefault.getSignerType()) self.assertTrue(Name().equals(infoDefault.getSignerName())) self.assertEquals(DigestAlgorithm.SHA256, infoDefault.getDigestAlgorithm()) infoId = SigningInfo("id:/my-identity") self.assertEquals(SigningInfo.SignerType.ID, infoId.getSignerType()) self.assertTrue(Name("/my-identity").equals(infoId.getSignerName())) self.assertEquals(DigestAlgorithm.SHA256, infoId.getDigestAlgorithm()) infoKey = SigningInfo("key:/my-key") self.assertEquals(SigningInfo.SignerType.KEY, infoKey.getSignerType()) self.assertTrue(Name("/my-key").equals(infoKey.getSignerName())) self.assertEquals(DigestAlgorithm.SHA256, infoKey.getDigestAlgorithm()) infoCert = SigningInfo("cert:/my-cert") self.assertEquals(SigningInfo.SignerType.CERT, infoCert.getSignerType()) self.assertTrue(Name("/my-cert").equals(infoCert.getSignerName())) self.assertEquals(DigestAlgorithm.SHA256, infoCert.getDigestAlgorithm()) infoSha = SigningInfo("id:/localhost/identity/digest-sha256") self.assertEquals(SigningInfo.SignerType.SHA256, infoSha.getSignerType()) self.assertTrue(Name().equals(infoSha.getSignerName())) self.assertEquals(DigestAlgorithm.SHA256, infoSha.getDigestAlgorithm())
def test_basic(self): identityName = Name("/my-identity") keyName = Name("/my-key") certificateName = Name("/my-cert") info = SigningInfo() self.assertEquals(SigningInfo.SignerType.NULL, info.getSignerType()) self.assertTrue(Name().equals(info.getSignerName())) self.assertEquals(DigestAlgorithm.SHA256, info.getDigestAlgorithm()) info.setSigningIdentity(identityName) self.assertEquals(SigningInfo.SignerType.ID, info.getSignerType()) self.assertTrue(identityName.equals(info.getSignerName())) self.assertEquals(DigestAlgorithm.SHA256, info.getDigestAlgorithm()) infoId = SigningInfo(SigningInfo.SignerType.ID, identityName) self.assertEquals(SigningInfo.SignerType.ID, infoId.getSignerType()) self.assertTrue(identityName.equals(infoId.getSignerName())) self.assertEquals(DigestAlgorithm.SHA256, infoId.getDigestAlgorithm()) info.setSigningKeyName(keyName) self.assertEquals(SigningInfo.SignerType.KEY, info.getSignerType()) self.assertTrue(keyName.equals(info.getSignerName())) self.assertEquals(DigestAlgorithm.SHA256, info.getDigestAlgorithm()) infoKey = SigningInfo(SigningInfo.SignerType.KEY, keyName) self.assertEquals(SigningInfo.SignerType.KEY, infoKey.getSignerType()) self.assertTrue(keyName.equals(infoKey.getSignerName())) self.assertEquals(DigestAlgorithm.SHA256, infoKey.getDigestAlgorithm()) info.setSigningCertificateName(certificateName) self.assertEquals(SigningInfo.SignerType.CERT, info.getSignerType()) self.assertTrue(certificateName.equals(info.getSignerName())) self.assertEquals(DigestAlgorithm.SHA256, info.getDigestAlgorithm()) infoCert = SigningInfo(SigningInfo.SignerType.CERT, certificateName) self.assertEquals(SigningInfo.SignerType.CERT, infoCert.getSignerType()) self.assertTrue(certificateName.equals(infoCert.getSignerName())) self.assertEquals(DigestAlgorithm.SHA256, infoCert.getDigestAlgorithm()) info.setSha256Signing() self.assertEquals(SigningInfo.SignerType.SHA256, info.getSignerType()) self.assertTrue(Name().equals(info.getSignerName())) self.assertEquals(DigestAlgorithm.SHA256, info.getDigestAlgorithm()) infoSha256 = SigningInfo(SigningInfo.SignerType.SHA256) self.assertEquals(SigningInfo.SignerType.SHA256, infoSha256.getSignerType()) self.assertTrue(Name().equals(infoSha256.getSignerName())) self.assertEquals(DigestAlgorithm.SHA256, infoSha256.getDigestAlgorithm())
def test_basic(self): identityName = Name("/my-identity") keyName = Name("/my-key") certificateName = Name("/my-cert") info = SigningInfo() self.assertEqual(SigningInfo.SignerType.NULL, info.getSignerType()) self.assertTrue(Name().equals(info.getSignerName())) self.assertEqual(DigestAlgorithm.SHA256, info.getDigestAlgorithm()) info.setSigningIdentity(identityName) self.assertEqual(SigningInfo.SignerType.ID, info.getSignerType()) self.assertTrue(identityName.equals(info.getSignerName())) self.assertEqual(DigestAlgorithm.SHA256, info.getDigestAlgorithm()) infoId = SigningInfo(SigningInfo.SignerType.ID, identityName) self.assertEqual(SigningInfo.SignerType.ID, infoId.getSignerType()) self.assertTrue(identityName.equals(infoId.getSignerName())) self.assertEqual(DigestAlgorithm.SHA256, infoId.getDigestAlgorithm()) info.setSigningKeyName(keyName) self.assertEqual(SigningInfo.SignerType.KEY, info.getSignerType()) self.assertTrue(keyName.equals(info.getSignerName())) self.assertEqual(DigestAlgorithm.SHA256, info.getDigestAlgorithm()) infoKey = SigningInfo(SigningInfo.SignerType.KEY, keyName) self.assertEqual(SigningInfo.SignerType.KEY, infoKey.getSignerType()) self.assertTrue(keyName.equals(infoKey.getSignerName())) self.assertEqual(DigestAlgorithm.SHA256, infoKey.getDigestAlgorithm()) info.setSigningCertificateName(certificateName) self.assertEqual(SigningInfo.SignerType.CERT, info.getSignerType()) self.assertTrue(certificateName.equals(info.getSignerName())) self.assertEqual(DigestAlgorithm.SHA256, info.getDigestAlgorithm()) infoCert = SigningInfo(SigningInfo.SignerType.CERT, certificateName) self.assertEqual(SigningInfo.SignerType.CERT, infoCert.getSignerType()) self.assertTrue(certificateName.equals(infoCert.getSignerName())) self.assertEqual(DigestAlgorithm.SHA256, infoCert.getDigestAlgorithm()) info.setSha256Signing() self.assertEqual(SigningInfo.SignerType.SHA256, info.getSignerType()) self.assertTrue(Name().equals(info.getSignerName())) self.assertEqual(DigestAlgorithm.SHA256, info.getDigestAlgorithm()) infoSha256 = SigningInfo(SigningInfo.SignerType.SHA256) self.assertEqual(SigningInfo.SignerType.SHA256, infoSha256.getSignerType()) self.assertTrue(Name().equals(infoSha256.getSignerName())) self.assertEqual(DigestAlgorithm.SHA256, infoSha256.getDigestAlgorithm())
def test_from_string(self): infoDefault = SigningInfo("") self.assertEqual(SigningInfo.SignerType.NULL, infoDefault.getSignerType()) self.assertTrue(Name().equals(infoDefault.getSignerName())) self.assertEqual(DigestAlgorithm.SHA256, infoDefault.getDigestAlgorithm()) infoId = SigningInfo("id:/my-identity") self.assertEqual(SigningInfo.SignerType.ID, infoId.getSignerType()) self.assertTrue(Name("/my-identity").equals(infoId.getSignerName())) self.assertEqual(DigestAlgorithm.SHA256, infoId.getDigestAlgorithm()) infoKey = SigningInfo("key:/my-key") self.assertEqual(SigningInfo.SignerType.KEY, infoKey.getSignerType()) self.assertTrue(Name("/my-key").equals(infoKey.getSignerName())) self.assertEqual(DigestAlgorithm.SHA256, infoKey.getDigestAlgorithm()) infoCert = SigningInfo("cert:/my-cert") self.assertEqual(SigningInfo.SignerType.CERT, infoCert.getSignerType()) self.assertTrue(Name("/my-cert").equals(infoCert.getSignerName())) self.assertEqual(DigestAlgorithm.SHA256, infoCert.getDigestAlgorithm()) infoSha = SigningInfo("id:/localhost/identity/digest-sha256") self.assertEqual(SigningInfo.SignerType.SHA256, infoSha.getSignerType()) self.assertTrue(Name().equals(infoSha.getSignerName())) self.assertEqual(DigestAlgorithm.SHA256, infoSha.getDigestAlgorithm())
def test_validate_interests_but_bypass_for_data(self): interest = Interest( Name("/Security/V2/ValidatorFixture/Sub1/Sub2/Interest")) data = Data(Name("/Security/V2/ValidatorFixture/Sub1/Sub2/Interest")) self.validateExpectFailure(interest, "Unsigned") self.validateExpectSuccess( data, "The policy requests to bypass validation for all data") self.assertEqual(0, len(self._fixture._face._sentInterests)) self._fixture._face._sentInterests = [] interest = Interest( Name("/Security/V2/ValidatorFixture/Sub1/Sub2/Interest")) self._fixture._keyChain.sign( interest, SigningInfo(SigningInfo.SignerType.SHA256)) self._fixture._keyChain.sign( data, SigningInfo(SigningInfo.SignerType.SHA256)) self.validateExpectFailure( interest, "Required KeyLocator/Name is missing (not passed to the policy)") self.validateExpectSuccess( data, "The policy requests to bypass validation for all data") self.assertEqual(0, len(self._fixture._face._sentInterests)) self._fixture._face._sentInterests = [] interest = Interest( Name("/Security/V2/ValidatorFixture/Sub1/Sub2/Interest")) self._fixture._keyChain.sign(interest, SigningInfo(self._fixture._identity)) self._fixture._keyChain.sign(data, SigningInfo(self._fixture._identity)) self.validateExpectSuccess( interest, "Should be successful since it is signed by the anchor") self.validateExpectSuccess( data, "The policy requests to bypass validation for all data") self.assertEqual(0, len(self._fixture._face._sentInterests)) self._fixture._face._sentInterests = [] interest = Interest( Name("/Security/V2/ValidatorFixture/Sub1/Sub2/Interest")) self._fixture._keyChain.sign(interest, SigningInfo(self._fixture._subIdentity)) self._fixture._keyChain.sign(data, SigningInfo(self._fixture._subIdentity)) self.validateExpectFailure( interest, "Should fail since the policy is not allowed to create new trust anchors" ) self.validateExpectSuccess( data, "The policy requests to bypass validation for all data") self.assertEqual(1, len(self._fixture._face._sentInterests)) self._fixture._face._sentInterests = [] interest = Interest( Name("/Security/V2/ValidatorFixture/Sub1/Sub2/Interest")) self._fixture._keyChain.sign(interest, SigningInfo(self._fixture._otherIdentity)) self._fixture._keyChain.sign(data, SigningInfo(self._fixture._otherIdentity)) self.validateExpectFailure( interest, "Should fail since it is signed by a policy-violating certificate") self.validateExpectSuccess( data, "The policy requests to bypass validation for all data") # No network operations are expected since the certificate is not # validated by the policy. self.assertEqual(0, len(self._fixture._face._sentInterests)) self._fixture._face._sentInterests = [] # Make the trusted cache simulate a time 2 hours later, after expiration. self._fixture._validator._setCacheNowOffsetMilliseconds(2 * 3600 * 1000.0) interest = Interest( Name("/Security/V2/ValidatorFixture/Sub1/Sub2/Interest")) self._fixture._keyChain.sign( interest, SigningInfo(self._fixture._subSelfSignedIdentity)) self._fixture._keyChain.sign( data, SigningInfo(self._fixture._subSelfSignedIdentity)) self.validateExpectFailure( interest, "Should fail since the policy is not allowed to create new trust anchors" ) self.validateExpectSuccess( data, "The policy requests to bypass validation for all data") self.assertEqual(1, len(self._fixture._face._sentInterests)) self._fixture._face._sentInterests = []