better filtering when importing. ignore DSA keys.
[sfa.git] / plc / import.py
1 ##
2 # Import PLC records into the Geni database. It is indended that this tool be
3 # run once to create Geni records that reflect the current state of the
4 # planetlab database.
5 #
6 # The import tool assumes that the existing PLC hierarchy should all be part
7 # of "planetlab.us" (see the root_auth and level1_auth variables below).
8 #
9 # Public keys are extracted from the users' SSH keys automatically and used to
10 # create GIDs. This is relatively experimental as a custom tool had to be
11 # written to perform conversion from SSH to OpenSSL format. It only supports
12 # RSA keys at this time, not DSA keys.
13 ##
14
15 import getopt
16 import sys
17 import tempfile
18
19 from cert import *
20 from trustedroot import *
21 from hierarchy import *
22 from record import *
23 from genitable import *
24 from misc import *
25
26 shell = None
27
28 ##
29 # Two authorities are specified: the root authority and the level1 authority.
30
31 root_auth = "planetlab"
32 level1_auth = "planetlab.us"
33
34 def un_unicode(str):
35    if isinstance(str, unicode):
36        return str.encode("ascii", "ignore")
37    else:
38        return str
39
40 def cleanup_string(str):
41     # pgsql has a fit with strings that have high ascii in them, so filter it
42     # out when generating the hrns.
43     tmp = ""
44     for c in str:
45         if ord(c) < 128:
46             tmp = tmp + c
47     str = tmp
48
49     str = un_unicode(str)
50     str = str.replace(" ", "_")
51     str = str.replace(".", "_")
52     str = str.replace("(", "_")
53     str = str.replace("'", "_")
54     str = str.replace(")", "_")
55     str = str.replace('"', "_")
56     return str
57
58 def process_options():
59    global hrn
60
61    (options, args) = getopt.getopt(sys.argv[1:], '', [])
62    for opt in options:
63        name = opt[0]
64        val = opt[1]
65
66 def connect_shell():
67     global pl_auth, shell
68
69     # get PL account settings from config module
70     pl_auth = get_pl_auth()
71
72     # connect to planetlab
73     if "Url" in pl_auth:
74         import remoteshell
75         shell = remoteshell.RemoteShell()
76     else:
77         import PLC.Shell
78         shell = PLC.Shell.Shell(globals = globals())
79
80 def get_auth_table(auth_name):
81     auth_info = AuthHierarchy.get_auth_info(auth_name)
82
83     table = GeniTable(hrn=auth_name,
84                       cninfo=auth_info.get_dbinfo())
85
86     # if the table doesn't exist, then it means we haven't put any records
87     # into this authority yet.
88
89     if not table.exists():
90         report.trace("Import: creating table for authority " + auth_name)
91         table.create()
92
93     return table
94
95 def get_pl_pubkey(key_id):
96     keys = shell.GetKeys(pl_auth, [key_id])
97     if keys:
98         key_str = keys[0]['key']
99
100         if "ssh-dss" in key_str:
101             print "XXX: DSA key encountered, ignoring"
102             return None
103
104         # generate temporary files to hold the keys
105         (ssh_f, ssh_fn) = tempfile.mkstemp()
106         ssl_fn = tempfile.mktemp()
107
108         os.write(ssh_f, key_str)
109         os.close(ssh_f)
110
111         cmd = "../keyconvert/keyconvert " + ssh_fn + " " + ssl_fn
112         print cmd
113         os.system(cmd)
114
115         # this check leaves the temporary file containing the public key so
116         # that it can be expected to see why it failed.
117         # TODO: for production, cleanup the temporary files
118         if not os.path.exists(ssl_fn):
119             report.trace("  failed to convert key from " + ssh_fn + " to " + ssl_fn)
120             return None
121
122         k = Keypair()
123         try:
124             k.load_pubkey_from_file(ssl_fn)
125         except:
126             print "XXX: Error while converting key: ", key_str
127             k = None
128
129         # remove the temporary files
130         os.remove(ssh_fn)
131         os.remove(ssl_fn)
132
133         return k
134     else:
135         return None
136
137 def person_to_hrn(parent_hrn, person):
138     personname = person['last_name'] + "_" + person['first_name']
139
140     personname = cleanup_string(personname)
141
142     hrn = parent_hrn + "." + personname
143     return hrn
144
145 def import_person(parent_hrn, person):
146     hrn = person_to_hrn(parent_hrn, person)
147
148     # ASN.1 will have problems with hrn's longer than 64 characters
149     if len(hrn) > 64:
150         hrn = hrn[:64]
151
152     report.trace("Import: importing person " + hrn)
153
154     table = get_auth_table(parent_hrn)
155
156     person_record = table.resolve("slice", hrn)
157     if not person_record:
158         key_ids = person["key_ids"]
159
160         if key_ids:
161             # get the user's private key from the SSH keys they have uploaded
162             # to planetlab
163             pkey = get_pl_pubkey(key_ids[0])
164         else:
165             # the user has no keys
166             report.trace("   person " + hrn + " does not have a PL public key")
167             pkey = None
168
169         # if a key is unavailable, then we still need to put something in the
170         # user's GID. So make one up.
171         if not pkey:
172             pkey = Keypair(create=True)
173
174         person_gid = AuthHierarchy.create_gid(hrn, create_uuid(), pkey)
175         person_record = GeniRecord(name=hrn, gid=person_gid, type="user", pointer=person['person_id'])
176         report.trace("  inserting user record for " + hrn)
177         table.insert(person_record)
178
179 def import_slice(parent_hrn, slice):
180     slicename = slice['name'].split("_",1)[-1]
181     slicename = cleanup_string(slicename)
182
183     if not slicename:
184         report.error("Import_Slice: failed to parse slice name " + slice['name'])
185         return
186
187     hrn = parent_hrn + "." + slicename
188     report.trace("Import: importing slice " + hrn)
189
190     table = get_auth_table(parent_hrn)
191
192     slice_record = table.resolve("slice", hrn)
193     if not slice_record:
194         pkey = Keypair(create=True)
195         slice_gid = AuthHierarchy.create_gid(hrn, create_uuid(), pkey)
196         slice_record = GeniRecord(name=hrn, gid=slice_gid, type="slice", pointer=slice['slice_id'])
197         report.trace("  inserting slice record for " + hrn)
198         table.insert(slice_record)
199
200 def import_site(parent_hrn, site):
201     sitename = site['login_base']
202     sitename = cleanup_string(sitename)
203
204     hrn = parent_hrn + "." + sitename
205
206     report.trace("Import_Site: importing site " + hrn)
207
208     # create the authority
209     if not AuthHierarchy.auth_exists(hrn):
210         AuthHierarchy.create_auth(hrn)
211
212     auth_info = AuthHierarchy.get_auth_info(hrn)
213
214     table = get_auth_table(parent_hrn)
215
216     sa_record = table.resolve("sa", hrn)
217     if not sa_record:
218         sa_record = GeniRecord(name=hrn, gid=auth_info.get_gid_object(), type="sa", pointer=site['site_id'])
219         report.trace("  inserting sa record for " + hrn)
220         table.insert(sa_record)
221
222     ma_record = table.resolve("ma", hrn)
223     if not ma_record:
224         ma_record = GeniRecord(name=hrn, gid=auth_info.get_gid_object(), type="ma", pointer=site['site_id'])
225         report.trace("  inserting ma record for " + hrn)
226         table.insert(ma_record)
227
228     for person_id in site['person_ids']:
229         persons = shell.GetPersons(pl_auth, [person_id])
230         if persons:
231             import_person(hrn, persons[0])
232
233     for slice_id in site['slice_ids']:
234         slices = shell.GetSlices(pl_auth, [slice_id])
235         if slices:
236             import_slice(hrn, slices[0])
237
238 def create_top_level_auth_records(hrn):
239     parent_hrn = get_authority(hrn)
240
241     auth_info = AuthHierarchy.get_auth_info(parent_hrn)
242     table = get_auth_table(parent_hrn)
243
244     sa_record = table.resolve("sa", hrn)
245     if not sa_record:
246         sa_record = GeniRecord(name=hrn, gid=auth_info.get_gid_object(), type="sa", pointer=-1)
247         report.trace("  inserting sa record for " + hrn)
248         table.insert(sa_record)
249
250     ma_record = table.resolve("ma", hrn)
251     if not ma_record:
252         ma_record = GeniRecord(name=hrn, gid=auth_info.get_gid_object(), type="ma", pointer=-1)
253         report.trace("  inserting ma record for " + hrn)
254         table.insert(ma_record)
255
256 def main():
257     global AuthHierarchy
258     global TrustedRoots
259
260     process_options()
261
262     AuthHierarchy = Hierarchy()
263     TrustedRoots = TrustedRootList()
264
265     print "Import: creating top level authorities"
266
267     if not AuthHierarchy.auth_exists(root_auth):
268         AuthHierarchy.create_auth(root_auth)
269     #create_top_level_auth_records(root_auth)
270     if not AuthHierarchy.auth_exists(level1_auth):
271         AuthHierarchy.create_auth(level1_auth)
272     create_top_level_auth_records(level1_auth)
273
274     print "Import: adding", root_auth, "to trusted list"
275     root = AuthHierarchy.get_auth_info(root_auth)
276     TrustedRoots.add_gid(root.get_gid_object())
277
278     connect_shell()
279
280     sites = shell.GetSites(pl_auth)
281     for site in sites:
282         import_site(level1_auth, site)
283
284 if __name__ == "__main__":
285     main()