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 discrepancy
31 # * read operations (resolve) expose stuff like e.g.
32 # 'reg-researchers', or 'reg-pis', but that
33 # * write operations (register, update) need e.g.
34 # 'researcher' or 'pi' to be set - reg-* are just ignored
36 # the '_normalize_input' helper functions below aim at ironing this out
37 # however in order to break as few code as possible we essentially make sure that *both* fields are set
38 # upon entering the write methods (so again register and update) for legacy, as some driver code
39 # might depend on the presence of, say, 'researcher'
41 # normalize an input record to a write method - register or update
42 # e.g. registry calls this 'reg-researchers'
43 # while some drivers call this 'researcher'
44 # we need to make sure that both keys appear and are the same
45 def _normalize_input (record, reg_key, driver_key):
46 # this looks right, use this for both keys
48 # and issue a warning if they were both set and different
49 # as we're overwriting some user data here
50 if driver_key in record:
51 logger.warning ("normalize_input: incoming record has both values, using %s"%reg_key)
52 record[driver_key]=record[reg_key]
53 # we only have one key set, duplicate for the other one
54 elif driver_key in record:
55 logger.warning ("normalize_input: you should use '%s' instead of '%s'"%(reg_key,driver_key))
56 record[reg_key]=record[driver_key]
58 def normalize_input_record (record):
59 _normalize_input (record, 'reg-researchers','researcher')
60 _normalize_input (record, 'reg-pis','pi')
61 _normalize_input (record, 'reg-keys','keys')
62 # xxx the keys thing could use a little bit more attention:
63 # some parts of the code are using 'keys' while they should use 'reg-keys'
64 # but I run out of time for now
65 if 'reg-keys' in record: record['keys']=record['reg-keys']
68 class RegistryManager:
70 def __init__ (self, config):
71 logger.info("Creating RegistryManager[%s]"%id(self))
73 # The GENI GetVersion call
74 def GetVersion(self, api, options):
75 peers = dict ( [ (hrn,interface.get_url()) for (hrn,interface) in api.registries.iteritems()
77 xrn=Xrn(api.hrn,type='authority')
78 return version_core({'interface':'registry',
84 def GetCredential(self, api, xrn, input_type, caller_xrn=None):
87 hrn, _ = urn_to_hrn(xrn)
90 hrn, type = urn_to_hrn(xrn)
92 # Slivers don't have credentials but users should be able to
93 # specify a sliver xrn and receive the slice's credential
94 # However if input_type is specified
95 if type == 'sliver' or ( not input_type and '-' in Xrn(hrn).leaf):
96 slice_xrn = api.driver.sliver_to_slice_xrn(hrn)
99 # Is this a root or sub authority
100 auth_hrn = api.auth.get_authority(hrn)
101 if not auth_hrn or hrn == api.config.SFA_INTERFACE_HRN:
103 auth_info = api.auth.get_auth_info(auth_hrn)
106 dbsession = api.dbsession()
107 record=dbsession.query(RegRecord).filter_by(type=type,hrn=hrn).first()
109 raise RecordNotFound("hrn=%s, type=%s"%(hrn,type))
111 # get the callers gid
112 # if caller_xrn is not specified assume the caller is the record
116 caller_gid = record.get_gid_object()
118 caller_hrn, caller_type = urn_to_hrn(caller_xrn)
120 caller_record = dbsession.query(RegRecord).filter_by(hrn=caller_hrn,type=caller_type).first()
122 caller_record = dbsession.query(RegRecord).filter_by(hrn=caller_hrn).first()
123 if not caller_record:
124 raise RecordNotFound("Unable to associated caller (hrn=%s, type=%s) with credential for (hrn: %s, type: %s)"%(caller_hrn, caller_type, hrn, type))
125 caller_gid = GID(string=caller_record.gid)
127 object_hrn = record.get_gid_object().get_hrn()
128 # call the builtin authorization/credential generation engine
129 rights = api.auth.determine_user_rights(caller_hrn, record)
130 # make sure caller has rights to this object
131 if rights.is_empty():
132 raise PermissionError("%s has no rights to %s (%s)" % \
133 (caller_hrn, object_hrn, xrn))
134 object_gid = GID(string=record.gid)
135 new_cred = Credential(subject = object_gid.get_subject())
136 new_cred.set_gid_caller(caller_gid)
137 new_cred.set_gid_object(object_gid)
138 new_cred.set_issuer_keys(auth_info.get_privkey_filename(), auth_info.get_gid_filename())
139 #new_cred.set_pubkey(object_gid.get_pubkey())
140 new_cred.set_privileges(rights)
141 new_cred.get_privileges().delegate_all_privileges(True)
142 if hasattr(record,'expires'):
143 date = utcparse(record.expires)
144 expires = datetime_to_epoch(date)
145 new_cred.set_expiration(int(expires))
146 auth_kind = "authority,ma,sa"
147 # Parent not necessary, verify with certs
148 #new_cred.set_parent(api.auth.hierarchy.get_auth_cred(auth_hrn, kind=auth_kind))
152 return new_cred.save_to_string(save_parents=True)
155 # the default for full, which means 'dig into the testbed as well', should be false
156 def Resolve(self, api, xrns, type=None, details=False):
158 dbsession = api.dbsession()
159 if not isinstance(xrns, types.ListType):
160 # try to infer type if not set and we get a single input
162 type = Xrn(xrns).get_type()
164 hrns = [urn_to_hrn(xrn)[0] for xrn in xrns]
166 # load all known registry names into a prefix tree and attempt to find
167 # the longest matching prefix
168 # create a dict where key is a registry hrn and its value is a list
169 # of hrns at that registry (determined by the known prefix tree).
171 registries = api.registries
173 registry_hrns = registries.keys()
174 tree.load(registry_hrns)
176 registry_hrn = tree.best_match(urn_to_hrn(xrn)[0])
177 if registry_hrn not in xrn_dict:
178 xrn_dict[registry_hrn] = []
179 xrn_dict[registry_hrn].append(xrn)
182 for registry_hrn in xrn_dict:
183 # skip the hrn without a registry hrn
184 # XX should we let the user know the authority is unknown?
188 # if the best match (longest matching hrn) is not the local registry,
189 # forward the request
190 xrns = xrn_dict[registry_hrn]
191 if registry_hrn != api.hrn:
192 credential = api.getCredential()
193 interface = api.registries[registry_hrn]
194 server_proxy = api.server_proxy(interface, credential)
195 # should propagate the details flag but that's not supported in the xmlrpc interface yet
196 #peer_records = server_proxy.Resolve(xrns, credential,type, details=details)
197 peer_records = server_proxy.Resolve(xrns, credential)
198 # pass foreign records as-is
199 # previous code used to read
200 # records.extend([SfaRecord(dict=record).as_dict() for record in peer_records])
201 # not sure why the records coming through xmlrpc had to be processed at all
202 records.extend(peer_records)
204 # try resolving the remaining unfound records at the local registry
205 local_hrns = list ( set(hrns).difference([record['hrn'] for record in records]) )
207 local_records = dbsession.query(RegRecord).filter(RegRecord.hrn.in_(local_hrns))
209 local_records = local_records.filter_by(type=type)
210 local_records=local_records.all()
212 for local_record in local_records:
213 augment_with_sfa_builtins (local_record)
215 logger.info("Resolve, (details=%s,type=%s) local_records=%s "%(details,type,local_records))
216 local_dicts = [ record.__dict__ for record in local_records ]
219 # in details mode we get as much info as we can, which involves contacting the
220 # testbed for getting implementation details about the record
221 api.driver.augment_records_with_testbed_info(local_dicts)
222 # also we fill the 'url' field for known authorities
223 # used to be in the driver code, sounds like a poorman thing though
224 def solve_neighbour_url (record):
225 if not record.type.startswith('authority'): return
227 for neighbour_dict in [ api.aggregates, api.registries ]:
228 if hrn in neighbour_dict:
229 record.url=neighbour_dict[hrn].get_url()
231 for record in local_records: solve_neighbour_url (record)
233 # convert local record objects to dicts for xmlrpc
234 # xxx somehow here calling dict(record) issues a weird error
235 # however record.todict() seems to work fine
236 # records.extend( [ dict(record) for record in local_records ] )
237 records.extend( [ record.todict(exclude_types=[InstrumentedList]) for record in local_records ] )
240 raise RecordNotFound(str(hrns))
244 def List (self, api, xrn, origin_hrn=None, options=None):
245 if options is None: options={}
246 dbsession=api.dbsession()
247 # load all know registry names into a prefix tree and attempt to find
248 # the longest matching prefix
249 hrn, type = urn_to_hrn(xrn)
250 registries = api.registries
251 registry_hrns = registries.keys()
253 tree.load(registry_hrns)
254 registry_hrn = tree.best_match(hrn)
256 #if there was no match then this record belongs to an unknow registry
258 raise MissingAuthority(xrn)
259 # if the best match (longest matching hrn) is not the local registry,
260 # forward the request
262 if registry_hrn != api.hrn:
263 credential = api.getCredential()
264 interface = api.registries[registry_hrn]
265 server_proxy = api.server_proxy(interface, credential)
266 record_list = server_proxy.List(xrn, credential, options)
267 # same as above, no need to process what comes from through xmlrpc
268 # pass foreign records as-is
269 record_dicts = record_list
271 # if we still have not found the record yet, try the local registry
272 # logger.debug("before trying local records, %d foreign records"% len(record_dicts))
275 if ('recursive' in options and options['recursive']):
277 elif hrn.endswith('*'):
281 if not api.auth.hierarchy.auth_exists(hrn):
282 raise MissingAuthority(hrn)
284 records = dbsession.query(RegRecord).filter(RegRecord.hrn.startswith(hrn)).all()
285 # logger.debug("recursive mode, found %d local records"%(len(records)))
287 records = dbsession.query(RegRecord).filter_by(authority=hrn).all()
288 # logger.debug("non recursive mode, found %d local records"%(len(records)))
289 # so that sfi list can show more than plain names...
290 for record in records: augment_with_sfa_builtins (record)
291 record_dicts=[ record.todict(exclude_types=[InstrumentedList]) for record in records ]
295 def CreateGid(self, api, xrn, cert):
297 authority = Xrn(xrn=xrn).get_authority_hrn()
298 auth_info = api.auth.get_auth_info(authority)
300 pkey = Keypair(create=True)
302 certificate = Certificate(string=cert)
303 pkey = certificate.get_pubkey()
305 # Add the email of the user to SubjectAltName in the GID
307 hrn = Xrn(xrn).get_hrn()
308 dbsession=api.dbsession()
309 record=dbsession.query(RegUser).filter_by(hrn=hrn).first()
311 email=getattr(record,'email',None)
312 gid = api.auth.hierarchy.create_gid(xrn, create_uuid(), pkey, email = email)
313 return gid.save_to_string(save_parents=True)
316 # utility for handling relationships among the SFA objects
318 # subject_record describes the subject of the relationships
319 # ref_record contains the target values for the various relationships we need to manage
320 # (to begin with, this is just the slice x person (researcher) and authority x person (pi) relationships)
321 def update_driver_relations (self, api, subject_obj, ref_obj):
322 type=subject_obj.type
323 #for (k,v) in subject_obj.__dict__.items(): print k,'=',v
324 if type=='slice' and hasattr(ref_obj,'researcher'):
325 self.update_driver_relation(api, subject_obj, ref_obj.researcher, 'user', 'researcher')
326 elif type=='authority' and hasattr(ref_obj,'pi'):
327 self.update_driver_relation(api, subject_obj,ref_obj.pi, 'user', 'pi')
329 # field_key is the name of one field in the record, typically 'researcher' for a 'slice' record
330 # hrns is the list of hrns that should be linked to the subject from now on
331 # target_type would be e.g. 'user' in the 'slice' x 'researcher' example
332 def update_driver_relation (self, api, record_obj, hrns, target_type, relation_name):
333 dbsession=api.dbsession()
334 # locate the linked objects in our db
335 subject_type=record_obj.type
336 subject_id=record_obj.pointer
337 # get the 'pointer' field of all matching records
338 link_id_tuples = dbsession.query(RegRecord.pointer).filter_by(type=target_type).filter(RegRecord.hrn.in_(hrns)).all()
339 # sqlalchemy returns named tuples for columns
340 link_ids = [ tuple.pointer for tuple in link_id_tuples ]
341 api.driver.update_relation (subject_type, target_type, relation_name, subject_id, link_ids)
343 def Register(self, api, record_dict):
345 logger.debug("Register: entering with record_dict=%s"%printable(record_dict))
346 normalize_input_record (record_dict)
347 logger.debug("Register: normalized record_dict=%s"%printable(record_dict))
349 dbsession=api.dbsession()
350 hrn, type = record_dict['hrn'], record_dict['type']
351 urn = hrn_to_urn(hrn,type)
353 if type not in ['authority', 'slice', 'node', 'user']:
354 raise UnknownSfaType(type)
356 # check if record_dict already exists
357 existing_records = dbsession.query(RegRecord).filter_by(type=type,hrn=hrn).all()
359 raise ExistingRecord(hrn)
361 assert ('type' in record_dict)
362 # returns the right type of RegRecord according to type in record
363 record = make_record(dict=record_dict)
364 record.just_created()
365 record.authority = get_authority(record.hrn)
366 auth_info = api.auth.get_auth_info(record.authority)
368 # make sure record has a gid
371 pkey = Keypair(create=True)
372 pub_key=getattr(record,'reg-keys',None)
373 if pub_key is not None:
374 # use only first key in record
375 if pub_key and isinstance(pub_key, types.ListType): pub_key = pub_key[0]
376 pkey = convert_public_key(pub_key)
378 email=getattr(record,'email',None)
379 gid_object = api.auth.hierarchy.create_gid(urn, uuid, pkey, email = email)
380 gid = gid_object.save_to_string(save_parents=True)
383 if isinstance (record, RegAuthority):
385 if not api.auth.hierarchy.auth_exists(hrn):
386 api.auth.hierarchy.create_auth(hrn_to_urn(hrn,'authority'))
388 # get the GID from the newly created authority
389 auth_info = api.auth.get_auth_info(hrn)
390 gid = auth_info.get_gid_object()
391 record.gid=gid.save_to_string(save_parents=True)
393 # locate objects for relationships
394 pi_hrns = getattr(record,'reg-pis',None)
395 if pi_hrns is not None: record.update_pis (pi_hrns, dbsession)
397 elif isinstance (record, RegSlice):
398 researcher_hrns = getattr(record,'reg-researchers',None)
399 if researcher_hrns is not None: record.update_researchers (researcher_hrns, dbsession)
401 elif isinstance (record, RegUser):
402 # create RegKey objects for incoming keys
403 if hasattr(record,'reg-keys'):
404 keys=getattr(record,'reg-keys')
405 # some people send the key as a string instead of a list of strings
406 if isinstance(keys,types.StringTypes): keys=[keys]
407 logger.debug ("creating %d keys for user %s"%(len(keys),record.hrn))
408 record.reg_keys = [ RegKey (key) for key in keys ]
410 # update testbed-specific data if needed
411 pointer = api.driver.register (record.__dict__, hrn, pub_key)
413 record.pointer=pointer
414 dbsession.add(record)
417 # update membership for researchers, pis, owners, operators
418 self.update_driver_relations (api, record, record)
420 return record.get_gid_object().save_to_string(save_parents=True)
422 def Update(self, api, record_dict):
424 logger.debug("Update: entering with record_dict=%s"%printable(record_dict))
425 normalize_input_record (record_dict)
426 logger.debug("Update: normalized record_dict=%s"%printable(record_dict))
428 dbsession=api.dbsession()
429 assert ('type' in record_dict)
430 new_record=make_record(dict=record_dict)
431 (type,hrn) = (new_record.type, new_record.hrn)
433 # make sure the record exists
434 record = dbsession.query(RegRecord).filter_by(type=type,hrn=hrn).first()
436 raise RecordNotFound("hrn=%s, type=%s"%(hrn,type))
437 record.just_updated()
439 # Use the pointer from the existing record, not the one that the user
440 # gave us. This prevents the user from inserting a forged pointer
441 pointer = record.pointer
443 # is there a change in keys ?
446 if getattr(new_record,'keys',None):
447 new_key=new_record.keys
448 if isinstance (new_key,types.ListType):
451 # take new_key into account
453 # update the openssl key and gid
454 pkey = convert_public_key(new_key)
456 urn = hrn_to_urn(hrn,type)
458 email=getattr(new_record,'email',None)
460 email=getattr(record,'email',None)
461 gid_object = api.auth.hierarchy.create_gid(urn, uuid, pkey, email = email)
462 gid = gid_object.save_to_string(save_parents=True)
464 # xxx should do side effects from new_record to record
465 # not too sure how to do that
466 # not too big a deal with planetlab as the driver is authoritative, but...
468 # update native relations
469 if isinstance (record, RegSlice):
470 researcher_hrns = getattr(new_record,'reg-researchers',None)
471 if researcher_hrns is not None: record.update_researchers (researcher_hrns, dbsession)
473 elif isinstance (record, RegAuthority):
474 pi_hrns = getattr(new_record,'reg-pis',None)
475 if pi_hrns is not None: record.update_pis (pi_hrns, dbsession)
477 # update the PLC information that was specified with the record
478 # xxx oddly enough, without this useless statement,
479 # record.__dict__ as received by the driver seems to be off
480 # anyway the driver should receive an object
481 # (and then extract __dict__ itself if needed)
482 print "DO NOT REMOVE ME before driver.update, record=%s"%record
485 (pointer, new_key_pointer) = api.driver.update (record.__dict__, new_record.__dict__, hrn, new_key)
488 if new_key and new_key_pointer:
489 record.reg_keys=[ RegKey (new_key, new_key_pointer)]
493 # update membership for researchers, pis, owners, operators
494 self.update_driver_relations (api, record, new_record)
498 # expecting an Xrn instance
499 def Remove(self, api, xrn, origin_hrn=None):
500 dbsession=api.dbsession()
503 request=dbsession.query(RegRecord).filter_by(hrn=hrn)
504 if type and type not in ['all', '*']:
505 request=request.filter_by(type=type)
507 record = request.first()
509 msg="Could not find hrn %s"%hrn
510 if type: msg += " type=%s"%type
511 raise RecordNotFound(msg)
514 if type not in ['slice', 'user', 'node', 'authority'] :
515 raise UnknownSfaType(type)
517 credential = api.getCredential()
518 registries = api.registries
520 # Try to remove the object from the PLCDB of federated agg.
521 # This is attempted before removing the object from the local agg's PLCDB and sfa table
522 if hrn.startswith(api.hrn) and type in ['user', 'slice', 'authority']:
523 for registry in registries:
524 if registry not in [api.hrn]:
526 result=registries[registry].remove_peer_object(credential, record, origin_hrn)
530 # call testbed callback first
531 # IIUC this is done on the local testbed TOO because of the refreshpeer link
532 if not api.driver.remove(record.__dict__):
533 logger.warning("driver.remove failed")
536 dbsession.delete(record)
541 # This is a PLC-specific thing, won't work with other platforms
542 def get_key_from_incoming_ip (self, api):
543 dbsession=api.dbsession()
544 # verify that the callers's ip address exist in the db and is an interface
545 # for a node in the db
546 (ip, port) = api.remote_addr
547 interfaces = api.driver.shell.GetInterfaces({'ip': ip}, ['node_id'])
549 raise NonExistingRecord("no such ip %(ip)s" % locals())
550 nodes = api.driver.shell.GetNodes([interfaces[0]['node_id']], ['node_id', 'hostname'])
552 raise NonExistingRecord("no such node using ip %(ip)s" % locals())
555 # look up the sfa record
556 record=dbsession.query(RegRecord).filter_by(type='node',pointer=node['node_id']).first()
558 raise RecordNotFound("node with pointer %s"%node['node_id'])
560 # generate a new keypair and gid
562 pkey = Keypair(create=True)
563 urn = hrn_to_urn(record.hrn, record.type)
565 email=getattr(record,'email',None)
566 gid_object = api.auth.hierarchy.create_gid(urn, uuid, pkey, email)
567 gid = gid_object.save_to_string(save_parents=True)
573 # attempt the scp the key
574 # and gid onto the node
575 # this will only work for planetlab based components
576 (kfd, key_filename) = tempfile.mkstemp()
577 (gfd, gid_filename) = tempfile.mkstemp()
578 pkey.save_to_file(key_filename)
579 gid_object.save_to_file(gid_filename, save_parents=True)
580 host = node['hostname']
581 key_dest="/etc/sfa/node.key"
582 gid_dest="/etc/sfa/node.gid"
584 #identity = "/etc/planetlab/root_ssh_key.rsa"
585 identity = "/etc/sfa/root_ssh_key"
586 scp_options=" -i %(identity)s " % locals()
587 scp_options+="-o StrictHostKeyChecking=no " % locals()
588 scp_key_command="%(scp)s %(scp_options)s %(key_filename)s root@%(host)s:%(key_dest)s" %\
590 scp_gid_command="%(scp)s %(scp_options)s %(gid_filename)s root@%(host)s:%(gid_dest)s" %\
593 all_commands = [scp_key_command, scp_gid_command]
595 for command in all_commands:
596 (status, output) = commands.getstatusoutput(command)
598 raise Exception, output
600 for filename in [key_filename, gid_filename]: