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.plxrn import hrn_to_pl_login_base
14 from sfa.util.version import version_core
15 from sfa.util.sfalogging import logger
17 from sfa.trust.gid import GID
18 from sfa.trust.credential import Credential
19 from sfa.trust.certificate import Certificate, Keypair, convert_public_key
20 from sfa.trust.gid import create_uuid
22 from sfa.storage.record import SfaRecord
23 from sfa.storage.table import SfaTable
25 class RegistryManager:
27 def __init__ (self, config): pass
29 # The GENI GetVersion call
30 def GetVersion(self, api, options):
31 peers = dict ( [ (hrn,interface.get_url()) for (hrn,interface) in api.registries.iteritems()
34 return version_core({'interface':'registry',
41 def GetCredential(self, api, xrn, type, is_self=False):
44 hrn = urn_to_hrn(xrn)[0]
46 hrn, type = urn_to_hrn(xrn)
48 # Is this a root or sub authority
49 auth_hrn = api.auth.get_authority(hrn)
50 if not auth_hrn or hrn == api.config.SFA_INTERFACE_HRN:
53 auth_info = api.auth.get_auth_info(auth_hrn)
55 records = table.findObjects({'type': type, 'hrn': hrn})
57 raise RecordNotFound(hrn)
60 # verify_cancreate_credential requires that the member lists
61 # (researchers, pis, etc) be filled in
62 self.driver.augment_records_with_testbed_info (record)
63 if not self.driver.is_enabled (record):
64 raise AccountNotEnabled(": PlanetLab account %s is not enabled. Please contact your site PI" %(record['email']))
67 # if this is a self cred the record's gid is the caller's gid
70 caller_gid = record.get_gid_object()
72 caller_gid = api.auth.client_cred.get_gid_caller()
73 caller_hrn = caller_gid.get_hrn()
75 object_hrn = record.get_gid_object().get_hrn()
76 rights = api.auth.determine_user_rights(caller_hrn, record)
77 # make sure caller has rights to this object
79 raise PermissionError(caller_hrn + " has no rights to " + record['name'])
81 object_gid = GID(string=record['gid'])
82 new_cred = Credential(subject = object_gid.get_subject())
83 new_cred.set_gid_caller(caller_gid)
84 new_cred.set_gid_object(object_gid)
85 new_cred.set_issuer_keys(auth_info.get_privkey_filename(), auth_info.get_gid_filename())
86 #new_cred.set_pubkey(object_gid.get_pubkey())
87 new_cred.set_privileges(rights)
88 new_cred.get_privileges().delegate_all_privileges(True)
89 if 'expires' in record:
90 date = utcparse(record['expires'])
91 expires = datetime_to_epoch(date)
92 new_cred.set_expiration(int(expires))
93 auth_kind = "authority,ma,sa"
94 # Parent not necessary, verify with certs
95 #new_cred.set_parent(api.auth.hierarchy.get_auth_cred(auth_hrn, kind=auth_kind))
99 return new_cred.save_to_string(save_parents=True)
102 def Resolve(self, api, xrns, type=None, full=True):
104 if not isinstance(xrns, types.ListType):
106 # try to infer type if not set and we get a single input
108 type = Xrn(xrns).get_type()
109 hrns = [urn_to_hrn(xrn)[0] for xrn in xrns]
110 # load all known registry names into a prefix tree and attempt to find
111 # the longest matching prefix
112 # create a dict where key is a registry hrn and its value is a
113 # hrns at that registry (determined by the known prefix tree).
115 registries = api.registries
117 registry_hrns = registries.keys()
118 tree.load(registry_hrns)
120 registry_hrn = tree.best_match(urn_to_hrn(xrn)[0])
121 if registry_hrn not in xrn_dict:
122 xrn_dict[registry_hrn] = []
123 xrn_dict[registry_hrn].append(xrn)
126 for registry_hrn in xrn_dict:
127 # skip the hrn without a registry hrn
128 # XX should we let the user know the authority is unknown?
132 # if the best match (longest matching hrn) is not the local registry,
133 # forward the request
134 xrns = xrn_dict[registry_hrn]
135 if registry_hrn != api.hrn:
136 credential = api.getCredential()
137 interface = api.registries[registry_hrn]
138 server_proxy = api.server_proxy(interface, credential)
139 peer_records = server_proxy.Resolve(xrns, credential)
140 records.extend([SfaRecord(dict=record).as_dict() for record in peer_records])
142 # try resolving the remaining unfound records at the local registry
143 local_hrns = list ( set(hrns).difference([record['hrn'] for record in records]) )
146 local_records = table.findObjects({'hrn': local_hrns})
149 # in full mode we get as much info as we can, which involves contacting the
150 # testbed for getting implementation details about the record
151 self.driver.augment_records_with_testbed_info(local_records)
152 # also we fill the 'url' field for known authorities
153 # used to be in the driver code, sounds like a poorman thing though
154 def solve_neighbour_url (record):
155 if not record['type'].startswith('authority'): return
157 for neighbour_dict in [ api.aggregates, api.registries ]:
158 if hrn in neighbour_dict:
159 record['url']=neighbour_dict[hrn].get_url()
161 [ solve_neighbour_url (record) for record in local_records ]
165 # convert local record objects to dicts
166 records.extend([dict(record) for record in local_records])
168 records = filter(lambda rec: rec['type'] in [type], records)
171 raise RecordNotFound(str(hrns))
175 def List(self, api, xrn, origin_hrn=None):
176 hrn, type = urn_to_hrn(xrn)
177 # load all know registry names into a prefix tree and attempt to find
178 # the longest matching prefix
180 registries = api.registries
181 registry_hrns = registries.keys()
183 tree.load(registry_hrns)
184 registry_hrn = tree.best_match(hrn)
186 #if there was no match then this record belongs to an unknow registry
188 raise MissingAuthority(xrn)
189 # if the best match (longest matching hrn) is not the local registry,
190 # forward the request
192 if registry_hrn != api.hrn:
193 credential = api.getCredential()
194 interface = api.registries[registry_hrn]
195 server_proxy = api.server_proxy(interface, credential)
196 record_list = server_proxy.List(xrn, credential)
197 records = [SfaRecord(dict=record).as_dict() for record in record_list]
199 # if we still have not found the record yet, try the local registry
201 if not api.auth.hierarchy.auth_exists(hrn):
202 raise MissingAuthority(hrn)
205 records = table.find({'authority': hrn})
210 def CreateGid(self, api, xrn, cert):
212 authority = Xrn(xrn=xrn).get_authority_hrn()
213 auth_info = api.auth.get_auth_info(authority)
215 pkey = Keypair(create=True)
217 certificate = Certificate(string=cert)
218 pkey = certificate.get_pubkey()
219 gid = api.auth.hierarchy.create_gid(xrn, create_uuid(), pkey)
220 return gid.save_to_string(save_parents=True)
223 # utility for handling relationships among the SFA objects
224 # given that the SFA db does not handle this sort of relationsships
225 # it will rely on side-effects in the testbed to keep this persistent
227 # subject_record describes the subject of the relationships
228 # ref_record contains the target values for the various relationships we need to manage
229 # (to begin with, this is just the slice x person relationship)
230 def update_relations (self, subject_record, ref_record):
231 type=subject_record['type']
233 self.update_relation(subject_record, 'researcher', ref_record.get('researcher'), 'user')
235 # field_key is the name of one field in the record, typically 'researcher' for a 'slice' record
236 # hrns is the list of hrns that should be linked to the subject from now on
237 # target_type would be e.g. 'user' in the 'slice' x 'researcher' example
238 def update_relation (self, sfa_record, field_key, hrns, target_type):
239 # locate the linked objects in our db
240 subject_type=sfa_record['type']
241 subject_id=sfa_record['pointer']
243 link_sfa_records = table.find ({'type':target_type, 'hrn': hrns})
244 link_ids = [ rec.get('pointer') for rec in link_sfa_records ]
245 self.driver.update_relation (subject_type, target_type, subject_id, link_ids)
248 def Register(self, api, record):
250 hrn, type = record['hrn'], record['type']
251 urn = hrn_to_urn(hrn,type)
253 if type not in ['authority', 'slice', 'node', 'user']:
254 raise UnknownSfaType(type)
256 # check if record already exists
258 existing_records = table.find({'type': type, 'hrn': hrn})
260 raise ExistingRecord(hrn)
262 record = SfaRecord(dict = record)
263 record['authority'] = get_authority(record['hrn'])
264 auth_info = api.auth.get_auth_info(record['authority'])
266 # make sure record has a gid
267 if 'gid' not in record:
269 pkey = Keypair(create=True)
270 if 'keys' in record and record['keys']:
271 pub_key=record['keys']
272 # use only first key in record
273 if isinstance(record['keys'], types.ListType):
274 pub_key = record['keys'][0]
275 pkey = convert_public_key(pub_key)
277 gid_object = api.auth.hierarchy.create_gid(urn, uuid, pkey)
278 gid = gid_object.save_to_string(save_parents=True)
282 if type in ["authority"]:
284 if not api.auth.hierarchy.auth_exists(hrn):
285 api.auth.hierarchy.create_auth(hrn_to_urn(hrn,'authority'))
287 # get the GID from the newly created authority
288 gid = auth_info.get_gid_object()
289 record.set_gid(gid.save_to_string(save_parents=True))
291 # update testbed-specific data if needed
292 pointer = self.driver.register (record, hrn, pub_key)
294 record.set_pointer(pointer)
295 record_id = table.insert(record)
296 record['record_id'] = record_id
298 # update membership for researchers, pis, owners, operators
299 self.update_relations (record, record)
301 return record.get_gid_object().save_to_string(save_parents=True)
303 def Update(self, api, record_dict):
304 new_record = SfaRecord(dict = record_dict)
305 type = new_record['type']
306 hrn = new_record['hrn']
307 urn = hrn_to_urn(hrn,type)
309 # make sure the record exists
310 records = table.findObjects({'type': type, 'hrn': hrn})
312 raise RecordNotFound(hrn)
314 record['last_updated'] = time.gmtime()
317 if type not in ['authority', 'slice', 'node', 'user']:
318 raise UnknownSfaType(type)
320 # Use the pointer from the existing record, not the one that the user
321 # gave us. This prevents the user from inserting a forged pointer
322 pointer = record['pointer']
324 # is the a change in keys ?
327 if 'keys' in new_record and new_record['keys']:
328 new_key=new_record['keys']
329 if isinstance (new_key,types.ListType):
332 # update the PLC information that was specified with the record
333 if not self.driver.update (record, new_record, hrn, new_key):
334 logger.warning("driver.update failed")
336 # take new_key into account
338 # update the openssl key and gid
339 pkey = convert_public_key(new_key)
341 gid_object = api.auth.hierarchy.create_gid(urn, uuid, pkey)
342 gid = gid_object.save_to_string(save_parents=True)
344 record = SfaRecord(dict=record)
347 # update membership for researchers, pis, owners, operators
348 self.update_relations (record, new_record)
352 # expecting an Xrn instance
353 def Remove(self, api, xrn, origin_hrn=None):
356 filter = {'hrn': xrn.get_hrn()}
359 if type and type not in ['all', '*']:
360 filter['type'] = type
362 records = table.find(filter)
363 if not records: raise RecordNotFound(hrn)
365 type = record['type']
367 if type not in ['slice', 'user', 'node', 'authority'] :
368 raise UnknownSfaType(type)
370 credential = api.getCredential()
371 registries = api.registries
373 # Try to remove the object from the PLCDB of federated agg.
374 # This is attempted before removing the object from the local agg's PLCDB and sfa table
375 if hrn.startswith(api.hrn) and type in ['user', 'slice', 'authority']:
376 for registry in registries:
377 if registry not in [api.hrn]:
379 result=registries[registry].remove_peer_object(credential, record, origin_hrn)
383 # call testbed callback first
384 # IIUC this is done on the local testbed TOO because of the refreshpeer link
385 if not self.driver.remove(record):
386 logger.warning("driver.remove failed")
393 # This is a PLC-specific thing...
394 def get_key_from_incoming_ip (self, api):
395 # verify that the callers's ip address exist in the db and is an interface
396 # for a node in the db
397 (ip, port) = api.remote_addr
398 interfaces = self.driver.shell.GetInterfaces({'ip': ip}, ['node_id'])
400 raise NonExistingRecord("no such ip %(ip)s" % locals())
401 nodes = self.driver.shell.GetNodes([interfaces[0]['node_id']], ['node_id', 'hostname'])
403 raise NonExistingRecord("no such node using ip %(ip)s" % locals())
406 # look up the sfa record
408 records = table.findObjects({'type': 'node', 'pointer': node['node_id']})
410 raise RecordNotFound("pointer:" + str(node['node_id']))
413 # generate a new keypair and gid
415 pkey = Keypair(create=True)
416 urn = hrn_to_urn(record['hrn'], record['type'])
417 gid_object = api.auth.hierarchy.create_gid(urn, uuid, pkey)
418 gid = gid_object.save_to_string(save_parents=True)
425 # attempt the scp the key
426 # and gid onto the node
427 # this will only work for planetlab based components
428 (kfd, key_filename) = tempfile.mkstemp()
429 (gfd, gid_filename) = tempfile.mkstemp()
430 pkey.save_to_file(key_filename)
431 gid_object.save_to_file(gid_filename, save_parents=True)
432 host = node['hostname']
433 key_dest="/etc/sfa/node.key"
434 gid_dest="/etc/sfa/node.gid"
436 #identity = "/etc/planetlab/root_ssh_key.rsa"
437 identity = "/etc/sfa/root_ssh_key"
438 scp_options=" -i %(identity)s " % locals()
439 scp_options+="-o StrictHostKeyChecking=no " % locals()
440 scp_key_command="%(scp)s %(scp_options)s %(key_filename)s root@%(host)s:%(key_dest)s" %\
442 scp_gid_command="%(scp)s %(scp_options)s %(gid_filename)s root@%(host)s:%(gid_dest)s" %\
445 all_commands = [scp_key_command, scp_gid_command]
447 for command in all_commands:
448 (status, output) = commands.getstatusoutput(command)
450 raise Exception, output
452 for filename in [key_filename, gid_filename]: