1 from __future__ import print_function
3 # for get_key_from_incoming_ip
8 from sfa.util.faults import RecordNotFound, AccountNotEnabled, PermissionError, MissingAuthority, \
9 UnknownSfaType, ExistingRecord, NonExistingRecord
10 from sfa.util.sfatime import utcparse, datetime_to_epoch
11 from sfa.util.prefixTree import prefixTree
12 from sfa.util.xrn import Xrn, get_authority, hrn_to_urn, urn_to_hrn
13 from sfa.util.version import version_core
14 from sfa.util.sfalogging import logger
16 from sfa.util.printable import printable
18 from sfa.trust.gid import GID
19 from sfa.trust.credential import Credential
20 from sfa.trust.certificate import Certificate, Keypair, convert_public_key
21 from sfa.trust.gid import create_uuid
23 from sfa.storage.model import make_record, RegRecord, RegAuthority, RegUser, RegSlice, RegKey, \
24 augment_with_sfa_builtins
25 ### the types that we need to exclude from sqlobjects before being able to dump
26 # them on the xmlrpc wire
27 from sqlalchemy.orm.collections import InstrumentedList
29 ### historical note -- april 2014
30 # the myslice chaps rightfully complained about the following discrepancy
32 # * read operations (resolve) expose stuff like e.g.
33 # 'reg-researchers', or 'reg-pis', but that
34 # * write operations (register, update) need e.g.
35 # 'researcher' or 'pi' to be set - reg-* are just ignored
37 # the '_normalize_input' helper functions below aim at ironing this out
38 # however in order to break as few code as possible we essentially make sure that *both* fields are set
39 # upon entering the write methods (so again register and update) for legacy, as some driver code
40 # might depend on the presence of, say, 'researcher'
42 # normalize an input record to a write method - register or update
43 # e.g. registry calls this 'reg-researchers'
44 # while some drivers call this 'researcher'
45 # we need to make sure that both keys appear and are the same
46 def _normalize_input(record, reg_key, driver_key):
47 # this looks right, use this for both keys
49 # and issue a warning if they were both set and different
50 # as we're overwriting some user data here
51 if driver_key in record:
52 logger.warning ("normalize_input: incoming record has both values, using {}"
54 record[driver_key] = record[reg_key]
55 # we only have one key set, duplicate for the other one
56 elif driver_key in record:
57 logger.warning ("normalize_input: you should use '{}' instead of '{}'"
58 .format(reg_key, driver_key))
59 record[reg_key] = record[driver_key]
61 def normalize_input_record (record):
62 _normalize_input (record, 'reg-researchers','researcher')
63 _normalize_input (record, 'reg-pis','pi')
64 _normalize_input (record, 'reg-keys','keys')
65 # xxx the keys thing could use a little bit more attention:
66 # some parts of the code are using 'keys' while they should use 'reg-keys'
67 # but I run out of time for now
68 if 'reg-keys' in record:
69 record['keys'] = record['reg-keys']
72 class RegistryManager:
74 def __init__ (self, config):
75 logger.info("Creating RegistryManager[{}]".format(id(self)))
77 # The GENI GetVersion call
78 def GetVersion(self, api, options):
79 peers = dict ( [ (hrn,interface.get_url()) for (hrn,interface) in api.registries.iteritems()
81 xrn=Xrn(api.hrn,type='authority')
82 return version_core({'interface':'registry',
88 def GetCredential(self, api, xrn, input_type, caller_xrn=None):
91 hrn, _ = urn_to_hrn(xrn)
94 hrn, type = urn_to_hrn(xrn)
96 # Slivers don't have credentials but users should be able to
97 # specify a sliver xrn and receive the slice's credential
98 # However if input_type is specified
99 if type == 'sliver' or ( not input_type and '-' in Xrn(hrn).leaf):
100 slice_xrn = api.driver.sliver_to_slice_xrn(hrn)
103 # Is this a root or sub authority
104 auth_hrn = api.auth.get_authority(hrn)
105 if not auth_hrn or hrn == api.config.SFA_INTERFACE_HRN:
107 auth_info = api.auth.get_auth_info(auth_hrn)
110 dbsession = api.dbsession()
111 record = dbsession.query(RegRecord).filter_by(type=type, hrn=hrn).first()
113 raise RecordNotFound("hrn={}, type={}".format(hrn, type))
115 # get the callers gid
116 # if caller_xrn is not specified assume the caller is the record
120 caller_gid = record.get_gid_object()
122 caller_hrn, caller_type = urn_to_hrn(caller_xrn)
124 caller_record = dbsession.query(RegRecord).filter_by(hrn=caller_hrn,type=caller_type).first()
126 caller_record = dbsession.query(RegRecord).filter_by(hrn=caller_hrn).first()
127 if not caller_record:
128 raise RecordNotFound(
129 "Unable to associated caller (hrn={}, type={}) with credential for (hrn: {}, type: {})"
130 .format(caller_hrn, caller_type, hrn, type))
131 caller_gid = GID(string=caller_record.gid)
133 object_hrn = record.get_gid_object().get_hrn()
134 # call the builtin authorization/credential generation engine
135 rights = api.auth.determine_user_rights(caller_hrn, record)
136 # make sure caller has rights to this object
137 if rights.is_empty():
138 raise PermissionError("{} has no rights to {} ({})"
139 .format(caller_hrn, object_hrn, xrn))
140 object_gid = GID(string=record.gid)
141 new_cred = Credential(subject = object_gid.get_subject())
142 new_cred.set_gid_caller(caller_gid)
143 new_cred.set_gid_object(object_gid)
144 new_cred.set_issuer_keys(auth_info.get_privkey_filename(), auth_info.get_gid_filename())
145 #new_cred.set_pubkey(object_gid.get_pubkey())
146 new_cred.set_privileges(rights)
147 new_cred.get_privileges().delegate_all_privileges(True)
148 if hasattr(record,'expires'):
149 date = utcparse(record.expires)
150 expires = datetime_to_epoch(date)
151 new_cred.set_expiration(int(expires))
152 auth_kind = "authority,ma,sa"
153 # Parent not necessary, verify with certs
154 #new_cred.set_parent(api.auth.hierarchy.get_auth_cred(auth_hrn, kind=auth_kind))
158 return new_cred.save_to_string(save_parents=True)
161 # the default for full, which means 'dig into the testbed as well', should be false
162 def Resolve(self, api, xrns, type=None, details=False):
164 dbsession = api.dbsession()
165 if not isinstance(xrns, list):
166 # try to infer type if not set and we get a single input
168 type = Xrn(xrns).get_type()
170 hrns = [urn_to_hrn(xrn)[0] for xrn in xrns]
172 # load all known registry names into a prefix tree and attempt to find
173 # the longest matching prefix
174 # create a dict where key is a registry hrn and its value is a list
175 # of hrns at that registry (determined by the known prefix tree).
177 registries = api.registries
179 registry_hrns = registries.keys()
180 tree.load(registry_hrns)
182 registry_hrn = tree.best_match(urn_to_hrn(xrn)[0])
183 if registry_hrn not in xrn_dict:
184 xrn_dict[registry_hrn] = []
185 xrn_dict[registry_hrn].append(xrn)
188 for registry_hrn in xrn_dict:
189 # skip the hrn without a registry hrn
190 # XX should we let the user know the authority is unknown?
194 # if the best match (longest matching hrn) is not the local registry,
195 # forward the request
196 xrns = xrn_dict[registry_hrn]
197 if registry_hrn != api.hrn:
198 credential = api.getCredential()
199 interface = api.registries[registry_hrn]
200 server_proxy = api.server_proxy(interface, credential)
201 # should propagate the details flag but that's not supported in the xmlrpc interface yet
202 #peer_records = server_proxy.Resolve(xrns, credential,type, details=details)
203 peer_records = server_proxy.Resolve(xrns, credential)
204 # pass foreign records as-is
205 # previous code used to read
206 # records.extend([SfaRecord(dict=record).as_dict() for record in peer_records])
207 # not sure why the records coming through xmlrpc had to be processed at all
208 records.extend(peer_records)
210 # try resolving the remaining unfound records at the local registry
211 local_hrns = list ( set(hrns).difference([record['hrn'] for record in records]) )
213 local_records = dbsession.query(RegRecord).filter(RegRecord.hrn.in_(local_hrns))
215 local_records = local_records.filter_by(type=type)
216 local_records = local_records.all()
218 for local_record in local_records:
219 augment_with_sfa_builtins(local_record)
221 logger.info("Resolve, (details={}, type={}) local_records={} "
222 .format(details, type, local_records))
223 local_dicts = [ record.__dict__ for record in local_records ]
226 # in details mode we get as much info as we can, which involves contacting the
227 # testbed for getting implementation details about the record
228 api.driver.augment_records_with_testbed_info(local_dicts)
229 # also we fill the 'url' field for known authorities
230 # used to be in the driver code, sounds like a poorman thing though
231 def solve_neighbour_url (record):
232 if not record.type.startswith('authority'): return
234 for neighbour_dict in [ api.aggregates, api.registries ]:
235 if hrn in neighbour_dict:
236 record.url=neighbour_dict[hrn].get_url()
238 for record in local_records:
239 solve_neighbour_url (record)
241 # convert local record objects to dicts for xmlrpc
242 # xxx somehow here calling dict(record) issues a weird error
243 # however record.todict() seems to work fine
244 # records.extend( [ dict(record) for record in local_records ] )
245 records.extend( [ record.record_to_dict(exclude_types=(InstrumentedList,)) for record in local_records ] )
248 raise RecordNotFound(str(hrns))
252 def List (self, api, xrn, origin_hrn=None, options=None):
253 if options is None: options={}
254 dbsession = api.dbsession()
255 # load all know registry names into a prefix tree and attempt to find
256 # the longest matching prefix
257 hrn, type = urn_to_hrn(xrn)
258 registries = api.registries
259 registry_hrns = registries.keys()
261 tree.load(registry_hrns)
262 registry_hrn = tree.best_match(hrn)
264 #if there was no match then this record belongs to an unknow registry
266 raise MissingAuthority(xrn)
267 # if the best match (longest matching hrn) is not the local registry,
268 # forward the request
270 if registry_hrn != api.hrn:
271 credential = api.getCredential()
272 interface = api.registries[registry_hrn]
273 server_proxy = api.server_proxy(interface, credential)
274 record_list = server_proxy.List(xrn, credential, options)
275 # same as above, no need to process what comes from through xmlrpc
276 # pass foreign records as-is
277 record_dicts = record_list
279 # if we still have not found the record yet, try the local registry
280 # logger.debug("before trying local records, {} foreign records".format(len(record_dicts)))
283 if ('recursive' in options and options['recursive']):
285 elif hrn.endswith('*'):
289 if not api.auth.hierarchy.auth_exists(hrn):
290 raise MissingAuthority(hrn)
292 records = dbsession.query(RegRecord).filter(RegRecord.hrn.startswith(hrn)).all()
293 # logger.debug("recursive mode, found {} local records".format(len(records)))
295 records = dbsession.query(RegRecord).filter_by(authority=hrn).all()
296 # logger.debug("non recursive mode, found {} local records".format(len(records)))
297 # so that sfi list can show more than plain names...
298 for record in records:
299 # xxx mystery - see also the bottom of model.py
300 # resulting records have been observed to not always have
301 # their __dict__ actually in line with the object's contents;
302 # was first observed with authorities' 'name' column
303 # that would be missing from result as received by client
304 augment_with_sfa_builtins(record)
305 record_dicts = [ record.record_to_dict(exclude_types=(InstrumentedList,)) for record in records ]
309 def CreateGid(self, api, xrn, cert):
311 authority = Xrn(xrn=xrn).get_authority_hrn()
312 auth_info = api.auth.get_auth_info(authority)
314 pkey = Keypair(create=True)
316 certificate = Certificate(string=cert)
317 pkey = certificate.get_pubkey()
319 # Add the email of the user to SubjectAltName in the GID
321 hrn = Xrn(xrn).get_hrn()
322 dbsession = api.dbsession()
323 record = dbsession.query(RegUser).filter_by(hrn=hrn).first()
325 email = getattr(record,'email',None)
326 gid = api.auth.hierarchy.create_gid(xrn, create_uuid(), pkey, email=email)
327 return gid.save_to_string(save_parents=True)
330 # utility for handling relationships among the SFA objects
332 # subject_record describes the subject of the relationships
333 # ref_record contains the target values for the various relationships we need to manage
334 # (to begin with, this is just the slice x person (researcher) and authority x person (pi) relationships)
335 def update_driver_relations (self, api, subject_obj, ref_obj):
336 type=subject_obj.type
337 #for (k,v) in subject_obj.__dict__.items(): print k,'=',v
338 if type=='slice' and hasattr(ref_obj,'researcher'):
339 self.update_driver_relation(api, subject_obj, ref_obj.researcher, 'user', 'researcher')
340 elif type=='authority' and hasattr(ref_obj,'pi'):
341 self.update_driver_relation(api, subject_obj,ref_obj.pi, 'user', 'pi')
343 # field_key is the name of one field in the record, typically 'researcher' for a 'slice' record
344 # hrns is the list of hrns that should be linked to the subject from now on
345 # target_type would be e.g. 'user' in the 'slice' x 'researcher' example
346 def update_driver_relation (self, api, record_obj, hrns, target_type, relation_name):
347 dbsession = api.dbsession()
348 # locate the linked objects in our db
349 subject_type=record_obj.type
350 subject_id=record_obj.pointer
351 # get the 'pointer' field of all matching records
352 link_id_tuples = dbsession.query(RegRecord.pointer).filter_by(type=target_type).filter(RegRecord.hrn.in_(hrns)).all()
353 # sqlalchemy returns named tuples for columns
354 link_ids = [ tuple.pointer for tuple in link_id_tuples ]
355 api.driver.update_relation (subject_type, target_type, relation_name, subject_id, link_ids)
357 def Register(self, api, record_dict):
359 logger.debug("Register: entering with record_dict={}".format(printable(record_dict)))
360 normalize_input_record (record_dict)
361 logger.debug("Register: normalized record_dict={}".format(printable(record_dict)))
363 dbsession = api.dbsession()
364 hrn, type = record_dict['hrn'], record_dict['type']
365 urn = hrn_to_urn(hrn,type)
367 if type not in ['authority', 'slice', 'node', 'user']:
368 raise UnknownSfaType(type)
370 # check if record_dict already exists
371 existing_records = dbsession.query(RegRecord).filter_by(type=type, hrn=hrn).all()
373 raise ExistingRecord(hrn)
375 assert ('type' in record_dict)
376 # returns the right type of RegRecord according to type in record
377 record = make_record(dict=record_dict)
378 record.just_created()
379 record.authority = get_authority(record.hrn)
380 auth_info = api.auth.get_auth_info(record.authority)
382 # make sure record has a gid
385 pkey = Keypair(create=True)
386 pub_key=getattr(record,'reg-keys',None)
387 if pub_key is not None:
388 # use only first key in record
389 if pub_key and isinstance(pub_key, list): pub_key = pub_key[0]
390 pkey = convert_public_key(pub_key)
392 email = getattr(record,'email',None)
393 gid_object = api.auth.hierarchy.create_gid(urn, uuid, pkey, email = email)
394 gid = gid_object.save_to_string(save_parents=True)
397 if isinstance (record, RegAuthority):
399 if not api.auth.hierarchy.auth_exists(hrn):
400 api.auth.hierarchy.create_auth(hrn_to_urn(hrn,'authority'))
402 # get the GID from the newly created authority
403 auth_info = api.auth.get_auth_info(hrn)
404 gid = auth_info.get_gid_object()
405 record.gid=gid.save_to_string(save_parents=True)
407 # locate objects for relationships
408 pi_hrns = getattr(record,'reg-pis',None)
409 if pi_hrns is not None: record.update_pis (pi_hrns, dbsession)
411 elif isinstance (record, RegSlice):
412 researcher_hrns = getattr(record,'reg-researchers',None)
413 if researcher_hrns is not None: record.update_researchers (researcher_hrns, dbsession)
415 elif isinstance (record, RegUser):
416 # create RegKey objects for incoming keys
417 if hasattr(record,'reg-keys'):
418 keys = getattr(record, 'reg-keys')
419 # some people send the key as a string instead of a list of strings
420 # note for python2/3 : no need to consider unicode in a key
421 if isinstance(keys, str):
423 logger.debug("creating {} keys for user {}".format(len(keys), record.hrn))
424 record.reg_keys = [ RegKey (key) for key in keys ]
426 # update testbed-specific data if needed
427 pointer = api.driver.register (record.__dict__, hrn, pub_key)
429 record.pointer=pointer
430 dbsession.add(record)
433 # update membership for researchers, pis, owners, operators
434 self.update_driver_relations (api, record, record)
436 return record.get_gid_object().save_to_string(save_parents=True)
438 def Update(self, api, record_dict):
440 logger.debug("Update: entering with record_dict={}".format(printable(record_dict)))
441 normalize_input_record (record_dict)
442 logger.debug("Update: normalized record_dict={}".format(printable(record_dict)))
444 dbsession = api.dbsession()
445 assert ('type' in record_dict)
446 new_record = make_record(dict=record_dict)
447 (type, hrn) = (new_record.type, new_record.hrn)
449 # make sure the record exists
450 record = dbsession.query(RegRecord).filter_by(type=type, hrn=hrn).first()
452 raise RecordNotFound("hrn={}, type={}".format(hrn, type))
453 record.just_updated()
455 # Use the pointer from the existing record, not the one that the user
456 # gave us. This prevents the user from inserting a forged pointer
457 pointer = record.pointer
459 # is there a change in keys ?
462 if getattr(new_record, 'keys', None):
463 new_key = new_record.keys
464 if isinstance (new_key, list):
467 # take new_key into account
469 # update the openssl key and gid
470 pkey = convert_public_key(new_key)
472 urn = hrn_to_urn(hrn,type)
474 email = getattr(new_record, 'email', None)
476 email = getattr(record, 'email', None)
477 gid_object = api.auth.hierarchy.create_gid(urn, uuid, pkey, email = email)
478 gid = gid_object.save_to_string(save_parents=True)
480 # xxx should do side effects from new_record to record
481 # not too sure how to do that
482 # not too big a deal with planetlab as the driver is authoritative, but...
484 # update native relations
485 if isinstance(record, RegSlice):
486 researcher_hrns = getattr(new_record, 'reg-researchers', None)
487 if researcher_hrns is not None:
488 record.update_researchers (researcher_hrns, dbsession)
490 elif isinstance(record, RegAuthority):
491 pi_hrns = getattr(new_record, 'reg-pis', None)
492 if pi_hrns is not None:
493 record.update_pis(pi_hrns, dbsession)
494 name = getattr(new_record, 'name', None)
498 elif isinstance(record, RegUser):
499 email = getattr(new_record, 'email', None)
500 if email is not None:
503 # update the PLC information that was specified with the record
504 # xxx mystery -- see also the bottom of model.py,
505 # oddly enough, without this useless statement,
506 # record.__dict__ as received by the driver seems to be off
507 # anyway the driver should receive an object
508 # (and then extract __dict__ itself if needed)
509 print("DO NOT REMOVE ME before driver.update, record={}".format(record))
510 # as of June 2015: I suspect we could remove that print line above and replace it with
511 # augment_with_sfa_builtins(record)
512 # instead, that checks for these fields, like it is done above in List()
513 # but that would need to be confirmed by more extensive tests
516 (pointer, new_key_pointer) = api.driver.update (record.__dict__, new_record.__dict__, hrn, new_key)
519 if new_key and new_key_pointer:
520 record.reg_keys = [ RegKey(new_key, new_key_pointer) ]
524 # update membership for researchers, pis, owners, operators
525 self.update_driver_relations(api, record, new_record)
529 # expecting an Xrn instance
530 def Remove(self, api, xrn, origin_hrn=None):
531 dbsession = api.dbsession()
533 type = xrn.get_type()
534 request = dbsession.query(RegRecord).filter_by(hrn=hrn)
535 if type and type not in ['all', '*']:
536 request = request.filter_by(type=type)
538 record = request.first()
540 msg = "Could not find hrn {}".format(hrn)
541 if type: msg += " type={}".format(type)
542 raise RecordNotFound(msg)
545 if type not in ['slice', 'user', 'node', 'authority'] :
546 raise UnknownSfaType(type)
548 credential = api.getCredential()
549 registries = api.registries
551 # Try to remove the object from the PLCDB of federated agg.
552 # This is attempted before removing the object from the local agg's PLCDB and sfa table
553 if hrn.startswith(api.hrn) and type in ['user', 'slice', 'authority']:
554 for registry in registries:
555 if registry not in [api.hrn]:
557 result=registries[registry].remove_peer_object(credential, record, origin_hrn)
561 # call testbed callback first
562 # IIUC this is done on the local testbed TOO because of the refreshpeer link
563 if not api.driver.remove(record.__dict__):
564 logger.warning("driver.remove failed")
567 dbsession.delete(record)
572 # This is a PLC-specific thing, won't work with other platforms
573 def get_key_from_incoming_ip (self, api):
574 dbsession = api.dbsession()
575 # verify that the callers's ip address exist in the db and is an interface
576 # for a node in the db
577 (ip, port) = api.remote_addr
578 interfaces = api.driver.shell.GetInterfaces({'ip': ip}, ['node_id'])
580 raise NonExistingRecord("no such ip {}".format(ip))
581 nodes = api.driver.shell.GetNodes([interfaces[0]['node_id']], ['node_id', 'hostname'])
583 raise NonExistingRecord("no such node using ip {}".format(ip))
586 # look up the sfa record
587 record = dbsession.query(RegRecord).filter_by(type='node', pointer=node['node_id']).first()
589 raise RecordNotFound("node with pointer {}".format(node['node_id']))
591 # generate a new keypair and gid
593 pkey = Keypair(create=True)
594 urn = hrn_to_urn(record.hrn, record.type)
596 email = getattr(record, 'email', None)
597 gid_object = api.auth.hierarchy.create_gid(urn, uuid, pkey, email)
598 gid = gid_object.save_to_string(save_parents=True)
604 # attempt the scp the key
605 # and gid onto the node
606 # this will only work for planetlab based components
607 (kfd, key_filename) = tempfile.mkstemp()
608 (gfd, gid_filename) = tempfile.mkstemp()
609 pkey.save_to_file(key_filename)
610 gid_object.save_to_file(gid_filename, save_parents=True)
611 host = node['hostname']
612 key_dest="/etc/sfa/node.key"
613 gid_dest="/etc/sfa/node.gid"
615 #identity = "/etc/planetlab/root_ssh_key.rsa"
616 identity = "/etc/sfa/root_ssh_key"
617 scp_options = " -i {identity} ".format(**locals())
618 scp_options += "-o StrictHostKeyChecking=no "
619 scp_key_command = "{scp} {scp_options} {key_filename} root@{host}:{key_dest}"\
621 scp_gid_command = "{scp} {scp_options} {gid_filename} root@{host}:{gid_dest}"\
624 all_commands = [scp_key_command, scp_gid_command]
626 for command in all_commands:
627 (status, output) = commands.getstatusoutput(command)
629 raise Exception(output)
631 for filename in [key_filename, gid_filename]: