本文整理汇总了Python中sfa.trust.credential.Credential类的典型用法代码示例。如果您正苦于以下问题:Python Credential类的具体用法?Python Credential怎么用?Python Credential使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Credential类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: call
def call(self, cred, record_dict, origin_hrn=None):
user_cred = Credential(string=cred)
#log the call
if not origin_hrn:
origin_hrn = user_cred.get_gid_caller().get_hrn()
self.api.logger.info("interface: %s\tcaller-hrn: %s\ttarget-hrn: %s\tmethod-name: %s"%(self.api.interface, origin_hrn, None, self.name))
# validate the cred
self.api.auth.check(cred, "register")
# make sure this is a peer record
if 'peer_authority' not in record_dict or \
not record_dict['peer_authority']:
raise SfaInvalidArgument, "peer_authority must be specified"
record = SfaRecord(dict = record_dict)
type, hrn, peer_authority = record['type'], record['hrn'], record['peer_authority']
record['authority'] = get_authority(record['hrn'])
# verify permissions
self.api.auth.verify_cred_is_me(cred)
# check if record already exists
table = SfaTable()
existing_records = table.find({'type': type, 'hrn': hrn, 'peer_authority': peer_authority})
if existing_records:
for existing_record in existing_records:
if existing_record['pointer'] != record['pointer']:
record['record_id'] = existing_record['record_id']
table.update(record)
else:
record_id = table.insert(record)
return 1
示例2: validate_credential
def validate_credential(self, filename):
valid = True
cred = Credential(filename=filename)
# check if credential is expires
if cred.get_expiration() < datetime.utcnow():
valid = False
return valid
示例3: get_cred
def get_cred(self, file, type, hrn):
# attempt to load a cached credential
cred = self.get_cached_credential(file)
if not cred:
if type in ['user']:
cert_string = self.cert.save_to_string(save_parents=True)
user_name = self.user.replace(self.authority + ".", '')
if user_name.count(".") > 0:
user_name = user_name.replace(".", '_')
self.user = self.authority + "." + user_name
cred_str = self.registry.GetSelfCredential(cert_string, hrn, "user")
else:
# bootstrap slice credential from user credential
user_cred = self.get_user_cred().save_to_string(save_parents=True)
cred_str = self.registry.GetCredential(user_cred, hrn, type)
if not cred_str:
self.logger.critical("Failed to get %s credential" % type)
sys.exit(-1)
cred = Credential(string=cred_str)
cred.save_to_file(file, save_parents=True)
self.logger.info("Writing %s credential to %s" %(type, file))
return cred
示例4: getCredential
def getCredential(self):
"""
Get our credential from a remote registry
"""
path = self.config.SFA_DATA_DIR
config_dir = self.config.config_path
cred_filename = path + os.sep + 'node.cred'
try:
credential = Credential(filename = cred_filename)
return credential.save_to_string(save_parents=True)
except IOError:
node_pkey_file = config_dir + os.sep + "node.key"
node_gid_file = config_dir + os.sep + "node.gid"
cert_filename = path + os.sep + 'server.cert'
if not os.path.exists(node_pkey_file) or \
not os.path.exists(node_gid_file):
self.get_node_key()
# get node's hrn
gid = GID(filename=node_gid_file)
hrn = gid.get_hrn()
# get credential from registry
cert_str = Certificate(filename=cert_filename).save_to_string(save_parents=True)
registry = self.get_registry()
cred = registry.GetSelfCredential(cert_str, hrn, 'node')
Credential(string=cred).save_to_file(credfile, save_parents=True)
return cred
示例5: delegate_credential_string
def delegate_credential_string (self, original_credential, to_hrn, to_type='authority'):
"""
sign a delegation credential to someone else
original_credential : typically one's user- or slice- credential to be delegated to s/b else
to_hrn : the hrn of the person that will be allowed to do stuff on our behalf
to_type : goes with to_hrn, usually 'user' or 'authority'
returns a string with the delegated credential
this internally uses self.my_gid()
it also retrieves the gid for to_hrn/to_type
and uses Credential.delegate()"""
# the gid and hrn of the object we are delegating
if isinstance (original_credential, str):
original_credential = Credential (string=original_credential)
original_gid = original_credential.get_gid_object()
original_hrn = original_gid.get_hrn()
if not original_credential.get_privileges().get_all_delegate():
self.logger.error("delegate_credential_string: original credential %s does not have delegate bit set"%original_hrn)
return
# the delegating user's gid
my_gid = self.my_gid()
# retrieve the GID for the entity that we're delegating to
to_gidfile = self.gid (to_hrn,to_type)
# to_gid = GID ( to_gidfile )
# to_hrn = delegee_gid.get_hrn()
# print 'to_hrn',to_hrn
delegated_credential = original_credential.delegate(to_gidfile, self.private_key(), my_gid)
return delegated_credential.save_to_string(save_parents=True)
示例6: __get_registry_objects
def __get_registry_objects(slice_xrn, creds, users):
"""
"""
hrn, type = urn_to_hrn(slice_xrn)
hrn_auth = get_authority(hrn)
# Build up objects that an SFA registry would return if SFA
# could contact the slice's registry directly
reg_objects = None
if users:
# dont allow special characters in the site login base
#only_alphanumeric = re.compile('[^a-zA-Z0-9]+')
#login_base = only_alphanumeric.sub('', hrn_auth[:20]).lower()
slicename = hrn_to_pl_slicename(hrn)
login_base = slicename.split('_')[0]
reg_objects = {}
site = {}
site['site_id'] = 0
site['name'] = 'geni.%s' % login_base
site['enabled'] = True
site['max_slices'] = 100
# Note:
# Is it okay if this login base is the same as one already at this myplc site?
# Do we need uniqueness? Should use hrn_auth instead of just the leaf perhaps?
site['login_base'] = login_base
site['abbreviated_name'] = login_base
site['max_slivers'] = 1000
reg_objects['site'] = site
slice = {}
# get_expiration always returns a normalized datetime - no need to utcparse
extime = Credential(string=creds[0]).get_expiration()
# If the expiration time is > 60 days from now, set the expiration time to 60 days from now
if extime > datetime.datetime.utcnow() + datetime.timedelta(days=60):
extime = datetime.datetime.utcnow() + datetime.timedelta(days=60)
slice['expires'] = int(time.mktime(extime.timetuple()))
slice['hrn'] = hrn
slice['name'] = hrn_to_pl_slicename(hrn)
slice['url'] = hrn
slice['description'] = hrn
slice['pointer'] = 0
reg_objects['slice_record'] = slice
reg_objects['users'] = {}
for user in users:
user['key_ids'] = []
hrn, _ = urn_to_hrn(user['urn'])
user['email'] = hrn_to_pl_slicename(hrn) + "@geni.net"
user['first_name'] = hrn
user['last_name'] = hrn
reg_objects['users'][user['email']] = user
return reg_objects
示例7: verify_cred_is_me
def verify_cred_is_me(self, credential):
is_me = False
cred = Credential(string=credential)
caller_gid = cred.get_gid_caller()
caller_hrn = caller_gid.get_hrn()
if caller_hrn != self.config.SFA_INTERFACE_HRN:
raise SfaPermissionDenied(self.config.SFA_INTEFACE_HRN)
return
示例8: log_invalid_cred
def log_invalid_cred(cred):
if not isinstance (cred, StringTypes):
logger.info("cannot validate credential %s - expecting a string"%cred)
error="checkCredentials: expected a string, received %s"%(type(cred))
else:
cred_obj=Credential(string=cred)
logger.info("failed to validate credential - dump=%s"%\
cred_obj.dump_string(dump_parents=True))
error = sys.exc_info()[:2]
return error
示例9: get_cached_credential
def get_cached_credential(self, file):
"""
Return a cached credential only if it hasn't expired.
"""
if (os.path.isfile(file)):
credential = Credential(filename=file)
# make sure it isnt expired
if not credential.get_expiration or \
datetime.datetime.today() < credential.get_expiration():
return credential
return None
示例10: check
def check(self, credential, operation, hrn = None):
"""
Check the credential against the peer cert (callerGID) included
in the credential matches the caller that is connected to the
HTTPS connection, check if the credential was signed by a
trusted cert and check if the credential is allowed to perform
the specified operation.
"""
cred = Credential(cred=credential)
self.client_cred = cred
logger.debug("Auth.check: handling hrn=%s and credential=%s"%\
(hrn,cred.pretty_cred()))
if cred.type not in ['geni_sfa']:
raise CredentialNotVerifiable(cred.type, "%s not supported" % cred.type)
self.client_gid = self.client_cred.get_gid_caller()
self.object_gid = self.client_cred.get_gid_object()
# make sure the client_gid is not blank
if not self.client_gid:
raise MissingCallerGID(self.client_cred.pretty_subject())
# validate the client cert if it exists
if self.peer_cert:
self.verifyPeerCert(self.peer_cert, self.client_gid)
# make sure the client is allowed to perform the operation
if operation:
if not self.client_cred.can_perform(operation):
raise InsufficientRights(operation)
if self.trusted_cert_list:
self.client_cred.verify(self.trusted_cert_file_list,
self.config.SFA_CREDENTIAL_SCHEMA)
else:
raise MissingTrustedRoots(self.config.get_trustedroots_dir())
# Make sure the credential's target matches the specified hrn.
# This check does not apply to trusted peers
trusted_peers = [gid.get_hrn() for gid in self.trusted_cert_list]
if hrn and self.client_gid.get_hrn() not in trusted_peers:
target_hrn = self.object_gid.get_hrn()
if not hrn == target_hrn:
raise PermissionError("Target hrn: %s doesn't match specified hrn: %s " % \
(target_hrn, hrn) )
return True
示例11: filter_creds_by_caller
def filter_creds_by_caller(self, creds, caller_hrn_list):
"""
Returns a list of creds who's gid caller matches the
specified caller hrn
"""
if not isinstance(creds, list):
creds = [creds]
creds = []
if not isinstance(caller_hrn_list, list):
caller_hrn_list = [caller_hrn_list]
for cred in creds:
try:
tmp_cred = Credential(string=cred)
if tmp_cred.get_gid_caller().get_hrn() in [caller_hrn_list]:
creds.append(cred)
except: pass
return creds
示例12: server_proxy
def server_proxy(self, interface, cred, timeout=30):
"""
Returns a connection to the specified interface. Use the specified
credential to determine the caller and look for the caller's key/cert
in the registry hierarchy cache.
"""
from sfa.trust.hierarchy import Hierarchy
if not isinstance(cred, Credential):
cred_obj = Credential(string=cred)
else:
cred_obj = cred
caller_gid = cred_obj.get_gid_caller()
hierarchy = Hierarchy()
auth_info = hierarchy.get_auth_info(caller_gid.get_hrn())
key_file = auth_info.get_privkey_filename()
cert_file = auth_info.get_gid_filename()
server = interface.server_proxy(key_file, cert_file, timeout)
return server
示例13: checkCredentials
def checkCredentials(self, creds, operation, hrn = None):
valid = []
if not isinstance(creds, list):
creds = [creds]
logger.debug("Auth.checkCredentials with %d creds"%len(creds))
for cred in creds:
try:
self.check(cred, operation, hrn)
valid.append(cred)
except:
cred_obj=Credential(string=cred)
logger.debug("failed to validate credential - dump=%s"%cred_obj.dump_string(dump_parents=True))
error = sys.exc_info()[:2]
continue
if not len(valid):
raise InsufficientRights('Access denied: %s -- %s' % (error[0],error[1]))
return valid
示例14: handle_input_kind
def handle_input_kind (filename, options, kind):
# dump methods current do 'print' so let's go this road for now
if kind=="certificate":
cert=Certificate (filename=filename)
print '--------------------',filename,'IS A',kind
cert.dump(show_extensions=options.show_extensions)
elif kind=="credential":
cred = Credential(filename = filename)
print '--------------------',filename,'IS A',kind
cred.dump(dump_parents = options.dump_parents, show_xml=options.show_xml)
if options.extract_gids:
print '--------------------',filename,'embedded GIDS'
extract_gids(cred, extract_parents = options.dump_parents)
elif kind=="gid":
gid = GID(filename = filename)
print '--------------------',filename,'IS A',kind
gid.dump(dump_parents = options.dump_parents)
else:
print "%s: unknown filekind '%s'"% (filename,kind)
示例15: delegate_cred
def delegate_cred(self, object_cred, hrn):
# the gid and hrn of the object we are delegating
if isinstance(object_cred, str):
object_cred = Credential(string=object_cred)
object_gid = object_cred.get_gid_object()
object_hrn = object_gid.get_hrn()
if not object_cred.get_privileges().get_all_delegate():
self.logger.error("Object credential %s does not have delegate bit set"%object_hrn)
return
# the delegating user's gid
caller_gid = self._get_gid(self.user)
caller_gidfile = os.path.join(self.options.sfi_dir, self.user + ".gid")
# the gid of the user who will be delegated to
delegee_gid = self._get_gid(hrn)
delegee_hrn = delegee_gid.get_hrn()
delegee_gidfile = os.path.join(self.options.sfi_dir, delegee_hrn + ".gid")
delegee_gid.save_to_file(filename=delegee_gidfile)
dcred = object_cred.delegate(delegee_gidfile, self.get_key_file(), caller_gidfile)
return dcred.save_to_string(save_parents=True)