import repository from arizona
[raven.git] / 2.0 / python / test / arizonacryptTest.py
1 #! /usr/bin/env python
2 """
3 Stork Project (http://www.cs.arizona.edu/stork/)
4 Module: arizonacryptTest
5 Description:  Test module for arizonacrypt
6
7 Notes:
8 See arizonacrypt for more details
9
10 """
11
12 import arizonacrypt
13 import arizonaconfig
14 import arizonaunittest
15 import os
16 import shutil
17
18
19 class test(arizonaunittest.TestCase):
20
21
22    #------------------------------------------------------------------
23    # valid_sl(filename)
24    #------------------------------------------------------------------
25    def test_valid_sl(self):
26
27       # Empty list is okay
28       self.assertEqual(arizonacrypt.valid_sl([]),True)
29  
30       # typical string list
31       self.assertEqual(arizonacrypt.valid_sl(["abc","def","ghi"]),True)
32
33       # not a list
34       self.assertEqual(arizonacrypt.valid_sl("abcdefghi"),False)
35       self.assertEqual(arizonacrypt.valid_sl(None),False)
36       self.assertEqual(arizonacrypt.valid_sl(7),False)
37
38       # Not all strings
39       self.assertEqual(arizonacrypt.valid_sl(["ag", None, "asdf"]),False)
40       self.assertEqual(arizonacrypt.valid_sl([3,"abfghi","asdf"]),False)
41       self.assertEqual(arizonacrypt.valid_sl(["adefghi", "asdf",5]),False)
42    
43
44
45
46
47    #------------------------------------------------------------------
48    # stream_to_sl(in_stream) 
49    # Collin: This is no longer a method in arizonacrypt
50    #------------------------------------------------------------------
51    #def test_stream_to_sl(self):
52    #
53    #   # Check these to make sure what is written is what is read
54    #   for test_sl in [ [], [""], ["abc","def","ghi"], ["aabfasd"*10]*10 ]:
55    #      tempfile = arizonacrypt.sl_to_fn(test_sl)
56    #      fileobj = open(tempfile,"r")
57    #      new_sl = arizonacrypt.stream_to_sl(fileobj)
58    #      fileobj.close()
59    #      os.remove(tempfile)
60    #      self.assertEqual(test_sl, new_sl)
61    #   
62    #   # Try to use a closed object
63    #   fileobj= open("/bin/ls","r")
64    #   fileobj.close()
65    #   self.assertException(ValueError,arizonacrypt.stream_to_sl,fileobj)
66    #   
67    #   # Try to use something that isn't a stream object
68    #   self.assertException(TypeError,arizonacrypt.stream_to_sl,[1,2,3])
69
70
71
72
73    #------------------------------------------------------------------
74    # sl_to_fn(stringlist):
75    #------------------------------------------------------------------
76    def test_sl_to_fn(self):
77
78       # Does it work on an empty sl correctly?
79       tempfile = arizonacrypt.sl_to_fn([])
80       fileobj = open(tempfile,"r")
81       result = fileobj.read()
82       os.remove(tempfile)
83       self.assertEqual(result,"")
84
85          
86       # Does it work on an empty sl correctly?
87       tempfile = arizonacrypt.sl_to_fn([""])
88       fileobj = open(tempfile,"r")
89       result = fileobj.read()
90       os.remove(tempfile)
91       self.assertEqual(result,"\n")
92          
93
94       # Does it work on an normal sl correctly?
95       tempfile = arizonacrypt.sl_to_fn(["abc","def","ghi"])
96       fileobj = open(tempfile,"r")
97       result = fileobj.read()
98       os.remove(tempfile)
99       self.assertEqual(result,"abc\ndef\nghi\n")
100          
101       # Try it on a bad sl
102       self.assertException(TypeError,arizonacrypt.sl_to_fn,123)
103       
104
105       # should not accept an empty parameter
106       self.assertException(TypeError, arizonacrypt.sl_to_fn, None)
107
108       # should not accept a list of integers
109       self.assertException(TypeError, arizonacrypt.sl_to_fn, [2, 4, 123])
110
111       # should not accept list of lists
112       self.assertException(TypeError, arizonacrypt.sl_to_fn, [[], ["asda"], [123]])
113
114       # should accept list of strings defined with the single quote character:
115       tempfile = arizonacrypt.sl_to_fn(['abc','def','ghi'])
116       fileobj = open(tempfile,"r")
117       result = fileobj.read()
118       os.remove(tempfile)
119       self.assertEqual(result,"abc\ndef\nghi\n")
120
121       # should accept partial list of strings defined with the single quote character:
122       #Collin: following returns TypeError "Invalid sl"
123       #tempfile = arizonacrypt.sl_to_fn([[],'abc', [], 'def','ghi', [], []])
124       tempfile = arizonacrypt.sl_to_fn(['abc', 'def','ghi'])
125       fileobj = open(tempfile,"r")
126       result = fileobj.read()
127       os.remove(tempfile)
128       self.assertEqual(result,"abc\ndef\nghi\n")
129
130       # should accept partial list of strings defined with the double quote character:
131       #Collin: following returns TypeErros "Invalid sl"
132       #tempfile = arizonacrypt.sl_to_fn([[], "abc", [], "def","ghi", [], []])
133       tempfile = arizonacrypt.sl_to_fn(["abc","def","ghi"])
134       fileobj = open(tempfile,"r")
135       result = fileobj.read()
136       os.remove(tempfile)
137       self.assertEqual(result,"abc\ndef\nghi\n")
138
139       # should accept partial list of strings defined with the double and/or single quote characters:
140       # Collin: following fails with TypeError "Invalid sl"
141       #tempfile = arizonacrypt.sl_to_fn([[],"abc", [], "def",'ghi', [], [], 'rte'])
142       tempfile = arizonacrypt.sl_to_fn(["abc","def",'ghi', 'rte'])
143       fileobj = open(tempfile,"r")
144       result = fileobj.read()
145       os.remove(tempfile)
146       self.assertEqual(result,"abc\ndef\nghi\nrte\n")
147
148
149
150
151
152    #------------------------------------------------------------------
153    # fn_to_sl(filename)
154    #------------------------------------------------------------------
155    def test_fn_to_sl(self):
156
157       # Check these to make sure what is written is what is read
158       for test_sl in [ [], [""], ["abc","def","ghi"], ["aabfasd"*10]*10 ]:
159          tempfile = arizonacrypt.sl_to_fn(test_sl)
160          new_sl = arizonacrypt.fn_to_sl(tempfile)
161          os.remove(tempfile)
162          self.assertEqual(test_sl, new_sl)
163       
164       # Check that we get an IOError when trying a non-existant file
165       self.assertException(IOError,arizonacrypt.fn_to_sl,"/asdjkf/sakldfjklas")
166
167
168
169       # should not accept an empty parameter
170       self.assertException(TypeError, arizonacrypt.fn_to_sl, None)
171
172       
173
174
175
176    #------------------------------------------------------------------
177    #  get_genkey_type(type_of_genkey=None)
178    #------------------------------------------------------------------
179    def test_get_genkey_type(self):
180    
181       # returns what is given when it has a string argument
182       self.assertEquals(arizonacrypt.get_genkey_type("abc"),"abc")
183
184       # returns the default if given None
185       self.assertNotEquals(arizonacrypt.get_genkey_type(None),None)
186
187       # Try it with a non-string...
188       self.assertException(TypeError, arizonacrypt.get_genkey_type, 1)
189       self.assertException(TypeError, arizonacrypt.get_genkey_type, [])
190       
191       
192       
193       
194       
195    #------------------------------------------------------------------
196    #   get_key_numbits(numbits_of_key=None)
197    #------------------------------------------------------------------
198    def test_get_key_numbits(self):
199    
200       # make sure the method works with default numbits
201       self.assertEquals(arizonacrypt.get_key_numbits(),"1024")
202       
203       # make sure method works with custom numbits
204       self.assertEquals(arizonacrypt.get_key_numbits("512"),"512")
205       
206       # should fail since the numbits is < 512
207       self.assertException(ValueError,arizonacrypt.get_key_numbits,"400")
208       
209       # should also fail because the string cannot be parsed to int
210       self.assertException(ValueError,arizonacrypt.get_key_numbits,"abc")
211       
212    
213
214
215
216    #------------------------------------------------------------------
217    #  get_key_type(type_of_key=None)
218    #------------------------------------------------------------------
219    def test_get_key_type(self):
220    
221       # returns what is given when it has a string argument
222       self.assertEquals(arizonacrypt.get_key_type("abc"),"abc")
223
224       # returns the default if given None
225       self.assertNotEquals(arizonacrypt.get_key_type(None),None)
226
227       # Try it with a non-string...
228       self.assertException(TypeError, arizonacrypt.get_key_type, 1)
229       self.assertException(TypeError, arizonacrypt.get_key_type, [])
230
231
232
233    #------------------------------------------------------------------
234    #  get_hash_type(type_of_hash=None)
235    #------------------------------------------------------------------
236    def test_get_hash_type(self):
237    
238       # returns what is given when it has a string argument
239       self.assertEquals(arizonacrypt.get_hash_type("-abc"),"-abc")
240
241       # returns the default if given None
242       self.assertNotEquals(arizonacrypt.get_hash_type(None),None)
243
244       # Try it with a non-string...
245       self.assertException(TypeError, arizonacrypt.get_hash_type, 1)
246       self.assertException(TypeError, arizonacrypt.get_hash_type, [])
247
248
249
250
251    #------------------------------------------------------------------
252    #  generate_privatekey_sl(type_of_key=None):
253    #------------------------------------------------------------------
254    def test_generate_privatekey_sl(self):
255       
256       # Create a valid privatekey (default type)...
257       self.assertNotEqual([],arizonacrypt.generate_privatekey_sl())
258
259       # Create a valid privatekey (specify the type)...
260       self.assertNotEqual([],arizonacrypt.generate_privatekey_sl("genrsa"))
261
262       # Invalid keytype
263       self.assertException(AssertionError,arizonacrypt.generate_privatekey_sl,"aklsdf")
264       
265
266
267
268
269    #------------------------------------------------------------------
270    #  generate_privatekey_fn(filename,type_of_key=None):
271    #------------------------------------------------------------------
272    def test_generate_privatekey_fn(self):
273
274       # Create a valid privatekey (default type)...
275       arizonacrypt.generate_privatekey_fn("/tmp/test1")
276       does_exist = os.path.exists("/tmp/test1")
277       os.remove("/tmp/test1")
278       self.assertEqual(True, does_exist)
279
280       # Create a valid privatekey (specify the type)...
281       arizonacrypt.generate_privatekey_fn("/tmp/test1","genrsa")
282       does_exist = os.path.exists("/tmp/test1")
283       os.remove("/tmp/test1")
284       self.assertEqual(True, does_exist)
285
286       # Invalid name (not a filename)
287       self.assertException(AssertionError,arizonacrypt.generate_privatekey_fn,123)
288
289
290       # Invalid keytype
291       self.assertException(AssertionError,arizonacrypt.generate_privatekey_fn,"/tmp/test2","asdfkasd")
292
293       # Invalid filename
294       self.assertException(IOError,arizonacrypt.generate_privatekey_fn,"aklsdfjas/asfasdf/asflas")
295
296       # Target is dir
297       self.assertException(IOError,arizonacrypt.generate_privatekey_fn,"/usr/bin")
298
299
300    
301    #------------------------------------------------------------------
302    #  extract_publickey_sl_from_privatekey_fn(privatekey_fn,type_of_key=None)
303    #------------------------------------------------------------------
304    def test_extract_publickey_sl_from_privatekey_fn(self):
305
306       # check that it seems to work on a valid key
307       arizonacrypt.generate_privatekey_fn("/tmp/test1")
308       publickey_sl = arizonacrypt.extract_publickey_sl_from_privatekey_fn("/tmp/test1")
309       os.remove("/tmp/test1")
310       self.assertNotEqual([],publickey_sl)
311
312       
313       # Invalid keytype
314       arizonacrypt.generate_privatekey_fn("/tmp/test1")
315       self.assertException(TypeError,arizonacrypt.extract_publickey_sl_from_privatekey_fn,"/tmp/test1","askfd")
316       os.remove("/tmp/test1")
317
318       # Invalid filename
319       self.assertException(IOError,arizonacrypt.extract_publickey_sl_from_privatekey_fn,"aklsdfjas/asfasdf/asflas")
320
321       # Not a private key
322       self.assertException(TypeError,arizonacrypt.extract_publickey_sl_from_privatekey_fn,"/bin/ls")
323
324
325
326
327
328    #------------------------------------------------------------------
329    #  extract_publickey_sl_from_privatekey_sl(privatekey_sl,type_of_key=None)
330    #------------------------------------------------------------------
331    def test_extract_publickey_sl_from_privatekey_sl(self):
332
333       # check that it seems to work on a valid key
334       privatekey_sl = arizonacrypt.generate_privatekey_sl()
335       publickey_sl = arizonacrypt.extract_publickey_sl_from_privatekey_sl(privatekey_sl)
336       self.assertNotEqual([],publickey_sl)
337
338       
339       # Invalid keytype
340       privatekey_sl = arizonacrypt.generate_privatekey_sl()
341       self.assertException(TypeError,arizonacrypt.extract_publickey_sl_from_privatekey_sl,privatekey_sl,"askfd")
342
343       # Not a stringlist
344       self.assertException(TypeError,arizonacrypt.extract_publickey_sl_from_privatekey_sl,123)
345
346       # Not a private key
347       self.assertException(TypeError,arizonacrypt.extract_publickey_sl_from_privatekey_sl,["abc","def","ghi"])
348
349
350
351
352
353
354    #------------------------------------------------------------------
355    #  publickey_fn_to_sl(filename, type_of_key=None):
356    #------------------------------------------------------------------
357    def test_publickey_fn_to_sl(self):
358
359       # check that it seems to work on a valid key
360       privatekey_sl = arizonacrypt.generate_privatekey_sl()
361       real_publickey_sl = arizonacrypt.extract_publickey_sl_from_privatekey_sl(privatekey_sl)
362       temp_publickey_fn = arizonacrypt.sl_to_fn(real_publickey_sl)
363       new_publickey_sl = arizonacrypt.publickey_fn_to_sl(temp_publickey_fn)
364       os.remove(temp_publickey_fn)
365       self.assertEquals(new_publickey_sl,(True, real_publickey_sl))
366
367
368
369       # should return (False, []) with an file that is not a publickey 
370       privatekey_fn = arizonacrypt.generate_privatekey_fn("/tmp/tempdasf")
371       self.assertEquals(arizonacrypt.publickey_fn_to_sl("/tmp/tempdasf"),(False,[]))
372       os.remove("/tmp/tempdasf")
373       self.assertEquals(arizonacrypt.publickey_fn_to_sl("/bin/ls"),(False,[]))
374
375
376       # should return (False, []) with a bad file name
377       #self.assertEquals(arizonacrypt.publickey_fn_to_sl("asldfkjasldfs"),(False,[]))
378       # Now this method returns a typeError that the file does not exist
379       self.assertException(TypeError,arizonacrypt.publickey_fn_to_sl,"asldf/kjasldfs")
380       self.assertException(TypeError,arizonacrypt.publickey_fn_to_sl,1)
381       
382
383       # should throw TypeError with a bad keytype 
384       privatekey_sl = arizonacrypt.generate_privatekey_sl()
385       real_publickey_sl = arizonacrypt.extract_publickey_sl_from_privatekey_sl(privatekey_sl)
386       temp_publickey_fn = arizonacrypt.sl_to_fn(real_publickey_sl)
387       new_publickey_sl = arizonacrypt.publickey_fn_to_sl(temp_publickey_fn)
388       # The following throws a TypeError, because new_publickey_sl is not a filename, it's a sl
389       self.assertException(TypeError,arizonacrypt.publickey_fn_to_sl,new_publickey_sl,3)
390       os.remove(temp_publickey_fn)
391
392    
393
394
395
396    #------------------------------------------------------------------
397    # valid_publickey_sl(publickey_sl, key_type=None):
398    #------------------------------------------------------------------
399    def test_valid_public_key_sl(self):
400       
401       # check that it seems to work on a valid key
402       privatekey_sl = arizonacrypt.generate_privatekey_sl()
403       real_publickey_sl = arizonacrypt.extract_publickey_sl_from_privatekey_sl(privatekey_sl)
404
405       self.assertEquals(arizonacrypt.valid_publickey_sl(real_publickey_sl),True)
406
407
408
409       # should return False with a string list that is not a public key
410       privatekey_sl = arizonacrypt.generate_privatekey_sl()
411       self.assertEquals(arizonacrypt.valid_publickey_sl(privatekey_sl),False)
412       self.assertEquals(arizonacrypt.valid_publickey_sl(["asdf"]),False)
413       self.assertEquals(arizonacrypt.valid_publickey_sl([]),False)
414       self.assertEquals(arizonacrypt.valid_publickey_sl(["asdf","asdsfd","asfasdfasdf"]),False)
415
416
417       # should fail an assertion if given a non-string list 
418       self.assertException(TypeError,arizonacrypt.valid_publickey_sl,1)
419
420
421
422
423    #------------------------------------------------------------------
424    # get_fn_hash(filename,hash_type=None):
425    #------------------------------------------------------------------
426    def test_get_fn_hash(self):
427
428       # It shouldn't throw an exception, etc.
429       arizonacrypt.get_fn_hash("/bin/ls")
430
431       # An invalid hash_type
432       self.assertException(TypeError, arizonacrypt.get_fn_hash,"/bin/ls",3)
433       self.assertException(IOError, arizonacrypt.get_fn_hash,"/bin/ls","askldfdas")
434
435       # A non-string
436       self.assertException(IOError, arizonacrypt.get_fn_hash,3)
437
438       # A non-string
439       self.assertException(IOError, arizonacrypt.get_fn_hash,3)
440
441       # An invalid path
442       self.assertException(IOError, arizonacrypt.get_fn_hash,"/lasfd/lasd")
443
444       # An invalid file
445       self.assertException(IOError, arizonacrypt.get_fn_hash,"/usr/lasd")
446
447       # A non-file
448       self.assertException(IOError, arizonacrypt.get_fn_hash,"/usr/bin")
449
450       # I'd like to test a non-readable file but root can read anything...
451 # Skip for now
452       #self.assertEqual(arizonacrypt.get_fn_hash("/usr/bin"),False)
453
454
455
456
457       
458    #------------------------------------------------------------------
459    # publickey_sl_to_fnstring(publickey_sl):
460    #------------------------------------------------------------------
461    def test_publickey_sl_to_fnstring(self):
462    
463       # Should raise TypeError since arg is not an sl
464       self.assertException(TypeError,arizonacrypt.publickey_sl_to_fnstring,"asdjiofsd")
465       self.assertException(TypeError,arizonacrypt.publickey_sl_to_fnstring,3)
466       self.assertException(TypeError,arizonacrypt.publickey_sl_to_fnstring,"")
467             
468             
469             
470
471       
472    #------------------------------------------------------------------
473    # fnstring_to_publickey_sl(fnstring):
474    #------------------------------------------------------------------
475    def test_fnstring_to_publickey_sl(self):
476  
477       # Try on a simple example
478       self.assertEqual(arizonacrypt.fnstring_to_publickey_sl(''),['-----BEGIN PUBLIC KEY-----','-----END PUBLIC KEY-----'] )
479
480       # note: see arizonacrypt for discussion of old-style key mangling
481
482       # try with a mangled 512 bit key (the standard thing that would be in an old-style filename)
483       key_string = "MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAN3_C9Q3wwo_alFitDsZW8a4gCn0Sba82serR9qGL+v_WO1PEQQdyk6PZZ9BtXeIeiu4o8qpuOH20mMxp4ECLO8CAwEAAQ"
484       key_sl = arizonacrypt.fnstring_to_publickey_sl(key_string)
485       publickey = arizonacrypt.PublicKey(sl=key_sl)
486       self.assertTrue(publickey.is_valid())
487       
488       # try with a mangled non-512 bit key (what old code would embed for a USER in a tpfile
489       # if it was trying to add a user with a longer key, in which case unmangling has to be
490       # manually forced)
491       key_string = "MIGdMA0GCSqGSIb3DQEBAQUAA4GLADCBhwKBgQDK9oR7kfPrVKhodxv4+EjWkYD3JTJd6MNF228VtrmGO3yYtvfhQ5vAHxq6y63voUb7HExxJnbRmb5B0kKXI7nJjVFL+HL3g3b8r_A_InNh5BBKSY6wTOwM+KVpFOTgQlQKNqmkNGKU_McHN3WUMgFyeAdQZ_y0IyUJHSzyHlztLQIBIw"
492       key_sl = arizonacrypt.fnstring_to_publickey_sl(key_string, force_unmangling=True)
493       publickey = arizonacrypt.PublicKey(sl=key_sl)
494       self.assertTrue(publickey.is_valid())
495       
496       # make sure it doesn't try to unmangle a non-mangled long key
497       key_string = "MIGdMA0GCSqGSIb3DQEBAQUAA4GLADCBhwKBgQDK9oR7kfPrVKhodxv4+EjWkYD3JTJd6MNF228VtrmGO3yYtvfhQ5vAHxq6y63voUb7HExxJnbRmb5B0kKXI7nJjVFL+HL3g3b8r/A/InNh5BBKSY6wTOwM+KVpFOTgQlQKNqmkNGKU/McHN3WUMgFyeAdQZ/y0IyUJHSzyHlztLQIBIw=="
498       key_sl = arizonacrypt.fnstring_to_publickey_sl(key_string)
499       publickey = arizonacrypt.PublicKey(sl=key_sl)
500       self.assertTrue(publickey.is_valid())
501       
502       # forcibly unmangle a key that is already valid and make sure it ends up invalid
503       key_string = "MIGdMA0GCSqGSIb3DQEBAQUAA4GLADCBhwKBgQDK9oR7kfPrVKhodxv4+EjWkYD3JTJd6MNF228VtrmGO3yYtvfhQ5vAHxq6y63voUb7HExxJnbRmb5B0kKXI7nJjVFL+HL3g3b8r/A/InNh5BBKSY6wTOwM+KVpFOTgQlQKNqmkNGKU/McHN3WUMgFyeAdQZ/y0IyUJHSzyHlztLQIBIw=="
504       key_sl = arizonacrypt.fnstring_to_publickey_sl(key_string, force_unmangling=True)
505       publickey = arizonacrypt.PublicKey(sl=key_sl)
506       self.assertFalse(publickey.is_valid())
507
508
509
510
511    #------------------------------------------------------------------
512    # publickey_sl_to_fnstring_compat(publickey_sl):
513    #------------------------------------------------------------------
514    def test_publickey_sl_to_fnstring_compat(self):
515
516       # Try on some simple examples
517       self.assertEqual(arizonacrypt.publickey_sl_to_fnstring_compat(['-----']),'')
518       self.assertEqual(arizonacrypt.publickey_sl_to_fnstring_compat(['-----','abc','---------asfdasdf','def']),'abcdef')
519       self.assertEqual(arizonacrypt.publickey_sl_to_fnstring_compat(['-----','====abc','---------a/f','=d=ef///=']),'abc=d=ef___')
520       
521       # below we verify that fnstring_to_publickey_sl() restores 512 keys that have been run through
522       # publickey_sl_to_fnstring_compat() back to a good valid key. Only need to worry about
523       # this for 512 bit keys as that is all that was used in the old versions of stork that
524       # used this type of mangling in filenames
525       
526       # trailing ='s but no slashes
527       key_sl = "MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAL4XBJVaBJ4blK9KcveRbOXRwtsDsuedEdGZSUqXvHifIm4EzWmXH+jxHBsc0JBRBLWuY2m5kImdYkT5lZfKz+MCAwEAAQ=="
528       key_string = arizonacrypt.publickey_sl_to_fnstring_compat(key_sl)
529       restored_sl = arizonacrypt.fnstring_to_publickey_sl(key_string)
530       publickey = arizonacrypt.PublicKey(sl=restored_sl)
531       self.assertTrue(publickey.is_valid())
532       
533       # trailing ='s and slashes
534       key_sl = "MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBANHZ/RbnBKDDF2imcVpfhhce4PEs14AqbrLUn/jLLxwzaADJ9TPgd8388+a3QL7ztYxrwwmEfGX0aDMAm5DFV6kCAwEAAQ=="
535       key_string = arizonacrypt.publickey_sl_to_fnstring_compat(key_sl)
536       restored_sl = arizonacrypt.fnstring_to_publickey_sl(key_string)
537       publickey = arizonacrypt.PublicKey(sl=restored_sl)
538       self.assertTrue(publickey.is_valid())
539       
540
541
542
543
544
545    #------------------------------------------------------------------
546    # get_fn_signedhash_using_privatekey_fn(filename, privatekey_fn, type_of_hash=None):
547    #------------------------------------------------------------------
548    def test_get_fn_signedhash_using_privatekey_fn(self):
549  
550       # Make sure something is returned in the normal case 
551       arizonacrypt.generate_privatekey_fn("/tmp/temp5")
552       signedhash = arizonacrypt.get_fn_signedhash_using_privatekey_fn("/bin/ls","/tmp/temp5")
553       os.remove("/tmp/temp5")
554       self.assertNotEqual(signedhash,'')
555       
556       # Try an invalid filename
557       arizonacrypt.generate_privatekey_fn("/tmp/temp5")
558       self.assertException(IOError,arizonacrypt.get_fn_signedhash_using_privatekey_fn,"/asfaskj/asdfkjasklsf","/tmp/temp5")
559       os.remove("/tmp/temp5")
560       
561       # Try an invalid privatekey file
562       self.assertException(IOError,arizonacrypt.get_fn_signedhash_using_privatekey_fn,"/bin/ls","/askdf/askjlsa")
563       
564       # Try an invalid hash type
565       arizonacrypt.generate_privatekey_fn("/tmp/temp5")
566       # Collin: added None, was not testing right thing
567       self.assertException(TypeError,arizonacrypt.get_fn_signedhash_using_privatekey_fn,"/bin/ls","/tmp/temp5",None,"asdsfsdf")
568       os.remove("/tmp/temp5")
569
570
571
572    #------------------------------------------------------------------
573    # get_verify_fn_signedhash_using_publickey_fn(filename, signedhash, publickey_fn, type_of_hash = None):
574    #------------------------------------------------------------------
575    def test_verify_fn_signedhash_using_publickey_fn(self):
576  
577       # Make sure it works in the normal case 
578  
579       # Get a private key and hash
580       arizonacrypt.generate_privatekey_fn("/tmp/temp5")
581       signedhash = arizonacrypt.get_fn_signedhash_using_privatekey_fn("/bin/ls","/tmp/temp5")
582       # Get the corresponding public key 
583       publickey_sl = arizonacrypt.extract_publickey_sl_from_privatekey_fn("/tmp/temp5")
584       temp_publickey_fn = arizonacrypt.sl_to_fn(publickey_sl)
585       # Kill the private key
586       os.remove("/tmp/temp5")
587       # Check it
588       validity = arizonacrypt.verify_fn_signedhash_using_publickey_fn("/bin/ls",signedhash,temp_publickey_fn)
589       # Kill the public key
590       os.remove(temp_publickey_fn)
591       self.assertEqual(validity,True)
592       
593       # Make sure it doesn't work when we muck with it
594
595       # Get a private key and hash
596       arizonacrypt.generate_privatekey_fn("/tmp/temp5")
597       signedhash = arizonacrypt.get_fn_signedhash_using_privatekey_fn("/bin/ls","/tmp/temp5")
598       # Modify the hash
599       signedhash = "a3"+signedhash
600       # Get the corresponding public key 
601       publickey_sl = arizonacrypt.extract_publickey_sl_from_privatekey_fn("/tmp/temp5")
602       temp_publickey_fn = arizonacrypt.sl_to_fn(publickey_sl)
603       # Kill the private key
604       os.remove("/tmp/temp5")
605       # Check it
606       validity = arizonacrypt.verify_fn_signedhash_using_publickey_fn("/bin/ls",signedhash,temp_publickey_fn)
607       # Kill the public key
608       os.remove(temp_publickey_fn)
609       self.assertEqual(validity,False)
610       
611
612
613
614
615
616    #------------------------------------------------------------------
617    # retrieve_hash_from_signatureblock_sl(signatureblock):
618    # Method has been commented out in arizonacrypt.py
619    #------------------------------------------------------------------
620    #def test_retrieve_hash_from_signatureblock_sl(self):
621    #
622    #   # Make sure it works in the normal cases
623    #   self.assertEqual((["abc"],"-sha1"), arizonacrypt.retrieve_hash_from_signatureblock_sl(["-----SIGNATURE (stork 1) BEGINS-----","abc","-----SIGNATURE (stork 1) ENDS-----"]))
624    #
625    #   self.assertEqual((["ghi"],"xyz"), arizonacrypt.retrieve_hash_from_signatureblock_sl(["<!-- -----SIGNATURE xyz BEGINS-----","ghi","-----SIGNATURE xyz ENDS-----"]))
626    #
627    #   
628    #   # Should fail in these cases
629    #   self.assertException(TypeError,arizonacrypt.retrieve_hash_from_signatureblock_sl,[])
630    #   
631    #   # Bad header
632    #   self.assertException(TypeError, arizonacrypt.retrieve_hash_from_signatureblock_sl,["<!- -----SIGNATURE xyz BEGINS-----","ghi","-----SIGNATURE xyz ENDS-----"])
633    #
634    #   # Bad footer
635    #   self.assertException(TypeError, arizonacrypt.retrieve_hash_from_signatureblock_sl,["<!-- -----SIGNATURE xyz BEGINS-----","ghi","-----SINATURE xyz ENDS-----"])
636    #
637    #   # No middle
638    #   self.assertException(TypeError, arizonacrypt.retrieve_hash_from_signatureblock_sl,["<!-- -----SIGNATURE xyz BEGINS-----","-----SIGNATURE xyz ENDS-----"])
639
640
641
642    #------------------------------------------------------------------
643    # retrieve_signatureblock_from_sl(signatureblock):
644    # Method has been commented out in arizonacrypt.py
645    #------------------------------------------------------------------
646    #def test_retrieve_signatureblock_from_sl(self):
647    # 
648    #   # Make sure it works in the normal cases
649    #   self.assertEqual(([],["-----SIGNATURE (stork 1) BEGINS-----","abc","-----SIGNATURE (stork 1) ENDS-----"]), arizonacrypt.retrieve_signatureblock_from_sl(["-----SIGNATURE (stork 1) BEGINS-----","abc","-----SIGNATURE (stork 1) ENDS-----"]))
650    #
651    #   self.assertEqual((["abc","def","ghi","jkl"],["-----SIGNATURE (stork 1) BEGINS-----","abc","-----SIGNATURE (stork 1) ENDS-----"]), arizonacrypt.retrieve_signatureblock_from_sl(["abc","def","ghi","jkl","-----SIGNATURE (stork 1) BEGINS-----","abc","-----SIGNATURE (stork 1) ENDS-----"]))
652    #
653    #   
654    #   # Should fail in these cases
655    #   self.assertException(TypeError,arizonacrypt.retrieve_signatureblock_from_sl,[])
656    #
657    #   self.assertException(TypeError,arizonacrypt.retrieve_signatureblock_from_sl,7)
658    #   
659    #   # Bad header
660    #   self.assertException(TypeError,arizonacrypt.retrieve_signatureblock_from_sl,["abc","def","ghi","jkl","-----IGNAURE (stork 1) BEGINS-----","abc","-----SIGNATURE (stork 1) ENDS-----"])
661
662
663       
664
665
666    #------------------------------------------------------------------
667    # verify_signatureblock_using_publickey_fn(stringlist, signatureblock, publickey_fn):
668    # create_signatureblock_using_privatekey_fn(stringlist, signatureblock, publickey_fn):
669    # These two methods have been commented out in arizonacrypt.py
670    #------------------------------------------------------------------
671    #def test_signatureblock_routines(self):
672    # 
673    #
674    #
675    #   temp_privatekey_fn = "/tmp/testdsfasdf"
676    #   # Make a private key
677    #   arizonacrypt.generate_privatekey_fn(temp_privatekey_fn)
678    #
679    #   publickey_sl = arizonacrypt.extract_publickey_sl_from_privatekey_fn(temp_privatekey_fn)
680    # 
681    #  temp_publickey_fn = arizonacrypt.sl_to_fn(publickey_sl)
682    #
683    #   # Try some common cases
684    #   for testfile in [ '/bin/ls', '/dev/null', '/etc/passwd' ]:
685    #      file_sl = arizonacrypt.fn_to_sl(testfile)
686    #
687    #      signatureblock = arizonacrypt.create_signatureblock_using_privatekey_fn(file_sl, temp_privatekey_fn)
688    # 
689    #      # Make sure it works in the normal case
690    #      self.assertEqual(True, arizonacrypt.verify_signatureblock_using_publickey_fn(file_sl, signatureblock, temp_publickey_fn))
691    #
692    #      # Make sure it fails if the string list is changed
693    #      self.assertEqual(False, arizonacrypt.verify_signatureblock_using_publickey_fn(file_sl+["a"], signatureblock, temp_publickey_fn))
694    #      
695    #      # Make sure it fails if the signature changed
696    #      self.assertException(TypeError,arizonacrypt.verify_signatureblock_using_publickey_fn,file_sl, signatureblock+['a'], temp_publickey_fn)
697    #      
698    #      
699    #   os.remove(temp_publickey_fn)
700    #   os.remove(temp_privatekey_fn)
701
702
703
704
705       
706       
707
708    #------------------------------------------------------------------
709    # sign_file_using_privatekey_fn(filename, privatekey_fn, type_of_hash=None):
710    # Method has been commented out in arizonacrypt.py
711    #------------------------------------------------------------------
712    #def test_sign_file_using_privatekey_fn(self):
713    # 
714    #
715    #   temp_privatekey_fn = "/tmp/tessasdf"
716    #
717    #   # Make a private key
718    #   arizonacrypt.generate_privatekey_fn(temp_privatekey_fn) 
719    #
720    #   # Get the corresponding public key
721    #   publickey_sl = arizonacrypt.extract_publickey_sl_from_privatekey_fn(temp_privatekey_fn)
722    # 
723    #   # Write the public key out to a file
724    #   temp_publickey_fn = arizonacrypt.sl_to_fn(publickey_sl)
725    #
726    #   # For each of the test files...
727    #   for testfile in [ "/etc/passwd", "/bin/ls", "/dev/null" ]:
728    #      # Get the file data
729    #      test_sl = arizonacrypt.fn_to_sl(testfile)
730    #
731    #      # Dump it to a new temp file
732    #      temp_fn = arizonacrypt.sl_to_fn(test_sl)
733    #
734    #      # Sign the temp file
735    #      arizonacrypt.sign_file_using_privatekey_fn(temp_fn,temp_privatekey_fn)
736    #
737    #      # read the temp file back in...
738    #      temp2_sl = arizonacrypt.fn_to_sl(temp_fn)
739    #
740    #      # Clean up the temp file
741    #      os.remove(temp_fn)
742    #
743    #      # strip the signatureblock
744    #      ( original_sl, signatureblock ) = arizonacrypt.retrieve_signatureblock_from_sl(temp2_sl)
745    #
746    #      # Make sure the file data is the same
747    #      self.assertEqual(original_sl, test_sl)
748    #
749    #      # Now make sure the signature is valid
750    #      self.assertEqual(True, arizonacrypt.verify_signatureblock_using_publickey_fn(original_sl, signatureblock, temp_publickey_fn))
751    #
752    #
753    #   # Remove the temporary public/private key pair...
754    #   os.remove(temp_publickey_fn)
755    #   os.remove(temp_privatekey_fn)
756       
757
758    #------------------------------------------------------------------
759    # XML_sign_file_using_privatekey_fn(filename, privatekey_fn, type_of_hash=None, timestamp=None, duration=None, file_encoding=None):
760    #------------------------------------------------------------------
761    def test_XML_sign_file_using_privatekey_fn(self):
762       privkey = "/tmp/my_test_privkey"
763       tempfile = "/tmp/testfile2"
764       arizonacrypt.generate_privatekey_fn(privkey)
765       try:
766          
767          
768          # Create a signedfile
769          for testfile in [ "/etc/passwd", "trustedpackages.dtd", "/bin/ls", "/dev/null"]:
770             shutil.copy(testfile, tempfile)
771             # Correct
772             arizonacrypt.XML_sign_file_using_privatekey_fn(tempfile,privkey)
773             # Correct with options
774             arizonacrypt.XML_sign_file_using_privatekey_fn(tempfile,privkey, type_of_hash="-sha1", timestamp=1, duration=10, file_encoding="hex")
775
776             # Bad hash
777             self.assertException(TypeError, arizonacrypt.XML_sign_file_using_privatekey_fn, tempfile,privkey, None, "abc")
778
779             # Bad timestamp 
780             self.assertException(TypeError, arizonacrypt.XML_sign_file_using_privatekey_fn, tempfile,privkey, None, None, "abc")
781             # Bad duration
782             self.assertException(TypeError, arizonacrypt.XML_sign_file_using_privatekey_fn, tempfile,privkey, None, None, None, "abc")
783             # Bad encoding
784             self.assertException(TypeError, arizonacrypt.XML_sign_file_using_privatekey_fn, tempfile,privkey, None, None, None, None, "abc")
785
786             # Bad file name
787             self.assertException(TypeError, arizonacrypt.XML_sign_file_using_privatekey_fn, tempfile+"123",privkey)
788          
789             # Bad private key name
790             self.assertException(TypeError, arizonacrypt.XML_sign_file_using_privatekey_fn, tempfile,privkey+"123")
791          
792          
793       finally:
794          os.remove(privkey)
795          os.remove(tempfile)
796       
797
798
799    #------------------------------------------------------------------
800    # XML_timestamp_signedfile_with_publickey_fn(signedfile_fn, publickey_fn)
801    #------------------------------------------------------------------
802    def test_XML_timestamp_signedfile_with_publickey_fn(self):
803
804       privkey = "/tmp/my_test_privkey"
805       tempfile = "/tmp/testfile"
806       arizonacrypt.generate_privatekey_fn(privkey)
807       try:
808          pubkey_sl = arizonacrypt.extract_publickey_sl_from_privatekey_fn(privkey)
809          pubkey = arizonacrypt.sl_to_fn(pubkey_sl)
810          
811          
812          # Create a few signedfiles and play with the timestamps
813          for testfile in [ "/etc/passwd", "trustedpackages.dtd", "/bin/ls", "/dev/null"]:
814             shutil.copy(testfile, tempfile)
815             # Sign normally
816             arizonacrypt.XML_sign_file_using_privatekey_fn(tempfile,privkey)
817             # Should throw an exception if there is a problem
818             arizonacrypt.XML_timestamp_signedfile_with_publickey_fn(tempfile, pubkey)
819
820
821             # Sign with timestamp 1
822             arizonacrypt.XML_sign_file_using_privatekey_fn(tempfile,privkey,type_of_hash="-sha1",timestamp=1, duration=0, file_encoding="hex")
823             self.assertEquals(int(arizonacrypt.XML_timestamp_signedfile_with_publickey_fn(tempfile, pubkey)), 1)
824
825             # Sign so that the signature has expired
826             # XML_sign_file_using_privatekey_fn changed so that it should not raise exception for expired file anymore
827             # it now just returns the timestamp and doesn't check expiration
828             #arizonacrypt.XML_sign_file_using_privatekey_fn(tempfile,privkey, type_of_hash="-sha1",timestamp=1, duration=1, file_encoding="hex")
829             #self.assertException(TypeError, arizonacrypt.XML_timestamp_signedfile_with_publickey_fn,tempfile, pubkey)
830             arizonacrypt.XML_sign_file_using_privatekey_fn(tempfile,privkey, type_of_hash="-sha1",timestamp=1, duration=1, file_encoding="hex")
831             self.assertEquals(1, arizonacrypt.XML_timestamp_signedfile_with_publickey_fn(tempfile, publickey_fn=pubkey))
832             
833             # Bad publickey
834             arizonacrypt.XML_sign_file_using_privatekey_fn(tempfile,privkey, type_of_hash="-sha1",timestamp=1, duration=1, file_encoding="hex")
835             self.assertException(TypeError, arizonacrypt.XML_timestamp_signedfile_with_publickey_fn,tempfile, pubkey+"123")
836             self.assertException(TypeError, arizonacrypt.XML_timestamp_signedfile_with_publickey_fn,tempfile, "/dev/null")
837             
838          
839       finally:
840          os.remove(privkey)
841          os.remove(pubkey)
842          os.remove(tempfile)
843       
844
845
846    #------------------------------------------------------------------
847    # XML_retrieve_originalfile_from_signedfile(original_fn):
848    #------------------------------------------------------------------
849    def test_XML_retrieve_originalfile_from_signedfile(self):
850
851       privkey = "/tmp/my_test_privkey"
852       tempfile = "/tmp/testfile"
853       signedtempfile = "/tmp/signedtemptestfile"
854       arizonacrypt.generate_privatekey_fn(privkey)
855       try:
856          
857          # Create a few signedfiles...
858          for testfile in [ "/etc/passwd", "trustedpackages.dtd", "/bin/ls", "/dev/null"]:
859             shutil.copy(testfile, tempfile)
860             shutil.copy(tempfile, signedtempfile)
861
862             # Sign
863             arizonacrypt.XML_sign_file_using_privatekey_fn(signedtempfile,privkey)
864
865             # Extract
866             new_tempfile = arizonacrypt.XML_retrieve_originalfile_from_signedfile(signedtempfile)
867
868             # Check
869             self.assertEquals(0, os.system("diff "+tempfile+" "+new_tempfile+" > /dev/null"))
870             os.remove(new_tempfile)
871             
872          
873       finally:
874          os.remove(privkey)
875          os.remove(tempfile)
876          os.remove(signedtempfile)
877       
878
879
880
881    #------------------------------------------------------------------
882    #  class SignedFileApplication(arizonaxml.XMLApplication):
883    #------------------------------------------------------------------
884 #   def test_SignedFileApplication(self):
885 #      arizonacrypt.generate_privatekey_fn("/tmp/my_test_privkey")
886 #      a = arizonacrypt.SignedFileApplication()
887 #      a.read_file("sample.signedfile")
888 #      a.debug_print()
889 #      a.write_file("sample.signedfile2")
890 #      a.get_signedhash("/tmp/my_test_privkey")
891 #      a.write_file("sample.signedfile3")
892 #      a.dump_file_data("/tmp/abc")
893 #      a.dump_file_data("/tmp/def")
894 #      a.read_file_data("/bin/ls")
895 #      a.write_file("sample.signedfile4")
896 #      a = arizonacrypt.SignedFileApplication()
897 #      a.read_file("sample.signedfile4")
898 #      a.dump_file_data("/tmp/ls")
899 #      a = arizonacrypt.SignedFileApplication()
900 #      a.read_file("sample.signedfile")
901 #      a.read_file_data("sample.signedfile")
902 #      a.file_encoding = "escaped"
903 #      a.raw_write_file("sample.signedfile5")
904 #      a = arizonacrypt.SignedFileApplication()
905 #      a.read_file("sample.signedfile5")
906 #      a.debug_print()
907 #      os.remove("/tmp/my_test_privkey")
908 #      fn = arizonacrypt.XML_retrieve_originalfile_from_signedfile("sample.signedfile")
909 #      os.system("cat "+fn)
910 #      os.remove(fn)
911       
912
913
914
915
916       
917
918
919       
920
921
922
923
924
925
926
927
928
929
930
931    #------------------------------------------------------------------
932    # example
933    #------------------------------------------------------------------
934    def test_example(self):
935       pass
936
937
938
939
940
941
942 #=====================================================================
943 # Run tests
944 #=====================================================================
945 if __name__=='__main__':
946    arizonaconfig.init_options()
947    arizonaunittest.main()