source: TI12-security/trunk/python/ndg.security.test/ndg/security/test/x509/test_x509.py @ 4680

Subversion URL: http://proj.badc.rl.ac.uk/svn/ndg/TI12-security/trunk/python/ndg.security.test/ndg/security/test/x509/test_x509.py@4734
Revision 4680, 6.6 KB checked in by pjkersha, 11 years ago (diff)

Global replace to fix copyright from STFC & NERC to STFC alone because it's not possible to have copyright held by two orgs.

  • Property svn:executable set to *
  • Property svn:keywords set to Id
Line 
1#!/usr/bin/env python
2"""NDG X509 Module unit tests
3
4NERC Data Grid Project
5"""
6__author__ = "P J Kershaw"
7__date__ = "03/01/07"
8__copyright__ = "(C) 2007 STFC"
9__license__ = \
10"""This software may be distributed under the terms of the Q Public
11License, version 1.0 or later."""
12__contact__ = "Philip.Kershaw@stfc.ac.uk"
13__revision__ = '$Id:test_x509.py 4335 2008-10-14 12:44:22Z pjkersha $'
14import logging
15logging.basicConfig(level=logging.DEBUG)
16log = logging.getLogger(__name__)
17
18import unittest
19import os
20import sys
21import getpass
22from StringIO import StringIO
23
24from ConfigParser import SafeConfigParser
25from ndg.security.common.X509 import X509CertRead, X509CertParse, X500DN, \
26    X509Stack, X509StackEmptyError, SelfSignedCert, X509CertIssuerNotFound
27
28from os.path import expandvars as xpdVars
29from os.path import join as jnPath
30mkPath = lambda file: jnPath(os.environ['NDGSEC_X509_UNITTEST_DIR'], file)
31
32class X509TestCase(unittest.TestCase):
33   
34    def setUp(self):
35       
36        if 'NDGSEC_INT_DEBUG' in os.environ:
37            import pdb
38            pdb.set_trace()
39       
40        if 'NDGSEC_X509_UNITTEST_DIR' not in os.environ:
41            os.environ['NDGSEC_X509_UNITTEST_DIR'] = \
42                os.path.abspath(os.path.dirname(__file__))
43       
44        configParser = SafeConfigParser()
45        configFilePath = jnPath(os.environ['NDGSEC_X509_UNITTEST_DIR'],
46                                "x509Test.cfg")
47        configParser.read(configFilePath)
48       
49        self.cfg = {}
50        for section in configParser.sections():
51            self.cfg[section] = dict(configParser.items(section))
52       
53           
54    def test1X509CertRead(self):
55        'test1X509CertRead: read in a cert from file'
56        print(self.test1X509CertRead.__doc__)
57        self.x509Cert = \
58            X509CertRead(xpdVars(self.cfg['test1X509CertRead']['certfile']))
59        self.assert_(self.x509Cert)
60
61    def test2X509CertAsPEM(self):
62        'test2X509CertAsPEM: display as a PEM format string'
63        self.test1X509CertRead()
64        print(self.test2X509CertAsPEM.__doc__)
65        self.pemString = self.x509Cert.asPEM()
66        print(self.pemString)
67
68
69    def test3X509CertParse(self):
70        'test3X509CertParse: parse from a PEM format string'
71        self.test2X509CertAsPEM()
72        print(self.test3X509CertParse.__doc__)
73        self.assert_(X509CertParse(self.pemString))
74
75
76    def test4GetDN(self):
77        'test4GetDN: extract distinguished name'
78        self.test1X509CertRead()
79        print(self.test4GetDN.__doc__)
80        self.dn = self.x509Cert.dn
81        print(self.dn)
82       
83    def test5DN(self):
84        'test5DN: test X.500 Distinguished Name attributes'
85        print(self.test5DN.__doc__)
86        self.test4GetDN()
87        for item in self.dn.items():
88            print("%s=%s" % item)
89       
90    def test6DNCmp(self):
91        '''test6DNCmp: test X.500 Distinguished Name comparison
92        operators'''
93        print(self.test6DNCmp.__doc__)
94        self.test4GetDN()
95        testDN = X500DN(dn="/O=a/OU=b/CN=c")
96
97        self.assert_(not(testDN == self.dn))
98        self.assert_(testDN != self.dn)
99        self.assert_(self.dn == self.dn)
100        self.assert_(not(self.dn != self.dn))
101           
102    def test7X509Stack(self):
103        '''test7X509Stack: test X509Stack functionality'''
104        print(self.test7X509Stack.__doc__)
105        self.test1X509CertRead()
106        stack = X509Stack()
107        self.assert_(len(stack)==0)
108        self.assert_(stack.push(self.x509Cert))
109        self.assert_(len(stack)==1)
110        print("stack[0] = %s" % stack[0])
111        for i in stack:
112            print("stack iterator i = %s" % i)
113        print("stack.pop() = %s" % stack.pop())
114        self.assert_(len(stack)==0)
115           
116    def test8X509StackVerifyCertChain(self):
117        '''test8X509StackVerifyCertChain: testVerifyCertChain method'''
118        print(self.test8X509StackVerifyCertChain.__doc__)
119        self.test1X509CertRead()
120        proxyCert=X509CertRead(xpdVars(
121                   self.cfg['test8X509StackVerifyCertChain']['proxycertfile']))
122
123        stack1 = X509Stack()
124        stack1.push(self.x509Cert)
125       
126        caCert=X509CertRead(xpdVars(\
127                   self.cfg['test8X509StackVerifyCertChain']['cacertfile']))
128        caStack = X509Stack()
129        caStack.push(caCert)
130       
131        print("Verification of external cert with external CA stack...")
132        stack1.verifyCertChain(x509Cert2Verify=proxyCert, 
133                               caX509Stack=caStack)
134       
135        print("Verification of stack content using CA stack...")
136        stack1.push(proxyCert)
137        stack1.verifyCertChain(caX509Stack=caStack)
138       
139        print("Verification of stack alone...")
140        stack1.push(caCert)
141        stack1.verifyCertChain()
142       
143        print("Reject self-signed cert. ...")
144        stack2 = X509Stack()
145        try:
146            stack2.verifyCertChain()
147            self.fail("Empty stack error expected")
148        except X509StackEmptyError:
149            pass
150
151        stack2.push(caCert)
152        try:
153            stack2.verifyCertChain()
154            self.fail("Reject of self-signed cert. expected")
155        except SelfSignedCert:
156            pass
157       
158        print("Accept self-signed cert. ...")
159        stack2.verifyCertChain(rejectSelfSignedCert=False)
160       
161        self.assert_(stack2.pop())
162        print("Test no cert. issuer found ...")
163        stack2.push(proxyCert)
164        try:
165            stack2.verifyCertChain()
166            self.fail("No cert. issuer error expected")
167        except X509CertIssuerNotFound:
168            pass
169       
170        print("Test no cert. issuer found again with incomplete chain ...")
171        stack2.push(self.x509Cert)
172        try:
173            stack2.verifyCertChain()
174            self.fail("No cert. issuer error expected")
175        except X509CertIssuerNotFound:
176            pass
177
178    def test9ExpiryTime(self):
179        self.test1X509CertRead()
180       
181        # Set ridiculous bounds for expiry warning to ensure a warning message
182        # is output
183        try:
184            saveStderr = sys.stderr
185            sys.stderr = StringIO()
186            self.assert_(self.x509Cert.isValidTime(
187                                                nDaysBeforeExpiryLimit=36500), 
188                                                "Certificate has expired")
189            msg = sys.stderr.getvalue()
190            if not msg:
191                self.fail("No warning message was set")
192            else:
193                print("PASSED - Got warning message from X509Cert."
194                      "isValidTime: %s" % msg)
195        finally:
196            sys.stderr = saveStderr
197                                       
198if __name__ == "__main__":
199    unittest.main()
Note: See TracBrowser for help on using the repository browser.