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,43 @@ def test02_open(self):
3637 self .assertTrue (res )
3738 print ("res = %s" % res .read ())
3839
40+ @unittest .skipIf (Constants .HOSTNAME != 'localhost' , 'Skip non-local host' )
3941 def test03_open_fails_unknown_loc (self ):
4042 opener = build_opener ()
4143 self .assertRaises (URLError_ , opener .open , Constants .TEST_URI2 )
4244
4345 def test04_open_peer_cert_verification_fails (self ):
4446 # Explicitly set empty CA directory to make verification fail
45- ctx = SSL .Context (SSL .TLSv1_METHOD )
47+ ctx = SSL .Context (SSL .TLSv1_2_METHOD )
4648 verify_callback = lambda conn , x509 , errnum , errdepth , preverify_ok : \
4749 preverify_ok
4850
4951 ctx .set_verify (SSL .VERIFY_PEER , verify_callback )
5052 ctx .load_verify_locations (None , './' )
5153 opener = build_opener (ssl_context = ctx )
5254 self .assertRaises (SSL .Error , opener .open , Constants .TEST_URI )
53-
55+
56+ def test05_open_with_subj_alt_names_verification (self ):
57+ ctx = SSL .Context (SSL .TLSv1_2_METHOD )
58+
59+ # Set wildcard hostname for subject alternative name matching -
60+ # setting a minimum of two name components for hostname
61+ split_hostname = Constants .HOSTNAME .split ('.' , 1 )
62+ if len (split_hostname ) > 1 :
63+ _hostname = '*.' + split_hostname [- 1 ]
64+ else :
65+ _hostname = Constants .HOSTNAME
66+
67+ server_ssl_verify = ServerSSLCertVerification (hostname = _hostname )
68+ verify_callback_ = server_ssl_verify .get_verify_server_cert_func ()
69+ ctx .set_verify (SSL .VERIFY_PEER , verify_callback_ )
70+ ctx .set_default_verify_paths ()
71+
72+ opener = build_opener (ssl_context = ctx )
73+ res = opener .open (Constants .TEST_URI )
74+ self .assertTrue (res )
75+ print ("res = %s" % res .read ())
76+
5477
5578if __name__ == "__main__" :
5679 unittest .main ()
0 commit comments