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.trust.gid import GID
16 from sfa.trust.credential import Credential
17 from sfa.trust.certificate import Certificate, Keypair, convert_public_key
18 from sfa.trust.gid import create_uuid
20 from sfa.storage.model import make_record, RegRecord, RegAuthority, RegUser, RegSlice, RegKey
21 from sfa.storage.alchemy import dbsession
23 class RegistryManager:
25 def __init__ (self, config): pass
27 # The GENI GetVersion call
28 def GetVersion(self, api, options):
29 peers = dict ( [ (hrn,interface.get_url()) for (hrn,interface) in api.registries.iteritems()
32 return version_core({'interface':'registry',
39 def GetCredential(self, api, xrn, type, caller_xrn=None):
42 hrn = urn_to_hrn(xrn)[0]
44 hrn, type = urn_to_hrn(xrn)
46 # Is this a root or sub authority
47 auth_hrn = api.auth.get_authority(hrn)
48 if not auth_hrn or hrn == api.config.SFA_INTERFACE_HRN:
50 auth_info = api.auth.get_auth_info(auth_hrn)
52 record=dbsession.query(RegRecord).filter_by(type=type,hrn=hrn).first()
54 raise RecordNotFound("hrn=%s, type=%s"%(hrn,type))
56 # xxx for the record only
57 # used to call this, which was wrong, now all needed data is natively is our DB
58 # self.driver.augment_records_with_testbed_info (record.__dict__)
59 # likewise, we deprecate is_enabled which was not really useful
60 # if not self.driver.is_enabled (record.__dict__): ...
61 # xxx for the record only
64 # if caller_xrn is not specified assume the caller is the record
68 caller_gid = record.get_gid_object()
70 caller_hrn, caller_type = urn_to_hrn(caller_xrn)
72 caller_record = dbsession.query(RegRecord).filter_by(hrn=caller_hrn,type=caller_type).first()
74 caller_record = dbsession.query(RegRecord).filter_by(hrn=caller_hrn).first()
76 raise RecordNotFound("Unable to associated caller (hrn=%s, type=%s) with credential for (hrn: %s, type: %s)"%(caller_hrn, caller_type, hrn, type))
77 caller_gid = GID(string=caller_record.gid)
79 object_hrn = record.get_gid_object().get_hrn()
80 # call the builtin authorization/credential generation engine
81 rights = api.auth.determine_user_rights(caller_hrn, record)
82 # make sure caller has rights to this object
84 raise PermissionError("%s has no rights to %s (%s)" % \
85 (caller_hrn, object_hrn, xrn))
86 object_gid = GID(string=record.gid)
87 new_cred = Credential(subject = object_gid.get_subject())
88 new_cred.set_gid_caller(caller_gid)
89 new_cred.set_gid_object(object_gid)
90 new_cred.set_issuer_keys(auth_info.get_privkey_filename(), auth_info.get_gid_filename())
91 #new_cred.set_pubkey(object_gid.get_pubkey())
92 new_cred.set_privileges(rights)
93 new_cred.get_privileges().delegate_all_privileges(True)
94 if hasattr(record,'expires'):
95 date = utcparse(record.expires)
96 expires = datetime_to_epoch(date)
97 new_cred.set_expiration(int(expires))
98 auth_kind = "authority,ma,sa"
99 # Parent not necessary, verify with certs
100 #new_cred.set_parent(api.auth.hierarchy.get_auth_cred(auth_hrn, kind=auth_kind))
104 return new_cred.save_to_string(save_parents=True)
107 def Resolve(self, api, xrns, type=None, full=True):
109 if not isinstance(xrns, types.ListType):
110 # try to infer type if not set and we get a single input
112 type = Xrn(xrns).get_type()
114 hrns = [urn_to_hrn(xrn)[0] for xrn in xrns]
116 # load all known registry names into a prefix tree and attempt to find
117 # the longest matching prefix
118 # create a dict where key is a registry hrn and its value is a list
119 # of hrns at that registry (determined by the known prefix tree).
121 registries = api.registries
123 registry_hrns = registries.keys()
124 tree.load(registry_hrns)
126 registry_hrn = tree.best_match(urn_to_hrn(xrn)[0])
127 if registry_hrn not in xrn_dict:
128 xrn_dict[registry_hrn] = []
129 xrn_dict[registry_hrn].append(xrn)
132 for registry_hrn in xrn_dict:
133 # skip the hrn without a registry hrn
134 # XX should we let the user know the authority is unknown?
138 # if the best match (longest matching hrn) is not the local registry,
139 # forward the request
140 xrns = xrn_dict[registry_hrn]
141 if registry_hrn != api.hrn:
142 credential = api.getCredential()
143 interface = api.registries[registry_hrn]
144 server_proxy = api.server_proxy(interface, credential)
145 peer_records = server_proxy.Resolve(xrns, credential,type)
146 # pass foreign records as-is
147 # previous code used to read
148 # records.extend([SfaRecord(dict=record).as_dict() for record in peer_records])
149 # not sure why the records coming through xmlrpc had to be processed at all
150 records.extend(peer_records)
152 # try resolving the remaining unfound records at the local registry
153 local_hrns = list ( set(hrns).difference([record['hrn'] for record in records]) )
155 local_records = dbsession.query(RegRecord).filter(RegRecord.hrn.in_(local_hrns))
157 local_records = local_records.filter_by(type=type)
158 local_records=local_records.all()
159 logger.info("Resolve: local_records=%s (type=%s)"%(local_records,type))
160 local_dicts = [ record.__dict__ for record in local_records ]
163 # in full mode we get as much info as we can, which involves contacting the
164 # testbed for getting implementation details about the record
165 self.driver.augment_records_with_testbed_info(local_dicts)
166 # also we fill the 'url' field for known authorities
167 # used to be in the driver code, sounds like a poorman thing though
168 def solve_neighbour_url (record):
169 if not record.type.startswith('authority'): return
171 for neighbour_dict in [ api.aggregates, api.registries ]:
172 if hrn in neighbour_dict:
173 record.url=neighbour_dict[hrn].get_url()
175 for record in local_records: solve_neighbour_url (record)
177 # convert local record objects to dicts for xmlrpc
178 # xxx somehow here calling dict(record) issues a weird error
179 # however record.todict() seems to work fine
180 # records.extend( [ dict(record) for record in local_records ] )
181 records.extend( [ record.todict() for record in local_records ] )
183 raise RecordNotFound(str(hrns))
187 def List (self, api, xrn, origin_hrn=None):
188 hrn, type = urn_to_hrn(xrn)
190 if hrn.endswith('*'):
193 # load all know registry names into a prefix tree and attempt to find
194 # the longest matching prefix
195 registries = api.registries
196 registry_hrns = registries.keys()
198 tree.load(registry_hrns)
199 registry_hrn = tree.best_match(hrn)
201 #if there was no match then this record belongs to an unknow registry
203 raise MissingAuthority(xrn)
204 # if the best match (longest matching hrn) is not the local registry,
205 # forward the request
207 if registry_hrn != api.hrn:
208 credential = api.getCredential()
209 interface = api.registries[registry_hrn]
210 server_proxy = api.server_proxy(interface, credential)
211 record_list = server_proxy.List(xrn, credential)
212 # same as above, no need to process what comes from through xmlrpc
213 # pass foreign records as-is
214 record_dicts = record_list
216 # if we still have not found the record yet, try the local registry
218 if not api.auth.hierarchy.auth_exists(hrn):
219 raise MissingAuthority(hrn)
221 records = dbsession.query(RegRecord).filter(RegRecord.hrn.startswith(hrn))
223 records = dbsession.query(RegRecord).filter_by(authority=hrn)
224 record_dicts=[ record.todict() for record in records ]
229 def CreateGid(self, api, xrn, cert):
231 authority = Xrn(xrn=xrn).get_authority_hrn()
232 auth_info = api.auth.get_auth_info(authority)
234 pkey = Keypair(create=True)
236 certificate = Certificate(string=cert)
237 pkey = certificate.get_pubkey()
238 gid = api.auth.hierarchy.create_gid(xrn, create_uuid(), pkey)
239 return gid.save_to_string(save_parents=True)
242 # utility for handling relationships among the SFA objects
243 # given that the SFA db does not handle this sort of relationsships
244 # it will rely on side-effects in the testbed to keep this persistent
246 # subject_record describes the subject of the relationships
247 # ref_record contains the target values for the various relationships we need to manage
248 # (to begin with, this is just the slice x person relationship)
249 def update_relations (self, subject_obj, ref_obj):
250 type=subject_obj.type
252 self.update_relation(subject_obj, 'researcher', ref_obj.researcher, 'user')
254 # field_key is the name of one field in the record, typically 'researcher' for a 'slice' record
255 # hrns is the list of hrns that should be linked to the subject from now on
256 # target_type would be e.g. 'user' in the 'slice' x 'researcher' example
257 def update_relation (self, record_obj, field_key, hrns, target_type):
258 # locate the linked objects in our db
259 subject_type=record_obj.type
260 subject_id=record_obj.pointer
261 # get the 'pointer' field of all matching records
262 link_id_tuples = dbsession.query(RegRecord.pointer).filter_by(type=target_type).filter(RegRecord.hrn.in_(hrns)).all()
263 # sqlalchemy returns named tuples for columns
264 link_ids = [ tuple.pointer for tuple in link_id_tuples ]
265 self.driver.update_relation (subject_type, target_type, subject_id, link_ids)
267 def Register(self, api, record_dict):
269 hrn, type = record_dict['hrn'], record_dict['type']
270 urn = hrn_to_urn(hrn,type)
272 if type not in ['authority', 'slice', 'node', 'user']:
273 raise UnknownSfaType(type)
275 # check if record_dict already exists
276 existing_records = dbsession.query(RegRecord).filter_by(type=type,hrn=hrn).all()
278 raise ExistingRecord(hrn)
280 assert ('type' in record_dict)
281 # returns the right type of RegRecord according to type in record
282 record = make_record(dict=record_dict)
283 record.just_created()
284 record.authority = get_authority(record.hrn)
285 auth_info = api.auth.get_auth_info(record.authority)
287 # make sure record has a gid
290 pkey = Keypair(create=True)
291 if getattr(record,'keys',None):
293 # use only first key in record
294 if isinstance(record.keys, types.ListType):
295 pub_key = record.keys[0]
296 pkey = convert_public_key(pub_key)
298 gid_object = api.auth.hierarchy.create_gid(urn, uuid, pkey)
299 gid = gid_object.save_to_string(save_parents=True)
302 if isinstance (record, RegAuthority):
304 if not api.auth.hierarchy.auth_exists(hrn):
305 api.auth.hierarchy.create_auth(hrn_to_urn(hrn,'authority'))
307 # get the GID from the newly created authority
308 gid = auth_info.get_gid_object()
309 record.gid=gid.save_to_string(save_parents=True)
311 elif isinstance (record, RegSlice):
312 # locate objects for relationships
313 if hasattr (record, 'researcher'):
314 # we get the list of researcher hrns as
315 researcher_hrns = record.researcher
316 # strip that in case we have <researcher> words </researcher>
317 researcher_hrns = [ x.strip() for x in researcher_hrns ]
318 logger.info ("incoming researchers %s"%researcher_hrns)
319 request = dbsession.query (RegUser).filter(RegUser.hrn.in_(researcher_hrns))
320 logger.info ("%d incoming hrns, %d matches found"%(len(researcher_hrns),request.count()))
321 researchers = dbsession.query (RegUser).filter(RegUser.hrn.in_(researcher_hrns)).all()
322 record.reg_researchers = researchers
324 elif isinstance (record, RegUser):
325 # create RegKey objects for incoming keys
326 if hasattr(record,'keys'):
327 logger.debug ("creating %d keys for user %s"%(len(record.keys),record.hrn))
328 record.reg_keys = [ RegKey (key) for key in record.keys ]
330 # update testbed-specific data if needed
331 pointer = self.driver.register (record.__dict__, hrn, pub_key)
333 record.pointer=pointer
334 dbsession.add(record)
337 # update membership for researchers, pis, owners, operators
338 self.update_relations (record, record)
340 return record.get_gid_object().save_to_string(save_parents=True)
342 def Update(self, api, record_dict):
343 assert ('type' in record_dict)
344 new_record=RegRecord(dict=record_dict)
345 type = new_record.type
348 # make sure the record exists
349 record = dbsession.query(RegRecord).filter_by(type=type,hrn=hrn).first()
351 raise RecordNotFound("hrn=%s, type=%s"%(hrn,type))
352 record.just_updated()
355 if type not in ['authority', 'slice', 'node', 'user']:
356 raise UnknownSfaType(type)
358 # Use the pointer from the existing record, not the one that the user
359 # gave us. This prevents the user from inserting a forged pointer
360 pointer = record.pointer
362 # is the a change in keys ?
365 if getattr(new_key,'keys',None):
366 new_key=new_record.keys
367 if isinstance (new_key,types.ListType):
370 # update the PLC information that was specified with the record
371 if not self.driver.update (record.__dict__, new_record.__dict__, hrn, new_key):
372 logger.warning("driver.update failed")
374 # take new_key into account
376 # update the openssl key and gid
377 pkey = convert_public_key(new_key)
379 urn = hrn_to_urn(hrn,type)
380 gid_object = api.auth.hierarchy.create_gid(urn, uuid, pkey)
381 gid = gid_object.save_to_string(save_parents=True)
385 # update membership for researchers, pis, owners, operators
386 self.update_relations (record, new_record)
390 # expecting an Xrn instance
391 def Remove(self, api, xrn, origin_hrn=None):
394 request=dbsession.query(RegRecord).filter_by(hrn=hrn)
395 if type and type not in ['all', '*']:
396 request=request.filter_by(type=type)
398 record = request.first()
400 msg="Could not find hrn %s"%hrn
401 if type: msg += " type=%s"%type
402 raise RecordNotFound(msg)
405 if type not in ['slice', 'user', 'node', 'authority'] :
406 raise UnknownSfaType(type)
408 credential = api.getCredential()
409 registries = api.registries
411 # Try to remove the object from the PLCDB of federated agg.
412 # This is attempted before removing the object from the local agg's PLCDB and sfa table
413 if hrn.startswith(api.hrn) and type in ['user', 'slice', 'authority']:
414 for registry in registries:
415 if registry not in [api.hrn]:
417 result=registries[registry].remove_peer_object(credential, record, origin_hrn)
421 # call testbed callback first
422 # IIUC this is done on the local testbed TOO because of the refreshpeer link
423 if not self.driver.remove(record.__dict__):
424 logger.warning("driver.remove failed")
427 dbsession.delete(record)
432 # This is a PLC-specific thing, won't work with other platforms
433 def get_key_from_incoming_ip (self, api):
434 # verify that the callers's ip address exist in the db and is an interface
435 # for a node in the db
436 (ip, port) = api.remote_addr
437 interfaces = self.driver.shell.GetInterfaces({'ip': ip}, ['node_id'])
439 raise NonExistingRecord("no such ip %(ip)s" % locals())
440 nodes = self.driver.shell.GetNodes([interfaces[0]['node_id']], ['node_id', 'hostname'])
442 raise NonExistingRecord("no such node using ip %(ip)s" % locals())
445 # look up the sfa record
446 record=dbsession.query(RegRecord).filter_by(type='node',pointer=node['node_id']).first()
448 raise RecordNotFound("node with pointer %s"%node['node_id'])
450 # generate a new keypair and gid
452 pkey = Keypair(create=True)
453 urn = hrn_to_urn(record.hrn, record.type)
454 gid_object = api.auth.hierarchy.create_gid(urn, uuid, pkey)
455 gid = gid_object.save_to_string(save_parents=True)
461 # attempt the scp the key
462 # and gid onto the node
463 # this will only work for planetlab based components
464 (kfd, key_filename) = tempfile.mkstemp()
465 (gfd, gid_filename) = tempfile.mkstemp()
466 pkey.save_to_file(key_filename)
467 gid_object.save_to_file(gid_filename, save_parents=True)
468 host = node['hostname']
469 key_dest="/etc/sfa/node.key"
470 gid_dest="/etc/sfa/node.gid"
472 #identity = "/etc/planetlab/root_ssh_key.rsa"
473 identity = "/etc/sfa/root_ssh_key"
474 scp_options=" -i %(identity)s " % locals()
475 scp_options+="-o StrictHostKeyChecking=no " % locals()
476 scp_key_command="%(scp)s %(scp_options)s %(key_filename)s root@%(host)s:%(key_dest)s" %\
478 scp_gid_command="%(scp)s %(scp_options)s %(gid_filename)s root@%(host)s:%(gid_dest)s" %\
481 all_commands = [scp_key_command, scp_gid_command]
483 for command in all_commands:
484 (status, output) = commands.getstatusoutput(command)
486 raise Exception, output
488 for filename in [key_filename, gid_filename]: