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.prefixTree import prefixTree
11 from sfa.util.record import SfaRecord
12 from sfa.util.table import SfaTable
13 from sfa.util.xrn import Xrn, get_authority, hrn_to_urn, urn_to_hrn
14 from sfa.util.plxrn import hrn_to_pl_login_base
15 from sfa.util.version import version_core
16 from sfa.util.sfalogging import logger
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 class RegistryManager:
25 def __init__ (self): pass
27 # The GENI GetVersion call
28 def GetVersion(self, api):
29 peers = dict ( [ (hrn,interface._ServerProxy__host) for (hrn,interface) in api.registries.iteritems()
32 return version_core({'interface':'registry',
37 def GetCredential(self, api, xrn, type, is_self=False):
40 hrn = urn_to_hrn(xrn)[0]
42 hrn, type = urn_to_hrn(xrn)
44 # Is this a root or sub authority
45 auth_hrn = api.auth.get_authority(hrn)
46 if not auth_hrn or hrn == api.config.SFA_INTERFACE_HRN:
49 auth_info = api.auth.get_auth_info(auth_hrn)
51 records = table.findObjects({'type': type, 'hrn': hrn})
53 raise RecordNotFound(hrn)
56 # verify_cancreate_credential requires that the member lists
57 # (researchers, pis, etc) be filled in
58 if not self.driver.is_enabled_entity (record):
59 raise AccountNotEnabled(": PlanetLab account %s is not enabled. Please contact your site PI" %(record['email']))
62 # if this is a self cred the record's gid is the caller's gid
65 caller_gid = record.get_gid_object()
67 caller_gid = api.auth.client_cred.get_gid_caller()
68 caller_hrn = caller_gid.get_hrn()
70 object_hrn = record.get_gid_object().get_hrn()
71 rights = api.auth.determine_user_rights(caller_hrn, record)
72 # make sure caller has rights to this object
74 raise PermissionError(caller_hrn + " has no rights to " + record['name'])
76 object_gid = GID(string=record['gid'])
77 new_cred = Credential(subject = object_gid.get_subject())
78 new_cred.set_gid_caller(caller_gid)
79 new_cred.set_gid_object(object_gid)
80 new_cred.set_issuer_keys(auth_info.get_privkey_filename(), auth_info.get_gid_filename())
81 #new_cred.set_pubkey(object_gid.get_pubkey())
82 new_cred.set_privileges(rights)
83 new_cred.get_privileges().delegate_all_privileges(True)
84 if 'expires' in record:
85 new_cred.set_expiration(int(record['expires']))
86 auth_kind = "authority,ma,sa"
87 # Parent not necessary, verify with certs
88 #new_cred.set_parent(api.auth.hierarchy.get_auth_cred(auth_hrn, kind=auth_kind))
92 return new_cred.save_to_string(save_parents=True)
95 def Resolve(self, api, xrns, type=None, full=True):
97 if not isinstance(xrns, types.ListType):
99 # try to infer type if not set and we get a single input
101 type = Xrn(xrns).get_type()
102 hrns = [urn_to_hrn(xrn)[0] for xrn in xrns]
103 # load all known registry names into a prefix tree and attempt to find
104 # the longest matching prefix
105 # create a dict where key is a registry hrn and its value is a
106 # hrns at that registry (determined by the known prefix tree).
108 registries = api.registries
110 registry_hrns = registries.keys()
111 tree.load(registry_hrns)
113 registry_hrn = tree.best_match(urn_to_hrn(xrn)[0])
114 if registry_hrn not in xrn_dict:
115 xrn_dict[registry_hrn] = []
116 xrn_dict[registry_hrn].append(xrn)
119 for registry_hrn in xrn_dict:
120 # skip the hrn without a registry hrn
121 # XX should we let the user know the authority is unknown?
125 # if the best match (longest matching hrn) is not the local registry,
126 # forward the request
127 xrns = xrn_dict[registry_hrn]
128 if registry_hrn != api.hrn:
129 credential = api.getCredential()
130 interface = api.registries[registry_hrn]
131 server_proxy = api.server_proxy(interface, credential)
132 peer_records = server_proxy.Resolve(xrns, credential)
133 records.extend([SfaRecord(dict=record).as_dict() for record in peer_records])
135 # try resolving the remaining unfound records at the local registry
136 local_hrns = list ( set(hrns).difference([record['hrn'] for record in records]) )
139 local_records = table.findObjects({'hrn': local_hrns})
142 # in full mode we get as much info as we can, which involves contacting the
143 # testbed for getting implementation details about the record
144 self.driver.fill_record_info(local_records)
145 # also we fill the 'url' field for known authorities
146 # used to be in the driver code, sounds like a poorman thing though
147 def solve_neighbour_url (record):
148 if not record['type'].startswith('authority'): return
150 for neighbour_dict in [ api.aggregates, api.registries ]:
151 if hrn in neighbour_dict:
152 record['url']=neighbour_dict[hrn].get_url()
154 [ solve_neighbour_url (record) for record in local_records ]
158 # convert local record objects to dicts
159 records.extend([dict(record) for record in local_records])
161 records = filter(lambda rec: rec['type'] in [type], records)
164 raise RecordNotFound(str(hrns))
168 def List(self, api, xrn, origin_hrn=None):
169 hrn, type = urn_to_hrn(xrn)
170 # load all know registry names into a prefix tree and attempt to find
171 # the longest matching prefix
173 registries = api.registries
174 registry_hrns = registries.keys()
176 tree.load(registry_hrns)
177 registry_hrn = tree.best_match(hrn)
179 #if there was no match then this record belongs to an unknow registry
181 raise MissingAuthority(xrn)
182 # if the best match (longest matching hrn) is not the local registry,
183 # forward the request
185 if registry_hrn != api.hrn:
186 credential = api.getCredential()
187 interface = api.registries[registry_hrn]
188 server_proxy = api.server_proxy(interface, credential)
189 record_list = server_proxy.List(xrn, credential)
190 records = [SfaRecord(dict=record).as_dict() for record in record_list]
192 # if we still have not found the record yet, try the local registry
194 if not api.auth.hierarchy.auth_exists(hrn):
195 raise MissingAuthority(hrn)
198 records = table.find({'authority': hrn})
203 def CreateGid(self, api, xrn, cert):
205 authority = Xrn(xrn=xrn).get_authority_hrn()
206 auth_info = api.auth.get_auth_info(authority)
208 pkey = Keypair(create=True)
210 certificate = Certificate(string=cert)
211 pkey = certificate.get_pubkey()
212 gid = api.auth.hierarchy.create_gid(xrn, create_uuid(), pkey)
213 return gid.save_to_string(save_parents=True)
215 def Register(self, api, record):
217 hrn, type = record['hrn'], record['type']
218 urn = hrn_to_urn(hrn,type)
220 if type not in ['authority', 'slice', 'node', 'user']:
221 raise UnknownSfaType(type)
223 # check if record already exists
225 existing_records = table.find({'type': type, 'hrn': hrn})
227 raise ExistingRecord(hrn)
229 record = SfaRecord(dict = record)
230 record['authority'] = get_authority(record['hrn'])
231 auth_info = api.auth.get_auth_info(record['authority'])
233 # make sure record has a gid
234 if 'gid' not in record:
236 pkey = Keypair(create=True)
237 if 'keys' in record and record['keys']:
238 pub_key=record['keys']
239 # use only first key in record
240 if isinstance(record['keys'], types.ListType):
241 pub_key = record['keys'][0]
242 pkey = convert_public_key(pub_key)
244 gid_object = api.auth.hierarchy.create_gid(urn, uuid, pkey)
245 gid = gid_object.save_to_string(save_parents=True)
249 if type in ["authority"]:
251 if not api.auth.hierarchy.auth_exists(hrn):
252 api.auth.hierarchy.create_auth(hrn_to_urn(hrn,'authority'))
254 # get the GID from the newly created authority
255 gid = auth_info.get_gid_object()
256 record.set_gid(gid.save_to_string(save_parents=True))
258 # update testbed-specific data f needed
259 logger.info("Getting driver from manager=%s"%self)
260 pointer = self.driver.register (record, hrn, pub_key)
262 record.set_pointer(pointer)
263 record_id = table.insert(record)
264 record['record_id'] = record_id
266 # update membership for researchers, pis, owners, operators
267 self.driver.update_membership(None, record)
269 return record.get_gid_object().save_to_string(save_parents=True)
271 def Update(self, api, record_dict):
272 new_record = SfaRecord(dict = record_dict)
273 type = new_record['type']
274 hrn = new_record['hrn']
275 urn = hrn_to_urn(hrn,type)
277 # make sure the record exists
278 records = table.findObjects({'type': type, 'hrn': hrn})
280 raise RecordNotFound(hrn)
282 record['last_updated'] = time.gmtime()
285 if type not in ['authority', 'slice', 'node', 'user']:
286 raise UnknownSfaType(type)
288 # Use the pointer from the existing record, not the one that the user
289 # gave us. This prevents the user from inserting a forged pointer
290 pointer = record['pointer']
292 # is the a change in keys ?
295 if 'keys' in new_record and new_record['keys']:
296 new_key=new_record['keys']
297 if isinstance (new_key,types.ListType):
300 # Update_membership needs the membership lists in the existing record
301 # filled in, so it can see if members were added or removed
302 self.driver.fill_record_info(record)
304 # update the PLC information that was specified with the record
305 if not self.driver.update (record, new_record, hrn, new_key):
306 logger.warning("driver.update failed")
308 # take new_key into account
310 # update the openssl key and gid
311 pkey = convert_public_key(new_key)
313 gid_object = api.auth.hierarchy.create_gid(urn, uuid, pkey)
314 gid = gid_object.save_to_string(save_parents=True)
316 record = SfaRecord(dict=record)
319 # update membership for researchers, pis, owners, operators
320 self.driver.update_membership(record, new_record)
324 # expecting an Xrn instance
325 def Remove(self, api, xrn, origin_hrn=None):
328 filter = {'hrn': xrn.get_hrn()}
331 if type and type not in ['all', '*']:
332 filter['type'] = type
334 records = table.find(filter)
335 if not records: raise RecordNotFound(hrn)
337 type = record['type']
339 if type not in ['slice', 'user', 'node', 'authority'] :
340 raise UnknownSfaType(type)
342 credential = api.getCredential()
343 registries = api.registries
345 # Try to remove the object from the PLCDB of federated agg.
346 # This is attempted before removing the object from the local agg's PLCDB and sfa table
347 if hrn.startswith(api.hrn) and type in ['user', 'slice', 'authority']:
348 for registry in registries:
349 if registry not in [api.hrn]:
351 result=registries[registry].remove_peer_object(credential, record, origin_hrn)
355 # call testbed callback first
356 # IIUC this is done on the local testbed TOO because of the refreshpeer link
357 if not self.driver.remove(record):
358 logger.warning("driver.remove failed")
365 # This is a PLC-specific thing...
366 def get_key_from_incoming_ip (self, api):
367 # verify that the callers's ip address exist in the db and is an interface
368 # for a node in the db
369 (ip, port) = api.remote_addr
370 interfaces = self.driver.GetInterfaces({'ip': ip}, ['node_id'])
372 raise NonExistingRecord("no such ip %(ip)s" % locals())
373 nodes = self.driver.GetNodes([interfaces[0]['node_id']], ['node_id', 'hostname'])
375 raise NonExistingRecord("no such node using ip %(ip)s" % locals())
378 # look up the sfa record
380 records = table.findObjects({'type': 'node', 'pointer': node['node_id']})
382 raise RecordNotFound("pointer:" + str(node['node_id']))
385 # generate a new keypair and gid
387 pkey = Keypair(create=True)
388 urn = hrn_to_urn(record['hrn'], record['type'])
389 gid_object = api.auth.hierarchy.create_gid(urn, uuid, pkey)
390 gid = gid_object.save_to_string(save_parents=True)
397 # attempt the scp the key
398 # and gid onto the node
399 # this will only work for planetlab based components
400 (kfd, key_filename) = tempfile.mkstemp()
401 (gfd, gid_filename) = tempfile.mkstemp()
402 pkey.save_to_file(key_filename)
403 gid_object.save_to_file(gid_filename, save_parents=True)
404 host = node['hostname']
405 key_dest="/etc/sfa/node.key"
406 gid_dest="/etc/sfa/node.gid"
408 #identity = "/etc/planetlab/root_ssh_key.rsa"
409 identity = "/etc/sfa/root_ssh_key"
410 scp_options=" -i %(identity)s " % locals()
411 scp_options+="-o StrictHostKeyChecking=no " % locals()
412 scp_key_command="%(scp)s %(scp_options)s %(key_filename)s root@%(host)s:%(key_dest)s" %\
414 scp_gid_command="%(scp)s %(scp_options)s %(gid_filename)s root@%(host)s:%(gid_dest)s" %\
417 all_commands = [scp_key_command, scp_gid_command]
419 for command in all_commands:
420 (status, output) = commands.getstatusoutput(command)
422 raise Exception, output
424 for filename in [key_filename, gid_filename]: