GID using email in SubjectAltName
[sfa.git] / sfa / managers / registry_manager.py
1 import types
2 # for get_key_from_incoming_ip
3 import tempfile
4 import os
5 import commands
6
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
14
15 from sfa.util.printable import printable
16
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
21
22 from sfa.storage.model import make_record, RegRecord, RegAuthority, RegUser, RegSlice, RegKey, \
23     augment_with_sfa_builtins
24 ### the types that we need to exclude from sqlobjects before being able to dump
25 # them on the xmlrpc wire
26 from sqlalchemy.orm.collections import InstrumentedList
27
28 ### historical note -- april 2014
29 # the myslice chaps rightfully complained about the following discrepancy
30 # they found that
31 # * read operations (resolve) expose stuff like e.g. 
32 #   'reg-researchers', or 'reg-pis', but that
33 # * write operations (register, update) need e.g. 
34 #   'researcher' or 'pi' to be set - reg-* are just ignored
35 #
36 # the '_normalize_input' helper functions below aim at ironing this out
37 # however in order to break as few code as possible we essentially make sure that *both* fields are set
38 # upon entering the write methods (so again register and update) for legacy, as some driver code
39 # might depend on the presence of, say, 'researcher'
40
41 # normalize an input record to a write method - register or update
42 # e.g. registry calls this 'reg-researchers'
43 # while some drivers call this 'researcher'
44 # we need to make sure that both keys appear and are the same
45 def _normalize_input (record, reg_key, driver_key):
46     # this looks right, use this for both keys
47     if reg_key in record:
48         # and issue a warning if they were both set and different
49         # as we're overwriting some user data here
50         if driver_key in record:
51             logger.warning ("normalize_input: incoming record has both values, using %s"%reg_key)
52         record[driver_key]=record[reg_key]
53     # we only have one key set, duplicate for the other one
54     elif driver_key in record:
55         logger.warning ("normalize_input: you should use '%s' instead of '%s'"%(reg_key,driver_key))
56         record[reg_key]=record[driver_key]
57
58 def normalize_input_record (record):
59     _normalize_input (record, 'reg-researchers','researcher')
60     _normalize_input (record, 'reg-pis','pi')
61     _normalize_input (record, 'reg-keys','keys')
62     # xxx the keys thing could use a little bit more attention:
63     # some parts of the code are using 'keys' while they should use 'reg-keys' 
64     # but I run out of time for now
65     if 'reg-keys' in record: record['keys']=record['reg-keys']
66     return record
67
68 class RegistryManager:
69
70     def __init__ (self, config): 
71         logger.info("Creating RegistryManager[%s]"%id(self))
72
73     # The GENI GetVersion call
74     def GetVersion(self, api, options):
75         peers = dict ( [ (hrn,interface.get_url()) for (hrn,interface) in api.registries.iteritems() 
76                        if hrn != api.hrn])
77         xrn=Xrn(api.hrn,type='authority')
78         return version_core({'interface':'registry',
79                              'sfa': 3,
80                              'hrn':xrn.get_hrn(),
81                              'urn':xrn.get_urn(),
82                              'peers':peers})
83     
84     def GetCredential(self, api, xrn, input_type, caller_xrn=None):
85         # convert xrn to hrn     
86         if input_type:
87             hrn, _ = urn_to_hrn(xrn)
88             type = input_type
89         else:
90             hrn, type = urn_to_hrn(xrn)
91
92         # Slivers don't have credentials but users should be able to 
93         # specify a sliver xrn and receive the slice's credential
94         # However if input_type is specified
95         if type == 'sliver' or ( not input_type and '-' in Xrn(hrn).leaf):
96             slice_xrn = api.driver.sliver_to_slice_xrn(hrn)
97             hrn = slice_xrn.hrn 
98   
99         # Is this a root or sub authority
100         auth_hrn = api.auth.get_authority(hrn)
101         if not auth_hrn or hrn == api.config.SFA_INTERFACE_HRN:
102             auth_hrn = hrn
103         auth_info = api.auth.get_auth_info(auth_hrn)
104
105         # get record info
106         dbsession = api.dbsession()
107         record=dbsession.query(RegRecord).filter_by(type=type,hrn=hrn).first()
108         if not record:
109             raise RecordNotFound("hrn=%s, type=%s"%(hrn,type))
110
111         # get the callers gid
112         # if caller_xrn is not specified assume the caller is the record
113         # object itself.
114         if not caller_xrn:
115             caller_hrn = hrn
116             caller_gid = record.get_gid_object()
117         else:
118             caller_hrn, caller_type = urn_to_hrn(caller_xrn)
119             if caller_type:
120                 caller_record = dbsession.query(RegRecord).filter_by(hrn=caller_hrn,type=caller_type).first()
121             else:
122                 caller_record = dbsession.query(RegRecord).filter_by(hrn=caller_hrn).first()
123             if not caller_record:
124                 raise RecordNotFound("Unable to associated caller (hrn=%s, type=%s) with credential for (hrn: %s, type: %s)"%(caller_hrn, caller_type, hrn, type))
125             caller_gid = GID(string=caller_record.gid)
126  
127         object_hrn = record.get_gid_object().get_hrn()
128         # call the builtin authorization/credential generation engine
129         rights = api.auth.determine_user_rights(caller_hrn, record)
130         # make sure caller has rights to this object
131         if rights.is_empty():
132             raise PermissionError("%s has no rights to %s (%s)" % \
133                                   (caller_hrn, object_hrn, xrn))    
134         object_gid = GID(string=record.gid)
135         new_cred = Credential(subject = object_gid.get_subject())
136         new_cred.set_gid_caller(caller_gid)
137         new_cred.set_gid_object(object_gid)
138         new_cred.set_issuer_keys(auth_info.get_privkey_filename(), auth_info.get_gid_filename())
139         #new_cred.set_pubkey(object_gid.get_pubkey())
140         new_cred.set_privileges(rights)
141         new_cred.get_privileges().delegate_all_privileges(True)
142         if hasattr(record,'expires'):
143             date = utcparse(record.expires)
144             expires = datetime_to_epoch(date)
145             new_cred.set_expiration(int(expires))
146         auth_kind = "authority,ma,sa"
147         # Parent not necessary, verify with certs
148         #new_cred.set_parent(api.auth.hierarchy.get_auth_cred(auth_hrn, kind=auth_kind))
149         new_cred.encode()
150         new_cred.sign()
151     
152         return new_cred.save_to_string(save_parents=True)
153     
154     
155     # the default for full, which means 'dig into the testbed as well', should be false
156     def Resolve(self, api, xrns, type=None, details=False):
157     
158         dbsession = api.dbsession()
159         if not isinstance(xrns, types.ListType):
160             # try to infer type if not set and we get a single input
161             if not type:
162                 type = Xrn(xrns).get_type()
163             xrns = [xrns]
164         hrns = [urn_to_hrn(xrn)[0] for xrn in xrns] 
165
166         # load all known registry names into a prefix tree and attempt to find
167         # the longest matching prefix
168         # create a dict where key is a registry hrn and its value is a list
169         # of hrns at that registry (determined by the known prefix tree).  
170         xrn_dict = {}
171         registries = api.registries
172         tree = prefixTree()
173         registry_hrns = registries.keys()
174         tree.load(registry_hrns)
175         for xrn in xrns:
176             registry_hrn = tree.best_match(urn_to_hrn(xrn)[0])
177             if registry_hrn not in xrn_dict:
178                 xrn_dict[registry_hrn] = []
179             xrn_dict[registry_hrn].append(xrn)
180             
181         records = [] 
182         for registry_hrn in xrn_dict:
183             # skip the hrn without a registry hrn
184             # XX should we let the user know the authority is unknown?       
185             if not registry_hrn:
186                 continue
187     
188             # if the best match (longest matching hrn) is not the local registry,
189             # forward the request
190             xrns = xrn_dict[registry_hrn]
191             if registry_hrn != api.hrn:
192                 credential = api.getCredential()
193                 interface = api.registries[registry_hrn]
194                 server_proxy = api.server_proxy(interface, credential)
195                 # should propagate the details flag but that's not supported in the xmlrpc interface yet
196                 #peer_records = server_proxy.Resolve(xrns, credential,type, details=details)
197                 peer_records = server_proxy.Resolve(xrns, credential)
198                 # pass foreign records as-is
199                 # previous code used to read
200                 # records.extend([SfaRecord(dict=record).as_dict() for record in peer_records])
201                 # not sure why the records coming through xmlrpc had to be processed at all
202                 records.extend(peer_records)
203     
204         # try resolving the remaining unfound records at the local registry
205         local_hrns = list ( set(hrns).difference([record['hrn'] for record in records]) )
206         # 
207         local_records = dbsession.query(RegRecord).filter(RegRecord.hrn.in_(local_hrns))
208         if type:
209             local_records = local_records.filter_by(type=type)
210         local_records=local_records.all()
211         
212         for local_record in local_records:
213             augment_with_sfa_builtins (local_record)
214
215         logger.info("Resolve, (details=%s,type=%s) local_records=%s "%(details,type,local_records))
216         local_dicts = [ record.__dict__ for record in local_records ]
217         
218         if details:
219             # in details mode we get as much info as we can, which involves contacting the 
220             # testbed for getting implementation details about the record
221             api.driver.augment_records_with_testbed_info(local_dicts)
222             # also we fill the 'url' field for known authorities
223             # used to be in the driver code, sounds like a poorman thing though
224             def solve_neighbour_url (record):
225                 if not record.type.startswith('authority'): return 
226                 hrn=record.hrn
227                 for neighbour_dict in [ api.aggregates, api.registries ]:
228                     if hrn in neighbour_dict:
229                         record.url=neighbour_dict[hrn].get_url()
230                         return 
231             for record in local_records: solve_neighbour_url (record)
232         
233         # convert local record objects to dicts for xmlrpc
234         # xxx somehow here calling dict(record) issues a weird error
235         # however record.todict() seems to work fine
236         # records.extend( [ dict(record) for record in local_records ] )
237         records.extend( [ record.todict(exclude_types=[InstrumentedList]) for record in local_records ] )
238
239         if not records:
240             raise RecordNotFound(str(hrns))
241     
242         return records
243     
244     def List (self, api, xrn, origin_hrn=None, options=None):
245         if options is None: options={}
246         dbsession=api.dbsession()
247         # load all know registry names into a prefix tree and attempt to find
248         # the longest matching prefix
249         hrn, type = urn_to_hrn(xrn)
250         registries = api.registries
251         registry_hrns = registries.keys()
252         tree = prefixTree()
253         tree.load(registry_hrns)
254         registry_hrn = tree.best_match(hrn)
255        
256         #if there was no match then this record belongs to an unknow registry
257         if not registry_hrn:
258             raise MissingAuthority(xrn)
259         # if the best match (longest matching hrn) is not the local registry,
260         # forward the request
261         record_dicts = []    
262         if registry_hrn != api.hrn:
263             credential = api.getCredential()
264             interface = api.registries[registry_hrn]
265             server_proxy = api.server_proxy(interface, credential)
266             record_list = server_proxy.List(xrn, credential, options)
267             # same as above, no need to process what comes from through xmlrpc
268             # pass foreign records as-is
269             record_dicts = record_list
270         
271         # if we still have not found the record yet, try the local registry
272 #        logger.debug("before trying local records, %d foreign records"% len(record_dicts))
273         if not record_dicts:
274             recursive = False
275             if ('recursive' in options and options['recursive']):
276                 recursive = True
277             elif hrn.endswith('*'):
278                 hrn = hrn[:-1]
279                 recursive = True
280
281             if not api.auth.hierarchy.auth_exists(hrn):
282                 raise MissingAuthority(hrn)
283             if recursive:
284                 records = dbsession.query(RegRecord).filter(RegRecord.hrn.startswith(hrn)).all()
285 #                logger.debug("recursive mode, found %d local records"%(len(records)))
286             else:
287                 records = dbsession.query(RegRecord).filter_by(authority=hrn).all()
288 #                logger.debug("non recursive mode, found %d local records"%(len(records)))
289             # so that sfi list can show more than plain names...
290             for record in records: augment_with_sfa_builtins (record)
291             record_dicts=[ record.todict(exclude_types=[InstrumentedList]) for record in records ]
292     
293         return record_dicts
294     
295     def CreateGid(self, api, xrn, cert):
296         # get the authority
297         authority = Xrn(xrn=xrn).get_authority_hrn()
298         auth_info = api.auth.get_auth_info(authority)
299         if not cert:
300             pkey = Keypair(create=True)
301         else:
302             certificate = Certificate(string=cert)
303             pkey = certificate.get_pubkey()    
304
305         # Add the email of the user to SubjectAltName in the GID
306         email = None
307         hrn = Xrn(xrn).get_hrn()
308         dbsession=api.dbsession()
309         record=dbsession.query(RegUser).filter_by(hrn=hrn).first()
310         if record:
311             email=getattr(record,'email',None)
312         gid = api.auth.hierarchy.create_gid(xrn, create_uuid(), pkey, email = email)
313         return gid.save_to_string(save_parents=True)
314     
315     ####################
316     # utility for handling relationships among the SFA objects 
317     
318     # subject_record describes the subject of the relationships
319     # ref_record contains the target values for the various relationships we need to manage
320     # (to begin with, this is just the slice x person (researcher) and authority x person (pi) relationships)
321     def update_driver_relations (self, api, subject_obj, ref_obj):
322         type=subject_obj.type
323         #for (k,v) in subject_obj.__dict__.items(): print k,'=',v
324         if type=='slice' and hasattr(ref_obj,'researcher'):
325             self.update_driver_relation(api, subject_obj, ref_obj.researcher, 'user', 'researcher')
326         elif type=='authority' and hasattr(ref_obj,'pi'):
327             self.update_driver_relation(api, subject_obj,ref_obj.pi, 'user', 'pi')
328         
329     # field_key is the name of one field in the record, typically 'researcher' for a 'slice' record
330     # hrns is the list of hrns that should be linked to the subject from now on
331     # target_type would be e.g. 'user' in the 'slice' x 'researcher' example
332     def update_driver_relation (self, api, record_obj, hrns, target_type, relation_name):
333         dbsession=api.dbsession()
334         # locate the linked objects in our db
335         subject_type=record_obj.type
336         subject_id=record_obj.pointer
337         # get the 'pointer' field of all matching records
338         link_id_tuples = dbsession.query(RegRecord.pointer).filter_by(type=target_type).filter(RegRecord.hrn.in_(hrns)).all()
339         # sqlalchemy returns named tuples for columns
340         link_ids = [ tuple.pointer for tuple in link_id_tuples ]
341         api.driver.update_relation (subject_type, target_type, relation_name, subject_id, link_ids)
342
343     def Register(self, api, record_dict):
344     
345         logger.debug("Register: entering with record_dict=%s"%printable(record_dict))
346         normalize_input_record (record_dict)
347         logger.debug("Register: normalized record_dict=%s"%printable(record_dict))
348
349         dbsession=api.dbsession()
350         hrn, type = record_dict['hrn'], record_dict['type']
351         urn = hrn_to_urn(hrn,type)
352         # validate the type
353         if type not in ['authority', 'slice', 'node', 'user']:
354             raise UnknownSfaType(type) 
355         
356         # check if record_dict already exists
357         existing_records = dbsession.query(RegRecord).filter_by(type=type,hrn=hrn).all()
358         if existing_records:
359             raise ExistingRecord(hrn)
360            
361         assert ('type' in record_dict)
362         # returns the right type of RegRecord according to type in record
363         record = make_record(dict=record_dict)
364         record.just_created()
365         record.authority = get_authority(record.hrn)
366         auth_info = api.auth.get_auth_info(record.authority)
367         pub_key = None
368         # make sure record has a gid
369         if not record.gid:
370             uuid = create_uuid()
371             pkey = Keypair(create=True)
372             pub_key=getattr(record,'reg-keys',None)
373             if pub_key is not None:
374                 # use only first key in record
375                 if pub_key and isinstance(pub_key, types.ListType): pub_key = pub_key[0]
376                 pkey = convert_public_key(pub_key)
377     
378             email=getattr(record,'email',None)
379             gid_object = api.auth.hierarchy.create_gid(urn, uuid, pkey, email = email)
380             gid = gid_object.save_to_string(save_parents=True)
381             record.gid = gid
382     
383         if isinstance (record, RegAuthority):
384             # update the tree
385             if not api.auth.hierarchy.auth_exists(hrn):
386                 api.auth.hierarchy.create_auth(hrn_to_urn(hrn,'authority'))
387     
388             # get the GID from the newly created authority
389             auth_info = api.auth.get_auth_info(hrn)
390             gid = auth_info.get_gid_object()
391             record.gid=gid.save_to_string(save_parents=True)
392
393             # locate objects for relationships
394             pi_hrns = getattr(record,'reg-pis',None)
395             if pi_hrns is not None: record.update_pis (pi_hrns, dbsession)
396
397         elif isinstance (record, RegSlice):
398             researcher_hrns = getattr(record,'reg-researchers',None)
399             if researcher_hrns is not None: record.update_researchers (researcher_hrns, dbsession)
400         
401         elif isinstance (record, RegUser):
402             # create RegKey objects for incoming keys
403             if hasattr(record,'reg-keys'):
404                 keys=getattr(record,'reg-keys')
405                 # some people send the key as a string instead of a list of strings
406                 if isinstance(keys,types.StringTypes): keys=[keys]
407                 logger.debug ("creating %d keys for user %s"%(len(keys),record.hrn))
408                 record.reg_keys = [ RegKey (key) for key in keys ]
409             
410         # update testbed-specific data if needed
411         pointer = api.driver.register (record.__dict__, hrn, pub_key)
412
413         record.pointer=pointer
414         dbsession.add(record)
415         dbsession.commit()
416     
417         # update membership for researchers, pis, owners, operators
418         self.update_driver_relations (api, record, record)
419         
420         return record.get_gid_object().save_to_string(save_parents=True)
421     
422     def Update(self, api, record_dict):
423
424         logger.debug("Update: entering with record_dict=%s"%printable(record_dict))
425         normalize_input_record (record_dict)
426         logger.debug("Update: normalized record_dict=%s"%printable(record_dict))
427
428         dbsession=api.dbsession()
429         assert ('type' in record_dict)
430         new_record=make_record(dict=record_dict)
431         (type,hrn) = (new_record.type, new_record.hrn)
432         
433         # make sure the record exists
434         record = dbsession.query(RegRecord).filter_by(type=type,hrn=hrn).first()
435         if not record:
436             raise RecordNotFound("hrn=%s, type=%s"%(hrn,type))
437         record.just_updated()
438     
439         # Use the pointer from the existing record, not the one that the user
440         # gave us. This prevents the user from inserting a forged pointer
441         pointer = record.pointer
442
443         # is there a change in keys ?
444         new_key=None
445         if type=='user':
446             if getattr(new_record,'keys',None):
447                 new_key=new_record.keys
448                 if isinstance (new_key,types.ListType):
449                     new_key=new_key[0]
450
451         # take new_key into account
452         if new_key:
453             # update the openssl key and gid
454             pkey = convert_public_key(new_key)
455             uuid = create_uuid()
456             urn = hrn_to_urn(hrn,type)
457
458             email=getattr(new_record,'email',None)
459             if email is None:
460                 email=getattr(record,'email',None)
461             gid_object = api.auth.hierarchy.create_gid(urn, uuid, pkey, email = email)
462             gid = gid_object.save_to_string(save_parents=True)
463         
464         # xxx should do side effects from new_record to record
465         # not too sure how to do that
466         # not too big a deal with planetlab as the driver is authoritative, but...
467
468         # update native relations
469         if isinstance (record, RegSlice):
470             researcher_hrns = getattr(new_record,'reg-researchers',None)
471             if researcher_hrns is not None: record.update_researchers (researcher_hrns, dbsession)
472
473         elif isinstance (record, RegAuthority):
474             pi_hrns = getattr(new_record,'reg-pis',None)
475             if pi_hrns is not None: record.update_pis (pi_hrns, dbsession)
476         
477         # update the PLC information that was specified with the record
478         # xxx oddly enough, without this useless statement, 
479         # record.__dict__ as received by the driver seems to be off
480         # anyway the driver should receive an object 
481         # (and then extract __dict__ itself if needed)
482         print "DO NOT REMOVE ME before driver.update, record=%s"%record
483         new_key_pointer = -1
484         try:
485            (pointer, new_key_pointer) = api.driver.update (record.__dict__, new_record.__dict__, hrn, new_key)
486         except:
487            pass
488         if new_key and new_key_pointer:
489             record.reg_keys=[ RegKey (new_key, new_key_pointer)]
490             record.gid = gid
491
492         dbsession.commit()
493         # update membership for researchers, pis, owners, operators
494         self.update_driver_relations (api, record, new_record)
495         
496         return 1 
497     
498     # expecting an Xrn instance
499     def Remove(self, api, xrn, origin_hrn=None):
500         dbsession=api.dbsession()
501         hrn=xrn.get_hrn()
502         type=xrn.get_type()
503         request=dbsession.query(RegRecord).filter_by(hrn=hrn)
504         if type and type not in ['all', '*']:
505             request=request.filter_by(type=type)
506     
507         record = request.first()
508         if not record:
509             msg="Could not find hrn %s"%hrn
510             if type: msg += " type=%s"%type
511             raise RecordNotFound(msg)
512
513         type = record.type
514         if type not in ['slice', 'user', 'node', 'authority'] :
515             raise UnknownSfaType(type)
516
517         credential = api.getCredential()
518         registries = api.registries
519     
520         # Try to remove the object from the PLCDB of federated agg.
521         # This is attempted before removing the object from the local agg's PLCDB and sfa table
522         if hrn.startswith(api.hrn) and type in ['user', 'slice', 'authority']:
523             for registry in registries:
524                 if registry not in [api.hrn]:
525                     try:
526                         result=registries[registry].remove_peer_object(credential, record, origin_hrn)
527                     except:
528                         pass
529
530         # call testbed callback first
531         # IIUC this is done on the local testbed TOO because of the refreshpeer link
532         if not api.driver.remove(record.__dict__):
533             logger.warning("driver.remove failed")
534
535         # delete from sfa db
536         dbsession.delete(record)
537         dbsession.commit()
538     
539         return 1
540
541     # This is a PLC-specific thing, won't work with other platforms
542     def get_key_from_incoming_ip (self, api):
543         dbsession=api.dbsession()
544         # verify that the callers's ip address exist in the db and is an interface
545         # for a node in the db
546         (ip, port) = api.remote_addr
547         interfaces = api.driver.shell.GetInterfaces({'ip': ip}, ['node_id'])
548         if not interfaces:
549             raise NonExistingRecord("no such ip %(ip)s" % locals())
550         nodes = api.driver.shell.GetNodes([interfaces[0]['node_id']], ['node_id', 'hostname'])
551         if not nodes:
552             raise NonExistingRecord("no such node using ip %(ip)s" % locals())
553         node = nodes[0]
554        
555         # look up the sfa record
556         record=dbsession.query(RegRecord).filter_by(type='node',pointer=node['node_id']).first()
557         if not record:
558             raise RecordNotFound("node with pointer %s"%node['node_id'])
559         
560         # generate a new keypair and gid
561         uuid = create_uuid()
562         pkey = Keypair(create=True)
563         urn = hrn_to_urn(record.hrn, record.type)
564
565         email=getattr(record,'email',None)
566         gid_object = api.auth.hierarchy.create_gid(urn, uuid, pkey, email)
567         gid = gid_object.save_to_string(save_parents=True)
568         record.gid = gid
569
570         # update the record
571         dbsession.commit()
572   
573         # attempt the scp the key
574         # and gid onto the node
575         # this will only work for planetlab based components
576         (kfd, key_filename) = tempfile.mkstemp() 
577         (gfd, gid_filename) = tempfile.mkstemp() 
578         pkey.save_to_file(key_filename)
579         gid_object.save_to_file(gid_filename, save_parents=True)
580         host = node['hostname']
581         key_dest="/etc/sfa/node.key"
582         gid_dest="/etc/sfa/node.gid" 
583         scp = "/usr/bin/scp" 
584         #identity = "/etc/planetlab/root_ssh_key.rsa"
585         identity = "/etc/sfa/root_ssh_key"
586         scp_options=" -i %(identity)s " % locals()
587         scp_options+="-o StrictHostKeyChecking=no " % locals()
588         scp_key_command="%(scp)s %(scp_options)s %(key_filename)s root@%(host)s:%(key_dest)s" %\
589                          locals()
590         scp_gid_command="%(scp)s %(scp_options)s %(gid_filename)s root@%(host)s:%(gid_dest)s" %\
591                          locals()    
592
593         all_commands = [scp_key_command, scp_gid_command]
594         
595         for command in all_commands:
596             (status, output) = commands.getstatusoutput(command)
597             if status:
598                 raise Exception, output
599
600         for filename in [key_filename, gid_filename]:
601             os.unlink(filename)
602
603         return 1