예제 #1
0
    def test_match(self):
        name = Name("/edu/cmu/andrew/user/3498478")
        name2 = Name(name)
        self.assertTrue(name.match(name2), 'Name does not match deep copy of itself')

        name2 = name[:2]
        self.assertTrue(name2.match(name), 'Name did not match prefix')
        self.assertFalse(name.match(name2), 'Name should not match shorter name')
        self.assertTrue(Name().match(name), 'Empty name should always match another')
예제 #2
0
    def test_match(self):
        name = Name("/edu/cmu/andrew/user/3498478")
        name2 = Name(name)
        self.assertTrue(name.match(name2), 'Name does not match deep copy of itself')

        name2 = name.getPrefix(2)
        self.assertTrue(name2.match(name), 'Name did not match prefix')
        self.assertFalse(name.match(name2), 'Name should not match shorter name')
        self.assertTrue(Name().match(name), 'Empty name should always match another')
예제 #3
0
    def _onCommandReceived(self, prefix, interest, transport, prefixId):

        # first off, we shouldn't be here if we have no configured environment
        # just let this interest time out
        if (self._policyManager.getTrustRootIdentity() is None
                or self._policyManager.getEnvironmentPrefix() is None):
            return

        # if this is a cert request, we can serve it from our store (if it exists)
        certData = self._identityStorage.getCertificate(interest.getName())
        if certData is not None:
            self.log.info("Serving certificate request")
            # if we sign the certificate, we lose the controller's signature!
            self.sendData(certData, transport, False)
            return

        # else we must look in our command list to see if this requires verification
        # we dispatch directly or after verification as necessary

        # now we look for the first command that matches in our config
        self.log.debug("Received {}".format(interest.getName().toUri()))

        for command in self._commands:
            fullCommandName = Name(self.prefix).append(Name(command.suffix))
            if fullCommandName.match(interest.getName()):
                dispatchFunc = command.function

                if not command.isSigned:
                    responseData = dispatchFunc(interest)
                    self.sendData(responseData, transport)
                else:
                    try:
                        self._keyChain.verifyInterest(
                            interest,
                            self._makeVerifiedCommandDispatch(
                                dispatchFunc, transport),
                            self.verificationFailed)
                        return
                    except Exception as e:
                        self.log.exception("Exception while verifying command",
                                           exc_info=True)
                        self.verificationFailed(interest)
                        return
        #if we get here, just let it timeout
        return
예제 #4
0
    def _onCommandReceived(self, prefix, interest, transport, prefixId):

        # first off, we shouldn't be here if we have no configured environment
        # just let this interest time out
        if (self._policyManager.getTrustRootIdentity() is None or
                self._policyManager.getEnvironmentPrefix() is None):
            return

        # if this is a cert request, we can serve it from our store (if it exists)
        certData = self._identityStorage.getCertificate(interest.getName())
        if certData is not None:
            self.log.info("Serving certificate request")
            # if we sign the certificate, we lose the controller's signature!
            self.sendData(certData, transport, False)
            return

        # else we must look in our command list to see if this requires verification
        # we dispatch directly or after verification as necessary

        # now we look for the first command that matches in our config
        self.log.debug("Received {}".format(interest.getName().toUri()))
        
        for command in self._commands:
            fullCommandName = Name(self.prefix).append(Name(command.suffix))
            if fullCommandName.match(interest.getName()):
                dispatchFunc = command.function
                
                if not command.isSigned:
                    responseData = dispatchFunc(interest)
                    self.sendData(responseData, transport)
                else:
                    try:
                        self._keyChain.verifyInterest(interest, 
                                self._makeVerifiedCommandDispatch(dispatchFunc, transport),
                                self.verificationFailed)
                        return
                    except Exception as e:
                        self.log.exception("Exception while verifying command", exc_info=True)
                        self.verificationFailed(interest)
                        return
        #if we get here, just let it timeout
        return
예제 #5
0
class IotPolicyManager(ConfigPolicyManager):
    def __init__(self, identityStorage, configFilename=None):
        """
        :param pyndn.IdentityStorage: A class that stores signing identities and certificates.
        :param str configFilename: A configuration file specifying validation rules and network
            name settings.
        """

        # use the default configuration where possible
        # TODO: use environment variable for this, fall back to default
        path = os.path.dirname(__file__)
        templateFilename = os.path.join(path, '.default.conf')
        self._configTemplate = BoostInfoParser()
        self._configTemplate.read(templateFilename)

        if configFilename is None:
            configFilename = templateFilename
        
        certificateCache = CertificateCache()
        super(IotPolicyManager, self).__init__(configFilename, certificateCache)
        self._identityStorage = identityStorage

        self.setEnvironmentPrefix(None)
        self.setTrustRootIdentity(None)
        self.setDeviceIdentity(None)

    def updateTrustRules(self):
        """
        Should be called after either the device identity, trust root or network
        prefix is changed.

        Not called automatically in case they are all changing (typical for
        bootstrapping).

        Resets the validation rules if we don't have a trust root or enivronment

        """
        validatorTree = self._configTemplate["validator"][0].clone()

        if (self._environmentPrefix.size() > 0 and 
            self._trustRootIdentity.size() > 0 and 
            self._deviceIdentity.size() > 0):
            # don't sneak in a bad identity
            if not self._environmentPrefix.match(self._deviceIdentity):
                raise SecurityException("Device identity does not belong to configured network!")
            
            environmentUri = self._environmentPrefix.toUri()
            deviceUri = self._deviceIdentity.toUri()
             
            for rule in validatorTree["rule"]:
                ruleId = rule["id"][0].value
                if ruleId == 'Certificate Trust':
                    #modify the 'Certificate Trust' rule
                    rule["checker/key-locator/name"][0].value = environmentUri
                elif ruleId == 'Command Interests':
                    rule["filter/name"][0].value = deviceUri
                    rule["checker/key-locator/name"][0].value = environmentUri
            
        #remove old validation rules from config
        # replace with new validator rules
        self.config._root.subtrees["validator"] = [validatorTree]
        

    def inferSigningIdentity(self, fromName):
        """
        Used to map Data or Interest names to identitites.
        :param pyndn.Name fromName: The name of a Data or Interest packet
        """
        # works if you have an IotIdentityStorage
        return self._identityStorage.inferIdentityForName(fromName)

    def setTrustRootIdentity(self, identityName):
        """
        : param pyndn.Name identityName: The new identity to trust as the controller.
        """
        self._trustRootIdentity = Name(identityName)

    def getTrustRootIdentity(self):
        """
        : return pyndn.Name: The trusted controller's network name.
        """
        return Name(self._trustRootIdentity)

    def setEnvironmentPrefix(self, name):
        """
        : param pyndn.Name name: The new root of the network namespace (network prefix)
        """
        self._environmentPrefix = Name(name)

    def getEnvironmentPrefix(self):
        """
        :return: The root of the network namespace
        :rtype: pyndn.Name
        """
        return Name(self._environmentPrefix)

    def getDeviceIdentity(self):
        return self._deviceIdentity

    def setDeviceIdentity(self, identity):
        self._deviceIdentity = Name(identity)

    def hasRootCertificate(self):
        """
        :return: Whether we've downloaded the controller's network certificate
        :rtype: boolean
        """
        try:
            rootCertName = self._identityStorage.getDefaultCertificateNameForIdentity(
                    self._trustRootIdentity)
        except SecurityException:
            return False

        try:
            rootCert = self._identityStorage.getCertificate(rootCertName)
            if rootCert is not None:
                return True
        finally:
            return False

    def hasRootSignedCertificate(self):
        """
        :return: Whether we've received a network certificate from our controller
        :rtype: boolean
        """
        try:
            myCertName = self._identityStorage.getDefaultCertificateNameForIdentity(
                       self._deviceIdentity)
            myCert = self._identityStorage.getCertificate(myCertName)
            if self._trustRootIdentity.match(
                   myCert.getSignature().getKeyLocator().getKeyName()):
               return True
        except SecurityException:
           pass
       
        return False

    def removeTrustRules(self):
        """
        Resets the network prefix, device identity and trust root identity to
         empty values
        """
        self.setDeviceIdentity(None)
        self.setTrustRootIdentity(None)
        self.setEnvironmentPrefix(None)
        self.updateTrustRules()
예제 #6
0
class IotPolicyManager(ConfigPolicyManager):
    def __init__(self, identityStorage, configFilename=None):
        """
        :param pyndn.IdentityStorage: A class that stores signing identities and certificates.
        :param str configFilename: A configuration file specifying validation rules and network
            name settings.
        """

        # use the default configuration where possible
        # TODO: use environment variable for this, fall back to default
        path = os.path.dirname(__file__)
        templateFilename = os.path.join(path, '.default.conf')
        self._configTemplate = BoostInfoParser()
        self._configTemplate.read(templateFilename)

        if configFilename is None:
            configFilename = templateFilename

        certificateCache = CertificateCache()
        super(IotPolicyManager, self).__init__(configFilename,
                                               certificateCache)
        self._identityStorage = identityStorage

        self.setEnvironmentPrefix(None)
        self.setTrustRootIdentity(None)
        self.setDeviceIdentity(None)

    def updateTrustRules(self):
        """
        Should be called after either the device identity, trust root or network
        prefix is changed.

        Not called automatically in case they are all changing (typical for
        bootstrapping).

        Resets the validation rules if we don't have a trust root or environment

        """
        validatorTree = self._configTemplate["validator"][0].clone()

        if (self._environmentPrefix.size() > 0
                and self._trustRootIdentity.size() > 0
                and self._deviceIdentity.size() > 0):
            # don't sneak in a bad identity
            if not self._environmentPrefix.match(self._deviceIdentity):
                raise SecurityException(
                    "Device identity does not belong to configured network!")

            environmentUri = self._environmentPrefix.toUri()
            deviceUri = self._deviceIdentity.toUri()

            for rule in validatorTree["rule"]:
                ruleId = rule["id"][0].value
                if ruleId == 'Certificate Trust':
                    #modify the 'Certificate Trust' rule
                    rule["checker/key-locator/name"][0].value = environmentUri
                elif ruleId == 'Command Interests':
                    rule["filter/name"][0].value = deviceUri
                    rule["checker/key-locator/name"][0].value = environmentUri

        #debug for adding trust anchor
        # try:
        #     validatorTree["trust-anchor"][0]["type"][0].value = "base64"
        #     rootCertificate = self._identityStorage.getCertificate(self._identityStorage.getDefaultCertificateNameForIdentity(self._trustRootIdentity))
        #     validatorTree["trust-anchor"][0]["base64-string"][0].value = Blob(b64encode(rootCertificate.wireEncode().toBytes()), False).toRawStr()
        # except KeyError as e:
        #     rootCertificate = self._identityStorage.getCertificate(self._identityStorage.getDefaultCertificateNameForIdentity(self._trustRootIdentity))
        #     treeNode = self.config._root.subtrees["validator"][0].createSubtree("trust-anchor")
        #     # todo: change this!
        #     treeNode.createSubtree("type", "file")
        #     print Blob(b64encode(rootCertificate.wireEncode().toBytes()), False).toRawStr()
        #     treeNode.createSubtree("file-name", "/home/zhehao/.ndn/.iot.root.cert")
        # self._loadTrustAnchorCertificates()

        #remove old validation rules from config
        # replace with new validator rules
        self.config._root.subtrees["validator"] = [validatorTree]

    def inferSigningIdentity(self, fromName):
        """
        Used to map Data or Interest names to identitites.
        :param pyndn.Name fromName: The name of a Data or Interest packet
        """
        # works if you have an IotIdentityStorage
        return self._identityStorage.inferIdentityForName(fromName)

    def setTrustRootIdentity(self, identityName):
        """
        : param pyndn.Name identityName: The new identity to trust as the controller.
        """
        self._trustRootIdentity = Name(identityName)

    def getTrustRootIdentity(self):
        """
        : return pyndn.Name: The trusted controller's network name.
        """
        return Name(self._trustRootIdentity)

    def setEnvironmentPrefix(self, name):
        """
        : param pyndn.Name name: The new root of the network namespace (network prefix)
        """
        self._environmentPrefix = Name(name)

    def getEnvironmentPrefix(self):
        """
        :return: The root of the network namespace
        :rtype: pyndn.Name
        """
        return Name(self._environmentPrefix)

    def getDeviceIdentity(self):
        return self._deviceIdentity

    def setDeviceIdentity(self, identity):
        self._deviceIdentity = Name(identity)

    def hasRootCertificate(self):
        """
        :return: Whether we've downloaded the controller's network certificate
        :rtype: boolean
        """
        try:
            rootCertName = self._identityStorage.getDefaultCertificateNameForIdentity(
                self._trustRootIdentity)
        except SecurityException:
            return False

        try:
            rootCert = self._identityStorage.getCertificate(rootCertName)
            if rootCert is not None:
                return True
        finally:
            return False

    def hasRootSignedCertificate(self):
        """
        :return: Whether we've received a network certificate from our controller
        :rtype: boolean
        """
        try:
            myCertName = self._identityStorage.getDefaultCertificateNameForIdentity(
                self._deviceIdentity)
            myCert = self._identityStorage.getCertificate(myCertName)
            if self._trustRootIdentity.match(
                    myCert.getSignature().getKeyLocator().getKeyName()):
                return True
        except SecurityException:
            pass

        return False

    def removeTrustRules(self):
        """
        Resets the network prefix, device identity and trust root identity to
         empty values
        """
        self.setDeviceIdentity(None)
        self.setTrustRootIdentity(None)
        self.setEnvironmentPrefix(None)
        self.updateTrustRules()
예제 #7
0
 def findDeviceIdMatching(self, matchPrefix):
     for d in self._deviceList:
         devName = Name(d.id)
         if devName.match(matchPrefix):
             return devName.toUri()
     return None