1 # pylint: disable=c0111, w1202
5 # for get_key_from_incoming_ip
10 from sfa.util.faults import (
11 RecordNotFound, AccountNotEnabled, PermissionError, MissingAuthority,
12 UnknownSfaType, ExistingRecord, NonExistingRecord)
13 from sfa.util.sfatime import utcparse, datetime_to_epoch
14 from sfa.util.prefixTree import prefixTree
15 from sfa.util.xrn import Xrn, get_authority, hrn_to_urn, urn_to_hrn
16 from sfa.util.version import version_core
17 from sfa.util.sfalogging import logger
19 from sfa.util.printable import printable
21 from sfa.trust.gid import GID
22 from sfa.trust.credential import Credential
23 from sfa.trust.certificate import Certificate, Keypair, convert_public_key
24 from sfa.trust.gid import create_uuid
26 from sfa.storage.model import (
27 make_record, RegRecord, RegAuthority, RegUser, RegSlice, RegKey,
28 augment_with_sfa_builtins)
29 # the types that we need to exclude from sqlobjects before being able to dump
30 # them on the xmlrpc wire
31 from sqlalchemy.orm.collections import InstrumentedList
33 # historical note -- april 2014
34 # the myslice chaps rightfully complained about the following discrepancy
36 # * read operations (resolve) expose stuff like e.g.
37 # 'reg-researchers', or 'reg-pis', but that
38 # * write operations (register, update) need e.g.
39 # 'researcher' or 'pi' to be set - reg-* are just ignored
41 # the '_normalize_input' helper functions below aim at ironing this out
42 # however in order to break as few code as possible we essentially
43 # make sure that *both* fields are set upon entering the write methods
44 # (again: register and update) for legacy, as some driver code
45 # might depend on the presence of, say, 'researcher'
47 # normalize an input record to a write method - register or update
48 # e.g. registry calls this 'reg-researchers'
49 # while some drivers call this 'researcher'
50 # we need to make sure that both keys appear and are the same
53 def _normalize_input(record, reg_key, driver_key):
54 # this looks right, use this for both keys
56 # and issue a warning if they were both set and different
57 # as we're overwriting some user data here
58 if driver_key in record:
59 logger.warning("normalize_input: incoming record has both values, using {}"
61 record[driver_key] = record[reg_key]
62 # we only have one key set, duplicate for the other one
63 elif driver_key in record:
64 logger.warning("normalize_input: you should use '{}' instead of '{}'"
65 .format(reg_key, driver_key))
66 record[reg_key] = record[driver_key]
69 def normalize_input_record(record):
70 _normalize_input(record, 'reg-researchers', 'researcher')
71 _normalize_input(record, 'reg-pis', 'pi')
72 _normalize_input(record, 'reg-keys', 'keys')
73 # xxx the keys thing could use a little bit more attention:
74 # some parts of the code are using 'keys' while they should use 'reg-keys'
75 # but I run out of time for now
76 if 'reg-keys' in record:
77 record['keys'] = record['reg-keys']
81 class RegistryManager:
83 def __init__(self, config):
84 logger.debug("Creating RegistryManager[{}]".format(id(self)))
86 # The GENI GetVersion call
87 def GetVersion(self, api, options):
88 peers = {hrn: interface.get_url()
89 for (hrn, interface) in api.registries.items()
91 xrn = Xrn(api.hrn, type='authority')
92 return version_core({'interface': 'registry',
98 def GetCredential(self, api, xrn, input_type, caller_xrn=None):
101 hrn, _ = urn_to_hrn(xrn)
104 hrn, type = urn_to_hrn(xrn)
106 # Slivers don't have credentials but users should be able to
107 # specify a sliver xrn and receive the slice's credential
108 # However if input_type is specified
109 if type == 'sliver' or (not input_type and '-' in Xrn(hrn).leaf):
110 slice_xrn = api.driver.sliver_to_slice_xrn(hrn)
113 # Is this a root or sub authority
114 auth_hrn = api.auth.get_authority(hrn)
115 if not auth_hrn or hrn == api.config.SFA_INTERFACE_HRN:
117 auth_info = api.auth.get_auth_info(auth_hrn)
120 dbsession = api.dbsession()
121 record = dbsession.query(RegRecord).filter_by(
122 type=type, hrn=hrn).first()
124 raise RecordNotFound("hrn={}, type={}".format(hrn, type))
126 # get the callers gid
127 # if caller_xrn is not specified assume the caller is the record
131 caller_gid = record.get_gid_object()
133 caller_hrn, caller_type = urn_to_hrn(caller_xrn)
135 caller_record = dbsession.query(RegRecord).filter_by(
136 hrn=caller_hrn, type=caller_type).first()
138 caller_record = dbsession.query(
139 RegRecord).filter_by(hrn=caller_hrn).first()
140 if not caller_record:
141 raise RecordNotFound(
142 "Unable to associated caller (hrn={}, type={}) "
143 "with credential for (hrn: {}, type: {})"
144 .format(caller_hrn, caller_type, hrn, type))
145 caller_gid = GID(string=caller_record.gid)
147 object_hrn = record.get_gid_object().get_hrn()
148 # call the builtin authorization/credential generation engine
149 rights = api.auth.determine_user_rights(caller_hrn, record)
150 # make sure caller has rights to this object
151 if rights.is_empty():
152 raise PermissionError("{} has no rights to {} ({})"
153 .format(caller_hrn, object_hrn, xrn))
154 object_gid = GID(string=record.gid)
155 new_cred = Credential(subject=object_gid.get_subject())
156 new_cred.set_gid_caller(caller_gid)
157 new_cred.set_gid_object(object_gid)
158 new_cred.set_issuer_keys(
159 auth_info.get_privkey_filename(), auth_info.get_gid_filename())
160 # new_cred.set_pubkey(object_gid.get_pubkey())
161 new_cred.set_privileges(rights)
162 new_cred.get_privileges().delegate_all_privileges(True)
163 if hasattr(record, 'expires'):
164 date = utcparse(record.expires)
165 expires = datetime_to_epoch(date)
166 new_cred.set_expiration(int(expires))
167 auth_kind = "authority,ma,sa"
168 # Parent not necessary, verify with certs
169 # new_cred.set_parent(api.auth.hierarchy.get_auth_cred(auth_hrn, kind=auth_kind))
173 return new_cred.save_to_string(save_parents=True)
175 # the default for full, which means 'dig into the testbed as well', should
177 def Resolve(self, api, xrns, type=None, details=False):
179 dbsession = api.dbsession()
180 if not isinstance(xrns, list):
181 # try to infer type if not set and we get a single input
183 type = Xrn(xrns).get_type()
185 hrns = [urn_to_hrn(xrn)[0] for xrn in xrns]
187 # load all known registry names into a prefix tree and attempt to find
188 # the longest matching prefix
189 # create a dict where key is a registry hrn and its value is a list
190 # of hrns at that registry (determined by the known prefix tree).
192 registries = api.registries
194 registry_hrns = list(registries.keys())
195 tree.load(registry_hrns)
197 registry_hrn = tree.best_match(urn_to_hrn(xrn)[0])
198 if registry_hrn not in xrn_dict:
199 xrn_dict[registry_hrn] = []
200 xrn_dict[registry_hrn].append(xrn)
203 for registry_hrn in xrn_dict:
204 # skip the hrn without a registry hrn
205 # XX should we let the user know the authority is unknown?
209 # if the best match (longest matching hrn) is not the local registry,
210 # forward the request
211 xrns = xrn_dict[registry_hrn]
212 if registry_hrn != api.hrn:
213 credential = api.getCredential()
214 interface = api.registries[registry_hrn]
215 server_proxy = api.server_proxy(interface, credential)
216 # should propagate the details flag but that's not supported
217 # in the xmlrpc interface yet
218 # peer_records = server_proxy.Resolve(xrns, credential,type, details=details)
219 peer_records = server_proxy.Resolve(xrns, credential)
220 # pass foreign records as-is
221 # previous code used to read
222 # records.extend([SfaRecord(dict=record).as_dict() for record in peer_records])
223 # not sure why the records coming through xmlrpc had to be
225 records.extend(peer_records)
227 # try resolving the remaining unfound records at the local registry
228 local_hrns = list(set(hrns).difference(
229 [record['hrn'] for record in records]))
231 local_records = dbsession.query(RegRecord).filter(
232 RegRecord.hrn.in_(local_hrns))
234 local_records = local_records.filter_by(type=type)
235 local_records = local_records.all()
237 for local_record in local_records:
238 augment_with_sfa_builtins(local_record)
240 logger.info("Resolve, (details={}, type={}) local_records={} "
241 .format(details, type, local_records))
242 local_dicts = [record.__dict__ for record in local_records]
245 # in details mode we get as much info as we can, which involves contacting the
246 # testbed for getting implementation details about the record
247 api.driver.augment_records_with_testbed_info(local_dicts)
248 # also we fill the 'url' field for known authorities
249 # used to be in the driver code, sounds like a poorman thing though
251 def solve_neighbour_url(record):
252 if not record.type.startswith('authority'):
255 for neighbour_dict in [api.aggregates, api.registries]:
256 if hrn in neighbour_dict:
257 record.url = neighbour_dict[hrn].get_url()
259 for record in local_records:
260 solve_neighbour_url(record)
262 # convert local record objects to dicts for xmlrpc
263 # xxx somehow here calling dict(record) issues a weird error
264 # however record.todict() seems to work fine
265 # records.extend( [ dict(record) for record in local_records ] )
266 records.extend([record.record_to_dict(exclude_types=(
267 InstrumentedList,)) for record in local_records])
270 raise RecordNotFound(str(hrns))
274 def List(self, api, xrn, origin_hrn=None, options=None):
277 dbsession = api.dbsession()
278 # load all know registry names into a prefix tree and attempt to find
279 # the longest matching prefix
280 hrn, type = urn_to_hrn(xrn)
281 registries = api.registries
282 registry_hrns = list(registries.keys())
284 tree.load(registry_hrns)
285 registry_hrn = tree.best_match(hrn)
287 # if there was no match then this record belongs to an unknow registry
289 raise MissingAuthority(xrn)
290 # if the best match (longest matching hrn) is not the local registry,
291 # forward the request
293 if registry_hrn != api.hrn:
294 credential = api.getCredential()
295 interface = api.registries[registry_hrn]
296 server_proxy = api.server_proxy(interface, credential)
297 record_list = server_proxy.List(xrn, credential, options)
298 # same as above, no need to process what comes from through xmlrpc
299 # pass foreign records as-is
300 record_dicts = record_list
302 # if we still have not found the record yet, try the local registry
303 # logger.debug("before trying local records, {} foreign records"
304 # .format(len(record_dicts)))
307 if ('recursive' in options and options['recursive']):
309 elif hrn.endswith('*'):
313 if not api.auth.hierarchy.auth_exists(hrn):
314 raise MissingAuthority(hrn)
316 records = dbsession.query(RegRecord).filter(
317 RegRecord.hrn.startswith(hrn)).all()
318 # logger.debug("recursive mode, found {} local records".
319 # format(len(records)))
321 records = dbsession.query(
322 RegRecord).filter_by(authority=hrn).all()
323 # logger.debug("non recursive mode, found {} local records"
324 # .format(len(records)))
325 # so that sfi list can show more than plain names...
326 for record in records:
327 # xxx mystery - see also the bottom of model.py
328 # resulting records have been observed to not always have
329 # their __dict__ actually in line with the object's contents;
330 # was first observed with authorities' 'name' column
331 # that would be missing from result as received by client
332 augment_with_sfa_builtins(record)
333 record_dicts = [record.record_to_dict(
334 exclude_types=(InstrumentedList,)) for record in records]
338 def CreateGid(self, api, xrn, cert):
340 authority = Xrn(xrn=xrn).get_authority_hrn()
341 auth_info = api.auth.get_auth_info(authority)
343 pkey = Keypair(create=True)
345 certificate = Certificate(string=cert)
346 pkey = certificate.get_pubkey()
348 # Add the email of the user to SubjectAltName in the GID
350 hrn = Xrn(xrn).get_hrn()
351 dbsession = api.dbsession()
352 record = dbsession.query(RegUser).filter_by(hrn=hrn).first()
354 email = getattr(record, 'email', None)
355 gid = api.auth.hierarchy.create_gid(
356 xrn, create_uuid(), pkey, email=email)
357 return gid.save_to_string(save_parents=True)
360 # utility for handling relationships among the SFA objects
362 # subject_record describes the subject of the relationships
363 # ref_record contains the target values for the various relationships
364 # we need to manage (to begin with, this is just the
365 # slice x person (researcher) and authority x person (pi) relationships)
366 def update_driver_relations(self, api, subject_obj, ref_obj):
367 type = subject_obj.type
368 # for (k,v) in subject_obj.__dict__.items(): print k,'=',v
369 if type == 'slice' and hasattr(ref_obj, 'researcher'):
370 self.update_driver_relation(
371 api, subject_obj, ref_obj.researcher, 'user', 'researcher')
372 elif type == 'authority' and hasattr(ref_obj, 'pi'):
373 self.update_driver_relation(
374 api, subject_obj, ref_obj.pi, 'user', 'pi')
376 # field_key is the name of one field in the record,
377 # typically 'researcher' for a 'slice' record
378 # hrns is the list of hrns that should be linked to the subject from now on
379 # target_type would be e.g. 'user' in the 'slice' x 'researcher' example
380 def update_driver_relation(self, api, record_obj, hrns,
381 target_type, relation_name):
382 dbsession = api.dbsession()
383 # locate the linked objects in our db
384 subject_type = record_obj.type
385 subject_id = record_obj.pointer
386 # get the 'pointer' field of all matching records
387 link_id_tuples = dbsession.query(RegRecord.pointer).filter_by(
388 type=target_type).filter(RegRecord.hrn.in_(hrns)).all()
389 # sqlalchemy returns named tuples for columns
390 link_ids = [tuple.pointer for tuple in link_id_tuples]
391 api.driver.update_relation(
392 subject_type, target_type, relation_name, subject_id, link_ids)
394 def Register(self, api, record_dict):
396 logger.debug("Register: entering with record_dict={}".format(
397 printable(record_dict)))
398 normalize_input_record(record_dict)
399 logger.debug("Register: normalized record_dict={}".format(
400 printable(record_dict)))
402 dbsession = api.dbsession()
403 hrn, type = record_dict['hrn'], record_dict['type']
404 urn = hrn_to_urn(hrn, type)
406 if type not in ['authority', 'slice', 'node', 'user']:
407 raise UnknownSfaType(type)
409 # check if record_dict already exists
410 existing_records = dbsession.query(
411 RegRecord).filter_by(type=type, hrn=hrn).all()
413 raise ExistingRecord(hrn)
415 assert ('type' in record_dict)
416 # returns the right type of RegRecord according to type in record
417 record = make_record(dict=record_dict)
418 record.just_created()
419 record.authority = get_authority(record.hrn)
420 auth_info = api.auth.get_auth_info(record.authority)
422 # make sure record has a gid
425 pkey = Keypair(create=True)
426 pub_key = getattr(record, 'reg-keys', None)
427 if pub_key is not None:
428 # use only first key in record
429 if pub_key and isinstance(pub_key, list):
431 pkey = convert_public_key(pub_key)
433 email = getattr(record, 'email', None)
434 gid_object = api.auth.hierarchy.create_gid(
435 urn, uuid, pkey, email=email)
436 gid = gid_object.save_to_string(save_parents=True)
439 if isinstance(record, RegAuthority):
441 if not api.auth.hierarchy.auth_exists(hrn):
442 api.auth.hierarchy.create_auth(hrn_to_urn(hrn, 'authority'))
444 # get the GID from the newly created authority
445 auth_info = api.auth.get_auth_info(hrn)
446 gid = auth_info.get_gid_object()
447 record.gid = gid.save_to_string(save_parents=True)
449 # locate objects for relationships
450 pi_hrns = getattr(record, 'reg-pis', None)
451 if pi_hrns is not None:
452 record.update_pis(pi_hrns, dbsession)
454 elif isinstance(record, RegSlice):
455 researcher_hrns = getattr(record, 'reg-researchers', None)
456 if researcher_hrns is not None:
457 record.update_researchers(researcher_hrns, dbsession)
459 elif isinstance(record, RegUser):
460 # create RegKey objects for incoming keys
461 if hasattr(record, 'reg-keys'):
462 keys = getattr(record, 'reg-keys')
463 # some people send the key as a string instead of a list of strings
464 # note for python2/3 : no need to consider unicode in a key
465 if isinstance(keys, str):
467 logger.debug("creating {} keys for user {}".format(
468 len(keys), record.hrn))
469 record.reg_keys = [RegKey(key) for key in keys]
471 # update testbed-specific data if needed
472 pointer = api.driver.register(record.__dict__, hrn, pub_key)
474 record.pointer = pointer
475 dbsession.add(record)
478 # update membership for researchers, pis, owners, operators
479 self.update_driver_relations(api, record, record)
481 return record.get_gid_object().save_to_string(save_parents=True)
483 def Update(self, api, record_dict):
485 logger.debug("Update: entering with record_dict={}".format(
486 printable(record_dict)))
487 normalize_input_record(record_dict)
488 logger.debug("Update: normalized record_dict={}".format(
489 printable(record_dict)))
491 dbsession = api.dbsession()
492 assert ('type' in record_dict)
493 new_record = make_record(dict=record_dict)
494 (type, hrn) = (new_record.type, new_record.hrn)
496 # make sure the record exists
497 record = dbsession.query(RegRecord).filter_by(
498 type=type, hrn=hrn).first()
500 raise RecordNotFound("hrn={}, type={}".format(hrn, type))
501 record.just_updated()
503 # Use the pointer from the existing record, not the one that the user
504 # gave us. This prevents the user from inserting a forged pointer
505 pointer = record.pointer
507 # is there a change in keys ?
510 if getattr(new_record, 'keys', None):
511 new_key = new_record.keys
512 if isinstance(new_key, list):
515 # take new_key into account
517 # update the openssl key and gid
518 pkey = convert_public_key(new_key)
520 urn = hrn_to_urn(hrn, type)
522 email = getattr(new_record, 'email', None)
524 email = getattr(record, 'email', None)
525 gid_object = api.auth.hierarchy.create_gid(
526 urn, uuid, pkey, email=email)
527 gid = gid_object.save_to_string(save_parents=True)
529 # xxx should do side effects from new_record to record
530 # not too sure how to do that
531 # not too big a deal with planetlab as the driver is authoritative,
534 # update native relations
535 if isinstance(record, RegSlice):
536 researcher_hrns = getattr(new_record, 'reg-researchers', None)
537 if researcher_hrns is not None:
538 record.update_researchers(researcher_hrns, dbsession)
540 elif isinstance(record, RegAuthority):
541 pi_hrns = getattr(new_record, 'reg-pis', None)
542 if pi_hrns is not None:
543 record.update_pis(pi_hrns, dbsession)
544 name = getattr(new_record, 'name', None)
548 elif isinstance(record, RegUser):
549 email = getattr(new_record, 'email', None)
550 if email is not None:
553 # update the PLC information that was specified with the record
554 # xxx mystery -- see also the bottom of model.py,
555 # oddly enough, without this useless statement,
556 # record.__dict__ as received by the driver seems to be off
557 # anyway the driver should receive an object
558 # (and then extract __dict__ itself if needed)
559 print("DO NOT REMOVE ME before driver.update, record={}".format(record))
560 # as of June 2015: I suspect we could remove that print line above and replace it with
561 # augment_with_sfa_builtins(record)
562 # instead, that checks for these fields, like it is done above in List()
563 # but that would need to be confirmed by more extensive tests
566 (pointer, new_key_pointer) = api.driver.update(
567 record.__dict__, new_record.__dict__, hrn, new_key)
570 if new_key and new_key_pointer:
571 record.reg_keys = [RegKey(new_key, new_key_pointer)]
575 # update membership for researchers, pis, owners, operators
576 self.update_driver_relations(api, record, new_record)
580 # expecting an Xrn instance
581 def Remove(self, api, xrn, origin_hrn=None):
582 dbsession = api.dbsession()
584 type = xrn.get_type()
585 request = dbsession.query(RegRecord).filter_by(hrn=hrn)
586 if type and type not in ['all', '*']:
587 request = request.filter_by(type=type)
589 record = request.first()
591 msg = "Could not find hrn {}".format(hrn)
593 msg += " type={}".format(type)
594 raise RecordNotFound(msg)
597 if type not in ['slice', 'user', 'node', 'authority']:
598 raise UnknownSfaType(type)
600 registries = api.registries
602 # Try to remove the object from the PLCDB of federated agg.
603 # This is attempted before removing the object from the local agg's
604 # PLCDB and sfa table
605 if hrn.startswith(api.hrn) and type in ['user', 'slice', 'authority']:
606 for registry in registries:
607 if registry not in [api.hrn]:
609 credential = api.getCredential()
610 result = registries[registry].remove_peer_object(
611 credential, record, origin_hrn)
615 # call testbed callback first
616 # IIUC this is done on the local testbed TOO because of the refreshpeer
618 if not api.driver.remove(record.__dict__):
619 logger.warning("driver.remove failed")
622 dbsession.delete(record)
627 # This is a PLC-specific thing, won't work with other platforms
628 def get_key_from_incoming_ip(self, api):
629 dbsession = api.dbsession()
630 # verify that the callers's ip address exist in the db and is an interface
631 # for a node in the db
632 (ip, port) = api.remote_addr
633 interfaces = api.driver.shell.GetInterfaces({'ip': ip}, ['node_id'])
635 raise NonExistingRecord("no such ip {}".format(ip))
636 nodes = api.driver.shell.GetNodes(
637 [interfaces[0]['node_id']], ['node_id', 'hostname'])
639 raise NonExistingRecord("no such node using ip {}".format(ip))
642 # look up the sfa record
643 record = dbsession.query(RegRecord).filter_by(
644 type='node', pointer=node['node_id']).first()
646 raise RecordNotFound(
647 "node with pointer {}".format(node['node_id']))
649 # generate a new keypair and gid
651 pkey = Keypair(create=True)
652 urn = hrn_to_urn(record.hrn, record.type)
654 email = getattr(record, 'email', None)
655 gid_object = api.auth.hierarchy.create_gid(urn, uuid, pkey, email)
656 gid = gid_object.save_to_string(save_parents=True)
662 # attempt the scp the key
663 # and gid onto the node
664 # this will only work for planetlab based components
665 (kfd, key_filename) = tempfile.mkstemp()
666 (gfd, gid_filename) = tempfile.mkstemp()
667 pkey.save_to_file(key_filename)
668 gid_object.save_to_file(gid_filename, save_parents=True)
669 host = node['hostname']
670 key_dest = "/etc/sfa/node.key"
671 gid_dest = "/etc/sfa/node.gid"
673 #identity = "/etc/planetlab/root_ssh_key.rsa"
674 identity = "/etc/sfa/root_ssh_key"
675 scp_options = " -i {identity} ".format(**locals())
676 scp_options += "-o StrictHostKeyChecking=no "
677 scp_key_command = "{scp} {scp_options} {key_filename} root@{host}:{key_dest}"\
679 scp_gid_command = "{scp} {scp_options} {gid_filename} root@{host}:{gid_dest}"\
682 all_commands = [scp_key_command, scp_gid_command]
684 for command in all_commands:
685 (status, output) = subprocess.getstatusoutput(command)
687 raise Exception(output)
689 for filename in [key_filename, gid_filename]: