From 4432a373dbe92dfdcaf8b4c4059cec947ce01394 Mon Sep 17 00:00:00 2001 From: Tony Mack Date: Fri, 19 Aug 2011 16:36:44 -0400 Subject: [PATCH] fix exploit that allowed an authorities to issue certs for objects that dont belong to them --- sfa/trust/credential.py | 70 ++++-- sfa/trust/gid.py | 465 +++++++++++++++++++++------------------- sfa/util/xrn.py | 396 +++++++++++++++++++--------------- 3 files changed, 510 insertions(+), 421 deletions(-) diff --git a/sfa/trust/credential.py b/sfa/trust/credential.py index 6fb8c0c9..3480a725 100644 --- a/sfa/trust/credential.py +++ b/sfa/trust/credential.py @@ -47,7 +47,7 @@ from sfa.trust.certificate import Keypair from sfa.trust.credential_legacy import CredentialLegacy from sfa.trust.rights import Right, Rights, determine_rights from sfa.trust.gid import GID -from sfa.util.xrn import urn_to_hrn +from sfa.util.xrn import urn_to_hrn, hrn_authfor_hrn # 2 weeks, in seconds DEFAULT_CREDENTIAL_LIFETIME = 86400 * 14 @@ -738,6 +738,7 @@ class Credential(object): # . That the issuer of the credential is the authority in the target's urn # . In the case of a delegated credential, this must be true of the root # . That all of the gids presented in the credential are valid + # . Including verifying GID chains, and includ the issuer # . The credential is not expired # # -- For Delegates (credentials with parents) @@ -805,7 +806,7 @@ class Credential(object): cert_args = " ".join(['--trusted-pem %s' % x for x in trusted_certs]) # If caller explicitly passed in None that means skip cert chain validation. - # Strange and not typical + # - Strange and not typical if trusted_certs is not None: # Verify the gids of this cred and of its parents for cur_cred in self.get_credential_list(): @@ -844,8 +845,9 @@ class Credential(object): if self.parent: self.verify_parent(self.parent) - # Make sure the issuer is the target's authority - self.verify_issuer() + # Make sure the issuer is the target's authority, and is + # itself a valid GID + self.verify_issuer(trusted_cert_objects) return True ## @@ -863,39 +865,61 @@ class Credential(object): return list ## - # Make sure the credential's target gid was signed by (or is the same) the entity that signed - # the original credential or an authority over that namespace. - def verify_issuer(self): + # Make sure the credential's target gid (a) was signed by or (b) + # is the same as the entity that signed the original credential, + # or (c) is an authority over the target's namespace. + # Also ensure that the credential issuer / signer itself has a valid + # GID signature chain (signed by an authority with namespace rights). + def verify_issuer(self, trusted_gids): root_cred = self.get_credential_list()[-1] root_target_gid = root_cred.get_gid_object() root_cred_signer = root_cred.get_signature().get_issuer_gid() + # Case 1: + # Allow non authority to sign target and cred about target. + # + # Why do we need to allow non authorities to sign? + # If in the target gid validation step we correctly + # checked that the target is only signed by an authority, + # then this is just a special case of case 3. + # This short-circuit is the common case currently - + # and cause GID validation doesn't check 'authority', + # this allows users to generate valid slice credentials. if root_target_gid.is_signed_by_cert(root_cred_signer): # cred signer matches target signer, return success return - root_target_gid_str = root_target_gid.save_to_string() - root_cred_signer_str = root_cred_signer.save_to_string() - if root_target_gid_str == root_cred_signer_str: - # cred signer is target, return success - return + # Case 2: + # Allow someone to sign credential about themeselves. Used? + # If not, remove this. + #root_target_gid_str = root_target_gid.save_to_string() + #root_cred_signer_str = root_cred_signer.save_to_string() + #if root_target_gid_str == root_cred_signer_str: + # # cred signer is target, return success + # return + + # Case 3: # root_cred_signer is not the target_gid - # So this is a different gid that we have not verified - # Did xmlsec1 verify the cert chain on this already? - # Regardless, it hasn't verified that the gid meets the HRN namespace - # requirements -# FIXME: Uncomment once we verify this is right -# root_cred_signer.verify_chain(trusted_cert_objects) - - # See if it the signer is an authority over the domain of the target + # So this is a different gid that we have not verified. + # xmlsec1 verified the cert chain on this already, but + # it hasn't verified that the gid meets the HRN namespace + # requirements. + # Below we'll ensure that it is an authority. + # But we haven't verified that it is _signed by_ an authority + # We also don't know if xmlsec1 requires that cert signers + # are marked as CAs. + root_cred_signer.verify_chain(trusted_gids) + + # See if the signer is an authority over the domain of the target. + # There are multiple types of authority - accept them all here # Maybe should be (hrn, type) = urn_to_hrn(root_cred_signer.get_urn()) root_cred_signer_type = root_cred_signer.get_type() - if (root_cred_signer_type == 'authority'): + if (root_cred_signer_type.find('authority') == 0): #logger.debug('Cred signer is an authority') # signer is an authority, see if target is in authority's domain - hrn = root_cred_signer.get_hrn() - if root_target_gid.get_hrn().startswith(hrn): + signerhrn = root_cred_signer.get_hrn() + if hrn_authfor_hrn(signerhrn, root_target_gid.get_hrn()): return # We've required that the credential be signed by an authority diff --git a/sfa/trust/gid.py b/sfa/trust/gid.py index b881a1f1..20e40977 100644 --- a/sfa/trust/gid.py +++ b/sfa/trust/gid.py @@ -1,224 +1,241 @@ -#---------------------------------------------------------------------- -# Copyright (c) 2008 Board of Trustees, Princeton University -# -# Permission is hereby granted, free of charge, to any person obtaining -# a copy of this software and/or hardware specification (the "Work") to -# deal in the Work without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, -# and/or sell copies of the Work, and to permit persons to whom the Work -# is furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be -# included in all copies or substantial portions of the Work. -# -# THE WORK IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT -# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, -# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE WORK OR THE USE OR OTHER DEALINGS -# IN THE WORK. -#---------------------------------------------------------------------- -## -# Implements SFA GID. GIDs are based on certificates, and the GID class is a -# descendant of the certificate class. -## - -import xmlrpclib -import uuid - -from sfa.util.sfalogging import logger -from sfa.trust.certificate import Certificate -from sfa.util.xrn import hrn_to_urn, urn_to_hrn - -## -# Create a new uuid. Returns the UUID as a string. - -def create_uuid(): - return str(uuid.uuid4().int) - -## -# GID is a tuple: -# (uuid, urn, public_key) -# -# UUID is a unique identifier and is created by the python uuid module -# (or the utility function create_uuid() in gid.py). -# -# HRN is a human readable name. It is a dotted form similar to a backward domain -# name. For example, planetlab.us.arizona.bakers. -# -# URN is a human readable identifier of form: -# "urn:publicid:IDN+toplevelauthority[:sub-auth.]*[\res. type]\ +object name" -# For example, urn:publicid:IDN+planetlab:us:arizona+user+bakers -# -# PUBLIC_KEY is the public key of the principal identified by the UUID/HRN. -# It is a Keypair object as defined in the cert.py module. -# -# It is expected that there is a one-to-one pairing between UUIDs and HRN, -# but it is uncertain how this would be inforced or if it needs to be enforced. -# -# These fields are encoded using xmlrpc into the subjectAltName field of the -# x509 certificate. Note: Call encode() once the fields have been filled in -# to perform this encoding. - - -class GID(Certificate): - uuid = None - hrn = None - urn = None - - ## - # Create a new GID object - # - # @param create If true, create the X509 certificate - # @param subject If subject!=None, create the X509 cert and set the subject name - # @param string If string!=None, load the GID from a string - # @param filename If filename!=None, load the GID from a file - - def __init__(self, create=False, subject=None, string=None, filename=None, uuid=None, hrn=None, urn=None): - - Certificate.__init__(self, create, subject, string, filename) - if subject: - logger.debug("Creating GID for subject: %s" % subject) - if uuid: - self.uuid = int(uuid) - if hrn: - self.hrn = hrn - self.urn = hrn_to_urn(hrn, 'unknown') - if urn: - self.urn = urn - self.hrn, type = urn_to_hrn(urn) - - def set_uuid(self, uuid): - if isinstance(uuid, str): - self.uuid = int(uuid) - else: - self.uuid = uuid - - def get_uuid(self): - if not self.uuid: - self.decode() - return self.uuid - - def set_hrn(self, hrn): - self.hrn = hrn - - def get_hrn(self): - if not self.hrn: - self.decode() - return self.hrn - - def set_urn(self, urn): - self.urn = urn - self.hrn, type = urn_to_hrn(urn) - - def get_urn(self): - if not self.urn: - self.decode() - return self.urn - - def get_type(self): - if not self.urn: - self.decode() - _, t = urn_to_hrn(self.urn) - return t - - ## - # Encode the GID fields and package them into the subject-alt-name field - # of the X509 certificate. This must be called prior to signing the - # certificate. It may only be called once per certificate. - - def encode(self): - if self.urn: - urn = self.urn - else: - urn = hrn_to_urn(self.hrn, None) - - str = "URI:" + urn - - if self.uuid: - str += ", " + "URI:" + uuid.UUID(int=self.uuid).urn - - self.set_data(str, 'subjectAltName') - - - - - ## - # Decode the subject-alt-name field of the X509 certificate into the - # fields of the GID. This is automatically called by the various get_*() - # functions in this class. - - def decode(self): - data = self.get_data('subjectAltName') - dict = {} - if data: - if data.lower().startswith('uri:http://'): - dict = xmlrpclib.loads(data[11:])[0][0] - else: - spl = data.split(', ') - for val in spl: - if val.lower().startswith('uri:urn:uuid:'): - dict['uuid'] = uuid.UUID(val[4:]).int - elif val.lower().startswith('uri:urn:publicid:idn+'): - dict['urn'] = val[4:] - - self.uuid = dict.get("uuid", None) - self.urn = dict.get("urn", None) - self.hrn = dict.get("hrn", None) - if self.urn: - self.hrn = urn_to_hrn(self.urn)[0] - - ## - # Dump the credential to stdout. - # - # @param indent specifies a number of spaces to indent the output - # @param dump_parents If true, also dump the parents of the GID - - def dump(self, *args, **kwargs): - print self.dump_string(*args,**kwargs) - - def dump_string(self, indent=0, dump_parents=False): - result=" "*(indent-2) + "GID\n" - result += " "*indent + "hrn:" + str(self.get_hrn()) +"\n" - result += " "*indent + "urn:" + str(self.get_urn()) +"\n" - result += " "*indent + "uuid:" + str(self.get_uuid()) + "\n" - filename=self.get_filename() - if filename: result += "Filename %s\n"%filename - - if self.parent and dump_parents: - result += " "*indent + "parent:\n" - result += self.parent.dump_string(indent+4, dump_parents) - return result - - ## - # Verify the chain of authenticity of the GID. First perform the checks - # of the certificate class (verifying that each parent signs the child, - # etc). In addition, GIDs also confirm that the parent's HRN is a prefix - # of the child's HRN. - # - # Verifying these prefixes prevents a rogue authority from signing a GID - # for a principal that is not a member of that authority. For example, - # planetlab.us.arizona cannot sign a GID for planetlab.us.princeton.foo. - - def verify_chain(self, trusted_certs = None): - # do the normal certificate verification stuff - trusted_root = Certificate.verify_chain(self, trusted_certs) - - if self.parent: - # make sure the parent's hrn is a prefix of the child's hrn - if not self.get_hrn().startswith(self.parent.get_hrn()): - raise GidParentHrn("This cert HRN %s doesnt start with parent HRN %s" % (self.get_hrn(), self.parent.get_hrn())) - else: - # make sure that the trusted root's hrn is a prefix of the child's - trusted_gid = GID(string=trusted_root.save_to_string()) - trusted_type = trusted_gid.get_type() - trusted_hrn = trusted_gid.get_hrn() - #if trusted_type == 'authority': - # trusted_hrn = trusted_hrn[:trusted_hrn.rindex('.')] - cur_hrn = self.get_hrn() - if not self.get_hrn().startswith(trusted_hrn): - raise GidParentHrn("Trusted roots HRN %s isnt start of this cert %s" % (trusted_hrn, cur_hrn)) - - return +#---------------------------------------------------------------------- +# Copyright (c) 2008 Board of Trustees, Princeton University +# +# Permission is hereby granted, free of charge, to any person obtaining +# a copy of this software and/or hardware specification (the "Work") to +# deal in the Work without restriction, including without limitation the +# rights to use, copy, modify, merge, publish, distribute, sublicense, +# and/or sell copies of the Work, and to permit persons to whom the Work +# is furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be +# included in all copies or substantial portions of the Work. +# +# THE WORK IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE WORK OR THE USE OR OTHER DEALINGS +# IN THE WORK. +#---------------------------------------------------------------------- +## +# Implements SFA GID. GIDs are based on certificates, and the GID class is a +# descendant of the certificate class. +## + +import xmlrpclib +import uuid + +from sfa.trust.certificate import Certificate + +from sfa.util.faults import * +from sfa.util.sfalogging import logger +from sfa.util.xrn import hrn_to_urn, urn_to_hrn, hrn_authfor_hrn + +## +# Create a new uuid. Returns the UUID as a string. + +def create_uuid(): + return str(uuid.uuid4().int) + +## +# GID is a tuple: +# (uuid, urn, public_key) +# +# UUID is a unique identifier and is created by the python uuid module +# (or the utility function create_uuid() in gid.py). +# +# HRN is a human readable name. It is a dotted form similar to a backward domain +# name. For example, planetlab.us.arizona.bakers. +# +# URN is a human readable identifier of form: +# "urn:publicid:IDN+toplevelauthority[:sub-auth.]*[\res. type]\ +object name" +# For example, urn:publicid:IDN+planetlab:us:arizona+user+bakers +# +# PUBLIC_KEY is the public key of the principal identified by the UUID/HRN. +# It is a Keypair object as defined in the cert.py module. +# +# It is expected that there is a one-to-one pairing between UUIDs and HRN, +# but it is uncertain how this would be inforced or if it needs to be enforced. +# +# These fields are encoded using xmlrpc into the subjectAltName field of the +# x509 certificate. Note: Call encode() once the fields have been filled in +# to perform this encoding. + + +class GID(Certificate): + uuid = None + hrn = None + urn = None + + ## + # Create a new GID object + # + # @param create If true, create the X509 certificate + # @param subject If subject!=None, create the X509 cert and set the subject name + # @param string If string!=None, load the GID from a string + # @param filename If filename!=None, load the GID from a file + # @param lifeDays life of GID in days - default is 1825==5 years + + def __init__(self, create=False, subject=None, string=None, filename=None, uuid=None, hrn=None, urn=None, lifeDays=1825): + + #Certificate.__init__(self, lifeDays, create, subject, string, filename) + Certificate.__init__(self, create, subject, string, filename) + if subject: + logger.debug("Creating GID for subject: %s" % subject) + if uuid: + self.uuid = int(uuid) + if hrn: + self.hrn = hrn + self.urn = hrn_to_urn(hrn, 'unknown') + if urn: + self.urn = urn + self.hrn, type = urn_to_hrn(urn) + + def set_uuid(self, uuid): + if isinstance(uuid, str): + self.uuid = int(uuid) + else: + self.uuid = uuid + + def get_uuid(self): + if not self.uuid: + self.decode() + return self.uuid + + def set_hrn(self, hrn): + self.hrn = hrn + + def get_hrn(self): + if not self.hrn: + self.decode() + return self.hrn + + def set_urn(self, urn): + self.urn = urn + self.hrn, type = urn_to_hrn(urn) + + def get_urn(self): + if not self.urn: + self.decode() + return self.urn + + def get_type(self): + if not self.urn: + self.decode() + _, t = urn_to_hrn(self.urn) + return t + + ## + # Encode the GID fields and package them into the subject-alt-name field + # of the X509 certificate. This must be called prior to signing the + # certificate. It may only be called once per certificate. + + def encode(self): + if self.urn: + urn = self.urn + else: + urn = hrn_to_urn(self.hrn, None) + + str = "URI:" + urn + + if self.uuid: + str += ", " + "URI:" + uuid.UUID(int=self.uuid).urn + + self.set_data(str, 'subjectAltName') + + + + + ## + # Decode the subject-alt-name field of the X509 certificate into the + # fields of the GID. This is automatically called by the various get_*() + # functions in this class. + + def decode(self): + data = self.get_data('subjectAltName') + dict = {} + if data: + if data.lower().startswith('uri:http://'): + dict = xmlrpclib.loads(data[11:])[0][0] + else: + spl = data.split(', ') + for val in spl: + if val.lower().startswith('uri:urn:uuid:'): + dict['uuid'] = uuid.UUID(val[4:]).int + elif val.lower().startswith('uri:urn:publicid:idn+'): + dict['urn'] = val[4:] + + self.uuid = dict.get("uuid", None) + self.urn = dict.get("urn", None) + self.hrn = dict.get("hrn", None) + if self.urn: + self.hrn = urn_to_hrn(self.urn)[0] + + ## + # Dump the credential to stdout. + # + # @param indent specifies a number of spaces to indent the output + # @param dump_parents If true, also dump the parents of the GID + + def dump(self, *args, **kwargs): + print self.dump_string(*args,**kwargs) + + def dump_string(self, indent=0, dump_parents=False): + result=" "*(indent-2) + "GID\n" + result += " "*indent + "hrn:" + str(self.get_hrn()) +"\n" + result += " "*indent + "urn:" + str(self.get_urn()) +"\n" + result += " "*indent + "uuid:" + str(self.get_uuid()) + "\n" + filename=self.get_filename() + if filename: result += "Filename %s\n"%filename + + if self.parent and dump_parents: + result += " "*indent + "parent:\n" + result += self.parent.dump_string(indent+4, dump_parents) + return result + + ## + # Verify the chain of authenticity of the GID. First perform the checks + # of the certificate class (verifying that each parent signs the child, + # etc). In addition, GIDs also confirm that the parent's HRN is a prefix + # of the child's HRN, and the parent is of type 'authority'. + # + # Verifying these prefixes prevents a rogue authority from signing a GID + # for a principal that is not a member of that authority. For example, + # planetlab.us.arizona cannot sign a GID for planetlab.us.princeton.foo. + + def verify_chain(self, trusted_certs = None): + # do the normal certificate verification stuff + trusted_root = Certificate.verify_chain(self, trusted_certs) + + if self.parent: + # make sure the parent's hrn is a prefix of the child's hrn + if not hrn_authfor_hrn(self.parent.get_hrn(), self.get_hrn()): + raise GidParentHrn("This cert HRN %s isn't in the namespace for parent HRN %s" % (self.get_hrn(), self.parent.get_hrn())) + + # Parent must also be an authority (of some type) to sign a GID + # There are multiple types of authority - accept them all here + if not self.parent.get_type().find('authority') == 0: + raise GidInvalidParentHrn("This cert %s's parent %s is not an authority (is a %s)" % (self.get_hrn(), self.parent.get_hrn(), self.parent.get_type())) + + # Then recurse up the chain - ensure the parent is a trusted + # root or is in the namespace of a trusted root + self.parent.verify_chain(trusted_certs) + else: + # make sure that the trusted root's hrn is a prefix of the child's + trusted_gid = GID(string=trusted_root.save_to_string()) + trusted_type = trusted_gid.get_type() + trusted_hrn = trusted_gid.get_hrn() + #if trusted_type == 'authority': + # trusted_hrn = trusted_hrn[:trusted_hrn.rindex('.')] + cur_hrn = self.get_hrn() + if not hrn_authfor_hrn(trusted_hrn, cur_hrn): + raise GidParentHrn("Trusted root with HRN %s isn't a namespace authority for this cert %s" % (trusted_hrn, cur_hrn)) + + # There are multiple types of authority - accept them all here + if not trusted_type.find('authority') == 0: + raise GidInvalidParentHrn("This cert %s's trusted root signer %s is not an authority (is a %s)" % (self.get_hrn(), trusted_hrn, trusted_type)) + + return diff --git a/sfa/util/xrn.py b/sfa/util/xrn.py index c166400e..d5410ab2 100644 --- a/sfa/util/xrn.py +++ b/sfa/util/xrn.py @@ -1,174 +1,222 @@ -import re - -from sfa.util.faults import * - -# for convenience and smoother translation - we should get rid of these functions eventually -def get_leaf(hrn): return Xrn(hrn).get_leaf() -def get_authority(hrn): return Xrn(hrn).get_authority_hrn() -def urn_to_hrn(urn): xrn=Xrn(urn); return (xrn.hrn, xrn.type) -def hrn_to_urn(hrn,type): return Xrn(hrn, type=type).urn - -def urn_to_sliver_id(urn, slice_id, node_id, index=0): - urn = urn.replace('+slice+', '+sliver+') - return ":".join([urn, str(slice_id), str(node_id), str(index)]) - -class Xrn: - - ########## basic tools on HRNs - # split a HRN-like string into pieces - # this is like split('.') except for escaped (backslashed) dots - # e.g. hrn_split ('a\.b.c.d') -> [ 'a\.b','c','d'] - @staticmethod - def hrn_split(hrn): - return [ x.replace('--sep--','\\.') for x in hrn.replace('\\.','--sep--').split('.') ] - - # e.g. hrn_leaf ('a\.b.c.d') -> 'd' - @staticmethod - def hrn_leaf(hrn): return Xrn.hrn_split(hrn)[-1] - - # e.g. hrn_auth_list ('a\.b.c.d') -> ['a\.b', 'c'] - @staticmethod - def hrn_auth_list(hrn): return Xrn.hrn_split(hrn)[0:-1] - - # e.g. hrn_auth ('a\.b.c.d') -> 'a\.b.c' - @staticmethod - def hrn_auth(hrn): return '.'.join(Xrn.hrn_auth_list(hrn)) - - # e.g. escape ('a.b') -> 'a\.b' - @staticmethod - def escape(token): return re.sub(r'([^\\])\.', r'\1\.', token) - # e.g. unescape ('a\.b') -> 'a.b' - @staticmethod - def unescape(token): return token.replace('\\.','.') - - URN_PREFIX = "urn:publicid:IDN" - - ########## basic tools on URNs - @staticmethod - def urn_full (urn): - if urn.startswith(Xrn.URN_PREFIX): return urn - else: return Xrn.URN_PREFIX+URN - @staticmethod - def urn_meaningful (urn): - if urn.startswith(Xrn.URN_PREFIX): return urn[len(Xrn.URN_PREFIX):] - else: return urn - @staticmethod - def urn_split (urn): - return Xrn.urn_meaningful(urn).split('+') - - #################### - # the local fields that are kept consistent - # self.urn - # self.hrn - # self.type - # self.path - # provide either urn, or (hrn + type) - def __init__ (self, xrn, type=None): - if not xrn: xrn = "" - # user has specified xrn : guess if urn or hrn - if xrn.startswith(Xrn.URN_PREFIX): - self.hrn=None - self.urn=xrn - self.urn_to_hrn() - else: - self.urn=None - self.hrn=xrn - self.type=type - self.hrn_to_urn() -# happens all the time .. -# if not type: -# debug_logger.debug("type-less Xrn's are not safe") - - def get_urn(self): return self.urn - def get_hrn(self): return self.hrn - def get_type(self): return self.type - def get_hrn_type(self): return (self.hrn, self.type) - - def _normalize(self): - if self.hrn is None: raise SfaAPIError, "Xrn._normalize" - if not hasattr(self,'leaf'): - self.leaf=Xrn.hrn_split(self.hrn)[-1] - # self.authority keeps a list - if not hasattr(self,'authority'): - self.authority=Xrn.hrn_auth_list(self.hrn) - - def get_leaf(self): - self._normalize() - return self.leaf - - def get_authority_hrn(self): - self._normalize() - return '.'.join( self.authority ) - - def get_authority_urn(self): - self._normalize() - return ':'.join( [Xrn.unescape(x) for x in self.authority] ) - - def urn_to_hrn(self): - """ - compute tuple (hrn, type) from urn - """ - -# if not self.urn or not self.urn.startswith(Xrn.URN_PREFIX): - if not self.urn.startswith(Xrn.URN_PREFIX): - raise SfaAPIError, "Xrn.urn_to_hrn" - - parts = Xrn.urn_split(self.urn) - type=parts.pop(2) - # Remove the authority name (e.g. '.sa') - if type == 'authority': - name = parts.pop() - # Drop the sa. This is a bad hack, but its either this - # or completely change how record types are generated/stored - if name != 'sa': - type = type + "+" + name - - # convert parts (list) into hrn (str) by doing the following - # 1. remove blank parts - # 2. escape dots inside parts - # 3. replace ':' with '.' inside parts - # 3. join parts using '.' - hrn = '.'.join([Xrn.escape(part).replace(':','.') for part in parts if part]) - - self.hrn=str(hrn) - self.type=str(type) - - def hrn_to_urn(self): - """ - compute urn from (hrn, type) - """ - -# if not self.hrn or self.hrn.startswith(Xrn.URN_PREFIX): - if self.hrn.startswith(Xrn.URN_PREFIX): - raise SfaAPIError, "Xrn.hrn_to_urn, hrn=%s"%self.hrn - - if self.type and self.type.startswith('authority'): - self.authority = Xrn.hrn_split(self.hrn) - type_parts = self.type.split("+") - self.type = type_parts[0] - name = 'sa' - if len(type_parts) > 1: - name = type_parts[1] - else: - self.authority = Xrn.hrn_auth_list(self.hrn) - name = Xrn.hrn_leaf(self.hrn) - - authority_string = self.get_authority_urn() - - if self.type == None: - urn = "+".join(['',authority_string,Xrn.unescape(name)]) - else: - urn = "+".join(['',authority_string,self.type,Xrn.unescape(name)]) - - self.urn = Xrn.URN_PREFIX + urn - - def dump_string(self): - result="-------------------- XRN\n" - result += "URN=%s\n"%self.urn - result += "HRN=%s\n"%self.hrn - result += "TYPE=%s\n"%self.type - result += "LEAF=%s\n"%self.get_leaf() - result += "AUTH(hrn format)=%s\n"%self.get_authority_hrn() - result += "AUTH(urn format)=%s\n"%self.get_authority_urn() - return result - +#---------------------------------------------------------------------- +# Copyright (c) 2008 Board of Trustees, Princeton University +# +# Permission is hereby granted, free of charge, to any person obtaining +# a copy of this software and/or hardware specification (the "Work") to +# deal in the Work without restriction, including without limitation the +# rights to use, copy, modify, merge, publish, distribute, sublicense, +# and/or sell copies of the Work, and to permit persons to whom the Work +# is furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be +# included in all copies or substantial portions of the Work. +# +# THE WORK IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE WORK OR THE USE OR OTHER DEALINGS +# IN THE WORK. +#---------------------------------------------------------------------- + +import re + +from sfa.util.faults import * + +# for convenience and smoother translation - we should get rid of these functions eventually +def get_leaf(hrn): return Xrn(hrn).get_leaf() +def get_authority(hrn): return Xrn(hrn).get_authority_hrn() +def urn_to_hrn(urn): xrn=Xrn(urn); return (xrn.hrn, xrn.type) +def hrn_to_urn(hrn,type): return Xrn(hrn, type=type).urn +def hrn_authfor_hrn(parenthrn, hrn): return Xrn.hrn_is_auth_for_hrn(parenthrn, hrn) + +class Xrn: + + ########## basic tools on HRNs + # split a HRN-like string into pieces + # this is like split('.') except for escaped (backslashed) dots + # e.g. hrn_split ('a\.b.c.d') -> [ 'a\.b','c','d'] + @staticmethod + def hrn_split(hrn): + return [ x.replace('--sep--','\\.') for x in hrn.replace('\\.','--sep--').split('.') ] + + # e.g. hrn_leaf ('a\.b.c.d') -> 'd' + @staticmethod + def hrn_leaf(hrn): return Xrn.hrn_split(hrn)[-1] + + # e.g. hrn_auth_list ('a\.b.c.d') -> ['a\.b', 'c'] + @staticmethod + def hrn_auth_list(hrn): return Xrn.hrn_split(hrn)[0:-1] + + # e.g. hrn_auth ('a\.b.c.d') -> 'a\.b.c' + @staticmethod + def hrn_auth(hrn): return '.'.join(Xrn.hrn_auth_list(hrn)) + + # e.g. escape ('a.b') -> 'a\.b' + @staticmethod + def escape(token): return re.sub(r'([^\\])\.', r'\1\.', token) + + # e.g. unescape ('a\.b') -> 'a.b' + @staticmethod + def unescape(token): return token.replace('\\.','.') + + # Return the HRN authority chain from top to bottom. + # e.g. hrn_auth_chain('a\.b.c.d') -> ['a\.b', 'a\.b.c'] + @staticmethod + def hrn_auth_chain(hrn): + parts = Xrn.hrn_auth_list(hrn) + chain = [] + for i in range(len(parts)): + chain.append('.'.join(parts[:i+1])) + # Include the HRN itself? + #chain.append(hrn) + return chain + + # Is the given HRN a true authority over the namespace of the other + # child HRN? + # A better alternative than childHRN.startswith(parentHRN) + # e.g. hrn_is_auth_for_hrn('a\.b', 'a\.b.c.d') -> True, + # but hrn_is_auth_for_hrn('a', 'a\.b.c.d') -> False + # Also hrn_is_uauth_for_hrn('a\.b.c.d', 'a\.b.c.d') -> True + @staticmethod + def hrn_is_auth_for_hrn(parenthrn, hrn): + if parenthrn == hrn: + return True + for auth in Xrn.hrn_auth_chain(hrn): + if parenthrn == auth: + return True + return False + + URN_PREFIX = "urn:publicid:IDN" + + ########## basic tools on URNs + @staticmethod + def urn_full (urn): + if urn.startswith(Xrn.URN_PREFIX): return urn + else: return Xrn.URN_PREFIX+URN + @staticmethod + def urn_meaningful (urn): + if urn.startswith(Xrn.URN_PREFIX): return urn[len(Xrn.URN_PREFIX):] + else: return urn + @staticmethod + def urn_split (urn): + return Xrn.urn_meaningful(urn).split('+') + + #################### + # the local fields that are kept consistent + # self.urn + # self.hrn + # self.type + # self.path + # provide either urn, or (hrn + type) + def __init__ (self, xrn, type=None): + if not xrn: xrn = "" + # user has specified xrn : guess if urn or hrn + if xrn.startswith(Xrn.URN_PREFIX): + self.hrn=None + self.urn=xrn + self.urn_to_hrn() + else: + self.urn=None + self.hrn=xrn + self.type=type + self.hrn_to_urn() +# happens all the time .. +# if not type: +# debug_logger.debug("type-less Xrn's are not safe") + + def get_urn(self): return self.urn + def get_hrn(self): return self.hrn + def get_type(self): return self.type + def get_hrn_type(self): return (self.hrn, self.type) + + def _normalize(self): + if self.hrn is None: raise SfaAPIError, "Xrn._normalize" + if not hasattr(self,'leaf'): + self.leaf=Xrn.hrn_split(self.hrn)[-1] + # self.authority keeps a list + if not hasattr(self,'authority'): + self.authority=Xrn.hrn_auth_list(self.hrn) + + def get_leaf(self): + self._normalize() + return self.leaf + + def get_authority_hrn(self): + self._normalize() + return '.'.join( self.authority ) + + def get_authority_urn(self): + self._normalize() + return ':'.join( [Xrn.unescape(x) for x in self.authority] ) + + def urn_to_hrn(self): + """ + compute tuple (hrn, type) from urn + """ + +# if not self.urn or not self.urn.startswith(Xrn.URN_PREFIX): + if not self.urn.startswith(Xrn.URN_PREFIX): + raise SfaAPIError, "Xrn.urn_to_hrn" + + parts = Xrn.urn_split(self.urn) + type=parts.pop(2) + # Remove the authority name (e.g. '.sa') + if type == 'authority': + name = parts.pop() + # Drop the sa. This is a bad hack, but its either this + # or completely change how record types are generated/stored + if name != 'sa': + type = type + "+" + name + + # convert parts (list) into hrn (str) by doing the following + # 1. remove blank parts + # 2. escape dots inside parts + # 3. replace ':' with '.' inside parts + # 3. join parts using '.' + hrn = '.'.join([Xrn.escape(part).replace(':','.') for part in parts if part]) + + self.hrn=str(hrn) + self.type=str(type) + + def hrn_to_urn(self): + """ + compute urn from (hrn, type) + """ + +# if not self.hrn or self.hrn.startswith(Xrn.URN_PREFIX): + if self.hrn.startswith(Xrn.URN_PREFIX): + raise SfaAPIError, "Xrn.hrn_to_urn, hrn=%s"%self.hrn + + if self.type and self.type.startswith('authority'): + self.authority = Xrn.hrn_split(self.hrn) + type_parts = self.type.split("+") + self.type = type_parts[0] + name = 'sa' + if len(type_parts) > 1: + name = type_parts[1] + else: + self.authority = Xrn.hrn_auth_list(self.hrn) + name = Xrn.hrn_leaf(self.hrn) + + authority_string = self.get_authority_urn() + + if self.type == None: + urn = "+".join(['',authority_string,Xrn.unescape(name)]) + else: + urn = "+".join(['',authority_string,self.type,Xrn.unescape(name)]) + + self.urn = Xrn.URN_PREFIX + urn + + def dump_string(self): + result="-------------------- XRN\n" + result += "URN=%s\n"%self.urn + result += "HRN=%s\n"%self.hrn + result += "TYPE=%s\n"%self.type + result += "LEAF=%s\n"%self.get_leaf() + result += "AUTH(hrn format)=%s\n"%self.get_authority_hrn() + result += "AUTH(urn format)=%s\n"%self.get_authority_urn() + return result + -- 2.43.0