示例#1
0
class TrustAnchorRefreshManager(object):
    """
    Manages the trust-anchor certificates, including refresh.
    """
    def __init__(self):
        super(TrustAnchorRefreshManager, self).__init__()

        self._certificateCache = CertificateCache()
        # maps the directory name to certificate names so they can be
        # deleted when necessary
        self._refreshDirectories = {}

    @staticmethod
    def loadIdentityCertificateFromFile(filename):
        with open(filename, 'r') as certFile:
            encodedData = certFile.read()
            decodedData = b64decode(encodedData)
            cert = IdentityCertificate()
            cert.wireDecode(Blob(decodedData, False))
            return cert

    def getCertificate(self, certificateName):
        # assumes timestamp is already removed
        return self._certificateCache.getCertificate(certificateName)

    # refershPeriod in milliseconds.
    def addDirectory(self, directoryName, refreshPeriod):
        allFiles = [
            f for f in os.listdir(directoryName)
            if os.path.isfile(os.path.join(directoryName, f))
        ]
        certificateNames = []
        for f in allFiles:
            try:
                fullPath = os.path.join(directoryName, f)
                cert = self.loadIdentityCertificateFromFile(fullPath)
            except SecurityException:
                pass  # allow files that are not certificates
            else:
                # cut off timestamp so it matches KeyLocator Name format
                certUri = cert.getName()[:-1].toUri()
                self._certificateCache.insertCertificate(cert)
                certificateNames.append(certUri)

        self._refreshDirectories[directoryName] = {
            'certificates': certificateNames,
            'nextRefresh': Common.getNowMilliseconds() + refreshPeriod,
            'refreshPeriod': refreshPeriod
        }

    def refreshAnchors(self):
        refreshTime = Common.getNowMilliseconds()
        for directory, info in self._refreshDirectories.items():
            nextRefreshTime = info['nextRefresh']
            if nextRefreshTime <= refreshTime:
                certificateList = info['certificates'][:]
                # delete the certificates associated with this directory if possible
                # then re-import
                # IdentityStorage subclasses may not support deletion
                # should we be deleting
                for c in certificateList:
                    try:
                        self._certificateCache.deleteCertificate(Name(c))
                    except KeyError:
                        # was already removed? not supported?
                        pass
                self.addDirectory(directory, info['refreshPeriod'])
示例#2
0
class TrustAnchorRefreshManager(object):
    """
    Manages the trust-anchor certificates, including refresh.
    """
    def __init__(self, isSecurityV1):
        self._isSecurityV1 = isSecurityV1

        self._certificateCache = CertificateCache()
        self._certificateCacheV2 = CertificateCacheV2()
        # maps the directory name to certificate names so they can be
        # deleted when necessary
        self._refreshDirectories = {}

    @staticmethod
    def loadIdentityCertificateFromFile(filename):
        """
        :param str filename:
        :rtype: IdentityCertificate
        """
        with open(filename, 'r') as certFile:
            encodedData = certFile.read()
            decodedData = b64decode(encodedData)
            cert = IdentityCertificate()
            cert.wireDecode(Blob(decodedData, False))
            return cert

    @staticmethod
    def loadCertificateV2FromFile(filename):
        """
        :param str filename:
        :rtype: CertificateV2
        """
        with open(filename, 'r') as certFile:
            encodedData = certFile.read()
            decodedData = b64decode(encodedData)
            cert = CertificateV2()
            cert.wireDecode(Blob(decodedData, False))
            return cert

    def getCertificate(self, certificateName):
        """
        :param Name certificateName:
        :rtype: IdentityCertificate
        """
        if not self._isSecurityV1:
            raise SecurityException(
                "getCertificate: For security v2, use getCertificateV2()")

        # assumes timestamp is already removed
        return self._certificateCache.getCertificate(certificateName)

    def getCertificateV2(self, certificateName):
        """
        :param Name certificateName:
        :rtype: CertificateV2
        """
        if self._isSecurityV1:
            raise SecurityException(
                "getCertificateV2: For security v1, use getCertificate()")

        # assumes timestamp is already removed
        return self._certificateCacheV2.find(certificateName)

    # refershPeriod in milliseconds.
    def addDirectory(self, directoryName, refreshPeriod):
        allFiles = [
            f for f in os.listdir(directoryName)
            if os.path.isfile(os.path.join(directoryName, f))
        ]
        certificateNames = []
        for f in allFiles:
            if self._isSecurityV1:
                try:
                    fullPath = os.path.join(directoryName, f)
                    cert = self.loadIdentityCertificateFromFile(fullPath)
                except Exception:
                    pass  # allow files that are not certificates
                else:
                    # Cut off the timestamp so it matches KeyLocator Name format.
                    certUri = cert.getName()[:-1].toUri()
                    self._certificateCache.insertCertificate(cert)
                    certificateNames.append(certUri)
            else:
                try:
                    fullPath = os.path.join(directoryName, f)
                    cert = self.loadCertificateV2FromFile(fullPath)
                except Exception:
                    pass  # allow files that are not certificates
                else:
                    # Get the key name since this is in the KeyLocator.
                    certUri = CertificateV2.extractKeyNameFromCertName(
                        cert.getName()).toUri()
                    self._certificateCacheV2.insert(cert)
                    certificateNames.append(certUri)

        self._refreshDirectories[directoryName] = {
            'certificates': certificateNames,
            'nextRefresh': Common.getNowMilliseconds() + refreshPeriod,
            'refreshPeriod': refreshPeriod
        }

    def refreshAnchors(self):
        refreshTime = Common.getNowMilliseconds()
        for directory, info in self._refreshDirectories.items():
            nextRefreshTime = info['nextRefresh']
            if nextRefreshTime <= refreshTime:
                certificateList = info['certificates'][:]
                # delete the certificates associated with this directory if possible
                # then re-import
                # IdentityStorage subclasses may not support deletion
                # should we be deleting
                for c in certificateList:
                    try:
                        if self._isSecurityV1:
                            self._certificateCache.deleteCertificate(Name(c))
                        else:
                            # The name in the CertificateCacheV2 contains the
                            # but the name in the certificateList does not, so
                            # find the certificate based on the prefix first.
                            foundCertificate = self._certificateCacheV2.find(
                                Name(c))
                            if foundCertificate != None:
                                self._certificateCacheV2.deleteCertificate(
                                    foundCertificate.getName())
                    except KeyError:
                        # was already removed? not supported?
                        pass
                self.addDirectory(directory, info['refreshPeriod'])
class TrustAnchorRefreshManager(object):
    """
    Manages the trust-anchor certificates, including refresh.
    """
    def __init__(self):
        super(TrustAnchorRefreshManager, self).__init__()

        self._certificateCache = CertificateCache()
        # maps the directory name to certificate names so they can be
        # deleted when necessary
        self._refreshDirectories = {}

    @staticmethod
    def loadIdentityCertificateFromFile(filename):
        with open(filename, 'r') as certFile:
            encodedData = certFile.read()
            decodedData = b64decode(encodedData)
            cert = IdentityCertificate()
            cert.wireDecode(Blob(decodedData, False))
            return cert

    def getCertificate(self, certificateName):
        # assumes timestamp is already removed
        return self._certificateCache.getCertificate(certificateName)

    # refershPeriod in milliseconds.
    def addDirectory(self, directoryName, refreshPeriod):
        allFiles = [f for f in os.listdir(directoryName)
                if os.path.isfile(os.path.join(directoryName, f))]
        certificateNames = []
        for f in allFiles:
            try:
                fullPath = os.path.join(directoryName, f)
                cert = self.loadIdentityCertificateFromFile(fullPath)
            except SecurityException:
                pass # allow files that are not certificates
            else:
                # cut off timestamp so it matches KeyLocator Name format
                certUri = cert.getName()[:-1].toUri()
                self._certificateCache.insertCertificate(cert)
                certificateNames.append(certUri)

        self._refreshDirectories[directoryName] = {
          'certificates': certificateNames,
          'nextRefresh': Common.getNowMilliseconds() + refreshPeriod,
          'refreshPeriod':refreshPeriod }

    def refreshAnchors(self):
        refreshTime =  Common.getNowMilliseconds()
        for directory, info in self._refreshDirectories.items():
            nextRefreshTime = info['nextRefresh']
            if nextRefreshTime <= refreshTime:
                certificateList = info['certificates'][:]
                # delete the certificates associated with this directory if possible
                # then re-import
                # IdentityStorage subclasses may not support deletion
                # should we be deleting 
                for c in certificateList:
                    try:
                        self._certificateCache.deleteCertificate(Name(c))
                    except KeyError:
                        # was already removed? not supported?
                        pass
                self.addDirectory(directory, info['refreshPeriod'])
class TrustAnchorRefreshManager(object):
    """
    Manages the trust-anchor certificates, including refresh.
    """
    def __init__(self, isSecurityV1):
        self._isSecurityV1 = isSecurityV1

        self._certificateCache = CertificateCache()
        self._certificateCacheV2 = CertificateCacheV2()
        # maps the directory name to certificate names so they can be
        # deleted when necessary
        self._refreshDirectories = {}

    @staticmethod
    def loadIdentityCertificateFromFile(filename):
        """
        :param str filename:
        :rtype: IdentityCertificate
        """
        with open(filename, 'r') as certFile:
            encodedData = certFile.read()
            decodedData = b64decode(encodedData)
            cert = IdentityCertificate()
            cert.wireDecode(Blob(decodedData, False))
            return cert

    @staticmethod
    def loadCertificateV2FromFile(filename):
        """
        :param str filename:
        :rtype: CertificateV2
        """
        with open(filename, 'r') as certFile:
            encodedData = certFile.read()
            decodedData = b64decode(encodedData)
            cert = CertificateV2()
            cert.wireDecode(Blob(decodedData, False))
            return cert

    def getCertificate(self, certificateName):
        """
        :param Name certificateName:
        :rtype: IdentityCertificate
        """
        if not self._isSecurityV1:
            raise SecurityException(
              "getCertificate: For security v2, use getCertificateV2()")

        # assumes timestamp is already removed
        return self._certificateCache.getCertificate(certificateName)

    def getCertificateV2(self, certificateName):
        """
        :param Name certificateName:
        :rtype: CertificateV2
        """
        if self._isSecurityV1:
            raise SecurityException(
              "getCertificateV2: For security v1, use getCertificate()")

        # assumes timestamp is already removed
        return self._certificateCacheV2.find(certificateName)

    # refershPeriod in milliseconds.
    def addDirectory(self, directoryName, refreshPeriod):
        allFiles = [f for f in os.listdir(directoryName)
                if os.path.isfile(os.path.join(directoryName, f))]
        certificateNames = []
        for f in allFiles:
            if self._isSecurityV1:
                try:
                    fullPath = os.path.join(directoryName, f)
                    cert = self.loadIdentityCertificateFromFile(fullPath)
                except Exception:
                    pass # allow files that are not certificates
                else:
                    # Cut off the timestamp so it matches KeyLocator Name format.
                    certUri = cert.getName()[:-1].toUri()
                    self._certificateCache.insertCertificate(cert)
                    certificateNames.append(certUri)
            else:
                try:
                    fullPath = os.path.join(directoryName, f)
                    cert = self.loadCertificateV2FromFile(fullPath)
                except Exception:
                    pass # allow files that are not certificates
                else:
                    # Get the key name since this is in the KeyLocator.
                    certUri = CertificateV2.extractKeyNameFromCertName(
                      cert.getName()).toUri()
                    self._certificateCacheV2.insert(cert)
                    certificateNames.append(certUri)

        self._refreshDirectories[directoryName] = {
          'certificates': certificateNames,
          'nextRefresh': Common.getNowMilliseconds() + refreshPeriod,
          'refreshPeriod':refreshPeriod }

    def refreshAnchors(self):
        refreshTime =  Common.getNowMilliseconds()
        for directory, info in self._refreshDirectories.items():
            nextRefreshTime = info['nextRefresh']
            if nextRefreshTime <= refreshTime:
                certificateList = info['certificates'][:]
                # delete the certificates associated with this directory if possible
                # then re-import
                # IdentityStorage subclasses may not support deletion
                # should we be deleting
                for c in certificateList:
                    try:
                        if self._isSecurityV1:
                            self._certificateCache.deleteCertificate(Name(c))
                        else:
                            # The name in the CertificateCacheV2 contains the
                            # but the name in the certificateList does not, so
                            # find the certificate based on the prefix first.
                            foundCertificate = self._certificateCacheV2.find(Name(c))
                            if foundCertificate != None:
                                self._certificateCacheV2.deleteCertificate(
                                  foundCertificate.getName())
                    except KeyError:
                        # was already removed? not supported?
                        pass
                self.addDirectory(directory, info['refreshPeriod'])