Imported Upstream version 1.10.2
[platform/upstream/krb5.git] / src / tests / mk_migr / db2_backend / mkmdb2.py
1 # Master Key Migration for db2
2
3 import os, sys, shutil, socket, time, string
4 from subprocess import Popen, PIPE
5 from optparse import OptionParser
6 from time import strftime
7
8 class MasterKeyMigrationTest:
9     def __init__(self, verbose_in, pw_in,  kdcPath_in, kdmdPath_in, kdbPath_in, kdmlPath_in, kdmPath_in, cltPath_in, sandir_in):
10         self.npass = 0
11         self.nfail = 0
12
13         self.verbose = verbose_in
14         self.pw = pw_in
15
16         self.krb5kdc = kdcPath_in #1 krb5kdc
17         self.kadmind = kdmdPath_in #2 kadmind
18         self.kdb5_util = kdbPath_in #3 kdb5_util
19         self.kadminlocal = kdmlPath_in #4 kadmin.local
20         self.kadmin = kdmPath_in #5 kadmin
21         self.clients = cltPath_in+"/" #6 clients
22
23         self.sandir = sandir_in
24
25         ########## SET UP Write Output File #####
26         self.outfile = open(self.sandir+"/outfile", 'w')
27
28         '''print os.environ'''
29
30     def _writeLine(self, astr, prt=False):
31         self.outfile.write(astr.strip()+"\n")
32         if prt:
33             print astr.strip()
34
35     def _writeHeader(self, astr, prt=True):
36         self.outfile.write("\n========== "+astr.strip()+" ==========\n")
37         if prt:
38             print "========== "+astr.strip()+" =========="
39     
40     def _sysexit(self, fatal=False, finished=False):
41         self._writeLine("++++++++++++++++++++++++++++++", True)
42         if fatal:
43             self._writeLine("++++ Test did NOT finish +++++", True)
44             self._writeLine("++++ FATAL FAILURE! Stopped ++", True)
45             self._writeLine("++++ See sandbox/outfile +++++", True)
46             self._writeLine("++++++++++++++++++++++++++++++", True)
47             sys.exit()
48         elif not finished:
49             self._writeLine("++++ Test did NOT finish +++++", True)
50             self._writeLine("++++ FAIL Detected! keep going", True)
51             self._writeLine("++++++++++++++++++++++++++++++", True)
52         else: #finished
53             self._writeLine("++++ MKM Test Finished +++++++", True)
54             self._writeLine("++++++++++++++++++++++++++++++", True)
55             self._writeLine("++++ Commands Passed: %s +++++" % self.npass, True)
56             self._writeLine("++++ Commands Failed: %s +++++" % self.nfail, True)
57             sys.exit()
58         
59     def _printig(self):
60         self._writeLine("~.~.~Error should be ignored~.~.~.~")
61
62     def _printerr(self, errm, stderr):
63         self._writeLine("#@#@#@#@#@#@#@#@#@#@#@#@#@#@#@#@#@#@#@#@#@#@#@#@#@#")
64         self._writeLine("-XX-FAILED: "+errm+". See stderr below:")
65         [self._writeLine(line) for line in stderr.readlines() ]
66
67     def _printout(self, cmd, pstdout):
68         if self.verbose:
69             self._writeLine("---------------------------------------")
70             self._writeLine("-command: "+cmd)
71             self._writeLine("-----out: ")
72             [self._writeLine(line) for line in pstdout.readlines()]
73
74     def _eval(self, succeed, pwait, errm, pstderr, fatal=False, msg2="", finished=False):
75         if int(pwait) != 0: # is bad
76             self._printerr(errm, pstderr)
77             if succeed==True: ## want good
78                 self.nfail += 1
79                 self._sysexit(fatal, finished)
80             else: ## want bad
81                 self.npass += 1
82                 self._printig()
83         else: # is good
84             if not succeed: ## want bad
85                 if msg2 != "":
86                     self._writeLine(msg2, True)
87                 self.nfail += 1
88                 self._sysexit(fatal, finished)
89             else: ## want good
90                 self.npass += 1 
91
92     def _metafunc(self, command,  errmsg, moreinfo="", isLocal=False, succeed=True, fatal=False):
93         l = command
94         if isLocal:
95             pl = Popen(l.split(None,2), stdin=PIPE, stdout=PIPE, stderr=PIPE)
96         else:
97             pl = Popen(l.split(), stdin=PIPE, stdout=PIPE, stderr=PIPE)
98         self._printout(l+moreinfo, pl.stdout)
99         
100         self._eval(succeed, pl.wait(), errmsg, pl.stderr, fatal)
101     
102     ###########################################
103
104     # Start the KDC daemons
105     def _startkdc(self):
106         self._writeLine("\nstarting kdc daemons ...")
107         l0 = self.krb5kdc
108         errm = "error at starting krb5kdc"
109         self._metafunc(l0, errm)
110         # below has been changed
111         l0b = self.kadmind + ' -W -nofork' #the W is for during off strong random numbers
112         errm = "error at starting kadmind, maybe it's already started"
113         pl0b = Popen(l0b.split(), stdin=PIPE, stdout=PIPE, stderr=PIPE)
114         self._writeLine( "kadmind -nofork")
115         started = False
116         while time.clock() < 3:
117             l = pl0b.stderr.readline()
118             if l.find("starting") > -1:
119                 self._writeLine( l.strip())          
120                 self.npass += 1
121                 started = True
122                 break  
123         else:
124             self.nfail += 1
125             self._printerr("kadmind not starting, check to see if there are any previous kadmind running with cmd: 'ps -ef | grep kadmind' and then do 'sudo kill -9 [# on the left]'", pl0b.stderr)
126             self._sysexit(fatal=True)
127         if not started:
128             self.nfail += 1
129             self._sysexit()
130         self._writeLine("end starting kdc daemons")
131
132     # Kill the KDC daemons in case they are running
133     def _killkdc(self, suc=True):
134         l1 = 'pkill -9 -x krb5kdc'
135         errm = "no krb5kdc killed"
136         self._metafunc(l1, errm, succeed=suc)
137         
138         l2 = 'pkill -9 -x kadmind'
139         errm = "no kadmind killed"
140         self._metafunc(l2, errm, succeed=suc)
141
142     # Destroys current database
143     def _destroykdc(self, suc=True):
144         l3 = self.kdb5_util+' destroy -f' #forced
145         errm = "no kdb database destroyed"
146         self._metafunc(l3, errm, succeed=suc)
147
148     # Create a new database with a new master key
149     def _createdb(self, pw):
150         l4 = self.kdb5_util+' -P '+pw+' create -s -W' #added W for svn version 22435 to avoid reading strong random numbers
151         errm = "error when creating new database, _createdb()"
152         self._metafunc(l4, errm, fatal=True)
153
154     # Addprinc
155     def _locAddprinc(self, passw, usern):
156         l5 = self.kadminlocal+' -q addprinc -pw '+passw+' '+usern
157         errm = "error when adding princ, _locAddprinc"
158         self._metafunc(l5, errm, isLocal=True)
159
160     # List princs
161     def _locListprincs(self):
162         l6 = self.kadminlocal+' -q listprincs'
163         errm = "error when listing princs, _locListprincs"        
164         self._metafunc(l6, errm, isLocal=True)
165
166     #  Get princs
167     def _locGetprinc(self, usern, extra=False, succeed=True):
168         l7 = self.kadminlocal+' -q getprinc '+usern
169         errm="error when getting princ, _locGetprinc"
170
171         pl7 = Popen(l7.split(None,2), stdin=PIPE, stdout=PIPE, stderr=PIPE)
172         if not extra:
173             self._printout(l7, pl7.stdout)
174         else:
175             if self.verbose:
176                 self._writeLine("-command: "+l7)
177                 self._writeLine("-----out: ")
178                 for line in pl7.stdout.readlines():
179                     if line.startswith("Princ") or line.startswith("MKey"):
180                         self._writeLine(line)
181         self._eval(succeed, pl7.wait(), errm, pl7.stderr)
182
183     # Get princs and finds something in the output
184     def _locGetprincFind(self, usern, findstr, succeed=True):
185         l7b = self.kadminlocal+' -q getprinc ' +usern
186         errm="error when getting princs, _locGetprinc, (regular output of getprincs is not printed here), will NOT continue to find string="+findstr
187         pl7b = Popen(l7b.split(None, 2), stdin=PIPE, stdout=PIPE, stderr=PIPE)
188         if self.verbose:
189             self._writeLine("-command: "+l7b)
190         if int(pl7b.wait()) != 0: # is bad
191             self._printerr(errm, pl7b.stderr)
192             if succeed: ## want good
193                 self.nfail += 1
194                 self._sysexit()
195             else: ## want bad
196                 self.npass += 1
197                 self._printig()
198         else: # is good
199             if self.verbose:            
200                 self._writeLine( "-----out: ")
201             boofound = False
202             for outl in pl7b.stdout.readlines():
203                 self._writeLine(outl)
204                 if string.find(outl, findstr) > -1:
205                     boofound = True
206             if boofound:
207                 self._writeLine("----FOUND: "+findstr)
208             else:
209                 self._writeLine("----NOT FOUND: "+findstr)
210             if not succeed: ## want bad
211                 self.nfail += 1
212                 self._sysexit()
213             else: ## want good
214                 self.npass += 1
215
216     # Add policy
217     def _locAddpol(self, maxtime, minlength, minclasses, history, policyname):
218         rest = ""
219         if maxtime != None:
220             rest += '-maxlife '+maxtime+' '
221         if minlength != None:
222             rest += '-minlength '+minlength+' '
223         if minclasses != None:
224             rest += '-minclasses '+minclasses+' '
225         if history != None:
226             rest += '-history '+history+' '
227         l8 = self.kadminlocal+' -q add_policy '+rest+policyname
228         errm = "error when adding policy, _locAddpol"
229         self._metafunc(l8, errm, isLocal=True)  
230
231     #  Get pol
232     def _locGetpol(self, poln):
233         l8b = self.kadminlocal+' -q getpol '+poln
234         errm="error when getting pol, _locGetpol"
235         self._metafunc(l8b, errm, isLocal=True)
236
237     # Modify Principal
238     def _locModprinc(self, rest):
239         l9 = self.kadminlocal+' -q modprinc '+rest
240         errm = "error when modifing principal, _locModprinc"
241         self._metafunc(l9, errm, isLocal=True)
242
243     # List mkeys
244     def _listmkeys(self):
245         l10 = self.kdb5_util+' list_mkeys'
246         errm = "error when listing mkeys, _listmkeys"
247         self._metafunc(l10, errm)
248
249     # Use mkeys
250     def _usemkey(self, kvno, time, succeed=True):
251         l11 = self.kdb5_util+' use_mkey '+kvno+' '+time
252         pl11 = Popen(l11.split(), stdin=PIPE, stdout=PIPE, stderr=PIPE)
253         self._printout(l11, pl11.stdout)
254         self._eval(succeed, pl11.wait(), "error when using mkeys, _usemkey", pl11.stderr, msg2="-XX-ERROR: "+l11+" should have failed.")        
255
256         
257     # Change password (cpw)
258     def _locCpw(self, passw, usern):
259         l12 = self.kadminlocal+' -q cpw -pw '+passw+' '+usern
260         errm = "error when changing password, _locCpw"
261         self._metafunc(l12, errm, moreinfo="\n--------: newpw='"+passw+"'", isLocal=True)
262
263     # Purge mkeys
264     def _purgemkeys(self):
265         l13 = self.kdb5_util+' purge_mkeys -f -v' #-f is forced, -v is verbose
266         errm = "error when purging mkeys, _purgemkeys"
267         self._metafunc(l13, errm)
268
269     # Add mkey
270     def _addmkey(self, passw, extra="", succeed=True):
271         l14 = self.kdb5_util+' add_mkey '+extra
272         pl14 = Popen(l14.split(), stdin=PIPE, stdout=PIPE, stderr=PIPE) 
273         pl14.stdin.write(passw+'\n') #enter 1st time
274         pl14.stdin.write(passw+'\n') #re-enter    
275         self._printout(l14+' [with password='+passw+']', pl14.stdout)
276         self._eval(succeed, pl14.wait(), "error when adding mkey, _addmkey", pl14.stderr)
277         self._writeLine( "----end of adding mkey")
278
279     # kinit user
280     def _kinit(self, passw_in, usern, succeed=True):
281         l15 = self.clients+'kinit/kinit '+usern
282         pl15 = Popen(l15.split(), stdin=PIPE, stdout=PIPE, stderr=PIPE)
283         pl15.stdin.write(passw_in+'\n')
284         pl15.stdin.close()
285         self._printout(l15, pl15.stdout)
286         self._eval(succeed, pl15.wait(), "error when kinit user, _kinit", pl15.stderr)
287         self._writeLine( "----end of kiniting user")
288
289     # change password on client's side
290     def _kpasswd(self, oldpw, newpw, usern, succeed=True):
291         l16 = self.clients+'kpasswd/kpasswd '+usern
292         pl16 = Popen(l16.split(), stdin=PIPE, stdout=PIPE, stderr=PIPE)
293         pl16.stdin.write(oldpw+'\n')
294         pl16.stdin.write(newpw+'\n')
295         pl16.stdin.write(newpw+'\n')
296         self._printout(l16+"\n--------: oldpw='"+oldpw+"' -> newpw='"+newpw+"'", pl16.stdout)
297         self._eval(succeed, pl16.wait(), "error when changing password on client's side, _kpasswd", pl16.stderr)
298         self._writeLine("----end of changing kpasswd")
299
300     # klist on client's side
301     def _klist(self):
302         l17 = self.clients+'klist/klist'
303         errm = "error when klist, _klist"
304         self._metafunc(l17, errm)
305
306     # Update principal encryption
307     def _updatePrincEnc(self):
308         l18 = self.kdb5_util+' update_princ_encryption -f -v'
309         errm = "error when updating principal encryption, _updatePrincEnc"
310         self._metafunc(l18, errm)
311
312     # kdestroy
313     def _kdestroy(self):
314         l19 = self.clients+'kdestroy/kdestroy'
315         errm = "error when kdestroy, _kdestroy"
316         self._metafunc(l19, errm)
317
318     # stash
319     def _stash(self):
320         l20 = self.kdb5_util+' stash'
321         errm="error at stash, _stash"
322         self._metafunc(l20, errm)
323
324     # any shell command
325     def _shell(self, command, succeed=True):
326         l21 = command
327         errm="error at executing this command in _shell(): "+l21
328         pl21 = Popen(l21, shell=True, stdin=PIPE, stdout=PIPE, stderr=PIPE)
329         self._printout(l21, pl21.stdout)
330         self._eval(succeed, pl21.wait(), errm, pl21.stderr)
331         '''self._printerr(errm, pl21.stderr)  Pointed out that kadmin had problems!'''
332
333     # get_princ_records()
334     def _get_princ_records(self, succeed=True):
335         l22 = self.kadminlocal+" -q listprincs 2>/dev/null|grep -v '^Authenticating as'|fgrep '@'|sort"
336         errm="error at listprincs in _get_princ_records() with this command: "+l22
337         pl22 = Popen(l22, shell=True, stdin=PIPE, stdout=PIPE, stderr=PIPE)
338         if int(pl22.wait()) != 0: # is bad
339             self.printerr(errm, pl22.stderr)
340             if succeed: ## want good
341                 self.nfail += 1
342                 self._sysexit()
343             else: ## want badd
344                 self.npass += 1
345                 self._printig()
346         else: # is good
347             if not succeed: ## want bad
348                 self.nfail += 1
349                 self._sysexit()
350             else: ## want good
351                 self.npass += 1
352                 self._writeLine( "\nget_princ_records() executing all listprincs command: "+l22+"\n------its results:")
353                 for princ in pl22.stdout.readlines():
354                     self._locGetprinc(princ.strip(), extra=True)
355                 self._writeLine("END executing command: "+l22+"\n~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~")
356         
357 ######################################################
358     def run(self):
359         #############RUN###################
360         passw=self.pw        
361     
362         self._writeHeader("START MASTER KEY MIGRATION TEST")        
363
364         # Set up database
365         self._writeHeader("SET UP: database")
366         self._killkdc("Either") #74 =1,2
367         self._destroykdc("Either") #77 =3
368         self._createdb(passw) #81 =4
369         #line 83-86 involves ktadd kadm5.keytab, which are out dated
370         
371         # add, get, and list princs
372         self._writeHeader("SET UP: add/get/list princs")        
373         self._locAddprinc(passw, 'kdc/admin') #87 =5
374         self._locListprincs() #89 =6
375         self._locGetprinc('K/M') #90 =7
376         self._locAddprinc('test123', 'haoqili') #91 =8
377         self._locGetprinc('haoqili') #92 =9
378         self._locAddprinc(passw, 'haoqili/admin') #93 =10
379         self._locAddprinc('foobar', 'test') #94 =11
380         self._locGetprinc('test') #95 =12
381         self._locListprincs() # I added =13
382         myfqdn = socket.getfqdn()
383         #self._shell(self.parentpath+"kadmin.local -q 'addprinc -randkey host/"+myfqdn+"'") #96
384         self._shell(self.kadminlocal+" -q 'addprinc -randkey host/"+myfqdn+"'") #96 =14
385         
386         # create policies
387         self._writeHeader("SET UP: create policies")
388         #print "\n~~~~~~~~~ create policies ~~~~~~~~~~~"
389         self._locAddpol('8days', None, None, None, 'testpolicy')#100 =15
390         self._locAddpol('20days', '8', '3', None,  'testpolicy2')#101 
391         self._locAddpol('90days', '2', '2', None,  'testpolicy3')#102
392         self._locAddpol('90days', '2', '2', '3', 'testpolicy4')#103
393             
394         self._locModprinc('-policy testpolicy haoqili')#105
395         self._locAddprinc(passw, 'foo')#106
396         self._locModprinc('-policy testpolicy3 foo')#107 =21
397         
398         # create all princ with all fields
399         self._writeHeader("SET UP: create all princ with all fields")
400         #print "\n~~~~~~~~~ create all princ with all fields ~~~~~"
401         self._locAddprinc(passw, 'all') #110 =22
402         self._locModprinc('-expire "2029-12-30 7pm" all') #112
403         self._locModprinc('-pwexpire 12/30/2029 all') #114
404         self._locGetprinc('all') #115
405         self._locModprinc('-maxlife 100days all') #116
406         self._locGetprinc('all') #117
407         self._locModprinc('-maxrenewlife 100days all') #118
408         self._locGetprinc('all') #119
409         self._locModprinc('+allow_postdated +allow_forwardable all') #120 =30
410         self._locModprinc('+allow_proxiable +allow_dup_skey all') #121
411         self._locModprinc('+requires_preauth +allow_svr +needchange all') #122
412         self._locModprinc('-policy testpolicy4 all') #123
413         self._locGetprinc('all') #124 =34
414         
415         # Testing stuff
416         self._writeHeader("TEST: initial mkey list") #126
417         self._writeLine("===== Listing mkeys at start of test") #I add
418         self._listmkeys() #127 =35
419         
420         self._writeLine( "Testing krb5kdc list_mkeys Done ==============================================") #128
421
422         self._writeLine("---------------\n xxxxxxxxxx \/\/\/ ERRORS (multiple) EXPECTED below xxxxxxxxxx")
423         self._writeLine("\nERRORS (multiple) EXPECTED below") 
424         self._writeLine("Testing bogus use_mkey (setting only mkey to future date, using non-existent kvno, so should return error) =======") #129, 130
425         self._writeLine( "-> must have a mkey currently active (setting mkey to 2 days from now), should fail and return error") #132     
426         self._usemkey('1', 'now+2days', False) #133-138 =36
427         
428         self._writeLine("-> must have a mkey currently active (setting mkey to 2019 the future), should fail and return error") #140
429         self._usemkey('1', '5/30/2019', False) #141 =37
430         self._writeLine("-> bogus kvno and setting mkey to 2 days from now, should fail and return error") #147
431         self._usemkey('2', 'now+2days', False) #148 =38
432         self._writeLine("-> bogus kvno, should fail and return error") #I add
433         self._usemkey('2', 'now-2days', False) #I add =39
434         self._writeLine( "^^^ABOVE^^ SHOULD HAVE *ALL* FAILED\n-----------------")
435
436         self._writeLine( "Listing mkeys at end of test") #I add
437         self._listmkeys() #155 =40
438         self._writeLine("Testing bogus use_mkey (setting only mkey to future date) Done ===========================") #156
439         
440         
441         self._writeLine("\nmake sure cpw [change password] works") #158
442         # this changes the password of 'test' from 'foobar' in "add, get, and list princs" above
443         self._locCpw('test1', 'test') #159 =41
444
445         self._writeHeader("TEST: bogus purge_mkeys (should be no keys purged, no error returned")
446         #print "\nTesting bogus purge_mkeys (should be no keys purged, no error returned) ===========================" #161
447         self._purgemkeys() #162 =42
448         self._writeLine("Testing bogus purge_mkeys (no error) Done ===========================") #163
449         
450         self._writeLine( "\nadd kvno 2") #164
451         self._addmkey('abcde', '-s') #165-167 =43
452         self._writeLine("\nlist mkeys")
453         self._listmkeys() #169 =44
454         
455         #start daemons
456         self._startkdc() #172 =45 46
457         self._writeLine("make sure kdc is up, by kinit test") #176
458         self._kinit('test1', 'test') #177 =47
459         
460         self._writeLine("---------------\n\/\/\/ ERROR EXPECTED below.  Test passwd policy.:") #180
461         self._kinit(passw, 'all', succeed=False) #181 =48
462         self._writeLine("^^ABOVE^^ SHOULD HAVE FAILED\n-----------------")
463         
464         #change passwd on client's side
465         self._kpasswd(passw, 'Test123.', 'all')#184-188 =49
466
467         self._kinit('Test123.', 'all') #189 =50
468         self._klist() #190 =51
469         
470         self._writeHeader("TEST: password history for principal 'all', new passwords must not be a previous password") #191
471         self._kpasswd('Test123.', 'Foobar2!', 'all') #192-195 =52
472         self._writeLine("--------------\n\/\/\/ ERROR EXPECTED below") #197
473         self._kpasswd('Foobar2!', passw, 'all', succeed=False) #199-202 =53
474         self._writeLine("^^^ABOVE^^ SHOULD HAVE FAILED\n----------")
475         
476         # this shouldn't change the mkvno for any princs (should be 1) #206
477         #self._updatePrincEnc() #207
478         # princs should still be protected by mkvno 1 #208
479         self._writeLine("@@@@@@@@ Wait for other people to fix bug in code 6507 update_princ_encryption to use mkey instead of latest mkey @@@@@@@@@@@@@\n")
480         self._locGetprincFind('test', 'MKey: vno 1') #209 =54
481                
482         self._purgemkeys() #210 =55   
483         self._listmkeys() #211 =56
484         self._usemkey('2', 'now-1day') #213 =57
485         self._listmkeys() #214 =58
486         
487         self._writeLine("-----------\n\/\/\/ ERROR EXPECTED below") #216
488         self._kpasswd('Foobar2!', passw, 'all', succeed=False) #217-221 =59
489         self._writeLine("^^^ABOVE^^ SHOULD HAVE FAILED\n--------") 
490         
491         self._kpasswd('Foobar2!', 'Barfoo3.', 'all') #224-228 =60
492         self._kinit('Barfoo3.', 'all') #229
493         self._klist() #230 =62
494         
495         self._writeLine("-------------\n\/\/\/ ERROR EXPECTED below") #231
496         self._kpasswd('Barfoo3.', 'Foobar2!', 'all',succeed=False) #233-235 =63
497         self._writeLine("^^^ABOVE^^ SHOULD HAVE FAILED\n---------")
498         
499         self._writeLine("\nTest's key should be protected by mkvno 2" ) #239
500         self._locCpw('foo', 'test') #240 =64
501         self._locGetprincFind('test', 'MKey: vno 2') #241 =65
502         self._kdestroy() #242 =66
503         
504         self._writeHeader("TEST: krb5kdc refetch of mkey")#243
505         self._kinit('foo', 'test') #244 =67
506         self._klist() #245 =68
507         self._writeLine("END. Testing krb5kdc refetch of mkey list Done ==============================================\n")     #246
508         
509         self._updatePrincEnc() #247 =69
510         self._get_princ_records() #248 =70 -83
511         self._kdestroy() #249 =84
512         self._kinit('foo', 'test') #250 =85
513         self._purgemkeys() #252 =86
514         
515         self._stash() #254 =87
516         self._shell(self.clients+'klist/klist' +" -ekt "+self.sandir+"/keyStashFile") #255 =88
517         
518         self._locGetprinc('K/M') #256 =89
519         self._purgemkeys() #257 =90
520         self._locGetprinc('K/M') #258
521         self._listmkeys() #259 =92
522         self._kdestroy() #260
523         self._kinit('foo', 'test') #261
524         self._klist() #262 =95
525    
526         self._writeLine("\n Adding in Master Key Number 3")
527         self._listmkeys() #265 =96
528         self._addmkey('abcde') #266-268
529         self._listmkeys() #270 =98
530         self._locCpw('foo', 'all') #271
531         self._locGetprinc('all') #272 =100
532         self._usemkey('3', 'now') #273
533         self._listmkeys() #274 =102
534         self._locCpw('99acefghI0!', 'all') #275
535         self._locGetprinc('all') #276 =104
536         self._kdestroy() #277
537         self._kinit('foo', 'test') #279 =106
538         self._klist() #280
539         self._shell(self.kadmin+" -p haoqili/admin -w "+passw+" -q 'listprincs'") #281 =108
540         self._shell(self.kadmin+" -p haoqili/admin -w "+passw+" -q 'getprinc test'") #282 =109
541         
542         self._writeHeader("TEST: add_mkey with aes128 enctype") #283      
543         self._addmkey('abcde', '-e aes128-cts-hmac-sha1-96') #284-287 =110
544         self._listmkeys() #288 =111
545         
546         self._writeLine( "END. Testing add_mkey with aes128 enctype done ==============================================")#289     
547
548         self._writeHeader("TEST: krb5kdc refetch of mkey list")
549         self._usemkey('4', 'now') #290 =112
550         self._listmkeys() #291 =113
551         self._shell(self.kadmin+" -p haoqili/admin -w "+passw+" -q 'cpw -pw abcde test'") #292 =114
552         self._shell(self.kadmin +" -p haoqili/admin -w "+passw+" -q 'getprinc test'") #293
553         self._kdestroy() #294 =116
554
555         self._writeLine("\nTesting krb5kdc refetch of mkey list =================================================") #295
556         self._kinit('abcde', 'test') #296 =117
557         #'self._klist() #297 =118
558         self._writeLine("Testing krb5kdc refetch of mkey list Done :) =================================================\n") #298
559
560         self._killkdc() #300 =119, 120
561         self._startkdc() #301 =121 122
562         self._shell("kadmin -p haoqili/admin -w "+passw+" -q 'cpw -pw foo test'") #304 =123
563         self._shell("kadmin -p haoqili/admin -w "+passw+" -q 'getprinc test'") #305 =124
564         self._kdestroy() #307 =125
565
566         self._writeLine("\nTesting krb5kdc refetch of mkey list =================================================") #308
567         self._kinit('foo', 'test') #309 =126
568         self._klist() #310 =127
569         self._writeLine("Testing krb5kdc refetch of mkey list Done =================================================\n") #311
570         
571         self._updatePrincEnc() #313 =128
572         self._locGetprinc('K/M') #314
573         self._locGetprinc('all') #315 =130
574         self._locGetprinc('haoqili') #316
575         self._kdestroy() #317 =132
576         self._kinit('foo', 'test') #318
577         self._stash() #319 =134
578         self._shell(self.clients+'klist/klist' + " -ekt "+self.sandir+"/keyStashFile") #320
579         self._locGetprinc('K/M') #321 =136
580         self._purgemkeys() #322
581         self._locGetprinc('K/M') #323 =138
582         self._locGetprinc('all') #324
583         self._shell("kadmin -p haoqili/admin -w "+passw+" -q 'getprinc test'") #325 =140
584         self._listmkeys() #326
585         self._kdestroy() #327 =142
586         self._kinit('foo', 'test') #328
587         self._klist() #329 =144
588         
589         self._get_princ_records() #330 =145-158
590         
591         self._writeHeader("TEST: add_meky with DES-crc enctype")
592         #print "\nTesting add_mkey with DES-crc enctype ==============================================" #331
593         self._addmkey('abcde', '-e des-cbc-crc') #332-335 =159
594         self._listmkeys() #336 =160
595         self._writeLine( "END. Testing add_mkey with DES-crc enctype Done ==============================================") #337
596         self._addmkey('abcde') #338-341 =161
597         self._listmkeys() #342 =162
598         self._writeLine( "current time: "+strftime("%Y-%m-%d %H:%M:%S") ) #343
599         
600         self._usemkey('5', 'now-1day') #344 =163
601         self._writeLine("current time: "+strftime("%Y-%m-%d %H:%M:%S") )#345
602         self._listmkeys() #346 =164
603         self._usemkey('5', 'now') #347 =165
604         self._writeLine("current time: "+strftime("%Y-%m-%d %H:%M:%S") )#348
605         self._listmkeys() #349 =166
606         self._usemkey('5', 'now+3days') #350 =167
607         self._writeLine("current time: "+strftime("%Y-%m-%d %H:%M:%S") )#351
608         self._listmkeys() #352 =168
609         self._writeLine("current time: "+strftime("%Y-%m-%d %H:%M:%S") )#353
610         self._usemkey('5', 'now+5sec') #354 =169
611         self._listmkeys() #355 =170
612         time.sleep(5) #356
613         self._listmkeys() #357 =171
614         self._writeLine("current time: "+strftime("%Y-%m-%d %H:%M:%S") )#358
615         self._usemkey('4', 'now+5sec') #359 =172
616         self._listmkeys() #360 =173
617         time.sleep(5) #361
618         self._listmkeys() #362 =174
619         self._usemkey('5', 'now+3days') #363 =175
620
621         self._writeLine("------------\n\/\/\/ ERROR EXPECTED below" )#364
622         self._writeLine("should fail, because there must be one mkey currently active") #365
623         self._usemkey('4', 'now+2days', False) #366 =176
624         self._writeLine("^^^ABOVE^^ SHOULD HAVE FAILED\n---------------")
625
626         self._listmkeys() #373 =177
627         self._usemkey('4', '1/30/2009') #375 =178
628         
629         self._writeHeader("TEST: purge_mkeys (removing mkey 5)")
630         #print "\nTesting purge_mkeys (removing mkey 5) ==============================================" #378
631         self._purgemkeys() #379 =179
632         self._stash() #380 =180
633         self._shell(self.clients+'klist/klist' +" -ekt "+self.sandir+"/keyStashFile") #381 =181
634         self._listmkeys() #382 =182
635         self._shell("kadmin -p haoqili/admin -w "+passw+" -q 'getprinc K/M'") #383 =183
636         self._writeLine("Testing purge_mkeys Done ==============================================") #384
637         self._writeHeader("MASTER KEY MIGRATION TEST DONE. please consult 'outfile' in your sandbox for more info.  The sandbox is at: %s" % self.sandir) 
638  # I added
639         self._sysexit(finished=True)
640         
641 ####################################################
642 ####################################################
643
644 class Launcher:
645     def __init__(self, path, sandP):
646         # srcdir, self._buildDir = InPath
647         self._buildDir = path
648         # self._confDir = InPath/tests/mk_migr/input_conf
649         self._confDir = '%s/tests/mk_migr/db2_backend/input_conf' % self._buildDir
650     
651         # setting up sand box
652         if sandP != "":
653             self._sandboxDir = sandP
654         else:
655             self._sandboxDir = '%s/tests/mk_migr/db2_backend/sandbox' % self._buildDir
656
657         self._vars = {'srcdir': self._buildDir,
658                       'sandboxdir': self._sandboxDir,
659                       'localFQDN':socket.getfqdn()}     
660
661     def _prepSandbox(self):
662         sandir = self._sandboxDir
663         if os.path.exists(sandir):
664             shutil.rmtree(sandir)
665         print "------about to make sandbox, with the path of:"
666         print sandir
667         os.makedirs(sandir, 0777)
668         print "------sandbox made"
669         return sandir
670
671     def _createFileFromTemplate(self, outpath, template, vars):
672         fin = open(template, 'r')
673         result = fin.read() % vars
674         fin.close()
675         fout = open(outpath, 'w')
676         fout.write(result)
677         fout.close()
678
679     ####### Launcher RUN ################
680     def runLauncher(self):
681         # create sandbox file directory if it does not exit
682         sandir = self._prepSandbox()
683         '''print os.environ
684         '''
685         #save the initial 3 things setup
686         orig_libpath = os.getenv('LD_LIBRARY_PATH')
687         orig_krbconf = os.getenv('KRB5_CONFIG')
688         orig_kdcprof = os.getenv('KRB5_KDC_PROFILE')
689
690         # change the 3 things
691         os.environ["LD_LIBRARY_PATH"] = '%s/lib' % self._buildDir
692         #os.environ["SRCDIR"] = '%s' % self._buildDir
693
694         str1 = '%s/krb5.conf' % self._sandboxDir
695         os.environ["KRB5_CONFIG"] = str1
696
697         str2 = '%s/kdc.conf' % self._sandboxDir
698         os.environ["KRB5_KDC_PROFILE"] = str2
699
700         str3 = '%s/kadm5.acl' % self._sandboxDir    
701
702         # Create adequate to the environment config files
703         self._createFileFromTemplate('%s' % str1, '%s/%s' % (self._confDir, 'krb5_template_db2.conf'), self._vars)
704         self._createFileFromTemplate('%s' % str2, '%s/%s' % (self._confDir, 'kdc_template_db2.conf'), self._vars)
705         self._createFileFromTemplate('%s' % str3, '%s/%s' % (self._confDir, 'kadm5_template_db2.acl'), self._vars)
706
707         return sandir
708
709 ####################################################
710 ####################################################
711 def makeBool(aStr):
712     if aStr == "True" or aStr == "T":
713         return True
714     if aStr == "False" or aStr == "F":
715         return False
716     else:
717         print "did NOT execute due to invalid True False argument.  Please enter either 'True', 'T', 'False', or 'F'"
718         sys.exit()
719
720 # # # # # # # # # # # # # # # # # # # # # # # # #
721
722 def processInputs(parser):
723     # get inputs
724     (options, args) = parser.parse_args()
725
726     verbose = makeBool(options.opVerbose)
727     pw = options.opPassword
728
729     kdcPath = options.opKdcPath #1
730     kdmdPath = options.opKdmdPath #2
731     kdbPath = options.opKdbPath #3
732     kdmlPath = options.opKdmlPath #4
733     kdmPath = options.opKdmPath #5
734     cltPath = options.opCltPath #6
735
736     sandPath = options.opSandbox
737
738     ########### Launch ###############
739
740     print "\n############ Start Launcher #############"    
741     src_path=os.environ["PWD"]
742     print "SOURCE PATH ==>" , src_path
743
744     myLaunch = Launcher(src_path, sandPath)
745     sandir = myLaunch.runLauncher()
746
747     test = MasterKeyMigrationTest(verbose, pw,  kdcPath, kdmdPath, kdbPath, kdmlPath, kdmPath, cltPath, sandir)
748     print "########## Finished Launcher ############\n"
749
750     return test
751 # # # # # # # # # # # # # # # # # # # # # # # # #
752
753 def makeParser():
754     usage = "\n\t%prog [-v][-p][-c][-d][-b][-l][-t][-s]"
755     description = "Description:\n\tTests for the master key migration commands."
756     parser = OptionParser(usage=usage, description=description)
757
758     parser.add_option("-v", "--verbose",  type="string", dest="opVerbose", 
759 default="True", help="'True' or 'False'.  Switch on for details of command lines and outputs.  Default is 'True'")
760
761     parser.add_option("-p", "--password",  type="string", dest="opPassword",  default="test123", help="master password for many of the passwords in the test. Default is 'test123'")
762
763     ## Default Paths
764     dSrcPath = src_path=os.environ["PWD"]
765     dKdcPath = '%s/kdc/krb5kdc' % dSrcPath #1    
766     dKdmdPath = '%s/kadmin/server/kadmind' % dSrcPath #2   
767     dKdbPath = '%s/kadmin/dbutil/kdb5_util' % dSrcPath #3
768     dKdmlPath = '%s/kadmin/cli/kadmin.local' % dSrcPath #4
769     dKdmPath = '%s/kadmin/cli/kadmin' % dSrcPath #5
770     dCltPath = '%s/clients' % dSrcPath #6
771
772     parser.add_option("-c", "--krb5kdcpath",
773 type="string", dest="opKdcPath", 
774 default=dKdcPath, help="set krb5kdc path, default="+dKdcPath) #1
775
776     parser.add_option("-d", "--kadmindpath", 
777 type="string", dest="opKdmdPath", 
778 default=dKdmdPath, help="set kadmind path, default="+dKdmdPath) #2
779
780     parser.add_option("-b", "--kdb5_utilpath", 
781 type="string", dest="opKdbPath", 
782 default=dKdbPath, help="set kdb5_util path, default="+dKdbPath) #3
783
784     parser.add_option("-l", "--kadminlocalpath", 
785 type="string", dest="opKdmlPath", 
786 default=dKdmlPath, help="set kadmin.local path, default="+dKdmlPath) #4
787
788     parser.add_option("-n", "--kadminpath", 
789 type="string", dest="opKdmPath", 
790 default=dKdmPath, help="set kadmin path, default="+dKdmPath) #5 
791
792     parser.add_option("-t", "--clientspath", 
793 type="string", dest="opCltPath", 
794 default=dCltPath, help="set clients path, default="+dCltPath) #6
795
796     # set up / initializing stuff for the sandbox
797     parser.add_option("-s", "--sandbox",
798 type="string", dest="opSandbox",
799 default="",
800 help="path for the sandbox. Default is '%s/tests/mk_migr/db2_backend/sandbox' % "+dSrcPath)
801
802     return parser
803
804 ####################################################
805 if __name__ == '__main__':
806     parser = makeParser()    
807     test = processInputs(parser)
808     result = test.run()