1 from __future__ import print_function
4 # for get_key_from_incoming_ip
9 from sfa.util.faults import RecordNotFound, AccountNotEnabled, PermissionError, MissingAuthority, \
10 UnknownSfaType, ExistingRecord, NonExistingRecord
11 from sfa.util.sfatime import utcparse, datetime_to_epoch
12 from sfa.util.prefixTree import prefixTree
13 from sfa.util.xrn import Xrn, get_authority, hrn_to_urn, urn_to_hrn
14 from sfa.util.version import version_core
15 from sfa.util.sfalogging import logger
17 from sfa.util.printable import printable
19 from sfa.trust.gid import GID
20 from sfa.trust.credential import Credential
21 from sfa.trust.certificate import Certificate, Keypair, convert_public_key
22 from sfa.trust.gid import create_uuid
24 from sfa.storage.model import make_record, RegRecord, RegAuthority, RegUser, RegSlice, RegKey, \
25 augment_with_sfa_builtins
26 ### the types that we need to exclude from sqlobjects before being able to dump
27 # them on the xmlrpc wire
28 from sqlalchemy.orm.collections import InstrumentedList
30 ### historical note -- april 2014
31 # the myslice chaps rightfully complained about the following discrepancy
33 # * read operations (resolve) expose stuff like e.g.
34 # 'reg-researchers', or 'reg-pis', but that
35 # * write operations (register, update) need e.g.
36 # 'researcher' or 'pi' to be set - reg-* are just ignored
38 # the '_normalize_input' helper functions below aim at ironing this out
39 # however in order to break as few code as possible we essentially make sure that *both* fields are set
40 # upon entering the write methods (so again register and update) for legacy, as some driver code
41 # might depend on the presence of, say, 'researcher'
43 # normalize an input record to a write method - register or update
44 # e.g. registry calls this 'reg-researchers'
45 # while some drivers call this 'researcher'
46 # we need to make sure that both keys appear and are the same
47 def _normalize_input(record, reg_key, driver_key):
48 # this looks right, use this for both keys
50 # and issue a warning if they were both set and different
51 # as we're overwriting some user data here
52 if driver_key in record:
53 logger.warning ("normalize_input: incoming record has both values, using {}"
55 record[driver_key] = record[reg_key]
56 # we only have one key set, duplicate for the other one
57 elif driver_key in record:
58 logger.warning ("normalize_input: you should use '{}' instead of '{}'"
59 .format(reg_key, driver_key))
60 record[reg_key] = record[driver_key]
62 def normalize_input_record (record):
63 _normalize_input (record, 'reg-researchers','researcher')
64 _normalize_input (record, 'reg-pis','pi')
65 _normalize_input (record, 'reg-keys','keys')
66 # xxx the keys thing could use a little bit more attention:
67 # some parts of the code are using 'keys' while they should use 'reg-keys'
68 # but I run out of time for now
69 if 'reg-keys' in record:
70 record['keys'] = record['reg-keys']
73 class RegistryManager:
75 def __init__ (self, config):
76 logger.info("Creating RegistryManager[{}]".format(id(self)))
78 # The GENI GetVersion call
79 def GetVersion(self, api, options):
80 peers = dict ( [ (hrn,interface.get_url()) for (hrn,interface) in api.registries.iteritems()
82 xrn=Xrn(api.hrn,type='authority')
83 return version_core({'interface':'registry',
89 def GetCredential(self, api, xrn, input_type, caller_xrn=None):
92 hrn, _ = urn_to_hrn(xrn)
95 hrn, type = urn_to_hrn(xrn)
97 # Slivers don't have credentials but users should be able to
98 # specify a sliver xrn and receive the slice's credential
99 # However if input_type is specified
100 if type == 'sliver' or ( not input_type and '-' in Xrn(hrn).leaf):
101 slice_xrn = api.driver.sliver_to_slice_xrn(hrn)
104 # Is this a root or sub authority
105 auth_hrn = api.auth.get_authority(hrn)
106 if not auth_hrn or hrn == api.config.SFA_INTERFACE_HRN:
108 auth_info = api.auth.get_auth_info(auth_hrn)
111 dbsession = api.dbsession()
112 record = dbsession.query(RegRecord).filter_by(type=type, hrn=hrn).first()
114 raise RecordNotFound("hrn={}, type={}".format(hrn, type))
116 # get the callers gid
117 # if caller_xrn is not specified assume the caller is the record
121 caller_gid = record.get_gid_object()
123 caller_hrn, caller_type = urn_to_hrn(caller_xrn)
125 caller_record = dbsession.query(RegRecord).filter_by(hrn=caller_hrn,type=caller_type).first()
127 caller_record = dbsession.query(RegRecord).filter_by(hrn=caller_hrn).first()
128 if not caller_record:
129 raise RecordNotFound(
130 "Unable to associated caller (hrn={}, type={}) with credential for (hrn: {}, type: {})"
131 .format(caller_hrn, caller_type, hrn, type))
132 caller_gid = GID(string=caller_record.gid)
134 object_hrn = record.get_gid_object().get_hrn()
135 # call the builtin authorization/credential generation engine
136 rights = api.auth.determine_user_rights(caller_hrn, record)
137 # make sure caller has rights to this object
138 if rights.is_empty():
139 raise PermissionError("{} has no rights to {} ({})"
140 .format(caller_hrn, object_hrn, xrn))
141 object_gid = GID(string=record.gid)
142 new_cred = Credential(subject = object_gid.get_subject())
143 new_cred.set_gid_caller(caller_gid)
144 new_cred.set_gid_object(object_gid)
145 new_cred.set_issuer_keys(auth_info.get_privkey_filename(), auth_info.get_gid_filename())
146 #new_cred.set_pubkey(object_gid.get_pubkey())
147 new_cred.set_privileges(rights)
148 new_cred.get_privileges().delegate_all_privileges(True)
149 if hasattr(record,'expires'):
150 date = utcparse(record.expires)
151 expires = datetime_to_epoch(date)
152 new_cred.set_expiration(int(expires))
153 auth_kind = "authority,ma,sa"
154 # Parent not necessary, verify with certs
155 #new_cred.set_parent(api.auth.hierarchy.get_auth_cred(auth_hrn, kind=auth_kind))
159 return new_cred.save_to_string(save_parents=True)
162 # the default for full, which means 'dig into the testbed as well', should be false
163 def Resolve(self, api, xrns, type=None, details=False):
165 dbsession = api.dbsession()
166 if not isinstance(xrns, types.ListType):
167 # try to infer type if not set and we get a single input
169 type = Xrn(xrns).get_type()
171 hrns = [urn_to_hrn(xrn)[0] for xrn in xrns]
173 # load all known registry names into a prefix tree and attempt to find
174 # the longest matching prefix
175 # create a dict where key is a registry hrn and its value is a list
176 # of hrns at that registry (determined by the known prefix tree).
178 registries = api.registries
180 registry_hrns = registries.keys()
181 tree.load(registry_hrns)
183 registry_hrn = tree.best_match(urn_to_hrn(xrn)[0])
184 if registry_hrn not in xrn_dict:
185 xrn_dict[registry_hrn] = []
186 xrn_dict[registry_hrn].append(xrn)
189 for registry_hrn in xrn_dict:
190 # skip the hrn without a registry hrn
191 # XX should we let the user know the authority is unknown?
195 # if the best match (longest matching hrn) is not the local registry,
196 # forward the request
197 xrns = xrn_dict[registry_hrn]
198 if registry_hrn != api.hrn:
199 credential = api.getCredential()
200 interface = api.registries[registry_hrn]
201 server_proxy = api.server_proxy(interface, credential)
202 # should propagate the details flag but that's not supported in the xmlrpc interface yet
203 #peer_records = server_proxy.Resolve(xrns, credential,type, details=details)
204 peer_records = server_proxy.Resolve(xrns, credential)
205 # pass foreign records as-is
206 # previous code used to read
207 # records.extend([SfaRecord(dict=record).as_dict() for record in peer_records])
208 # not sure why the records coming through xmlrpc had to be processed at all
209 records.extend(peer_records)
211 # try resolving the remaining unfound records at the local registry
212 local_hrns = list ( set(hrns).difference([record['hrn'] for record in records]) )
214 local_records = dbsession.query(RegRecord).filter(RegRecord.hrn.in_(local_hrns))
216 local_records = local_records.filter_by(type=type)
217 local_records = local_records.all()
219 for local_record in local_records:
220 augment_with_sfa_builtins(local_record)
222 logger.info("Resolve, (details={}, type={}) local_records={} "
223 .format(details, type, local_records))
224 local_dicts = [ record.__dict__ for record in local_records ]
227 # in details mode we get as much info as we can, which involves contacting the
228 # testbed for getting implementation details about the record
229 api.driver.augment_records_with_testbed_info(local_dicts)
230 # also we fill the 'url' field for known authorities
231 # used to be in the driver code, sounds like a poorman thing though
232 def solve_neighbour_url (record):
233 if not record.type.startswith('authority'): return
235 for neighbour_dict in [ api.aggregates, api.registries ]:
236 if hrn in neighbour_dict:
237 record.url=neighbour_dict[hrn].get_url()
239 for record in local_records:
240 solve_neighbour_url (record)
242 # convert local record objects to dicts for xmlrpc
243 # xxx somehow here calling dict(record) issues a weird error
244 # however record.todict() seems to work fine
245 # records.extend( [ dict(record) for record in local_records ] )
246 records.extend( [ record.record_to_dict(exclude_types=(InstrumentedList,)) for record in local_records ] )
249 raise RecordNotFound(str(hrns))
253 def List (self, api, xrn, origin_hrn=None, options=None):
254 if options is None: options={}
255 dbsession = api.dbsession()
256 # load all know registry names into a prefix tree and attempt to find
257 # the longest matching prefix
258 hrn, type = urn_to_hrn(xrn)
259 registries = api.registries
260 registry_hrns = registries.keys()
262 tree.load(registry_hrns)
263 registry_hrn = tree.best_match(hrn)
265 #if there was no match then this record belongs to an unknow registry
267 raise MissingAuthority(xrn)
268 # if the best match (longest matching hrn) is not the local registry,
269 # forward the request
271 if registry_hrn != api.hrn:
272 credential = api.getCredential()
273 interface = api.registries[registry_hrn]
274 server_proxy = api.server_proxy(interface, credential)
275 record_list = server_proxy.List(xrn, credential, options)
276 # same as above, no need to process what comes from through xmlrpc
277 # pass foreign records as-is
278 record_dicts = record_list
280 # if we still have not found the record yet, try the local registry
281 # logger.debug("before trying local records, {} foreign records".format(len(record_dicts)))
284 if ('recursive' in options and options['recursive']):
286 elif hrn.endswith('*'):
290 if not api.auth.hierarchy.auth_exists(hrn):
291 raise MissingAuthority(hrn)
293 records = dbsession.query(RegRecord).filter(RegRecord.hrn.startswith(hrn)).all()
294 # logger.debug("recursive mode, found {} local records".format(len(records)))
296 records = dbsession.query(RegRecord).filter_by(authority=hrn).all()
297 # logger.debug("non recursive mode, found {} local records".format(len(records)))
298 # so that sfi list can show more than plain names...
299 for record in records:
300 # xxx mystery - see also the bottom of model.py
301 # resulting records have been observed to not always have
302 # their __dict__ actually in line with the object's contents;
303 # was first observed with authorities' 'name' column
304 # that would be missing from result as received by client
305 augment_with_sfa_builtins(record)
306 record_dicts = [ record.record_to_dict(exclude_types=(InstrumentedList,)) for record in records ]
310 def CreateGid(self, api, xrn, cert):
312 authority = Xrn(xrn=xrn).get_authority_hrn()
313 auth_info = api.auth.get_auth_info(authority)
315 pkey = Keypair(create=True)
317 certificate = Certificate(string=cert)
318 pkey = certificate.get_pubkey()
320 # Add the email of the user to SubjectAltName in the GID
322 hrn = Xrn(xrn).get_hrn()
323 dbsession = api.dbsession()
324 record = dbsession.query(RegUser).filter_by(hrn=hrn).first()
326 email = getattr(record,'email',None)
327 gid = api.auth.hierarchy.create_gid(xrn, create_uuid(), pkey, email=email)
328 return gid.save_to_string(save_parents=True)
331 # utility for handling relationships among the SFA objects
333 # subject_record describes the subject of the relationships
334 # ref_record contains the target values for the various relationships we need to manage
335 # (to begin with, this is just the slice x person (researcher) and authority x person (pi) relationships)
336 def update_driver_relations (self, api, subject_obj, ref_obj):
337 type=subject_obj.type
338 #for (k,v) in subject_obj.__dict__.items(): print k,'=',v
339 if type=='slice' and hasattr(ref_obj,'researcher'):
340 self.update_driver_relation(api, subject_obj, ref_obj.researcher, 'user', 'researcher')
341 elif type=='authority' and hasattr(ref_obj,'pi'):
342 self.update_driver_relation(api, subject_obj,ref_obj.pi, 'user', 'pi')
344 # field_key is the name of one field in the record, typically 'researcher' for a 'slice' record
345 # hrns is the list of hrns that should be linked to the subject from now on
346 # target_type would be e.g. 'user' in the 'slice' x 'researcher' example
347 def update_driver_relation (self, api, record_obj, hrns, target_type, relation_name):
348 dbsession = api.dbsession()
349 # locate the linked objects in our db
350 subject_type=record_obj.type
351 subject_id=record_obj.pointer
352 # get the 'pointer' field of all matching records
353 link_id_tuples = dbsession.query(RegRecord.pointer).filter_by(type=target_type).filter(RegRecord.hrn.in_(hrns)).all()
354 # sqlalchemy returns named tuples for columns
355 link_ids = [ tuple.pointer for tuple in link_id_tuples ]
356 api.driver.update_relation (subject_type, target_type, relation_name, subject_id, link_ids)
358 def Register(self, api, record_dict):
360 logger.debug("Register: entering with record_dict={}".format(printable(record_dict)))
361 normalize_input_record (record_dict)
362 logger.debug("Register: normalized record_dict={}".format(printable(record_dict)))
364 dbsession = api.dbsession()
365 hrn, type = record_dict['hrn'], record_dict['type']
366 urn = hrn_to_urn(hrn,type)
368 if type not in ['authority', 'slice', 'node', 'user']:
369 raise UnknownSfaType(type)
371 # check if record_dict already exists
372 existing_records = dbsession.query(RegRecord).filter_by(type=type, hrn=hrn).all()
374 raise ExistingRecord(hrn)
376 assert ('type' in record_dict)
377 # returns the right type of RegRecord according to type in record
378 record = make_record(dict=record_dict)
379 record.just_created()
380 record.authority = get_authority(record.hrn)
381 auth_info = api.auth.get_auth_info(record.authority)
383 # make sure record has a gid
386 pkey = Keypair(create=True)
387 pub_key=getattr(record,'reg-keys',None)
388 if pub_key is not None:
389 # use only first key in record
390 if pub_key and isinstance(pub_key, types.ListType): pub_key = pub_key[0]
391 pkey = convert_public_key(pub_key)
393 email = getattr(record,'email',None)
394 gid_object = api.auth.hierarchy.create_gid(urn, uuid, pkey, email = email)
395 gid = gid_object.save_to_string(save_parents=True)
398 if isinstance (record, RegAuthority):
400 if not api.auth.hierarchy.auth_exists(hrn):
401 api.auth.hierarchy.create_auth(hrn_to_urn(hrn,'authority'))
403 # get the GID from the newly created authority
404 auth_info = api.auth.get_auth_info(hrn)
405 gid = auth_info.get_gid_object()
406 record.gid=gid.save_to_string(save_parents=True)
408 # locate objects for relationships
409 pi_hrns = getattr(record,'reg-pis',None)
410 if pi_hrns is not None: record.update_pis (pi_hrns, dbsession)
412 elif isinstance (record, RegSlice):
413 researcher_hrns = getattr(record,'reg-researchers',None)
414 if researcher_hrns is not None: record.update_researchers (researcher_hrns, dbsession)
416 elif isinstance (record, RegUser):
417 # create RegKey objects for incoming keys
418 if hasattr(record,'reg-keys'):
419 keys=getattr(record,'reg-keys')
420 # some people send the key as a string instead of a list of strings
421 if isinstance(keys,types.StringTypes): keys=[keys]
422 logger.debug ("creating {} keys for user {}".format(len(keys), record.hrn))
423 record.reg_keys = [ RegKey (key) for key in keys ]
425 # update testbed-specific data if needed
426 pointer = api.driver.register (record.__dict__, hrn, pub_key)
428 record.pointer=pointer
429 dbsession.add(record)
432 # update membership for researchers, pis, owners, operators
433 self.update_driver_relations (api, record, record)
435 return record.get_gid_object().save_to_string(save_parents=True)
437 def Update(self, api, record_dict):
439 logger.debug("Update: entering with record_dict={}".format(printable(record_dict)))
440 normalize_input_record (record_dict)
441 logger.debug("Update: normalized record_dict={}".format(printable(record_dict)))
443 dbsession = api.dbsession()
444 assert ('type' in record_dict)
445 new_record = make_record(dict=record_dict)
446 (type, hrn) = (new_record.type, new_record.hrn)
448 # make sure the record exists
449 record = dbsession.query(RegRecord).filter_by(type=type, hrn=hrn).first()
451 raise RecordNotFound("hrn={}, type={}".format(hrn, type))
452 record.just_updated()
454 # Use the pointer from the existing record, not the one that the user
455 # gave us. This prevents the user from inserting a forged pointer
456 pointer = record.pointer
458 # is there a change in keys ?
461 if getattr(new_record, 'keys', None):
462 new_key = new_record.keys
463 if isinstance (new_key, types.ListType):
466 # take new_key into account
468 # update the openssl key and gid
469 pkey = convert_public_key(new_key)
471 urn = hrn_to_urn(hrn,type)
473 email = getattr(new_record, 'email', None)
475 email = getattr(record, 'email', None)
476 gid_object = api.auth.hierarchy.create_gid(urn, uuid, pkey, email = email)
477 gid = gid_object.save_to_string(save_parents=True)
479 # xxx should do side effects from new_record to record
480 # not too sure how to do that
481 # not too big a deal with planetlab as the driver is authoritative, but...
483 # update native relations
484 if isinstance(record, RegSlice):
485 researcher_hrns = getattr(new_record, 'reg-researchers', None)
486 if researcher_hrns is not None:
487 record.update_researchers (researcher_hrns, dbsession)
489 elif isinstance(record, RegAuthority):
490 pi_hrns = getattr(new_record, 'reg-pis', None)
491 if pi_hrns is not None:
492 record.update_pis(pi_hrns, dbsession)
493 name = getattr(new_record, 'name', None)
497 elif isinstance(record, RegUser):
498 email = getattr(new_record, 'email', None)
499 if email is not None:
502 # update the PLC information that was specified with the record
503 # xxx mystery -- see also the bottom of model.py,
504 # oddly enough, without this useless statement,
505 # record.__dict__ as received by the driver seems to be off
506 # anyway the driver should receive an object
507 # (and then extract __dict__ itself if needed)
508 print("DO NOT REMOVE ME before driver.update, record={}".format(record))
509 # as of June 2015: I suspect we could remove that print line above and replace it with
510 # augment_with_sfa_builtins(record)
511 # instead, that checks for these fields, like it is done above in List()
512 # but that would need to be confirmed by more extensive tests
515 (pointer, new_key_pointer) = api.driver.update (record.__dict__, new_record.__dict__, hrn, new_key)
518 if new_key and new_key_pointer:
519 record.reg_keys = [ RegKey(new_key, new_key_pointer) ]
523 # update membership for researchers, pis, owners, operators
524 self.update_driver_relations(api, record, new_record)
528 # expecting an Xrn instance
529 def Remove(self, api, xrn, origin_hrn=None):
530 dbsession = api.dbsession()
532 type = xrn.get_type()
533 request = dbsession.query(RegRecord).filter_by(hrn=hrn)
534 if type and type not in ['all', '*']:
535 request = request.filter_by(type=type)
537 record = request.first()
539 msg = "Could not find hrn {}".format(hrn)
540 if type: msg += " type={}".format(type)
541 raise RecordNotFound(msg)
544 if type not in ['slice', 'user', 'node', 'authority'] :
545 raise UnknownSfaType(type)
547 credential = api.getCredential()
548 registries = api.registries
550 # Try to remove the object from the PLCDB of federated agg.
551 # This is attempted before removing the object from the local agg's PLCDB and sfa table
552 if hrn.startswith(api.hrn) and type in ['user', 'slice', 'authority']:
553 for registry in registries:
554 if registry not in [api.hrn]:
556 result=registries[registry].remove_peer_object(credential, record, origin_hrn)
560 # call testbed callback first
561 # IIUC this is done on the local testbed TOO because of the refreshpeer link
562 if not api.driver.remove(record.__dict__):
563 logger.warning("driver.remove failed")
566 dbsession.delete(record)
571 # This is a PLC-specific thing, won't work with other platforms
572 def get_key_from_incoming_ip (self, api):
573 dbsession = api.dbsession()
574 # verify that the callers's ip address exist in the db and is an interface
575 # for a node in the db
576 (ip, port) = api.remote_addr
577 interfaces = api.driver.shell.GetInterfaces({'ip': ip}, ['node_id'])
579 raise NonExistingRecord("no such ip {}".format(ip))
580 nodes = api.driver.shell.GetNodes([interfaces[0]['node_id']], ['node_id', 'hostname'])
582 raise NonExistingRecord("no such node using ip {}".format(ip))
585 # look up the sfa record
586 record = dbsession.query(RegRecord).filter_by(type='node', pointer=node['node_id']).first()
588 raise RecordNotFound("node with pointer {}".format(node['node_id']))
590 # generate a new keypair and gid
592 pkey = Keypair(create=True)
593 urn = hrn_to_urn(record.hrn, record.type)
595 email = getattr(record, 'email', None)
596 gid_object = api.auth.hierarchy.create_gid(urn, uuid, pkey, email)
597 gid = gid_object.save_to_string(save_parents=True)
603 # attempt the scp the key
604 # and gid onto the node
605 # this will only work for planetlab based components
606 (kfd, key_filename) = tempfile.mkstemp()
607 (gfd, gid_filename) = tempfile.mkstemp()
608 pkey.save_to_file(key_filename)
609 gid_object.save_to_file(gid_filename, save_parents=True)
610 host = node['hostname']
611 key_dest="/etc/sfa/node.key"
612 gid_dest="/etc/sfa/node.gid"
614 #identity = "/etc/planetlab/root_ssh_key.rsa"
615 identity = "/etc/sfa/root_ssh_key"
616 scp_options = " -i {identity} ".format(**locals())
617 scp_options += "-o StrictHostKeyChecking=no "
618 scp_key_command = "{scp} {scp_options} {key_filename} root@{host}:{key_dest}"\
620 scp_gid_command = "{scp} {scp_options} {gid_filename} root@{host}:{gid_dest}"\
623 all_commands = [scp_key_command, scp_gid_command]
625 for command in all_commands:
626 (status, output) = commands.getstatusoutput(command)
628 raise Exception, output
630 for filename in [key_filename, gid_filename]: