def test_hyper_relation(self):
        # Set up the validator.
        fetcher = CertificateFetcherOffline()
        validator = ValidatorConfig(fetcher)
        validator.load(
          os.path.join(self._policyConfigDirectory, "hyperrelation_ruleset.conf"))

        # Set up a Data packet and result object.
        data = Data()
        KeyLocator.getFromSignature(data.getSignature()).setType(KeyLocatorType.KEYNAME)
        result = TestValidationResult(data)

        data.setName(Name("/SecurityTestSecRule/Basic/Longer/Data2"))

        KeyLocator.getFromSignature(data.getSignature()).setKeyName(
          Name("/SecurityTestSecRule/Basic/Longer/KEY/123"))
        result.checkPolicy(validator)
        self.assertTrue(result._calledFailure and not result.calledContinue_)
        KeyLocator.getFromSignature(data.getSignature()).setKeyName(
          Name("/SecurityTestSecRule/Basic/KEY/123"))
        result.checkPolicy(validator)
        self.assertTrue(result._calledFailure and not result.calledContinue_)

        data.setName(Name("/SecurityTestSecRule/Basic/Other/Data1"))

        KeyLocator.getFromSignature(data.getSignature()).setKeyName(
          Name("/SecurityTestSecRule/Basic/Longer/KEY/123"))
        result.checkPolicy(validator)
        self.assertTrue(result._calledFailure and not result.calledContinue_)
        KeyLocator.getFromSignature(data.getSignature()).setKeyName(
          Name("/SecurityTestSecRule/Basic/KEY/123"))
        result.checkPolicy(validator)
        self.assertTrue(result._calledFailure and not result.calledContinue_)
    def test_hyper_relation(self):
        # Set up the validator.
        fetcher = CertificateFetcherOffline()
        validator = ValidatorConfig(fetcher)
        validator.load(
            os.path.join(self._policyConfigDirectory,
                         "hyperrelation_ruleset.conf"))

        # Set up a Data packet and result object.
        data = Data()
        KeyLocator.getFromSignature(data.getSignature()).setType(
            KeyLocatorType.KEYNAME)
        result = TestValidationResult(data)

        data.setName(Name("/SecurityTestSecRule/Basic/Longer/Data2"))

        KeyLocator.getFromSignature(data.getSignature()).setKeyName(
            Name("/SecurityTestSecRule/Basic/Longer/KEY/123"))
        result.checkPolicy(validator)
        self.assertTrue(result._calledFailure and not result.calledContinue_)
        KeyLocator.getFromSignature(data.getSignature()).setKeyName(
            Name("/SecurityTestSecRule/Basic/KEY/123"))
        result.checkPolicy(validator)
        self.assertTrue(result._calledFailure and not result.calledContinue_)

        data.setName(Name("/SecurityTestSecRule/Basic/Other/Data1"))

        KeyLocator.getFromSignature(data.getSignature()).setKeyName(
            Name("/SecurityTestSecRule/Basic/Longer/KEY/123"))
        result.checkPolicy(validator)
        self.assertTrue(result._calledFailure and not result.calledContinue_)
        KeyLocator.getFromSignature(data.getSignature()).setKeyName(
            Name("/SecurityTestSecRule/Basic/KEY/123"))
        result.checkPolicy(validator)
        self.assertTrue(result._calledFailure and not result.calledContinue_)
Esempio n. 3
0
    def test_setter_getter(self):
        content = EncryptedContent()
        self.assertEqual(content.getAlgorithmType(), None)
        self.assertTrue(content.getPayload().isNull())
        self.assertTrue(content.getInitialVector().isNull())
        self.assertEqual(content.getKeyLocator().getType(), None)

        content.setAlgorithmType(EncryptAlgorithmType.RsaOaep)
        self.assertEqual(content.getAlgorithmType(), EncryptAlgorithmType.RsaOaep)
        self.assertTrue(content.getPayload().isNull())
        self.assertTrue(content.getInitialVector().isNull())
        self.assertEqual(content.getKeyLocator().getType(), None)

        keyLocator = KeyLocator()
        keyLocator.setType(KeyLocatorType.KEYNAME)
        keyLocator.getKeyName().set("/test/key/locator")
        content.setKeyLocator(keyLocator)
        self.assertTrue(content.getKeyLocator().getType() != None)
        self.assertTrue(content.getKeyLocator().getKeyName().equals(
          Name("/test/key/locator")))
        self.assertTrue(content.getPayload().isNull())
        self.assertTrue(content.getInitialVector().isNull())

        content.setPayload(Blob(message, False))
        self.assertTrue(content.getPayload().equals(Blob(message, False)))

        content.setInitialVector(Blob(iv, False))
        self.assertTrue(content.getInitialVector().equals(Blob(iv, False)))

        encoded = content.wireEncode()
        contentBlob = Blob(encrypted, False)
        self.assertTrue(contentBlob.equals(encoded))
    def test_name_relation(self):
        # Set up the validators.
        fetcher = CertificateFetcherOffline()
        validatorPrefix = ValidatorConfig(fetcher)
        validatorEqual = ValidatorConfig(fetcher)
        validatorStrict = ValidatorConfig(fetcher)

        validatorPrefix.load(
            os.path.join(self._policyConfigDirectory,
                         "relation_ruleset_prefix.conf"))
        validatorEqual.load(
            os.path.join(self._policyConfigDirectory,
                         "relation_ruleset_equal.conf"))
        validatorStrict.load(
            os.path.join(self._policyConfigDirectory,
                         "relation_ruleset_strict.conf"))

        # Set up a Data packet and result object.
        data = Data()
        KeyLocator.getFromSignature(data.getSignature()).setType(
            KeyLocatorType.KEYNAME)
        KeyLocator.getFromSignature(data.getSignature()).setKeyName(
            Name("/SecurityTestSecRule/KEY/123"))
        result = TestValidationResult(data)

        data.setName(Name("/TestRule1"))
        result.checkPolicy(validatorPrefix)
        self.assertTrue(result.calledContinue_ and not result._calledFailure,
                        "Prefix relation should match prefix name")
        result.checkPolicy(validatorEqual)
        self.assertTrue(result.calledContinue_ and not result._calledFailure,
                        "Equal relation should match prefix name")
        result.checkPolicy(validatorStrict)
        self.assertTrue(result._calledFailure and not result.calledContinue_,
                        "Strict-prefix relation should not match prefix name")

        data.setName(Name("/TestRule1/hi"))
        result.checkPolicy(validatorPrefix)
        self.assertTrue(result.calledContinue_ and not result._calledFailure,
                        "Prefix relation should match longer name")
        result.checkPolicy(validatorEqual)
        self.assertTrue(result._calledFailure and not result.calledContinue_,
                        "Equal relation should not match longer name")
        result.checkPolicy(validatorStrict)
        self.assertTrue(result.calledContinue_ and not result._calledFailure,
                        "Strict-prefix relation should match longer name")

        data.setName(Name("/Bad/TestRule1/"))
        result.checkPolicy(validatorPrefix)
        self.assertTrue(result._calledFailure and not result.calledContinue_,
                        "Prefix relation should not match inner components")
        result.checkPolicy(validatorEqual)
        self.assertTrue(result._calledFailure and not result.calledContinue_,
                        "Equal relation should not match inner components")
        result.checkPolicy(validatorStrict)
        self.assertTrue(
            result._calledFailure and not result.calledContinue_,
            "Strict-prefix relation should  not match inner components")
    def test_name_relation(self):
        # Set up the validators.
        fetcher = CertificateFetcherOffline()
        validatorPrefix = ValidatorConfig(fetcher)
        validatorEqual = ValidatorConfig(fetcher)
        validatorStrict = ValidatorConfig(fetcher)

        validatorPrefix.load(
          os.path.join(self._policyConfigDirectory, "relation_ruleset_prefix.conf"))
        validatorEqual.load(
          os.path.join(self._policyConfigDirectory, "relation_ruleset_equal.conf"))
        validatorStrict.load(
          os.path.join(self._policyConfigDirectory, "relation_ruleset_strict.conf"))

        # Set up a Data packet and result object.
        data = Data()
        KeyLocator.getFromSignature(data.getSignature()).setType(
          KeyLocatorType.KEYNAME)
        KeyLocator.getFromSignature(data.getSignature()).setKeyName(
          Name("/SecurityTestSecRule/KEY/123"))
        result = TestValidationResult(data)

        data.setName(Name("/TestRule1"))
        result.checkPolicy(validatorPrefix)
        self.assertTrue(result.calledContinue_ and not result._calledFailure,
          "Prefix relation should match prefix name")
        result.checkPolicy(validatorEqual)
        self.assertTrue(result.calledContinue_ and not result._calledFailure,
          "Equal relation should match prefix name")
        result.checkPolicy(validatorStrict)
        self.assertTrue(result._calledFailure and not result.calledContinue_,
          "Strict-prefix relation should not match prefix name")

        data.setName(Name("/TestRule1/hi"))
        result.checkPolicy(validatorPrefix)
        self.assertTrue(result.calledContinue_ and not result._calledFailure,
          "Prefix relation should match longer name")
        result.checkPolicy(validatorEqual)
        self.assertTrue(result._calledFailure and not result.calledContinue_,
          "Equal relation should not match longer name")
        result.checkPolicy(validatorStrict)
        self.assertTrue(result.calledContinue_ and not result._calledFailure,
          "Strict-prefix relation should match longer name")

        data.setName(Name("/Bad/TestRule1/"))
        result.checkPolicy(validatorPrefix)
        self.assertTrue(result._calledFailure and not result.calledContinue_,
          "Prefix relation should not match inner components")
        result.checkPolicy(validatorEqual)
        self.assertTrue(result._calledFailure and not result.calledContinue_,
          "Equal relation should not match inner components")
        result.checkPolicy(validatorStrict)
        self.assertTrue(result._calledFailure and not result.calledContinue_,
          "Strict-prefix relation should  not match inner components")
    def test_bad_certificate_name(self):
        interest1 = self._fixture.makeCommandInterest(self._fixture._identity)
        keyLocator = KeyLocator()
        keyLocator.setType(KeyLocatorType.KEYNAME)
        keyLocator.setKeyName(Name("/bad/cert/name"))
        signatureInfo = Sha256WithRsaSignature()
        signatureInfo.setKeyLocator(keyLocator)

        setNameComponent(
          interest1, CommandInterestSigner.POS_SIGNATURE_INFO,
          TlvWireFormat.get().encodeSignatureInfo(signatureInfo))
        self.validateExpectFailure(interest1, "Should fail (bad certificate name)")
    def test_bad_key_locator_type(self):
        interest1 = self._fixture.makeCommandInterest(self._fixture._identity)
        keyLocator = KeyLocator()
        keyLocator.setType(KeyLocatorType.KEY_LOCATOR_DIGEST)
        keyLocator.setKeyData(Blob
          ([ 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd ]))
        signatureInfo = Sha256WithRsaSignature()
        signatureInfo.setKeyLocator(keyLocator)

        setNameComponent(
          interest1, CommandInterestSigner.POS_SIGNATURE_INFO,
          TlvWireFormat.get().encodeSignatureInfo(signatureInfo))
        self.validateExpectFailure(interest1, "Should fail (bad KeyLocator type)")
Esempio n. 8
0
    def test_setters(self):
        certificate = CertificateV2()
        certificate.setName(
          Name("/ndn/site1/KEY/ksk-1416425377094/0123/%FD%00%00%01I%C9%8B"))
        certificate.getMetaInfo().setFreshnessPeriod(3600 * 1000.0)
        certificate.setContent(Blob(PUBLIC_KEY, False))
        certificate.setSignature(self.generateFakeSignature())

        self.assertEqual(
          Name("/ndn/site1/KEY/ksk-1416425377094/0123/%FD%00%00%01I%C9%8B"),
          certificate.getName())
        self.assertEqual(Name("/ndn/site1/KEY/ksk-1416425377094"),
          certificate.getKeyName())
        self.assertEqual(Name("/ndn/site1"), certificate.getIdentity())
        self.assertEqual(Name.Component("0123"), certificate.getIssuerId())
        self.assertEqual(Name.Component("ksk-1416425377094"),
          certificate.getKeyId())
        self.assertEqual(Name("/ndn/site1/KEY/ksk-2516425377094"),
          KeyLocator.getFromSignature(certificate.getSignature()).getKeyName())
        self.assertEqual(fromIsoString("20141111T050000"),
          certificate.getValidityPeriod().getNotBefore(), 0)
        self.assertEqual(fromIsoString("20141111T060000"),
          certificate.getValidityPeriod().getNotAfter(), 0)

        try:
          certificate.getPublicKey()
        except:
          self.fail("Error in getPublicKey");
Esempio n. 9
0
    def test_constructor(self):
        certificate = CertificateV2()
        certificate.wireDecode(Blob(CERT, False))

        self.assertEqual(
          Name("/ndn/site1/KEY/ksk-1416425377094/0123/%FD%00%00%01I%C9%8B"),
          certificate.getName())
        self.assertEqual(Name("/ndn/site1/KEY/ksk-1416425377094"),
          certificate.getKeyName())
        self.assertEqual(Name("/ndn/site1"), certificate.getIdentity())
        self.assertEqual(Name.Component("0123"), certificate.getIssuerId())
        self.assertEqual(Name.Component("ksk-1416425377094"),
          certificate.getKeyId())
        self.assertEqual(Name("/ndn/site1/KEY/ksk-2516425377094"),
          KeyLocator.getFromSignature(certificate.getSignature()).getKeyName())
        self.assertEqual(fromIsoString("20150814T223739"),
          certificate.getValidityPeriod().getNotBefore(), 0)
        self.assertEqual(fromIsoString("20150818T223738"),
          certificate.getValidityPeriod().getNotAfter(), 0)

        try:
          certificate.getPublicKey()
        except:
          self.fail("Error in getPublicKey");

        data = Data()
        data.wireDecode(Blob(CERT, False))
        certificate2 = CertificateV2(data)
        self.assertEqual(certificate.getName(), certificate2.getName())
        self.assertTrue(certificate.getPublicKey().equals(certificate2.getPublicKey()))
Esempio n. 10
0
    def test_setter_getter(self):
        content = EncryptedContent()
        self.assertEqual(content.getAlgorithmType(), None)
        self.assertTrue(content.getPayload().isNull())
        self.assertTrue(content.getInitialVector().isNull())
        self.assertEqual(content.getKeyLocator().getType(), None)

        content.setAlgorithmType(EncryptAlgorithmType.RsaOaep)
        self.assertEqual(content.getAlgorithmType(),
                         EncryptAlgorithmType.RsaOaep)
        self.assertTrue(content.getPayload().isNull())
        self.assertTrue(content.getInitialVector().isNull())
        self.assertEqual(content.getKeyLocator().getType(), None)

        keyLocator = KeyLocator()
        keyLocator.setType(KeyLocatorType.KEYNAME)
        keyLocator.getKeyName().set("/test/key/locator")
        content.setKeyLocator(keyLocator)
        self.assertTrue(content.getKeyLocator().getType() != None)
        self.assertTrue(content.getKeyLocator().getKeyName().equals(
            Name("/test/key/locator")))
        self.assertTrue(content.getPayload().isNull())
        self.assertTrue(content.getInitialVector().isNull())

        content.setPayload(Blob(message, False))
        self.assertTrue(content.getPayload().equals(Blob(message, False)))

        content.setInitialVector(Blob(iv, False))
        self.assertTrue(content.getInitialVector().equals(Blob(iv, False)))

        encoded = content.wireEncode()
        contentBlob = Blob(encrypted, False)
        self.assertTrue(contentBlob.equals(encoded))
Esempio n. 11
0
    def addCertificate(self, certificate):
        """
        Add a certificate to the identity storage.

        :param IdentityCertificate certificate: The certificate to be added.
          This makes a copy of the certificate.
        :raises SecurityException: If the certificate is already installed.
        """
        certificateName = certificate.getName()
        keyName = certificate.getPublicKeyName()

        if not self.doesKeyExist(keyName):
            raise SecurityException("No corresponding Key record for certificate! " +
              keyName.toUri() + " " + certificateName.toUri())

        # Check if the certificate already exists.
        if self.doesCertificateExist(certificateName):
            raise SecurityException("Certificate has already been installed!")

        keyId = keyName.get(-1).toEscapedString()
        identity = keyName[:-1]

        # Check if the public key of the certificate is the same as the key record.
        keyBlob = self.getKey(keyName)
        if (keyBlob.isNull() or
            not keyBlob.equals(certificate.getPublicKeyInfo().getKeyDer())):
            raise SecurityException("Certificate does not match public key")

        # Insert the certificate.

        signature = certificate.getSignature()
        signerName = KeyLocator.getFromSignature(signature).getKeyName()
        # Convert from milliseconds to seconds since 1/1/1970.
        notBefore = int(math.floor(certificate.getNotBefore() / 1000.0))
        notAfter = int(math.floor(certificate.getNotAfter() / 1000.0))
        encodedCert = sqlite3.Binary(bytearray(certificate.wireEncode().buf()))

        cursor = self._database.cursor()
        cursor.execute(
          "INSERT INTO Certificate (cert_name, cert_issuer, identity_name, key_identifier, not_before, not_after, certificate_data) " +
          "VALUES (?,?,?,?,?,?,?)",
          (certificateName.toUri(), signerName.toUri(), identity.toUri(), keyId,
                notBefore, notAfter, encodedCert))
        self._database.commit()
        cursor.close()
Esempio n. 12
0
    def addCertificate(self, certificate):
        """
        Add a certificate to the identity storage.

        :param IdentityCertificate certificate: The certificate to be added.
          This makes a copy of the certificate.
        """
        certificateName = certificate.getName()
        keyName = certificate.getPublicKeyName()

        if not self.doesKeyExist(keyName):
            raise SecurityException(
                "No corresponding Key record for certificate! " +
                keyName.toUri() + " " + certificateName.toUri())

        # Check if the certificate already exists.
        if self.doesCertificateExist(certificateName):
            raise SecurityException("Certificate has already been installed!")

        keyId = keyName.get(-1).toEscapedString()
        identity = keyName[:-1]

        # Check if the public key of the certificate is the same as the key record.
        keyBlob = self.getKey(keyName)
        if (keyBlob.isNull() or not keyBlob.equals(
                certificate.getPublicKeyInfo().getKeyDer())):
            raise SecurityException("Certificate does not match public key")

        # Insert the certificate.

        signature = certificate.getSignature()
        signerName = KeyLocator.getFromSignature(signature).getKeyName()
        # Convert from milliseconds to seconds since 1/1/1970.
        notBefore = int(math.floor(certificate.getNotBefore() / 1000.0))
        notAfter = int(math.floor(certificate.getNotAfter() / 1000.0))
        encodedCert = sqlite3.Binary(bytearray(certificate.wireEncode().buf()))

        cursor = self._database.cursor()
        cursor.execute(
            "INSERT INTO Certificate (cert_name, cert_issuer, identity_name, key_identifier, not_before, not_after, certificate_data) "
            + "VALUES (?,?,?,?,?,?,?)",
            (certificateName.toUri(), signerName.toUri(), identity.toUri(),
             keyId, notBefore, notAfter, encodedCert))
        self._database.commit()
        cursor.close()
    def test_bad_certificate_name(self):
        interest1 = self._fixture.makeCommandInterest(self._fixture._identity)
        keyLocator = KeyLocator()
        keyLocator.setType(KeyLocatorType.KEYNAME)
        keyLocator.setKeyName(Name("/bad/cert/name"))
        signatureInfo = Sha256WithRsaSignature()
        signatureInfo.setKeyLocator(keyLocator)

        setNameComponent(
            interest1, CommandInterestSigner.POS_SIGNATURE_INFO,
            TlvWireFormat.get().encodeSignatureInfo(signatureInfo))
        self.validateExpectFailure(interest1,
                                   "Should fail (bad certificate name)")
    def test_bad_key_locator_type(self):
        interest1 = self._fixture.makeCommandInterest(self._fixture._identity)
        keyLocator = KeyLocator()
        keyLocator.setType(KeyLocatorType.KEY_LOCATOR_DIGEST)
        keyLocator.setKeyData(
            Blob([0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd]))
        signatureInfo = Sha256WithRsaSignature()
        signatureInfo.setKeyLocator(keyLocator)

        setNameComponent(
            interest1, CommandInterestSigner.POS_SIGNATURE_INFO,
            TlvWireFormat.get().encodeSignatureInfo(signatureInfo))
        self.validateExpectFailure(interest1,
                                   "Should fail (bad KeyLocator type)")
Esempio n. 15
0
    def _verify(self, signatureInfo, signedBlob):
        """
        Check the type of signatureInfo to get the KeyLocator. Look in the
        IdentityStorage for the public key with the name in the KeyLocator and
        use it to verify the signedBlob. If the public key can't be found,
        return false. (This is a generalized method which can verify both a Data
        packet and an interest.)

        :param Signature signatureInfo: An object of a subclass of Signature,
          e.g. Sha256WithRsaSignature.
        :param SignedBlob signedBlob: the SignedBlob with the signed portion to
          verify.
        :return: True if the signature verifies, False if not.
        :rtype: boolean
        """
        # We have already checked once that there is a key locator.
        keyLocator = KeyLocator.getFromSignature(signatureInfo)

        if (keyLocator.getType() == KeyLocatorType.KEYNAME):
            # Assume the key name is a certificate name.
            signatureName = keyLocator.getKeyName()
            certificate = self._refreshManager.getCertificate(signatureName)
            if certificate is None:
                certificate = self._certificateCache.getCertificate(
                    signatureName)
            if certificate is None:
                return False

            publicKeyDer = certificate.getPublicKeyInfo().getKeyDer()
            if publicKeyDer.isNull():
                # Can't find the public key with the name.
                return False

            return self.verifySignature(signatureInfo, signedBlob,
                                        publicKeyDer)
        else:
            # Can't find a key to verify.
            return False
Esempio n. 16
0
    def generateFakeSignature():
        signatureInfo = Sha256WithRsaSignature()

        keyLocatorName = Name("/ndn/site1/KEY/ksk-2516425377094")
        keyLocator = KeyLocator()
        keyLocator.setType(KeyLocatorType.KEYNAME)
        keyLocator.setKeyName(keyLocatorName)
        signatureInfo.setKeyLocator(keyLocator)

        period = ValidityPeriod()
        period.setPeriod(fromIsoString("20141111T050000"),
                         fromIsoString("20141111T060000"))
        signatureInfo.setValidityPeriod(period)

        block2 = Blob(SIG_VALUE, False)
        signatureInfo.setSignature(block2)

        return signatureInfo
Esempio n. 17
0
    def _verify(self, signatureInfo, signedBlob):
        """
        Check the type of signatureInfo to get the KeyLocator. Look in the
        IdentityStorage for the public key with the name in the KeyLocator and
        use it to verify the signedBlob. If the public key can't be found,
        return false. (This is a generalized method which can verify both a Data
        packet and an interest.)

        :param Signature signatureInfo: An object of a subclass of Signature,
          e.g. Sha256WithRsaSignature.
        :param SignedBlob signedBlob: the SignedBlob with the signed portion to
          verify.
        :return: True if the signature verifies, False if not.
        :rtype: boolean
        """
        # We have already checked once that there is a key locator.
        keyLocator = KeyLocator.getFromSignature(signatureInfo)

        if (keyLocator.getType() == KeyLocatorType.KEYNAME):
            # Assume the key name is a certificate name.
            signatureName = keyLocator.getKeyName()
            certificate = self._refreshManager.getCertificate(signatureName)
            if certificate is None:
                certificate = self._certificateCache.getCertificate(signatureName)
            if certificate is None:
                return False

            publicKeyDer = certificate.getPublicKeyInfo().getKeyDer()
            if publicKeyDer.isNull():
                # Can't find the public key with the name.
                return False

            return self.verifySignature(signatureInfo, signedBlob, publicKeyDer)
        else:
            # Can't find a key to verify.
            return False
Esempio n. 18
0
    def publish(self, line):
        # Pull out and parse datetime for log entry 
        # (note we shoudld use point time for timestamp)
        try:
            if not ": (point" in line: return
            point = parse.search("(point {})", line)[0].split(" ")
        except Exception as detail:
            print("publish: Parse error for", line, "-", detail)
            return
        try:
            tempTime = datetime.strptime(parse.search("[{}]", line)[0], "%Y-%m-%d %H:%M:%S.%f")
        except Exception as detail:
            print("publish: Date/time conversion error for", line, "-", detail)
            return
            
        sensorName = point[0]
        aggregationNamePrefix = self.pointNameToNDNName(sensorName)
        dataDict = self.pointToJSON(point)
        self._lastDataTimestamp = time.time()
        
        if aggregationNamePrefix is not None:
            #if __debug__:
            #    print(dateTime, aggregationNamePrefix, dataDict["timestamp"], "payload:", dataDict["value"])
            try:
                # TODO: since the leaf sensor publisher is not a separate node for now, we also publish aggregated data
                #       of the same sensor over the past given time period in this code;
                #       bms_node code has adaptation for leaf sensor publishers as well, ref: example-sensor1.conf

                # Here we make the assumption of fixed time window for *all* sensors
                # First publish aggregation
                dataTime = int(float(dataDict["timestamp"]) * 1000)
                if self._startTime == 0:
                    self._startTime = dataTime
                if not (sensorName in self._dataQueue):
                    # We don't have record of this sensor, so we create an identity for it, and print the cert string for now to get signed
                    sensorIdentityName = Name(self._namespace).append(aggregationNamePrefix).getPrefix(-3)
                    sensorCertificateName = self._keyChain.createIdentityAndCertificate(sensorIdentityName)
                    if __debug__:
                        print("Sensor identity name: " + sensorIdentityName.toUri())
                    certificateData = self._keyChain.getIdentityManager()._identityStorage.getCertificate(sensorCertificateName, True)

                    # We should only ask for cert to be signed upon the first run of a certain sensor
                    if DO_CERT_SETUP:
                        if (KeyLocator.getFromSignature(certificateData.getSignature()).getKeyName().equals(sensorCertificateName.getPrefix(-1))):
                            # Need to configure for remote gateway deployment; for now, remote uses its own branch with my public IP.
                            print("certificate " + sensorCertificateName.toUri() + " asking for signature")
                            response = urllib2.urlopen("http://192.168.56.1:5000/bms-cert-hack?cert=" + b64encode(certificateData.wireEncode().toBuffer()) + "&cert_prefix=" + sensorIdentityName.toUri() + '&subject_name=' + sensorIdentityName.toUri()).read()
                            
                            signedCertData = Data()
                            signedCertData.wireDecode(Blob(b64decode(response)))

                            self._cache.add(signedCertData)
                            cmdline = ['ndnsec-install-cert', '-']
                            p = subprocess.Popen(cmdline, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
                            cert, err = p.communicate(response)
                            if p.returncode != 0:
                                raise RuntimeError("ndnsec-install-cert error")
                        else:
                            self._cache.add(certificateData)
                    else:
                        self._cache.add(certificateData)

                    self._dataQueue[sensorName] = DataQueueItem([], self._startTime + self._defaultInterval, sensorIdentityName, sensorCertificateName)
                    self._dataQueue[sensorName]._dataList.append(dataDict["value"])
                elif dataTime > self._dataQueue[sensorName]._timeThreshold:
                    # calculate the aggregation with what's already in the queue, publish data packet, and delete current queue
                    # TODO: This should be mutex locked against self
                    if len(self._dataQueue[sensorName]._dataList) > 0:
                        avg = 0.0
                        for item in self._dataQueue[sensorName]._dataList:
                            avg += float(item)
                        avg = avg / len(self._dataQueue[sensorName]._dataList)
                        data = Data(Name(self._namespace).append(aggregationNamePrefix).append("avg").append(str(self._dataQueue[sensorName]._timeThreshold)).append(str(self._dataQueue[sensorName]._timeThreshold + self._defaultInterval)))
                        data.setContent(str(avg))
                        data.getMetaInfo().setFreshnessPeriod(self.DEFAULT_DATA_LIFETIME)
                        self._keyChain.sign(data, self._dataQueue[sensorName]._certificateName)
                        self._cache.add(data)
                        print("Aggregation produced " + data.getName().toUri())

                    self._dataQueue[sensorName]._dataList = [dataDict["value"]]
                    self._dataQueue[sensorName]._timeThreshold = self._dataQueue[sensorName]._timeThreshold + self._defaultInterval
                else:
                    self._dataQueue[sensorName]._dataList.append(dataDict["value"])
                
                # Then publish raw data
                # Timestamp in data name uses the timestamp from data payload
                instDataPrefix = self.pointNameToNDNName(sensorName, False)
                dataTemp = self.createData(instDataPrefix, dataDict["timestamp"], json.dumps(dataDict), self._dataQueue[sensorName]._certificateName)
                if __debug__:
                    print("Produced raw data name " + dataTemp.getName().toUri())
                    print("Produced raw data content " + dataTemp.getContent().toRawStr())
                self._cache.add(dataTemp)

                # For now we only insert raw data into repo
                parameter = repo_command_parameter_pb2.RepoCommandParameterMessage()
                # Add the Name.
                for i in range(dataTemp.getName().size()):
                    parameter.repo_command_parameter.name.component.append(
                      dataTemp.getName().get(i).toEscapedString())
                
                # Create the command interest.
                commandInterest = Interest(Name(repoCommandPrefix).append("insert")
                  .append(Name.Component(ProtobufTlv.encode(parameter))))
                self._face.makeCommandInterest(commandInterest)

                # Send the command interest and get the response or timeout.
                def onRepoCommandResponse(interest, data):
                    # repo_command_response_pb2 was produced by protoc.
                    response = repo_command_response_pb2.RepoCommandResponseMessage()
                    try:
                        ProtobufTlv.decode(response, data.content)
                    except:
                        print("Cannot decode the repo command response")
                        
                    if response.repo_command_response.status_code == 100:
                        if __debug__:
                            print("Insertion started")
                    else:
                        print("Got repo command error code", response.repo_command_response.status_code)
                        
                def onRepoCommandTimeout(interest):
                    if __debug__:
                        print("Insert repo command timeout")
                    
                self._face.expressInterest(commandInterest, onRepoCommandResponse, onRepoCommandTimeout)


            except Exception as detail:
                print("publish: Error calling createData for", line, "-", detail)
Esempio n. 19
0
    def test_constructor(self):
        # Check default settings.
        content = EncryptedContent()
        self.assertEqual(content.getAlgorithmType(), None)
        self.assertTrue(content.getPayload().isNull())
        self.assertTrue(content.getInitialVector().isNull())
        self.assertEqual(content.getKeyLocator().getType(), None)

        # Check an encrypted content with IV.
        keyLocator = KeyLocator()
        keyLocator.setType(KeyLocatorType.KEYNAME)
        keyLocator.getKeyName().set("/test/key/locator")
        rsaOaepContent = EncryptedContent()
        rsaOaepContent.setAlgorithmType(
            EncryptAlgorithmType.RsaOaep).setKeyLocator(keyLocator).setPayload(
                Blob(message, False)).setInitialVector(Blob(iv, False))

        self.assertEqual(rsaOaepContent.getAlgorithmType(),
                         EncryptAlgorithmType.RsaOaep)
        self.assertTrue(rsaOaepContent.getPayload().equals(Blob(
            message, False)))
        self.assertTrue(rsaOaepContent.getInitialVector().equals(
            Blob(iv, False)))
        self.assertTrue(rsaOaepContent.getKeyLocator().getType() != None)
        self.assertTrue(rsaOaepContent.getKeyLocator().getKeyName().equals(
            Name("/test/key/locator")))

        # Encoding.
        encryptedBlob = Blob(encrypted, False)
        encoded = rsaOaepContent.wireEncode()

        self.assertTrue(encryptedBlob.equals(encoded))

        # Decoding.
        rsaOaepContent2 = EncryptedContent()
        rsaOaepContent2.wireDecode(encryptedBlob)
        self.assertEqual(rsaOaepContent2.getAlgorithmType(),
                         EncryptAlgorithmType.RsaOaep)
        self.assertTrue(rsaOaepContent2.getPayload().equals(
            Blob(message, False)))
        self.assertTrue(rsaOaepContent2.getInitialVector().equals(
            Blob(iv, False)))
        self.assertTrue(rsaOaepContent2.getKeyLocator().getType() != None)
        self.assertTrue(rsaOaepContent2.getKeyLocator().getKeyName().equals(
            Name("/test/key/locator")))

        # Check the no IV case.
        rsaOaepContentNoIv = EncryptedContent()
        rsaOaepContentNoIv.setAlgorithmType(
            EncryptAlgorithmType.RsaOaep).setKeyLocator(keyLocator).setPayload(
                Blob(message, False))
        self.assertEqual(rsaOaepContentNoIv.getAlgorithmType(),
                         EncryptAlgorithmType.RsaOaep)
        self.assertTrue(rsaOaepContentNoIv.getPayload().equals(
            Blob(message, False)))
        self.assertTrue(rsaOaepContentNoIv.getInitialVector().isNull())
        self.assertTrue(rsaOaepContentNoIv.getKeyLocator().getType() != None)
        self.assertTrue(rsaOaepContentNoIv.getKeyLocator().getKeyName().equals(
            Name("/test/key/locator")))

        # Encoding.
        encryptedBlob2 = Blob(encryptedNoIv, False)
        encodedNoIv = rsaOaepContentNoIv.wireEncode()
        self.assertTrue(encryptedBlob2.equals(encodedNoIv))

        # Decoding.
        rsaOaepContentNoIv2 = EncryptedContent()
        rsaOaepContentNoIv2.wireDecode(encryptedBlob2)
        self.assertEqual(rsaOaepContentNoIv2.getAlgorithmType(),
                         EncryptAlgorithmType.RsaOaep)
        self.assertTrue(rsaOaepContentNoIv2.getPayload().equals(
            Blob(message, False)))
        self.assertTrue(rsaOaepContentNoIv2.getInitialVector().isNull())
        self.assertTrue(rsaOaepContentNoIv2.getKeyLocator().getType() != None)
        self.assertTrue(
            rsaOaepContentNoIv2.getKeyLocator().getKeyName().equals(
                Name("/test/key/locator")))
import pyndn
from pyndn import NDN, Name, Interest, ContentObject, SignedInfo, Key, KeyLocator, Closure
#from threading import Timer

k = NDN.getDefaultKey()
kl = KeyLocator(k)

n = Name("/forty/two")


class SenderClosure(Closure):
    def upcall(self, kind, upcallInfo):
        global sender_handle, n, k, kl

        print("Sender closure:")
        print(upcallInfo)

        co = ContentObject()
        co.name = Name(n)
        co.content = "Frou"

        si = SignedInfo()
        si.publisherPublicKeyDigest = k.publicKeyID
        si.type = pyndn.CONTENT_DATA
        si.freshnessSeconds = 5
        si.keyLocator = kl

        co.signedInfo = si

        co.sign(k)
        r = sender_handle.put(co)
Esempio n. 21
0
    def publish(self, line):
        # Pull out and parse datetime for log entry
        # (note we shoudld use point time for timestamp)
        try:
            if not ": (point" in line: return
            point = parse.search("(point {})", line)[0].split(" ")
        except Exception as detail:
            print("publish: Parse error for", line, "-", detail)
            return
        try:
            tempTime = datetime.strptime(
                parse.search("[{}]", line)[0], "%Y-%m-%d %H:%M:%S.%f")
        except Exception as detail:
            print("publish: Date/time conversion error for", line, "-", detail)
            return

        sensorName = point[0]
        aggregationNamePrefix = self.pointNameToNDNName(sensorName)
        dataDict = self.pointToJSON(point)

        if aggregationNamePrefix is not None:
            #if __debug__:
            #    print(dateTime, aggregationNamePrefix, dataDict["timestamp"], "payload:", dataDict["value"])
            try:
                # TODO: since the leaf sensor publisher is not a separate node for now, we also publish aggregated data
                #       of the same sensor over the past given time period in this code;
                #       bms_node code has adaptation for leaf sensor publishers as well, ref: example-sensor1.conf

                # Here we make the assumption of fixed time window for *all* sensors
                # First publish aggregation
                dataTime = int(float(dataDict["timestamp"]) * 1000)
                if self._startTime == 0:
                    self._startTime = dataTime
                if not (sensorName in self._dataQueue):
                    # We don't have record of this sensor, so we create an identity for it, and print the cert string for now to get signed
                    sensorIdentityName = Name(self._namespace).append(
                        aggregationNamePrefix).getPrefix(-3)
                    sensorCertificateName = self._keyChain.createIdentityAndCertificate(
                        sensorIdentityName)
                    if __debug__:
                        print("Sensor identity name: " +
                              sensorIdentityName.toUri())
                    certificateData = self._keyChain.getIdentityManager(
                    )._identityStorage.getCertificate(sensorCertificateName)

                    # We should only ask for cert to be signed upon the first run of a certain sensor
                    if DO_CERT_SETUP:
                        if (KeyLocator.getFromSignature(
                                certificateData.getSignature()).getKeyName().
                                equals(sensorCertificateName.getPrefix(-1))):
                            # Need to configure for remote gateway deployment; for now, remote uses its own branch with my public IP.
                            print("certificate " +
                                  sensorCertificateName.toUri() +
                                  " asking for signature")
                            response = urllib2.urlopen(
                                "http://192.168.56.1:5000/bms-cert-hack?cert="
                                + b64encode(
                                    certificateData.wireEncode().toBuffer()) +
                                "&cert_prefix=" + sensorIdentityName.toUri() +
                                '&subject_name=' +
                                sensorIdentityName.toUri()).read()

                            signedCertData = Data()
                            signedCertData.wireDecode(Blob(
                                b64decode(response)))

                            self._cache.add(signedCertData)
                            cmdline = ['ndnsec-install-cert', '-']
                            p = subprocess.Popen(cmdline,
                                                 stdin=subprocess.PIPE,
                                                 stdout=subprocess.PIPE)
                            cert, err = p.communicate(response)
                            if p.returncode != 0:
                                raise RuntimeError("ndnsec-install-cert error")
                        else:
                            self._cache.add(certificateData)
                    else:
                        self._cache.add(certificateData)

                    self._dataQueue[sensorName] = DataQueueItem(
                        [], self._startTime + self._defaultInterval,
                        sensorIdentityName, sensorCertificateName)
                    self._dataQueue[sensorName]._dataList.append(
                        dataDict["value"])
                elif dataTime > self._dataQueue[sensorName]._timeThreshold:
                    # calculate the aggregation with what's already in the queue, publish data packet, and delete current queue
                    # TODO: This should be mutex locked against self
                    if len(self._dataQueue[sensorName]._dataList) > 0:
                        avg = 0.0
                        for item in self._dataQueue[sensorName]._dataList:
                            avg += float(item)
                        avg = avg / len(self._dataQueue[sensorName]._dataList)
                        data = Data(
                            Name(self._namespace).
                            append(aggregationNamePrefix).append("avg").append(
                                str(self._dataQueue[sensorName]._timeThreshold)
                            ).append(
                                str(self._dataQueue[sensorName]._timeThreshold
                                    + self._defaultInterval)))
                        data.setContent(str(avg))
                        data.getMetaInfo().setFreshnessPeriod(
                            self.DEFAULT_DATA_LIFETIME)
                        self._keyChain.sign(
                            data, self._dataQueue[sensorName]._certificateName)
                        self._cache.add(data)
                        print("Aggregation produced " + data.getName().toUri())

                    self._dataQueue[sensorName]._dataList = [dataDict["value"]]
                    self._dataQueue[
                        sensorName]._timeThreshold = self._dataQueue[
                            sensorName]._timeThreshold + self._defaultInterval
                else:
                    self._dataQueue[sensorName]._dataList.append(
                        dataDict["value"])

                # Then publish raw data
                # Timestamp in data name uses the timestamp from data payload
                instDataPrefix = self.pointNameToNDNName(sensorName, False)
                dataTemp = self.createData(
                    instDataPrefix, dataDict["timestamp"], dataDict["value"],
                    self._dataQueue[sensorName]._certificateName)
                if __debug__:
                    print("Produced raw data name " +
                          dataTemp.getName().toUri())
                    print("Produced raw data content " +
                          dataTemp.getContent().toRawStr())
                self._cache.add(dataTemp)

            except Exception as detail:
                print("publish: Error calling createData for", line, "-",
                      detail)
Esempio n. 22
0
ret = NameCrypto.verify_command(state2,
                                name_from_js,
                                window,
                                fixture_key=secret)
print ret
assert (ret == True)

# Test asymmetric authentication

state = NameCrypto.new_state()

name = Name('/ndn/ucla.edu/apps/cuerda')

key = NDN.getDefaultKey()

keyLoc = KeyLocator(key)
keyLocStr = pyndn._pyndn.dump_charbuf(keyLoc.ndn_data)

name = name.append(keyLocStr)

auth_name = NameCrypto.authenticate_command_sig(state, name, app_name, key)
print auth_name

state2 = NameCrypto.new_state()

ret = NameCrypto.verify_command(state2, auth_name, window, pub_key=key)
print ret
assert (ret == True)

name_from_js2 = Name(
    '/ndn/ucla.edu/apps/cuerda/%01%E2%01%DA%0A%950%81%9F0%0D%06%09%2A%86H%86%F7%0D%01%01%01%05%00%03%81%8D%000%81%89%02%81%81%00%E1%7D0%A7%D8%28%AB%1B%84%0B%17T-%CA%F6%20z%FD%22%1E%08k%2A%60%D1l%B7%F5DH%BA%9F%3F%08%BC%D0%99%DB%21%DD%16%2Aw%9Ea%AA%89%EE%E5T%D3%A4%7D%E20%BCz%C5%90%D5%24%06%7C8%98%BB%A6%F5%DCC%60%B8E%ED%A4%8C%BD%9C%F1%26%A7%23D_%0E%19R%D72Zu%FA%F5V%14O%9A%98%AFq%86%B0%27%86%85%B8%E2%C0%8B%EA%87%17%1BM%EEX%5C%18%28%29%5BS%95%EBJ%17w%9F%02%03%01%00%01%00%00/%21D%07e%00%06cuerdaQk%90%CF%00%050%20%00%00%00%01%00%00%00%007%11%03%A1%0BS6%FF%CD%EA%5B%94%1B%9F%D8%1F0F%C0%A0%EA%CE%19%02%1D%E0k4%F0%E1%28%A1%881%BE%8F%60%95%9F%FB%21%04%D0%5C%90%EA%BC%0C%25%D1%05%CF%E8%1E%FB%A8%2AVp%BF%7B%06%07%C5Cs%A4%BB%B01%03%5D%8A%8EI%AA.%AA%9Cs%1F%DF%FE%C3%D5%BC%E5%DEL_%BF%EEj%D9G%E9%AC%EC%C69%5C%18%AE%A5%F3uv%91E%A4cM%EE%9B%F1+%26%C4%B3JsFk+%C5%3EP%2F'
Esempio n. 23
0
    def test_matches_data(self):
        interest = Interest(Name("/A"))
        interest.setMinSuffixComponents(2)
        interest.setMaxSuffixComponents(2)
        interest.getKeyLocator().setType(KeyLocatorType.KEYNAME)
        interest.getKeyLocator().setKeyName(Name("/B"))
        interest.getExclude().appendComponent(Name.Component("J"))
        interest.getExclude().appendAny()

        data = Data(Name("/A/D"))
        signature = Sha256WithRsaSignature()
        signature.getKeyLocator().setType(KeyLocatorType.KEYNAME)
        signature.getKeyLocator().setKeyName(Name("/B"))
        data.setSignature(signature)
        self.assertEqual(interest.matchesData(data), True)

        # Check violating MinSuffixComponents.
        data1 = Data(data)
        data1.setName(Name("/A"))
        self.assertEqual(interest.matchesData(data1), False)

        interest1 = Interest(interest)
        interest1.setMinSuffixComponents(1)
        self.assertEqual(interest1.matchesData(data1), True)

        # Check violating MaxSuffixComponents.
        data2 = Data(data)
        data2.setName(Name("/A/E/F"))
        self.assertEqual(interest.matchesData(data2), False)

        interest2 = Interest(interest)
        interest2.setMaxSuffixComponents(3)
        self.assertEqual(interest2.matchesData(data2), True)

        # Check violating PublisherPublicKeyLocator.
        data3 = Data(data)
        signature3 = Sha256WithRsaSignature()
        signature3.getKeyLocator().setType(KeyLocatorType.KEYNAME)
        signature3.getKeyLocator().setKeyName(Name("/G"))
        data3.setSignature(signature3)
        self.assertEqual(interest.matchesData(data3), False)

        interest3 = Interest(interest)
        interest3.getKeyLocator().setType(KeyLocatorType.KEYNAME)
        interest3.getKeyLocator().setKeyName(Name("/G"))
        self.assertEqual(interest3.matchesData(data3), True)

        data4 = Data(data)
        data4.setSignature(DigestSha256Signature())
        self.assertEqual(interest.matchesData(data4), False)

        interest4 = Interest(interest)
        interest4.setKeyLocator(KeyLocator())
        self.assertEqual(interest4.matchesData(data4), True)

        # Check violating Exclude.
        data5 = Data(data)
        data5.setName(Name("/A/J"))
        self.assertEqual(interest.matchesData(data5), False)

        interest5 = Interest(interest)
        interest5.getExclude().clear()
        interest5.getExclude().appendComponent(Name.Component("K"))
        interest5.getExclude().appendAny()
        self.assertEqual(interest5.matchesData(data5), True)

        # Check violating Name.
        data6 = Data(data)
        data6.setName(Name("/H/I"))
        self.assertEqual(interest.matchesData(data6), False)

        data7 = Data(data)
        data7.setName(Name("/A/B"))

        interest7 = Interest(
          Name("/A/B/sha256digest=" +
               "54008e240a7eea2714a161dfddf0dd6ced223b3856e9da96792151e180f3b128"))
        self.assertEqual(interest7.matchesData(data7), True)

        # Check violating the implicit digest.
        interest7b = Interest(
          Name("/A/B/%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00" +
               "%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00"))
        self.assertEqual(interest7b.matchesData(data7), False)

        # Check excluding the implicit digest.
        interest8 = Interest(Name("/A/B"))
        interest8.getExclude().appendComponent(interest7.getName().get(2))
        self.assertEqual(interest8.matchesData(data7), False)
Esempio n. 24
0
    def checkVerificationPolicy(self, dataOrInterest, stepCount, onVerified,
                                onVerifyFailed, wireFormat = None):
        """
        If there is a rule matching the data or interest, and the matching
        certificate is missing, download it. If there is no matching rule,
        verification fails. Otherwise, verify the signature using the public key
        in the IdentityStorage.

        :param dataOrInterest: The Data object or interest with the signature to
          check.
        :type dataOrInterest: Data or Interest
        :param int stepCount: The number of verification steps that have been
          done, used to track the verification progress.
        :param onVerified: If the signature is verified, this calls
          onVerified(dataOrInterest).
        :type onVerified: function object
        :param onVerifyFailed: If the signature check fails, this calls
          onVerifyFailed(dataOrInterest).
        :type onVerifyFailed: function object
        :return: None for no further step for looking up a certificate chain.
        :rtype: ValidationRequest
        """
        if stepCount > self._maxDepth:
            onVerifyFailed(dataOrInterest)
            return None

        signature = self._extractSignature(dataOrInterest, wireFormat)
        # no signature -> fail
        if signature is None:
            onVerifyFailed(dataOrInterest)
            return None

        if not KeyLocator.canGetFromSignature(signature):
            # We only support signature types with key locators.
            onVerifyFailed(dataOrInterest)
            return None

        keyLocator = None
        try:
            keyLocator = KeyLocator.getFromSignature(signature)
        except:
            # No key locator -> fail.
            onVerifyFailed(dataOrInterest)
            return None

        signatureName = keyLocator.getKeyName()
        # no key name in KeyLocator -> fail
        if signatureName.size() == 0:
            onVerifyFailed(dataOrInterest)
            return None

        objectName = dataOrInterest.getName()
        matchType = "data"

        #for command interests, we need to ignore the last 4 components when matching the name
        if isinstance(dataOrInterest, Interest):
            objectName = objectName.getPrefix(-4)
            matchType = "interest"

        # first see if we can find a rule to match this packet
        try:
            matchedRule = self._findMatchingRule(objectName, matchType)
        except:
            matchedRule = None

        # no matching rule -> fail
        if matchedRule is None:
            onVerifyFailed(dataOrInterest)
            return None

        signatureMatches = self._checkSignatureMatch(signatureName, objectName,
                matchedRule)
        if not signatureMatches:
            onVerifyFailed(dataOrInterest)
            return None

        # before we look up keys, refresh any certificate directories
        self._refreshManager.refreshAnchors()

        # now finally check that the data or interest was signed correctly
        # if we don't actually have the certificate yet, create a
        # ValidationRequest for it
        foundCert = self._refreshManager.getCertificate(signatureName)
        if foundCert is None:
            foundCert = self._certificateCache.getCertificate(signatureName)
        if foundCert is None:
            certificateInterest = Interest(signatureName)
            def onCertificateDownloadComplete(certificate):
                certificate = IdentityCertificate(certificate)
                self._certificateCache.insertCertificate(certificate)
                self.checkVerificationPolicy(dataOrInterest, stepCount+1,
                        onVerified, onVerifyFailed)

            nextStep = ValidationRequest(certificateInterest,
                    onCertificateDownloadComplete, onVerifyFailed,
                    2, stepCount+1)

            return nextStep

        # for interests, we must check that the timestamp is fresh enough
        # I do this after (possibly) downloading the certificate to avoid
        # filling the cache with bad keys
        if isinstance(dataOrInterest, Interest):
            keyName = foundCert.getPublicKeyName()
            timestamp = dataOrInterest.getName().get(-4).toNumber()

            if not self._interestTimestampIsFresh(keyName, timestamp):
                onVerifyFailed(dataOrInterest)
                return None

        # certificate is known, verify the signature
        if self._verify(signature, dataOrInterest.wireEncode()):
            onVerified(dataOrInterest)
            if isinstance(dataOrInterest, Interest):
                self._updateTimestampForKey(keyName, timestamp)
        else:
            onVerifyFailed(dataOrInterest)
Esempio n. 25
0
    def startPublishing(self):
        # One-time security setup
        self.prepareLogging()

        privateKeyStorage = FilePrivateKeyStorage()
        identityStorage = BasicIdentityStorage()
        policyManager = ConfigPolicyManager(self._trustSchemaFile)

        self._keyChain = KeyChain(
            IdentityManager(identityStorage, privateKeyStorage), policyManager)
        self._certificateName = self._keyChain.createIdentityAndCertificate(
            self._identityName)

        print("My Identity name: " + self._identityName.toUri())
        print("My certificate name: " + self._certificateName.toUri())
        certificateData = self._keyChain.getIdentityManager(
        )._identityStorage.getCertificate(self._certificateName)
        print("My certificate string: " +
              b64encode(certificateData.wireEncode().toBuffer()))
        # self._keyChain.getIdentityCertificate(self._certificateName).)

        self._loop = asyncio.get_event_loop()
        self._face = ThreadsafeFace(self._loop)
        self._keyChain.setFace(self._face)

        self._face.setCommandSigningInfo(self._keyChain, self._certificateName)
        self._memoryContentCache = MemoryContentCache(self._face)

        # We should only ask for cert to be signed upon the first run of a certain aggregator
        if DO_CERT_SETUP:
            if (KeyLocator.getFromSignature(
                    certificateData.getSignature()).getKeyName().equals(
                        self._certificateName.getPrefix(-1))):
                # Need to configure for mini-ndn; aggregation node runs outside of mini-ndn first so that signed cert get installed and mini-ndn won't ask for this again
                print("certificate " + self._certificateName.toUri() +
                      " asking for signature")
                response = urllib2.urlopen(
                    "http://192.168.56.1:5000/bms-cert-hack?cert=" +
                    b64encode(certificateData.wireEncode().toBuffer()) +
                    "&cert_prefix=" + self._identityName.toUri() +
                    '&subject_name=' + self._identityName.toUri()).read()

                signedCertData = Data()
                signedCertData.wireDecode(Blob(b64decode(response)))

                self._memoryContentCache.add(signedCertData)
                cmdline = ['ndnsec-install-cert', '-']
                p = subprocess.Popen(cmdline,
                                     stdin=subprocess.PIPE,
                                     stdout=subprocess.PIPE)
                # desanitize + sign in GET request
                cert, err = p.communicate(response)
                if p.returncode != 0:
                    raise RuntimeError("ndnsec-install-cert error")
            else:
                self._memoryContentCache.add(certificateData)
        else:
            self._memoryContentCache.add(certificateData)

        dataNode = self.conf.getDataNode()
        childrenNode = self.conf.getChildrenNode()

        self._memoryContentCache.registerPrefix(Name(self._identityName),
                                                self.onRegisterFailed,
                                                self.onDataNotFound)

        # For each type of data, we refresh each type of aggregation according to the interval in the configuration
        for i in range(len(dataNode.subtrees)):
            dataType = dataNode.subtrees.keys()[i]
            aggregationParams = self.conf.getProducingParamsForAggregationType(
                dataNode.subtrees.items()[i][1])

            if childrenNode == None:
                self._dataQueue[dataType] = DataQueue(None, None, None)
                self.generateData(dataType, 2, 0)

            for aggregationType in aggregationParams:
                childrenList = OrderedDict()
                if childrenNode != None:

                    for j in range(len(childrenNode.subtrees)):
                        if dataType in childrenNode.subtrees.items(
                        )[j][1].subtrees['data'].subtrees:
                            if aggregationType in childrenNode.subtrees.items(
                            )[j][1].subtrees['data'].subtrees[
                                    dataType].subtrees:
                                childrenList[childrenNode.subtrees.items()[j][
                                    0]] = self.conf.getProducingParamsForAggregationType(
                                        childrenNode.subtrees.items()[j]
                                        [1].subtrees['data'].subtrees[dataType]
                                    )[aggregationType]

                self.startPublishingAggregation(
                    aggregationParams[aggregationType], childrenList, dataType,
                    aggregationType)
        return
Esempio n. 26
0
    def test_constructor(self):
        # Check default settings.
        content = EncryptedContent()
        self.assertEqual(content.getAlgorithmType(), None)
        self.assertTrue(content.getPayload().isNull())
        self.assertTrue(content.getInitialVector().isNull())
        self.assertEqual(content.getKeyLocator().getType(), None)

        # Check an encrypted content with IV.
        keyLocator = KeyLocator()
        keyLocator.setType(KeyLocatorType.KEYNAME)
        keyLocator.getKeyName().set("/test/key/locator")
        rsaOaepContent = EncryptedContent()
        rsaOaepContent.setAlgorithmType(EncryptAlgorithmType.RsaOaep).setKeyLocator(
          keyLocator).setPayload(Blob(message, False)).setInitialVector(Blob(iv, False))

        self.assertEqual(rsaOaepContent.getAlgorithmType(), EncryptAlgorithmType.RsaOaep)
        self.assertTrue(rsaOaepContent.getPayload().equals(Blob(message, False)))
        self.assertTrue(rsaOaepContent.getInitialVector().equals(Blob(iv, False)))
        self.assertTrue(rsaOaepContent.getKeyLocator().getType() != None)
        self.assertTrue(rsaOaepContent.getKeyLocator().getKeyName().equals(
          Name("/test/key/locator")))

        # Encoding.
        encryptedBlob = Blob(encrypted, False)
        encoded = rsaOaepContent.wireEncode()

        self.assertTrue(encryptedBlob.equals(encoded))

        # Decoding.
        rsaOaepContent2 = EncryptedContent()
        rsaOaepContent2.wireDecode(encryptedBlob)
        self.assertEqual(rsaOaepContent2.getAlgorithmType(), EncryptAlgorithmType.RsaOaep)
        self.assertTrue(rsaOaepContent2.getPayload().equals(Blob(message, False)))
        self.assertTrue(rsaOaepContent2.getInitialVector().equals(Blob(iv, False)))
        self.assertTrue(rsaOaepContent2.getKeyLocator().getType() != None)
        self.assertTrue(rsaOaepContent2.getKeyLocator().getKeyName().equals(
          Name("/test/key/locator")))

        # Check the no IV case.
        rsaOaepContentNoIv = EncryptedContent()
        rsaOaepContentNoIv.setAlgorithmType(EncryptAlgorithmType.RsaOaep).setKeyLocator(
          keyLocator).setPayload(Blob(message, False))
        self.assertEqual(rsaOaepContentNoIv.getAlgorithmType(), EncryptAlgorithmType.RsaOaep)
        self.assertTrue(rsaOaepContentNoIv.getPayload().equals(Blob(message, False)))
        self.assertTrue(rsaOaepContentNoIv.getInitialVector().isNull())
        self.assertTrue(rsaOaepContentNoIv.getKeyLocator().getType() != None)
        self.assertTrue(rsaOaepContentNoIv.getKeyLocator().getKeyName().equals(
          Name("/test/key/locator")))

        # Encoding.
        encryptedBlob2 = Blob(encryptedNoIv, False)
        encodedNoIv = rsaOaepContentNoIv.wireEncode()
        self.assertTrue(encryptedBlob2.equals(encodedNoIv))

        # Decoding.
        rsaOaepContentNoIv2 = EncryptedContent()
        rsaOaepContentNoIv2.wireDecode(encryptedBlob2)
        self.assertEqual(rsaOaepContentNoIv2.getAlgorithmType(), EncryptAlgorithmType.RsaOaep)
        self.assertTrue(rsaOaepContentNoIv2.getPayload().equals(Blob(message, False)))
        self.assertTrue(rsaOaepContentNoIv2.getInitialVector().isNull())
        self.assertTrue(rsaOaepContentNoIv2.getKeyLocator().getType() != None)
        self.assertTrue(rsaOaepContentNoIv2.getKeyLocator().getKeyName().equals(
          Name("/test/key/locator")))
Esempio n. 27
0
    def startPublishing(self):
        # One-time security setup
        self.prepareLogging()

        privateKeyStorage = FilePrivateKeyStorage()
        identityStorage = BasicIdentityStorage()
        policyManager = ConfigPolicyManager(self._trustSchemaFile)

        self._keyChain = KeyChain(IdentityManager(identityStorage, privateKeyStorage), policyManager)
        self._certificateName = self._keyChain.createIdentityAndCertificate(self._identityName)

        print("My Identity name: " + self._identityName.toUri())
        print("My certificate name: " + self._certificateName.toUri())
        certificateData = self._keyChain.getIdentityManager()._identityStorage.getCertificate(self._certificateName, True)
        print("My certificate string: " + b64encode(certificateData.wireEncode().toBuffer()))
        # self._keyChain.getIdentityCertificate(self._certificateName).)

        self._loop = asyncio.get_event_loop()
        self._face = ThreadsafeFace(self._loop)
        self._keyChain.setFace(self._face)

        self._face.setCommandSigningInfo(self._keyChain, self._certificateName)
        self._memoryContentCache = MemoryContentCache(self._face)

        # We should only ask for cert to be signed upon the first run of a certain aggregator
        if DO_CERT_SETUP:
            if (KeyLocator.getFromSignature(certificateData.getSignature()).getKeyName().equals(self._certificateName.getPrefix(-1))):
                # Need to configure for mini-ndn; aggregation node runs outside of mini-ndn first so that signed cert get installed and mini-ndn won't ask for this again
                print("certificate " + self._certificateName.toUri() + " asking for signature")
                response = urllib2.urlopen("http://192.168.56.1:5000/bms-cert-hack?cert=" + b64encode(certificateData.wireEncode().toBuffer()) + "&cert_prefix=" + self._identityName.toUri() + '&subject_name=' + self._identityName.toUri()).read()
                
                signedCertData = Data()
                signedCertData.wireDecode(Blob(b64decode(response)))

                self._memoryContentCache.add(signedCertData)
                cmdline = ['ndnsec-install-cert', '-']
                p = subprocess.Popen(cmdline, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
                # desanitize + sign in GET request
                cert, err = p.communicate(response)
                if p.returncode != 0:
                    raise RuntimeError("ndnsec-install-cert error")
            else:
                self._memoryContentCache.add(certificateData)
        else:
            self._memoryContentCache.add(certificateData)

        dataNode = self.conf.getDataNode()
        childrenNode = self.conf.getChildrenNode()

        self._memoryContentCache.registerPrefix(Name(self._identityName), self.onRegisterFailed, self.onDataNotFound)

        # For each type of data, we refresh each type of aggregation according to the interval in the configuration
        for i in range(len(dataNode.subtrees)):
            dataType = dataNode.subtrees.keys()[i]
            aggregationParams = self.conf.getProducingParamsForAggregationType(dataNode.subtrees.items()[i][1])

            if childrenNode == None:
                self._dataQueue[dataType] = DataQueue(None, None, None)
                self.generateData(dataType, 2, 0)

            for aggregationType in aggregationParams:
                childrenList = OrderedDict()
                if childrenNode != None:

                    for j in range(len(childrenNode.subtrees)):
                        if dataType in childrenNode.subtrees.items()[j][1].subtrees['data'].subtrees:
                            if aggregationType in childrenNode.subtrees.items()[j][1].subtrees['data'].subtrees[dataType].subtrees:
                                childrenList[childrenNode.subtrees.items()[j][0]] = self.conf.getProducingParamsForAggregationType(childrenNode.subtrees.items()[j][1].subtrees['data'].subtrees[dataType])[aggregationType]

                self.startPublishingAggregation(aggregationParams[aggregationType], childrenList, dataType, aggregationType)
        return
Esempio n. 28
0
    def checkVerificationPolicy(self,
                                dataOrInterest,
                                stepCount,
                                onVerified,
                                onVerifyFailed,
                                wireFormat=None):
        """
        If there is a rule matching the data or interest, and the matching
        certificate is missing, download it. If there is no matching rule,
        verification fails. Otherwise, verify the signature using the public key
        in the IdentityStorage.

        :param dataOrInterest: The Data object or interest with the signature to
          check.
        :type dataOrInterest: Data or Interest
        :param int stepCount: The number of verification steps that have been
          done, used to track the verification progress.
        :param onVerified: If the signature is verified, this calls
          onVerified(dataOrInterest).
        :type onVerified: function object
        :param onVerifyFailed: If the signature check fails, this calls
          onVerifyFailed(dataOrInterest).
        :type onVerifyFailed: function object
        :return: None for no further step for looking up a certificate chain.
        :rtype: ValidationRequest
        """
        if stepCount > self._maxDepth:
            onVerifyFailed(dataOrInterest)
            return None

        signature = self._extractSignature(dataOrInterest, wireFormat)
        # no signature -> fail
        if signature is None:
            onVerifyFailed(dataOrInterest)
            return None

        if not KeyLocator.canGetFromSignature(signature):
            # We only support signature types with key locators.
            onVerifyFailed(dataOrInterest)
            return None

        keyLocator = None
        try:
            keyLocator = KeyLocator.getFromSignature(signature)
        except:
            # No key locator -> fail.
            onVerifyFailed(dataOrInterest)
            return None

        signatureName = keyLocator.getKeyName()
        # no key name in KeyLocator -> fail
        if signatureName.size() == 0:
            onVerifyFailed(dataOrInterest)
            return None

        objectName = dataOrInterest.getName()
        matchType = "data"

        #for command interests, we need to ignore the last 4 components when matching the name
        if isinstance(dataOrInterest, Interest):
            objectName = objectName.getPrefix(-4)
            matchType = "interest"

        # first see if we can find a rule to match this packet
        try:
            matchedRule = self._findMatchingRule(objectName, matchType)
        except:
            matchedRule = None

        # no matching rule -> fail
        if matchedRule is None:
            onVerifyFailed(dataOrInterest)
            return None

        signatureMatches = self._checkSignatureMatch(signatureName, objectName,
                                                     matchedRule)
        if not signatureMatches:
            onVerifyFailed(dataOrInterest)
            return None

        # before we look up keys, refresh any certificate directories
        self._refreshManager.refreshAnchors()

        # now finally check that the data or interest was signed correctly
        # if we don't actually have the certificate yet, create a
        # ValidationRequest for it
        foundCert = self._refreshManager.getCertificate(signatureName)
        if foundCert is None:
            foundCert = self._certificateCache.getCertificate(signatureName)
        if foundCert is None:
            certificateInterest = Interest(signatureName)

            def onCertificateDownloadComplete(certificate):
                certificate = IdentityCertificate(certificate)
                self._certificateCache.insertCertificate(certificate)
                self.checkVerificationPolicy(dataOrInterest, stepCount + 1,
                                             onVerified, onVerifyFailed)

            nextStep = ValidationRequest(certificateInterest,
                                         onCertificateDownloadComplete,
                                         onVerifyFailed, 2, stepCount + 1)

            return nextStep

        # for interests, we must check that the timestamp is fresh enough
        # I do this after (possibly) downloading the certificate to avoid
        # filling the cache with bad keys
        if isinstance(dataOrInterest, Interest):
            keyName = foundCert.getPublicKeyName()
            timestamp = dataOrInterest.getName().get(-4).toNumber()

            if not self._interestTimestampIsFresh(keyName, timestamp):
                onVerifyFailed(dataOrInterest)
                return None

        # certificate is known, verify the signature
        if self._verify(signature, dataOrInterest.wireEncode()):
            onVerified(dataOrInterest)
            if isinstance(dataOrInterest, Interest):
                self._updateTimestampForKey(keyName, timestamp)
        else:
            onVerifyFailed(dataOrInterest)