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
48 def _normalize_input(record, reg_key, driver_key):
49 # this looks right, use this for both keys
51 # and issue a warning if they were both set and different
52 # as we're overwriting some user data here
53 if driver_key in record:
54 logger.warning("normalize_input: incoming record has both values, using {}"
56 record[driver_key] = record[reg_key]
57 # we only have one key set, duplicate for the other one
58 elif driver_key in record:
59 logger.warning("normalize_input: you should use '{}' instead of '{}'"
60 .format(reg_key, driver_key))
61 record[reg_key] = record[driver_key]
64 def normalize_input_record(record):
65 _normalize_input(record, 'reg-researchers', 'researcher')
66 _normalize_input(record, 'reg-pis', 'pi')
67 _normalize_input(record, 'reg-keys', 'keys')
68 # xxx the keys thing could use a little bit more attention:
69 # some parts of the code are using 'keys' while they should use 'reg-keys'
70 # but I run out of time for now
71 if 'reg-keys' in record:
72 record['keys'] = record['reg-keys']
76 class RegistryManager:
78 def __init__(self, config):
79 logger.info("Creating RegistryManager[{}]".format(id(self)))
81 # The GENI GetVersion call
82 def GetVersion(self, api, options):
83 peers = dict([(hrn, interface.get_url()) for (hrn, interface) in api.registries.iteritems()
85 xrn = Xrn(api.hrn, type='authority')
86 return version_core({'interface': 'registry',
92 def GetCredential(self, api, xrn, input_type, caller_xrn=None):
95 hrn, _ = urn_to_hrn(xrn)
98 hrn, type = urn_to_hrn(xrn)
100 # Slivers don't have credentials but users should be able to
101 # specify a sliver xrn and receive the slice's credential
102 # However if input_type is specified
103 if type == 'sliver' or (not input_type and '-' in Xrn(hrn).leaf):
104 slice_xrn = api.driver.sliver_to_slice_xrn(hrn)
107 # Is this a root or sub authority
108 auth_hrn = api.auth.get_authority(hrn)
109 if not auth_hrn or hrn == api.config.SFA_INTERFACE_HRN:
111 auth_info = api.auth.get_auth_info(auth_hrn)
114 dbsession = api.dbsession()
115 record = dbsession.query(RegRecord).filter_by(
116 type=type, hrn=hrn).first()
118 raise RecordNotFound("hrn={}, type={}".format(hrn, type))
120 # get the callers gid
121 # if caller_xrn is not specified assume the caller is the record
125 caller_gid = record.get_gid_object()
127 caller_hrn, caller_type = urn_to_hrn(caller_xrn)
129 caller_record = dbsession.query(RegRecord).filter_by(
130 hrn=caller_hrn, type=caller_type).first()
132 caller_record = dbsession.query(
133 RegRecord).filter_by(hrn=caller_hrn).first()
134 if not caller_record:
135 raise RecordNotFound(
136 "Unable to associated caller (hrn={}, type={}) with credential for (hrn: {}, type: {})"
137 .format(caller_hrn, caller_type, hrn, type))
138 caller_gid = GID(string=caller_record.gid)
140 object_hrn = record.get_gid_object().get_hrn()
141 # call the builtin authorization/credential generation engine
142 rights = api.auth.determine_user_rights(caller_hrn, record)
143 # make sure caller has rights to this object
144 if rights.is_empty():
145 raise PermissionError("{} has no rights to {} ({})"
146 .format(caller_hrn, object_hrn, xrn))
147 object_gid = GID(string=record.gid)
148 new_cred = Credential(subject=object_gid.get_subject())
149 new_cred.set_gid_caller(caller_gid)
150 new_cred.set_gid_object(object_gid)
151 new_cred.set_issuer_keys(
152 auth_info.get_privkey_filename(), auth_info.get_gid_filename())
153 # new_cred.set_pubkey(object_gid.get_pubkey())
154 new_cred.set_privileges(rights)
155 new_cred.get_privileges().delegate_all_privileges(True)
156 if hasattr(record, 'expires'):
157 date = utcparse(record.expires)
158 expires = datetime_to_epoch(date)
159 new_cred.set_expiration(int(expires))
160 auth_kind = "authority,ma,sa"
161 # Parent not necessary, verify with certs
162 #new_cred.set_parent(api.auth.hierarchy.get_auth_cred(auth_hrn, kind=auth_kind))
166 return new_cred.save_to_string(save_parents=True)
168 # the default for full, which means 'dig into the testbed as well', should
170 def Resolve(self, api, xrns, type=None, details=False):
172 dbsession = api.dbsession()
173 if not isinstance(xrns, list):
174 # try to infer type if not set and we get a single input
176 type = Xrn(xrns).get_type()
178 hrns = [urn_to_hrn(xrn)[0] for xrn in xrns]
180 # load all known registry names into a prefix tree and attempt to find
181 # the longest matching prefix
182 # create a dict where key is a registry hrn and its value is a list
183 # of hrns at that registry (determined by the known prefix tree).
185 registries = api.registries
187 registry_hrns = registries.keys()
188 tree.load(registry_hrns)
190 registry_hrn = tree.best_match(urn_to_hrn(xrn)[0])
191 if registry_hrn not in xrn_dict:
192 xrn_dict[registry_hrn] = []
193 xrn_dict[registry_hrn].append(xrn)
196 for registry_hrn in xrn_dict:
197 # skip the hrn without a registry hrn
198 # XX should we let the user know the authority is unknown?
202 # if the best match (longest matching hrn) is not the local registry,
203 # forward the request
204 xrns = xrn_dict[registry_hrn]
205 if registry_hrn != api.hrn:
206 credential = api.getCredential()
207 interface = api.registries[registry_hrn]
208 server_proxy = api.server_proxy(interface, credential)
209 # should propagate the details flag but that's not supported in the xmlrpc interface yet
210 #peer_records = server_proxy.Resolve(xrns, credential,type, details=details)
211 peer_records = server_proxy.Resolve(xrns, credential)
212 # pass foreign records as-is
213 # previous code used to read
214 # records.extend([SfaRecord(dict=record).as_dict() for record in peer_records])
215 # not sure why the records coming through xmlrpc had to be
217 records.extend(peer_records)
219 # try resolving the remaining unfound records at the local registry
220 local_hrns = list(set(hrns).difference(
221 [record['hrn'] for record in records]))
223 local_records = dbsession.query(RegRecord).filter(
224 RegRecord.hrn.in_(local_hrns))
226 local_records = local_records.filter_by(type=type)
227 local_records = local_records.all()
229 for local_record in local_records:
230 augment_with_sfa_builtins(local_record)
232 logger.info("Resolve, (details={}, type={}) local_records={} "
233 .format(details, type, local_records))
234 local_dicts = [record.__dict__ for record in local_records]
237 # in details mode we get as much info as we can, which involves contacting the
238 # testbed for getting implementation details about the record
239 api.driver.augment_records_with_testbed_info(local_dicts)
240 # also we fill the 'url' field for known authorities
241 # used to be in the driver code, sounds like a poorman thing though
243 def solve_neighbour_url(record):
244 if not record.type.startswith('authority'):
247 for neighbour_dict in [api.aggregates, api.registries]:
248 if hrn in neighbour_dict:
249 record.url = neighbour_dict[hrn].get_url()
251 for record in local_records:
252 solve_neighbour_url(record)
254 # convert local record objects to dicts for xmlrpc
255 # xxx somehow here calling dict(record) issues a weird error
256 # however record.todict() seems to work fine
257 # records.extend( [ dict(record) for record in local_records ] )
258 records.extend([record.record_to_dict(exclude_types=(
259 InstrumentedList,)) for record in local_records])
262 raise RecordNotFound(str(hrns))
266 def List(self, api, xrn, origin_hrn=None, options=None):
269 dbsession = api.dbsession()
270 # load all know registry names into a prefix tree and attempt to find
271 # the longest matching prefix
272 hrn, type = urn_to_hrn(xrn)
273 registries = api.registries
274 registry_hrns = registries.keys()
276 tree.load(registry_hrns)
277 registry_hrn = tree.best_match(hrn)
279 # if there was no match then this record belongs to an unknow registry
281 raise MissingAuthority(xrn)
282 # if the best match (longest matching hrn) is not the local registry,
283 # forward the request
285 if registry_hrn != api.hrn:
286 credential = api.getCredential()
287 interface = api.registries[registry_hrn]
288 server_proxy = api.server_proxy(interface, credential)
289 record_list = server_proxy.List(xrn, credential, options)
290 # same as above, no need to process what comes from through xmlrpc
291 # pass foreign records as-is
292 record_dicts = record_list
294 # if we still have not found the record yet, try the local registry
295 # logger.debug("before trying local records, {} foreign records".format(len(record_dicts)))
298 if ('recursive' in options and options['recursive']):
300 elif hrn.endswith('*'):
304 if not api.auth.hierarchy.auth_exists(hrn):
305 raise MissingAuthority(hrn)
307 records = dbsession.query(RegRecord).filter(
308 RegRecord.hrn.startswith(hrn)).all()
309 # logger.debug("recursive mode, found {} local records".format(len(records)))
311 records = dbsession.query(
312 RegRecord).filter_by(authority=hrn).all()
313 # logger.debug("non recursive mode, found {} local records".format(len(records)))
314 # so that sfi list can show more than plain names...
315 for record in records:
316 # xxx mystery - see also the bottom of model.py
317 # resulting records have been observed to not always have
318 # their __dict__ actually in line with the object's contents;
319 # was first observed with authorities' 'name' column
320 # that would be missing from result as received by client
321 augment_with_sfa_builtins(record)
322 record_dicts = [record.record_to_dict(
323 exclude_types=(InstrumentedList,)) for record in records]
327 def CreateGid(self, api, xrn, cert):
329 authority = Xrn(xrn=xrn).get_authority_hrn()
330 auth_info = api.auth.get_auth_info(authority)
332 pkey = Keypair(create=True)
334 certificate = Certificate(string=cert)
335 pkey = certificate.get_pubkey()
337 # Add the email of the user to SubjectAltName in the GID
339 hrn = Xrn(xrn).get_hrn()
340 dbsession = api.dbsession()
341 record = dbsession.query(RegUser).filter_by(hrn=hrn).first()
343 email = getattr(record, 'email', None)
344 gid = api.auth.hierarchy.create_gid(
345 xrn, create_uuid(), pkey, email=email)
346 return gid.save_to_string(save_parents=True)
349 # utility for handling relationships among the SFA objects
351 # subject_record describes the subject of the relationships
352 # ref_record contains the target values for the various relationships we need to manage
353 # (to begin with, this is just the slice x person (researcher) and authority x person (pi) relationships)
354 def update_driver_relations(self, api, subject_obj, ref_obj):
355 type = subject_obj.type
356 # for (k,v) in subject_obj.__dict__.items(): print k,'=',v
357 if type == 'slice' and hasattr(ref_obj, 'researcher'):
358 self.update_driver_relation(
359 api, subject_obj, ref_obj.researcher, 'user', 'researcher')
360 elif type == 'authority' and hasattr(ref_obj, 'pi'):
361 self.update_driver_relation(
362 api, subject_obj, ref_obj.pi, 'user', 'pi')
364 # field_key is the name of one field in the record, typically 'researcher' for a 'slice' record
365 # hrns is the list of hrns that should be linked to the subject from now on
366 # target_type would be e.g. 'user' in the 'slice' x 'researcher' example
367 def update_driver_relation(self, api, record_obj, hrns, target_type, relation_name):
368 dbsession = api.dbsession()
369 # locate the linked objects in our db
370 subject_type = record_obj.type
371 subject_id = record_obj.pointer
372 # get the 'pointer' field of all matching records
373 link_id_tuples = dbsession.query(RegRecord.pointer).filter_by(
374 type=target_type).filter(RegRecord.hrn.in_(hrns)).all()
375 # sqlalchemy returns named tuples for columns
376 link_ids = [tuple.pointer for tuple in link_id_tuples]
377 api.driver.update_relation(
378 subject_type, target_type, relation_name, subject_id, link_ids)
380 def Register(self, api, record_dict):
382 logger.debug("Register: entering with record_dict={}".format(
383 printable(record_dict)))
384 normalize_input_record(record_dict)
385 logger.debug("Register: normalized record_dict={}".format(
386 printable(record_dict)))
388 dbsession = api.dbsession()
389 hrn, type = record_dict['hrn'], record_dict['type']
390 urn = hrn_to_urn(hrn, type)
392 if type not in ['authority', 'slice', 'node', 'user']:
393 raise UnknownSfaType(type)
395 # check if record_dict already exists
396 existing_records = dbsession.query(
397 RegRecord).filter_by(type=type, hrn=hrn).all()
399 raise ExistingRecord(hrn)
401 assert ('type' in record_dict)
402 # returns the right type of RegRecord according to type in record
403 record = make_record(dict=record_dict)
404 record.just_created()
405 record.authority = get_authority(record.hrn)
406 auth_info = api.auth.get_auth_info(record.authority)
408 # make sure record has a gid
411 pkey = Keypair(create=True)
412 pub_key = getattr(record, 'reg-keys', None)
413 if pub_key is not None:
414 # use only first key in record
415 if pub_key and isinstance(pub_key, list):
417 pkey = convert_public_key(pub_key)
419 email = getattr(record, 'email', None)
420 gid_object = api.auth.hierarchy.create_gid(
421 urn, uuid, pkey, email=email)
422 gid = gid_object.save_to_string(save_parents=True)
425 if isinstance(record, RegAuthority):
427 if not api.auth.hierarchy.auth_exists(hrn):
428 api.auth.hierarchy.create_auth(hrn_to_urn(hrn, 'authority'))
430 # get the GID from the newly created authority
431 auth_info = api.auth.get_auth_info(hrn)
432 gid = auth_info.get_gid_object()
433 record.gid = gid.save_to_string(save_parents=True)
435 # locate objects for relationships
436 pi_hrns = getattr(record, 'reg-pis', None)
437 if pi_hrns is not None:
438 record.update_pis(pi_hrns, dbsession)
440 elif isinstance(record, RegSlice):
441 researcher_hrns = getattr(record, 'reg-researchers', None)
442 if researcher_hrns is not None:
443 record.update_researchers(researcher_hrns, dbsession)
445 elif isinstance(record, RegUser):
446 # create RegKey objects for incoming keys
447 if hasattr(record, 'reg-keys'):
448 keys = getattr(record, 'reg-keys')
449 # some people send the key as a string instead of a list of strings
450 # note for python2/3 : no need to consider unicode in a key
451 if isinstance(keys, str):
453 logger.debug("creating {} keys for user {}".format(
454 len(keys), record.hrn))
455 record.reg_keys = [RegKey(key) for key in keys]
457 # update testbed-specific data if needed
458 pointer = api.driver.register(record.__dict__, hrn, pub_key)
460 record.pointer = pointer
461 dbsession.add(record)
464 # update membership for researchers, pis, owners, operators
465 self.update_driver_relations(api, record, record)
467 return record.get_gid_object().save_to_string(save_parents=True)
469 def Update(self, api, record_dict):
471 logger.debug("Update: entering with record_dict={}".format(
472 printable(record_dict)))
473 normalize_input_record(record_dict)
474 logger.debug("Update: normalized record_dict={}".format(
475 printable(record_dict)))
477 dbsession = api.dbsession()
478 assert ('type' in record_dict)
479 new_record = make_record(dict=record_dict)
480 (type, hrn) = (new_record.type, new_record.hrn)
482 # make sure the record exists
483 record = dbsession.query(RegRecord).filter_by(
484 type=type, hrn=hrn).first()
486 raise RecordNotFound("hrn={}, type={}".format(hrn, type))
487 record.just_updated()
489 # Use the pointer from the existing record, not the one that the user
490 # gave us. This prevents the user from inserting a forged pointer
491 pointer = record.pointer
493 # is there a change in keys ?
496 if getattr(new_record, 'keys', None):
497 new_key = new_record.keys
498 if isinstance(new_key, list):
501 # take new_key into account
503 # update the openssl key and gid
504 pkey = convert_public_key(new_key)
506 urn = hrn_to_urn(hrn, type)
508 email = getattr(new_record, 'email', None)
510 email = getattr(record, 'email', None)
511 gid_object = api.auth.hierarchy.create_gid(
512 urn, uuid, pkey, email=email)
513 gid = gid_object.save_to_string(save_parents=True)
515 # xxx should do side effects from new_record to record
516 # not too sure how to do that
517 # not too big a deal with planetlab as the driver is authoritative,
520 # update native relations
521 if isinstance(record, RegSlice):
522 researcher_hrns = getattr(new_record, 'reg-researchers', None)
523 if researcher_hrns is not None:
524 record.update_researchers(researcher_hrns, dbsession)
526 elif isinstance(record, RegAuthority):
527 pi_hrns = getattr(new_record, 'reg-pis', None)
528 if pi_hrns is not None:
529 record.update_pis(pi_hrns, dbsession)
530 name = getattr(new_record, 'name', None)
534 elif isinstance(record, RegUser):
535 email = getattr(new_record, 'email', None)
536 if email is not None:
539 # update the PLC information that was specified with the record
540 # xxx mystery -- see also the bottom of model.py,
541 # oddly enough, without this useless statement,
542 # record.__dict__ as received by the driver seems to be off
543 # anyway the driver should receive an object
544 # (and then extract __dict__ itself if needed)
545 print("DO NOT REMOVE ME before driver.update, record={}".format(record))
546 # as of June 2015: I suspect we could remove that print line above and replace it with
547 # augment_with_sfa_builtins(record)
548 # instead, that checks for these fields, like it is done above in List()
549 # but that would need to be confirmed by more extensive tests
552 (pointer, new_key_pointer) = api.driver.update(
553 record.__dict__, new_record.__dict__, hrn, new_key)
556 if new_key and new_key_pointer:
557 record.reg_keys = [RegKey(new_key, new_key_pointer)]
561 # update membership for researchers, pis, owners, operators
562 self.update_driver_relations(api, record, new_record)
566 # expecting an Xrn instance
567 def Remove(self, api, xrn, origin_hrn=None):
568 dbsession = api.dbsession()
570 type = xrn.get_type()
571 request = dbsession.query(RegRecord).filter_by(hrn=hrn)
572 if type and type not in ['all', '*']:
573 request = request.filter_by(type=type)
575 record = request.first()
577 msg = "Could not find hrn {}".format(hrn)
579 msg += " type={}".format(type)
580 raise RecordNotFound(msg)
583 if type not in ['slice', 'user', 'node', 'authority']:
584 raise UnknownSfaType(type)
586 registries = api.registries
588 # Try to remove the object from the PLCDB of federated agg.
589 # This is attempted before removing the object from the local agg's
590 # PLCDB and sfa table
591 if hrn.startswith(api.hrn) and type in ['user', 'slice', 'authority']:
592 for registry in registries:
593 if registry not in [api.hrn]:
595 credential = api.getCredential()
596 result = registries[registry].remove_peer_object(
597 credential, record, origin_hrn)
601 # call testbed callback first
602 # IIUC this is done on the local testbed TOO because of the refreshpeer
604 if not api.driver.remove(record.__dict__):
605 logger.warning("driver.remove failed")
608 dbsession.delete(record)
613 # This is a PLC-specific thing, won't work with other platforms
614 def get_key_from_incoming_ip(self, api):
615 dbsession = api.dbsession()
616 # verify that the callers's ip address exist in the db and is an interface
617 # for a node in the db
618 (ip, port) = api.remote_addr
619 interfaces = api.driver.shell.GetInterfaces({'ip': ip}, ['node_id'])
621 raise NonExistingRecord("no such ip {}".format(ip))
622 nodes = api.driver.shell.GetNodes(
623 [interfaces[0]['node_id']], ['node_id', 'hostname'])
625 raise NonExistingRecord("no such node using ip {}".format(ip))
628 # look up the sfa record
629 record = dbsession.query(RegRecord).filter_by(
630 type='node', pointer=node['node_id']).first()
632 raise RecordNotFound(
633 "node with pointer {}".format(node['node_id']))
635 # generate a new keypair and gid
637 pkey = Keypair(create=True)
638 urn = hrn_to_urn(record.hrn, record.type)
640 email = getattr(record, 'email', None)
641 gid_object = api.auth.hierarchy.create_gid(urn, uuid, pkey, email)
642 gid = gid_object.save_to_string(save_parents=True)
648 # attempt the scp the key
649 # and gid onto the node
650 # this will only work for planetlab based components
651 (kfd, key_filename) = tempfile.mkstemp()
652 (gfd, gid_filename) = tempfile.mkstemp()
653 pkey.save_to_file(key_filename)
654 gid_object.save_to_file(gid_filename, save_parents=True)
655 host = node['hostname']
656 key_dest = "/etc/sfa/node.key"
657 gid_dest = "/etc/sfa/node.gid"
659 #identity = "/etc/planetlab/root_ssh_key.rsa"
660 identity = "/etc/sfa/root_ssh_key"
661 scp_options = " -i {identity} ".format(**locals())
662 scp_options += "-o StrictHostKeyChecking=no "
663 scp_key_command = "{scp} {scp_options} {key_filename} root@{host}:{key_dest}"\
665 scp_gid_command = "{scp} {scp_options} {gid_filename} root@{host}:{gid_dest}"\
668 all_commands = [scp_key_command, scp_gid_command]
670 for command in all_commands:
671 (status, output) = commands.getstatusoutput(command)
673 raise Exception(output)
675 for filename in [key_filename, gid_filename]: