blob: 2d778d250c96907e083488a90681fcc5ef06a89f [file] [log] [blame]
Nobuaki Sukegawaf32bae72016-02-20 08:51:33 +09001#
2# licensed to the apache software foundation (asf) under one
3# or more contributor license agreements. see the notice file
4# distributed with this work for additional information
5# regarding copyright ownership. the asf licenses this file
6# to you under the apache license, version 2.0 (the
7# "license"); you may not use this file except in compliance
8# with the license. you may obtain a copy of the license at
9#
10# http://www.apache.org/licenses/license-2.0
11#
12# unless required by applicable law or agreed to in writing,
13# software distributed under the license is distributed on an
14# "as is" basis, without warranties or conditions of any
15# KIND, either express or implied. See the License for the
16# specific language governing permissions and limitations
17# under the License.
18#
19
20from thrift.transport.TTransport import TTransportException
21
22
23def legacy_validate_callback(self, cert, hostname):
24 """legacy method to validate the peer's SSL certificate, and to check
25 the commonName of the certificate to ensure it matches the hostname we
26 used to make this connection. Does not support subjectAltName records
27 in certificates.
28
29 raises TTransportException if the certificate fails validation.
30 """
31 if 'subject' not in cert:
32 raise TTransportException(
33 TTransportException.NOT_OPEN,
34 'No SSL certificate found from %s:%s' % (self.host, self.port))
35 fields = cert['subject']
36 for field in fields:
37 # ensure structure we get back is what we expect
38 if not isinstance(field, tuple):
39 continue
40 cert_pair = field[0]
41 if len(cert_pair) < 2:
42 continue
43 cert_key, cert_value = cert_pair[0:2]
44 if cert_key != 'commonName':
45 continue
46 certhost = cert_value
47 # this check should be performed by some sort of Access Manager
48 if certhost == hostname:
49 # success, cert commonName matches desired hostname
50 return
51 else:
52 raise TTransportException(
53 TTransportException.UNKNOWN,
54 'Hostname we connected to "%s" doesn\'t match certificate '
55 'provided commonName "%s"' % (self.host, certhost))
56 raise TTransportException(
57 TTransportException.UNKNOWN,
58 'Could not validate SSL certificate from host "%s". Cert=%s'
59 % (hostname, cert))
60
61
62try:
63 import ipaddress # noqa
64 _match_has_ipaddress = True
65except ImportError:
66 _match_has_ipaddress = False
67
68try:
69 from backports.ssl_match_hostname import match_hostname
70 _match_hostname = match_hostname
71except ImportError:
72 try:
73 from ssl import match_hostname
74 _match_hostname = match_hostname
75 except ImportError:
76 _match_hostname = legacy_validate_callback
77 _match_has_ipaddress = False