1212import sys
1313
1414if sys .version_info [0 ] > 2 :
15- from urllib .error import URLError as URLError_
15+ from urllib .error import URLError as URLError
1616else :
17- from urllib2 import URLError as URLError_
17+ from urllib2 import URLError as URLError
1818
1919import unittest
2020
2121from OpenSSL import SSL
2222from ndg .httpsclient .test import Constants
2323from ndg .httpsclient .urllib2_build_opener import build_opener
24+ from ndg .httpsclient .ssl_peer_verification import ServerSSLCertVerification
2425
2526
2627class Urllib2TestCase (unittest .TestCase ):
@@ -36,21 +37,53 @@ def test02_open(self):
3637 self .assertTrue (res )
3738 print ("res = %s" % res .read ())
3839
40+ # Skip this test for remote service as it can take a long time to timeout
41+ @unittest .skipIf (Constants .HOSTNAME != 'localhost' , 'Skip non-local host' )
3942 def test03_open_fails_unknown_loc (self ):
4043 opener = build_opener ()
41- self .assertRaises (URLError_ , opener .open , Constants .TEST_URI2 )
44+ self .assertRaises (URLError , opener .open , Constants .TEST_URI2 )
4245
4346 def test04_open_peer_cert_verification_fails (self ):
4447 # Explicitly set empty CA directory to make verification fail
45- ctx = SSL .Context (SSL .TLSv1_METHOD )
48+ ctx = SSL .Context (SSL .TLSv1_2_METHOD )
4649 verify_callback = lambda conn , x509 , errnum , errdepth , preverify_ok : \
4750 preverify_ok
4851
4952 ctx .set_verify (SSL .VERIFY_PEER , verify_callback )
5053 ctx .load_verify_locations (None , './' )
5154 opener = build_opener (ssl_context = ctx )
5255 self .assertRaises (SSL .Error , opener .open , Constants .TEST_URI )
56+
57+ def test05_open_with_subj_alt_names_verification (self ):
58+ ctx = SSL .Context (SSL .TLSv1_2_METHOD )
59+
60+ # Set wildcard hostname for subject alternative name matching -
61+ # setting a minimum of two name components for hostname
62+ split_hostname = Constants .HOSTNAME .split ('.' , 1 )
63+ if len (split_hostname ) > 1 :
64+ _hostname = '*.' + split_hostname [- 1 ]
65+ else :
66+ _hostname = Constants .HOSTNAME
67+
68+ server_ssl_verify = ServerSSLCertVerification (hostname = _hostname )
69+ verify_callback_ = server_ssl_verify .get_verify_server_cert_func ()
70+ ctx .set_verify (SSL .VERIFY_PEER , verify_callback_ )
71+
72+ # Set default verify paths if testing with peer that has corresponding
73+ # CA cert in bundle provided with the OS. In this case, load verify
74+ # locations is not needed.
75+ #ctx.set_default_verify_paths()
5376
77+ ctx .set_verify_depth (9 )
78+
79+ # Set correct location for CA certs to verify with
80+ ctx .load_verify_locations (None , Constants .CACERT_DIR )
81+
82+ opener = build_opener (ssl_context = ctx )
83+ res = opener .open (Constants .TEST_URI )
84+ self .assertTrue (res )
85+ print ("res = %s" % res .read ())
86+
5487
5588if __name__ == "__main__" :
5689 unittest .main ()
0 commit comments