Handle error when getting peer cert on older py27

If the create_default_context function is not available
create a context for python version < 2.7.9.

Change-Id: Iec1411a98faf36e2ad5d2deb772d6a20c063e7d2
This commit is contained in:
Isaac Mungai 2016-10-03 12:53:49 -04:00
parent d9ec45d8c2
commit 30f0332658
2 changed files with 52 additions and 1 deletions

View File

@ -120,8 +120,24 @@ def get_sans_by_host(remote_host):
return result
def _build_context():
import _ssl
context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
context.options |= ssl.OP_NO_SSLv2
context.options |= ssl.OP_NO_SSLv3
context.options |= getattr(_ssl, "OP_NO_COMPRESSION", 0)
context.verify_mode = ssl.CERT_REQUIRED
context.check_hostname = True
context.load_default_certs(ssl.Purpose.SERVER_AUTH)
return context
def _get_cert_alternate(remote_host):
context = ssl.create_default_context()
try:
context = ssl.create_default_context()
except AttributeError:
context = _build_context()
conn = context.wrap_socket(socket.socket(socket.AF_INET),
server_hostname=remote_host)
conn.connect((remote_host, 443))

View File

@ -38,6 +38,10 @@ class TestAkamaiUtils(base.TestCase):
self.mock_ssl_context = ssl_context_patcher.start()
self.addCleanup(ssl_context_patcher.stop)
context_patcher = mock.patch('ssl.SSLContext')
self.mock_context = context_patcher.start()
self.addCleanup(context_patcher.stop)
self.mock_ssl_context.return_value.wrap_socket.return_value. \
getpeercert.return_value = {
'issuer': (
@ -172,3 +176,34 @@ class TestAkamaiUtils(base.TestCase):
self.assertRaises(
ValueError, utils.get_ssl_number_of_hosts, 'remote_host')
self.assertRaises(ValueError, utils.get_sans_by_host, 'remote_host')
def test_default_context_error(self):
self.mock_ssl_context.side_effect = AttributeError(
'Mock -- Something went wrong create default context.'
)
self.mock_context.return_value.wrap_socket.return_value. \
getpeercert.return_value = {
'issuer': (
(('countryName', 'IL'),),
(('organizationName', 'Issuer Ltd.'),),
(('organizationalUnitName', 'Secure Cert Signing'),),
(('commonName', 'Secure CA'),)
),
'notAfter': 'Nov 22 08:15:19 2013 GMT',
'notBefore': 'Nov 21 03:09:52 2011 GMT',
'serialNumber': 'DEAD',
'subject': (
(('description', 'Some-DESCRIPTION'),),
(('countryName', 'US'),),
(('stateOrProvinceName', 'Georgia'),),
(('localityName', 'Atlanta'),),
(('organizationName', 'R_Host, Inc.'),),
(('commonName', '*.r_host'),),
(('emailAddress', 'host_master@r_host'),)
),
'subjectAltName': (('DNS', '*.r_host'), ('DNS', 'r_host')),
'version': 3
}
self.assertEqual(
2, utils.get_ssl_number_of_hosts_alternate('remote_host'))