1 | #!/usr/bin/env python |
---|
2 | """NDG X509 Module unit tests |
---|
3 | |
---|
4 | NERC Data Grid Project |
---|
5 | """ |
---|
6 | __author__ = "P J Kershaw" |
---|
7 | __date__ = "03/01/07" |
---|
8 | __copyright__ = "(C) 2009 Science and Technology Facilities Council" |
---|
9 | __license__ = "BSD - see LICENSE file in top-level directory" |
---|
10 | __contact__ = "Philip.Kershaw@stfc.ac.uk" |
---|
11 | __revision__ = '$Id:test_x509.py 4335 2008-10-14 12:44:22Z pjkersha $' |
---|
12 | import logging |
---|
13 | logging.basicConfig(level=logging.DEBUG) |
---|
14 | log = logging.getLogger(__name__) |
---|
15 | |
---|
16 | import unittest |
---|
17 | import os |
---|
18 | import sys |
---|
19 | import getpass |
---|
20 | from StringIO import StringIO |
---|
21 | |
---|
22 | from os.path import expandvars as xpdVars |
---|
23 | from os.path import join as jnPath |
---|
24 | mkPath = lambda file: jnPath(os.environ['NDGSEC_X509_UNITTEST_DIR'], file) |
---|
25 | |
---|
26 | from ConfigParser import SafeConfigParser |
---|
27 | from ndg.security.test.unit import BaseTestCase |
---|
28 | |
---|
29 | import warnings |
---|
30 | _warningMsg = None |
---|
31 | _origWarn = warnings.warn |
---|
32 | def _warnWrapper(*arg, **kw): |
---|
33 | global _warningMsg |
---|
34 | _warningMsg = arg[0] |
---|
35 | _origWarn(*arg, **kw) |
---|
36 | |
---|
37 | warnings.warn = _warnWrapper |
---|
38 | |
---|
39 | from ndg.security.common.X509 import X509CertRead, X509CertParse, X500DN, \ |
---|
40 | X509Stack, X509StackEmptyError, SelfSignedCert, X509CertIssuerNotFound |
---|
41 | |
---|
42 | class X509TestCase(BaseTestCase): |
---|
43 | """Unit test X509 module""" |
---|
44 | CA_DIR = os.path.join(BaseTestCase.NDGSEC_TEST_CONFIG_DIR, 'ca') |
---|
45 | |
---|
46 | def __del__(self): |
---|
47 | warnings.warn = _origWarn |
---|
48 | if getattr(super(X509TestCase, self), "__del__", None): |
---|
49 | super(X509TestCase, self).__del__() |
---|
50 | |
---|
51 | def setUp(self): |
---|
52 | super(X509TestCase, self).setUp() |
---|
53 | |
---|
54 | if 'NDGSEC_INT_DEBUG' in os.environ: |
---|
55 | import pdb |
---|
56 | pdb.set_trace() |
---|
57 | |
---|
58 | if 'NDGSEC_X509_UNITTEST_DIR' not in os.environ: |
---|
59 | os.environ['NDGSEC_X509_UNITTEST_DIR'] = os.path.abspath( |
---|
60 | os.path.dirname(__file__)) |
---|
61 | |
---|
62 | configParser = SafeConfigParser() |
---|
63 | configFilePath = jnPath(os.environ['NDGSEC_X509_UNITTEST_DIR'], |
---|
64 | "x509Test.cfg") |
---|
65 | configParser.read(configFilePath) |
---|
66 | |
---|
67 | self.cfg = {} |
---|
68 | for section in configParser.sections(): |
---|
69 | self.cfg[section] = dict(configParser.items(section)) |
---|
70 | |
---|
71 | def test01X509CertRead(self): |
---|
72 | # test01X509CertRead: read in a cert from file |
---|
73 | self.x509Cert = X509CertRead( |
---|
74 | xpdVars(self.cfg['test01X509CertRead']['certfile'])) |
---|
75 | self.assert_(self.x509Cert) |
---|
76 | |
---|
77 | def test02X509CertAsPEM(self): |
---|
78 | # test02X509CertAsPEM: display as a PEM format string |
---|
79 | self.test01X509CertRead() |
---|
80 | self.pemString = self.x509Cert.asPEM() |
---|
81 | print(self.pemString) |
---|
82 | |
---|
83 | |
---|
84 | def test03X509CertParse(self): |
---|
85 | # test03X509CertParse: parse from a PEM format string |
---|
86 | self.test02X509CertAsPEM() |
---|
87 | self.assert_(X509CertParse(self.pemString)) |
---|
88 | |
---|
89 | |
---|
90 | def test04GetDN(self): |
---|
91 | # test04GetDN: extract distinguished name |
---|
92 | self.test01X509CertRead() |
---|
93 | self.dn = self.x509Cert.dn |
---|
94 | print(self.dn) |
---|
95 | |
---|
96 | def test05DN(self): |
---|
97 | # test05DN: test X.500 Distinguished Name attributes |
---|
98 | self.test04GetDN() |
---|
99 | for item in self.dn.items(): |
---|
100 | print("%s=%s" % item) |
---|
101 | |
---|
102 | def test06DNCmp(self): |
---|
103 | # test06DNCmp: test X.500 Distinguished Name comparison operators |
---|
104 | self.test04GetDN() |
---|
105 | testDN = X500DN(dn="/O=a/OU=b/CN=c") |
---|
106 | |
---|
107 | self.assert_(not(testDN == self.dn)) |
---|
108 | self.assert_(testDN != self.dn) |
---|
109 | self.assert_(self.dn == self.dn) |
---|
110 | self.assert_(not(self.dn != self.dn)) |
---|
111 | |
---|
112 | def test07x509Stack(self): |
---|
113 | # test07X509Stack: test X509Stack functionality |
---|
114 | |
---|
115 | self.test01X509CertRead() |
---|
116 | stack = X509Stack() |
---|
117 | self.assert_(len(stack)==0) |
---|
118 | self.assert_(stack.push(self.x509Cert)) |
---|
119 | self.assert_(len(stack)==1) |
---|
120 | print("stack[0] = %s" % stack[0]) |
---|
121 | for i in stack: |
---|
122 | print("stack iterator i = %s" % i) |
---|
123 | print("stack.pop() = %s" % stack.pop()) |
---|
124 | self.assert_(len(stack)==0) |
---|
125 | |
---|
126 | def test08x509StackVerifyCertChain(self): |
---|
127 | # test08X509StackVerifyCertChain: testVerifyCertChain method |
---|
128 | |
---|
129 | self.test01X509CertRead() |
---|
130 | proxyCert=X509CertRead(xpdVars( |
---|
131 | self.cfg['test08X509StackVerifyCertChain']['proxycertfile'])) |
---|
132 | |
---|
133 | stack1 = X509Stack() |
---|
134 | stack1.push(self.x509Cert) |
---|
135 | |
---|
136 | caCert=X509CertRead(xpdVars(\ |
---|
137 | self.cfg['test08X509StackVerifyCertChain']['cacertfile'])) |
---|
138 | caStack = X509Stack() |
---|
139 | caStack.push(caCert) |
---|
140 | |
---|
141 | print("Verification of external cert with external CA stack...") |
---|
142 | stack1.verifyCertChain(x509Cert2Verify=proxyCert, |
---|
143 | caX509Stack=caStack) |
---|
144 | |
---|
145 | print("Verification of stack content using CA stack...") |
---|
146 | stack1.push(proxyCert) |
---|
147 | stack1.verifyCertChain(caX509Stack=caStack) |
---|
148 | |
---|
149 | print("Verification of stack alone...") |
---|
150 | stack1.push(caCert) |
---|
151 | stack1.verifyCertChain() |
---|
152 | |
---|
153 | print("Reject self-signed cert. ...") |
---|
154 | stack2 = X509Stack() |
---|
155 | try: |
---|
156 | stack2.verifyCertChain() |
---|
157 | self.fail("Empty stack error expected") |
---|
158 | except X509StackEmptyError: |
---|
159 | pass |
---|
160 | |
---|
161 | stack2.push(caCert) |
---|
162 | try: |
---|
163 | stack2.verifyCertChain() |
---|
164 | self.fail("Reject of self-signed cert. expected") |
---|
165 | except SelfSignedCert: |
---|
166 | pass |
---|
167 | |
---|
168 | print("Accept self-signed cert. ...") |
---|
169 | stack2.verifyCertChain(rejectSelfSignedCert=False) |
---|
170 | |
---|
171 | self.assert_(stack2.pop()) |
---|
172 | print("Test no cert. issuer found ...") |
---|
173 | stack2.push(proxyCert) |
---|
174 | try: |
---|
175 | stack2.verifyCertChain() |
---|
176 | self.fail("No cert. issuer error expected") |
---|
177 | except X509CertIssuerNotFound: |
---|
178 | pass |
---|
179 | |
---|
180 | print("Test no cert. issuer found again with incomplete chain ...") |
---|
181 | stack2.push(self.x509Cert) |
---|
182 | try: |
---|
183 | stack2.verifyCertChain() |
---|
184 | self.fail("No cert. issuer error expected") |
---|
185 | except X509CertIssuerNotFound: |
---|
186 | pass |
---|
187 | |
---|
188 | def test09ExpiryTime(self): |
---|
189 | self.test01X509CertRead() |
---|
190 | |
---|
191 | # Set ridiculous bounds for expiry warning to ensure a warning message |
---|
192 | # is output |
---|
193 | self.assert_(self.x509Cert.isValidTime(nDaysBeforeExpiryLimit=36500), |
---|
194 | "Certificate has expired") |
---|
195 | if not _warningMsg: |
---|
196 | self.fail("No warning message was set") |
---|
197 | else: |
---|
198 | print("PASSED - Got warning message from X509Cert." |
---|
199 | "isValidTime: %s" % _warningMsg) |
---|
200 | |
---|
201 | def test10ReadStackFromCADir(self): |
---|
202 | |
---|
203 | stack = X509Stack.fromCADir(X509TestCase.CA_DIR) |
---|
204 | self.assert_(stack) |
---|
205 | self.assert_(len(stack) > 0) |
---|
206 | |
---|
207 | class X500DNTestCase(BaseTestCase): |
---|
208 | def test01VerifyParsingForFieldsContainingSlash(self): |
---|
209 | # Slash is the delimiter but fields can contain a slash too - ensure |
---|
210 | # correct parsing based on a regular expression which handles this |
---|
211 | # scenario |
---|
212 | dnStr = ("/C=UK/O=eScience/OU=CLRC/L=RAL/CN=host/localhost/" |
---|
213 | "emailAddress=somebody@somewhere.ac.uk") |
---|
214 | dn = X500DN.fromString(dnStr) |
---|
215 | self.assert_(str(dn)) |
---|
216 | print(dn) |
---|
217 | |
---|
218 | if __name__ == "__main__": |
---|
219 | unittest.main() |
---|