2 # for get_key_from_incoming_ip
7 from sfa.util.faults import RecordNotFound, AccountNotEnabled, PermissionError, MissingAuthority, \
8 UnknownSfaType, ExistingRecord, NonExistingRecord
9 from sfa.util.sfatime import utcparse, datetime_to_epoch
10 from sfa.util.prefixTree import prefixTree
11 from sfa.util.xrn import Xrn, get_authority, hrn_to_urn, urn_to_hrn
12 from sfa.util.version import version_core
13 from sfa.util.sfalogging import logger
15 from sfa.util.printable import printable
17 from sfa.trust.gid import GID
18 from sfa.trust.credential import Credential
19 from sfa.trust.certificate import Certificate, Keypair, convert_public_key
20 from sfa.trust.gid import create_uuid
22 from sfa.storage.model import make_record, RegRecord, RegAuthority, RegUser, RegSlice, RegKey, \
23 augment_with_sfa_builtins
24 ### the types that we need to exclude from sqlobjects before being able to dump
25 # them on the xmlrpc wire
26 from sqlalchemy.orm.collections import InstrumentedList
28 ### historical note -- april 2014
29 # the myslice chaps rightfully complained about the following discrepency
31 # * read operations (resolve) expose stuff like e.g. 'reg-researchers', but that
32 # * write operations (register, update) need e.g. 'researcher' to be set - it ignores 'reg-researchers'
34 # the 'normalize' helper functions below aim at ironing this out
35 # however in order to break as few as possible we essentially make sure that *both* fields are set
36 # upon entering the write methods (so again register and update) because some driver code
37 # might depend on the presence of, say, 'researcher'
39 # registry calls this 'reg-researchers'
40 # some drivers call this 'researcher'
41 # this is even more confusing as people might use 'researchers'
42 def normalize_input_researcher (record):
43 # this aims at detecting a mispelled input
44 if 'researchers' in record and 'researcher' not in record:
45 record['researcher']=record['researchers']
46 del record['researchers']
47 # this looks right, use this for both keys
48 if 'reg-researchers' in record:
49 # and issue a warning if they were both set as we're overwriting some user data here
50 if 'researcher' in record:
51 logger.warning ("normalize_input_researcher: incoming record has both values, using reg-researchers")
52 record['researcher']=record['reg-researchers']
53 # we only have one key set, duplicate for the other one
54 elif 'researcher' in record:
55 logger.warning ("normalize_input_researcher: you should use 'reg-researchers' instead ot 'researcher'")
56 record['reg-researchers']=record['researcher']
57 # if at this point we still have 'researchers' it's going to be ignored and that might be confusing
58 if 'researchers' in record:
59 logger.warning ("normalize_input_researcher: incoming record has confusing 'researchers' key - ignored - use 'reg-researchers' instead")
61 def normalize_input_record (record):
62 normalize_input_researcher (record)
65 class RegistryManager:
67 def __init__ (self, config):
68 logger.info("Creating RegistryManager[%s]"%id(self))
70 # The GENI GetVersion call
71 def GetVersion(self, api, options):
72 peers = dict ( [ (hrn,interface.get_url()) for (hrn,interface) in api.registries.iteritems()
74 xrn=Xrn(api.hrn,type='authority')
75 return version_core({'interface':'registry',
82 def GetCredential(self, api, xrn, input_type, caller_xrn=None):
85 hrn, _ = urn_to_hrn(xrn)
88 hrn, type = urn_to_hrn(xrn)
90 # Slivers don't have credentials but users should be able to
91 # specify a sliver xrn and receive the slice's credential
92 # However if input_type is specified
93 if type == 'sliver' or ( not input_type and '-' in Xrn(hrn).leaf):
94 slice_xrn = api.driver.sliver_to_slice_xrn(hrn)
97 # Is this a root or sub authority
98 auth_hrn = api.auth.get_authority(hrn)
99 if not auth_hrn or hrn == api.config.SFA_INTERFACE_HRN:
101 auth_info = api.auth.get_auth_info(auth_hrn)
104 dbsession = api.dbsession()
105 record=dbsession.query(RegRecord).filter_by(type=type,hrn=hrn).first()
107 raise RecordNotFound("hrn=%s, type=%s"%(hrn,type))
109 # get the callers gid
110 # if caller_xrn is not specified assume the caller is the record
114 caller_gid = record.get_gid_object()
116 caller_hrn, caller_type = urn_to_hrn(caller_xrn)
118 caller_record = dbsession.query(RegRecord).filter_by(hrn=caller_hrn,type=caller_type).first()
120 caller_record = dbsession.query(RegRecord).filter_by(hrn=caller_hrn).first()
121 if not caller_record:
122 raise RecordNotFound("Unable to associated caller (hrn=%s, type=%s) with credential for (hrn: %s, type: %s)"%(caller_hrn, caller_type, hrn, type))
123 caller_gid = GID(string=caller_record.gid)
125 object_hrn = record.get_gid_object().get_hrn()
126 # call the builtin authorization/credential generation engine
127 rights = api.auth.determine_user_rights(caller_hrn, record)
128 # make sure caller has rights to this object
129 if rights.is_empty():
130 raise PermissionError("%s has no rights to %s (%s)" % \
131 (caller_hrn, object_hrn, xrn))
132 object_gid = GID(string=record.gid)
133 new_cred = Credential(subject = object_gid.get_subject())
134 new_cred.set_gid_caller(caller_gid)
135 new_cred.set_gid_object(object_gid)
136 new_cred.set_issuer_keys(auth_info.get_privkey_filename(), auth_info.get_gid_filename())
137 #new_cred.set_pubkey(object_gid.get_pubkey())
138 new_cred.set_privileges(rights)
139 new_cred.get_privileges().delegate_all_privileges(True)
140 if hasattr(record,'expires'):
141 date = utcparse(record.expires)
142 expires = datetime_to_epoch(date)
143 new_cred.set_expiration(int(expires))
144 auth_kind = "authority,ma,sa"
145 # Parent not necessary, verify with certs
146 #new_cred.set_parent(api.auth.hierarchy.get_auth_cred(auth_hrn, kind=auth_kind))
150 return new_cred.save_to_string(save_parents=True)
153 # the default for full, which means 'dig into the testbed as well', should be false
154 def Resolve(self, api, xrns, type=None, details=False):
156 dbsession = api.dbsession()
157 if not isinstance(xrns, types.ListType):
158 # try to infer type if not set and we get a single input
160 type = Xrn(xrns).get_type()
162 hrns = [urn_to_hrn(xrn)[0] for xrn in xrns]
164 # load all known registry names into a prefix tree and attempt to find
165 # the longest matching prefix
166 # create a dict where key is a registry hrn and its value is a list
167 # of hrns at that registry (determined by the known prefix tree).
169 registries = api.registries
171 registry_hrns = registries.keys()
172 tree.load(registry_hrns)
174 registry_hrn = tree.best_match(urn_to_hrn(xrn)[0])
175 if registry_hrn not in xrn_dict:
176 xrn_dict[registry_hrn] = []
177 xrn_dict[registry_hrn].append(xrn)
180 for registry_hrn in xrn_dict:
181 # skip the hrn without a registry hrn
182 # XX should we let the user know the authority is unknown?
186 # if the best match (longest matching hrn) is not the local registry,
187 # forward the request
188 xrns = xrn_dict[registry_hrn]
189 if registry_hrn != api.hrn:
190 credential = api.getCredential()
191 interface = api.registries[registry_hrn]
192 server_proxy = api.server_proxy(interface, credential)
193 # should propagate the details flag but that's not supported in the xmlrpc interface yet
194 #peer_records = server_proxy.Resolve(xrns, credential,type, details=details)
195 peer_records = server_proxy.Resolve(xrns, credential)
196 # pass foreign records as-is
197 # previous code used to read
198 # records.extend([SfaRecord(dict=record).as_dict() for record in peer_records])
199 # not sure why the records coming through xmlrpc had to be processed at all
200 records.extend(peer_records)
202 # try resolving the remaining unfound records at the local registry
203 local_hrns = list ( set(hrns).difference([record['hrn'] for record in records]) )
205 local_records = dbsession.query(RegRecord).filter(RegRecord.hrn.in_(local_hrns))
207 local_records = local_records.filter_by(type=type)
208 local_records=local_records.all()
210 for local_record in local_records:
211 augment_with_sfa_builtins (local_record)
213 logger.info("Resolve, (details=%s,type=%s) local_records=%s "%(details,type,local_records))
214 local_dicts = [ record.__dict__ for record in local_records ]
217 # in details mode we get as much info as we can, which involves contacting the
218 # testbed for getting implementation details about the record
219 api.driver.augment_records_with_testbed_info(local_dicts)
220 # also we fill the 'url' field for known authorities
221 # used to be in the driver code, sounds like a poorman thing though
222 def solve_neighbour_url (record):
223 if not record.type.startswith('authority'): return
225 for neighbour_dict in [ api.aggregates, api.registries ]:
226 if hrn in neighbour_dict:
227 record.url=neighbour_dict[hrn].get_url()
229 for record in local_records: solve_neighbour_url (record)
231 # convert local record objects to dicts for xmlrpc
232 # xxx somehow here calling dict(record) issues a weird error
233 # however record.todict() seems to work fine
234 # records.extend( [ dict(record) for record in local_records ] )
235 records.extend( [ record.todict(exclude_types=[InstrumentedList]) for record in local_records ] )
238 raise RecordNotFound(str(hrns))
242 def List (self, api, xrn, origin_hrn=None, options={}):
243 dbsession=api.dbsession()
244 # load all know registry names into a prefix tree and attempt to find
245 # the longest matching prefix
246 hrn, type = urn_to_hrn(xrn)
247 registries = api.registries
248 registry_hrns = registries.keys()
250 tree.load(registry_hrns)
251 registry_hrn = tree.best_match(hrn)
253 #if there was no match then this record belongs to an unknow registry
255 raise MissingAuthority(xrn)
256 # if the best match (longest matching hrn) is not the local registry,
257 # forward the request
259 if registry_hrn != api.hrn:
260 credential = api.getCredential()
261 interface = api.registries[registry_hrn]
262 server_proxy = api.server_proxy(interface, credential)
263 record_list = server_proxy.List(xrn, credential, options)
264 # same as above, no need to process what comes from through xmlrpc
265 # pass foreign records as-is
266 record_dicts = record_list
268 # if we still have not found the record yet, try the local registry
269 # logger.debug("before trying local records, %d foreign records"% len(record_dicts))
272 if ('recursive' in options and options['recursive']):
274 elif hrn.endswith('*'):
278 if not api.auth.hierarchy.auth_exists(hrn):
279 raise MissingAuthority(hrn)
281 records = dbsession.query(RegRecord).filter(RegRecord.hrn.startswith(hrn)).all()
282 # logger.debug("recursive mode, found %d local records"%(len(records)))
284 records = dbsession.query(RegRecord).filter_by(authority=hrn).all()
285 # logger.debug("non recursive mode, found %d local records"%(len(records)))
286 # so that sfi list can show more than plain names...
287 for record in records: augment_with_sfa_builtins (record)
288 record_dicts=[ record.todict(exclude_types=[InstrumentedList]) for record in records ]
293 def CreateGid(self, api, xrn, cert):
295 authority = Xrn(xrn=xrn).get_authority_hrn()
296 auth_info = api.auth.get_auth_info(authority)
298 pkey = Keypair(create=True)
300 certificate = Certificate(string=cert)
301 pkey = certificate.get_pubkey()
302 gid = api.auth.hierarchy.create_gid(xrn, create_uuid(), pkey)
303 return gid.save_to_string(save_parents=True)
306 # utility for handling relationships among the SFA objects
308 # subject_record describes the subject of the relationships
309 # ref_record contains the target values for the various relationships we need to manage
310 # (to begin with, this is just the slice x person (researcher) and authority x person (pi) relationships)
311 def update_driver_relations (self, api, subject_obj, ref_obj):
312 type=subject_obj.type
313 #for (k,v) in subject_obj.__dict__.items(): print k,'=',v
314 if type=='slice' and hasattr(ref_obj,'researcher'):
315 self.update_driver_relation(api, subject_obj, ref_obj.researcher, 'user', 'researcher')
316 elif type=='authority' and hasattr(ref_obj,'pi'):
317 self.update_driver_relation(api, subject_obj,ref_obj.pi, 'user', 'pi')
319 # field_key is the name of one field in the record, typically 'researcher' for a 'slice' record
320 # hrns is the list of hrns that should be linked to the subject from now on
321 # target_type would be e.g. 'user' in the 'slice' x 'researcher' example
322 def update_driver_relation (self, api, record_obj, hrns, target_type, relation_name):
323 dbsession=api.dbsession()
324 # locate the linked objects in our db
325 subject_type=record_obj.type
326 subject_id=record_obj.pointer
327 # get the 'pointer' field of all matching records
328 link_id_tuples = dbsession.query(RegRecord.pointer).filter_by(type=target_type).filter(RegRecord.hrn.in_(hrns)).all()
329 # sqlalchemy returns named tuples for columns
330 link_ids = [ tuple.pointer for tuple in link_id_tuples ]
331 api.driver.update_relation (subject_type, target_type, relation_name, subject_id, link_ids)
333 def Register(self, api, record_dict):
335 logger.debug("Register: entering with record_dict=%s"%printable(record_dict))
336 normalize_input_record (record_dict)
337 logger.debug("Register: normalized record_dict=%s"%printable(record_dict))
339 dbsession=api.dbsession()
340 hrn, type = record_dict['hrn'], record_dict['type']
341 urn = hrn_to_urn(hrn,type)
343 if type not in ['authority', 'slice', 'node', 'user']:
344 raise UnknownSfaType(type)
346 # check if record_dict already exists
347 existing_records = dbsession.query(RegRecord).filter_by(type=type,hrn=hrn).all()
349 raise ExistingRecord(hrn)
351 assert ('type' in record_dict)
352 # returns the right type of RegRecord according to type in record
353 record = make_record(dict=record_dict)
354 record.just_created()
355 record.authority = get_authority(record.hrn)
356 auth_info = api.auth.get_auth_info(record.authority)
358 # make sure record has a gid
361 pkey = Keypair(create=True)
362 if getattr(record,'keys',None):
364 # use only first key in record
365 if isinstance(record.keys, types.ListType):
366 pub_key = record.keys[0]
367 pkey = convert_public_key(pub_key)
369 gid_object = api.auth.hierarchy.create_gid(urn, uuid, pkey)
370 gid = gid_object.save_to_string(save_parents=True)
373 if isinstance (record, RegAuthority):
375 if not api.auth.hierarchy.auth_exists(hrn):
376 api.auth.hierarchy.create_auth(hrn_to_urn(hrn,'authority'))
378 # get the GID from the newly created authority
379 auth_info = api.auth.get_auth_info(hrn)
380 gid = auth_info.get_gid_object()
381 record.gid=gid.save_to_string(save_parents=True)
383 # locate objects for relationships
384 pi_hrns = getattr(record,'pi',None)
385 if pi_hrns is not None: record.update_pis (pi_hrns, dbsession)
387 elif isinstance (record, RegSlice):
388 researcher_hrns = getattr(record,'reg-researchers',None)
389 if researcher_hrns is not None: record.update_researchers (researcher_hrns, dbsession)
391 elif isinstance (record, RegUser):
392 # create RegKey objects for incoming keys
393 if hasattr(record,'keys'):
394 logger.debug ("creating %d keys for user %s"%(len(record.keys),record.hrn))
395 record.reg_keys = [ RegKey (key) for key in record.keys ]
397 # update testbed-specific data if needed
398 pointer = api.driver.register (record.__dict__, hrn, pub_key)
400 record.pointer=pointer
401 dbsession.add(record)
404 # update membership for researchers, pis, owners, operators
405 self.update_driver_relations (api, record, record)
407 return record.get_gid_object().save_to_string(save_parents=True)
409 def Update(self, api, record_dict):
411 logger.debug("Update: entering with record_dict=%s"%printable(record_dict))
412 normalize_input_record (record_dict)
413 logger.debug("Update: normalized record_dict=%s"%printable(record_dict))
415 dbsession=api.dbsession()
416 assert ('type' in record_dict)
417 new_record=make_record(dict=record_dict)
418 (type,hrn) = (new_record.type, new_record.hrn)
420 # make sure the record exists
421 record = dbsession.query(RegRecord).filter_by(type=type,hrn=hrn).first()
423 raise RecordNotFound("hrn=%s, type=%s"%(hrn,type))
424 record.just_updated()
426 # Use the pointer from the existing record, not the one that the user
427 # gave us. This prevents the user from inserting a forged pointer
428 pointer = record.pointer
430 # is there a change in keys ?
433 if getattr(new_record,'keys',None):
434 new_key=new_record.keys
435 if isinstance (new_key,types.ListType):
438 # take new_key into account
440 # update the openssl key and gid
441 pkey = convert_public_key(new_key)
443 urn = hrn_to_urn(hrn,type)
444 gid_object = api.auth.hierarchy.create_gid(urn, uuid, pkey)
445 gid = gid_object.save_to_string(save_parents=True)
447 # xxx should do side effects from new_record to record
448 # not too sure how to do that
449 # not too big a deal with planetlab as the driver is authoritative, but...
451 # update native relations
452 if isinstance (record, RegSlice):
453 researcher_hrns = getattr(new_record,'reg-researchers',None)
454 if researcher_hrns is not None: record.update_researchers (researcher_hrns, dbsession)
456 elif isinstance (record, RegAuthority):
457 pi_hrns = getattr(new_record,'pi',None)
458 if pi_hrns is not None: record.update_pis (pi_hrns, dbsession)
460 # update the PLC information that was specified with the record
461 # xxx oddly enough, without this useless statement,
462 # record.__dict__ as received by the driver seems to be off
463 # anyway the driver should receive an object
464 # (and then extract __dict__ itself if needed)
465 print "DO NOT REMOVE ME before driver.update, record=%s"%record
468 (pointer, new_key_pointer) = api.driver.update (record.__dict__, new_record.__dict__, hrn, new_key)
471 if new_key and new_key_pointer:
472 record.reg_keys=[ RegKey (new_key, new_key_pointer)]
476 # update membership for researchers, pis, owners, operators
477 self.update_driver_relations (api, record, new_record)
481 # expecting an Xrn instance
482 def Remove(self, api, xrn, origin_hrn=None):
483 dbsession=api.dbsession()
486 request=dbsession.query(RegRecord).filter_by(hrn=hrn)
487 if type and type not in ['all', '*']:
488 request=request.filter_by(type=type)
490 record = request.first()
492 msg="Could not find hrn %s"%hrn
493 if type: msg += " type=%s"%type
494 raise RecordNotFound(msg)
497 if type not in ['slice', 'user', 'node', 'authority'] :
498 raise UnknownSfaType(type)
500 credential = api.getCredential()
501 registries = api.registries
503 # Try to remove the object from the PLCDB of federated agg.
504 # This is attempted before removing the object from the local agg's PLCDB and sfa table
505 if hrn.startswith(api.hrn) and type in ['user', 'slice', 'authority']:
506 for registry in registries:
507 if registry not in [api.hrn]:
509 result=registries[registry].remove_peer_object(credential, record, origin_hrn)
513 # call testbed callback first
514 # IIUC this is done on the local testbed TOO because of the refreshpeer link
515 if not api.driver.remove(record.__dict__):
516 logger.warning("driver.remove failed")
519 dbsession.delete(record)
524 # This is a PLC-specific thing, won't work with other platforms
525 def get_key_from_incoming_ip (self, api):
526 dbsession=api.dbsession()
527 # verify that the callers's ip address exist in the db and is an interface
528 # for a node in the db
529 (ip, port) = api.remote_addr
530 interfaces = api.driver.shell.GetInterfaces({'ip': ip}, ['node_id'])
532 raise NonExistingRecord("no such ip %(ip)s" % locals())
533 nodes = api.driver.shell.GetNodes([interfaces[0]['node_id']], ['node_id', 'hostname'])
535 raise NonExistingRecord("no such node using ip %(ip)s" % locals())
538 # look up the sfa record
539 record=dbsession.query(RegRecord).filter_by(type='node',pointer=node['node_id']).first()
541 raise RecordNotFound("node with pointer %s"%node['node_id'])
543 # generate a new keypair and gid
545 pkey = Keypair(create=True)
546 urn = hrn_to_urn(record.hrn, record.type)
547 gid_object = api.auth.hierarchy.create_gid(urn, uuid, pkey)
548 gid = gid_object.save_to_string(save_parents=True)
554 # attempt the scp the key
555 # and gid onto the node
556 # this will only work for planetlab based components
557 (kfd, key_filename) = tempfile.mkstemp()
558 (gfd, gid_filename) = tempfile.mkstemp()
559 pkey.save_to_file(key_filename)
560 gid_object.save_to_file(gid_filename, save_parents=True)
561 host = node['hostname']
562 key_dest="/etc/sfa/node.key"
563 gid_dest="/etc/sfa/node.gid"
565 #identity = "/etc/planetlab/root_ssh_key.rsa"
566 identity = "/etc/sfa/root_ssh_key"
567 scp_options=" -i %(identity)s " % locals()
568 scp_options+="-o StrictHostKeyChecking=no " % locals()
569 scp_key_command="%(scp)s %(scp_options)s %(key_filename)s root@%(host)s:%(key_dest)s" %\
571 scp_gid_command="%(scp)s %(scp_options)s %(gid_filename)s root@%(host)s:%(gid_dest)s" %\
574 all_commands = [scp_key_command, scp_gid_command]
576 for command in all_commands:
577 (status, output) = commands.getstatusoutput(command)
579 raise Exception, output
581 for filename in [key_filename, gid_filename]: