Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 1 | # Wrapper module for _ssl, providing some additional facilities |
| 2 | # implemented in Python. Written by Bill Janssen. |
| 3 | |
Guido van Rossum | 5b8b155 | 2007-11-16 00:06:11 +0000 | [diff] [blame] | 4 | """This module provides some more Pythonic support for SSL. |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 5 | |
| 6 | Object types: |
| 7 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 8 | SSLSocket -- subtype of socket.socket which does SSL over the socket |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 9 | |
| 10 | Exceptions: |
| 11 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 12 | SSLError -- exception raised for I/O errors |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 13 | |
| 14 | Functions: |
| 15 | |
| 16 | cert_time_to_seconds -- convert time string used for certificate |
| 17 | notBefore and notAfter functions to integer |
| 18 | seconds past the Epoch (the time values |
| 19 | returned from time.time()) |
| 20 | |
| 21 | fetch_server_certificate (HOST, PORT) -- fetch the certificate provided |
| 22 | by the server running on HOST at port PORT. No |
| 23 | validation of the certificate is performed. |
| 24 | |
| 25 | Integer constants: |
| 26 | |
| 27 | SSL_ERROR_ZERO_RETURN |
| 28 | SSL_ERROR_WANT_READ |
| 29 | SSL_ERROR_WANT_WRITE |
| 30 | SSL_ERROR_WANT_X509_LOOKUP |
| 31 | SSL_ERROR_SYSCALL |
| 32 | SSL_ERROR_SSL |
| 33 | SSL_ERROR_WANT_CONNECT |
| 34 | |
| 35 | SSL_ERROR_EOF |
| 36 | SSL_ERROR_INVALID_ERROR_CODE |
| 37 | |
| 38 | The following group define certificate requirements that one side is |
| 39 | allowing/requiring from the other side: |
| 40 | |
| 41 | CERT_NONE - no certificates from the other side are required (or will |
| 42 | be looked at if provided) |
| 43 | CERT_OPTIONAL - certificates are not required, but if provided will be |
| 44 | validated, and if validation fails, the connection will |
| 45 | also fail |
| 46 | CERT_REQUIRED - certificates are required, and will be validated, and |
| 47 | if validation fails, the connection will also fail |
| 48 | |
| 49 | The following constants identify various SSL protocol variants: |
| 50 | |
| 51 | PROTOCOL_SSLv2 |
| 52 | PROTOCOL_SSLv3 |
| 53 | PROTOCOL_SSLv23 |
Christian Heimes | 598894f | 2016-09-05 23:19:05 +0200 | [diff] [blame] | 54 | PROTOCOL_TLS |
Christian Heimes | 5fe668c | 2016-09-12 00:01:11 +0200 | [diff] [blame] | 55 | PROTOCOL_TLS_CLIENT |
| 56 | PROTOCOL_TLS_SERVER |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 57 | PROTOCOL_TLSv1 |
Antoine Pitrou | 2463e5f | 2013-03-28 22:24:43 +0100 | [diff] [blame] | 58 | PROTOCOL_TLSv1_1 |
| 59 | PROTOCOL_TLSv1_2 |
Antoine Pitrou | 58ddc9d | 2013-01-05 21:20:29 +0100 | [diff] [blame] | 60 | |
| 61 | The following constants identify various SSL alert message descriptions as per |
| 62 | http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-6 |
| 63 | |
| 64 | ALERT_DESCRIPTION_CLOSE_NOTIFY |
| 65 | ALERT_DESCRIPTION_UNEXPECTED_MESSAGE |
| 66 | ALERT_DESCRIPTION_BAD_RECORD_MAC |
| 67 | ALERT_DESCRIPTION_RECORD_OVERFLOW |
| 68 | ALERT_DESCRIPTION_DECOMPRESSION_FAILURE |
| 69 | ALERT_DESCRIPTION_HANDSHAKE_FAILURE |
| 70 | ALERT_DESCRIPTION_BAD_CERTIFICATE |
| 71 | ALERT_DESCRIPTION_UNSUPPORTED_CERTIFICATE |
| 72 | ALERT_DESCRIPTION_CERTIFICATE_REVOKED |
| 73 | ALERT_DESCRIPTION_CERTIFICATE_EXPIRED |
| 74 | ALERT_DESCRIPTION_CERTIFICATE_UNKNOWN |
| 75 | ALERT_DESCRIPTION_ILLEGAL_PARAMETER |
| 76 | ALERT_DESCRIPTION_UNKNOWN_CA |
| 77 | ALERT_DESCRIPTION_ACCESS_DENIED |
| 78 | ALERT_DESCRIPTION_DECODE_ERROR |
| 79 | ALERT_DESCRIPTION_DECRYPT_ERROR |
| 80 | ALERT_DESCRIPTION_PROTOCOL_VERSION |
| 81 | ALERT_DESCRIPTION_INSUFFICIENT_SECURITY |
| 82 | ALERT_DESCRIPTION_INTERNAL_ERROR |
| 83 | ALERT_DESCRIPTION_USER_CANCELLED |
| 84 | ALERT_DESCRIPTION_NO_RENEGOTIATION |
| 85 | ALERT_DESCRIPTION_UNSUPPORTED_EXTENSION |
| 86 | ALERT_DESCRIPTION_CERTIFICATE_UNOBTAINABLE |
| 87 | ALERT_DESCRIPTION_UNRECOGNIZED_NAME |
| 88 | ALERT_DESCRIPTION_BAD_CERTIFICATE_STATUS_RESPONSE |
| 89 | ALERT_DESCRIPTION_BAD_CERTIFICATE_HASH_VALUE |
| 90 | ALERT_DESCRIPTION_UNKNOWN_PSK_IDENTITY |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 91 | """ |
| 92 | |
Antoine Pitrou | c481bfb | 2015-02-15 18:12:20 +0100 | [diff] [blame] | 93 | import ipaddress |
Christian Heimes | 05e8be1 | 2008-02-23 18:30:17 +0000 | [diff] [blame] | 94 | import textwrap |
Antoine Pitrou | 59fdd67 | 2010-10-08 10:37:08 +0000 | [diff] [blame] | 95 | import re |
Christian Heimes | 46bebee | 2013-06-09 19:03:31 +0200 | [diff] [blame] | 96 | import sys |
Christian Heimes | 6d7ad13 | 2013-06-09 18:02:55 +0200 | [diff] [blame] | 97 | import os |
Christian Heimes | a6bc95a | 2013-11-17 19:59:14 +0100 | [diff] [blame] | 98 | from collections import namedtuple |
Christian Heimes | 3aeacad | 2016-09-10 00:19:35 +0200 | [diff] [blame] | 99 | from enum import Enum as _Enum, IntEnum as _IntEnum, IntFlag as _IntFlag |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 100 | |
| 101 | import _ssl # if we can't import it, let the error propagate |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 102 | |
Antoine Pitrou | 04f6a32 | 2010-04-05 21:40:07 +0000 | [diff] [blame] | 103 | from _ssl import OPENSSL_VERSION_NUMBER, OPENSSL_VERSION_INFO, OPENSSL_VERSION |
Christian Heimes | 99a6570 | 2016-09-10 23:44:53 +0200 | [diff] [blame] | 104 | from _ssl import _SSLContext, MemoryBIO, SSLSession |
Antoine Pitrou | 41032a6 | 2011-10-27 23:56:55 +0200 | [diff] [blame] | 105 | from _ssl import ( |
| 106 | SSLError, SSLZeroReturnError, SSLWantReadError, SSLWantWriteError, |
Christian Heimes | b3ad0e5 | 2017-09-08 12:00:19 -0700 | [diff] [blame] | 107 | SSLSyscallError, SSLEOFError, SSLCertVerificationError |
Antoine Pitrou | 41032a6 | 2011-10-27 23:56:55 +0200 | [diff] [blame] | 108 | ) |
Christian Heimes | a6bc95a | 2013-11-17 19:59:14 +0100 | [diff] [blame] | 109 | from _ssl import txt2obj as _txt2obj, nid2obj as _nid2obj |
Victor Stinner | beeb512 | 2014-11-28 13:28:25 +0100 | [diff] [blame] | 110 | from _ssl import RAND_status, RAND_add, RAND_bytes, RAND_pseudo_bytes |
| 111 | try: |
| 112 | from _ssl import RAND_egd |
| 113 | except ImportError: |
| 114 | # LibreSSL does not provide RAND_egd |
| 115 | pass |
Antoine Pitrou | 58ddc9d | 2013-01-05 21:20:29 +0100 | [diff] [blame] | 116 | |
Antoine Pitrou | 58ddc9d | 2013-01-05 21:20:29 +0100 | [diff] [blame] | 117 | |
Christian Heimes | cb5b68a | 2017-09-07 18:07:00 -0700 | [diff] [blame] | 118 | from _ssl import HAS_SNI, HAS_ECDH, HAS_NPN, HAS_ALPN, HAS_TLSv1_3 |
Antoine Pitrou | b9ac25d | 2011-07-08 18:47:06 +0200 | [diff] [blame] | 119 | from _ssl import _OPENSSL_API_VERSION |
| 120 | |
Christian Heimes | 3aeacad | 2016-09-10 00:19:35 +0200 | [diff] [blame] | 121 | |
Ethan Furman | 24e837f | 2015-03-18 17:27:57 -0700 | [diff] [blame] | 122 | _IntEnum._convert( |
Christian Heimes | 3aeacad | 2016-09-10 00:19:35 +0200 | [diff] [blame] | 123 | '_SSLMethod', __name__, |
| 124 | lambda name: name.startswith('PROTOCOL_') and name != 'PROTOCOL_SSLv23', |
| 125 | source=_ssl) |
| 126 | |
| 127 | _IntFlag._convert( |
| 128 | 'Options', __name__, |
| 129 | lambda name: name.startswith('OP_'), |
| 130 | source=_ssl) |
| 131 | |
| 132 | _IntEnum._convert( |
| 133 | 'AlertDescription', __name__, |
| 134 | lambda name: name.startswith('ALERT_DESCRIPTION_'), |
| 135 | source=_ssl) |
| 136 | |
| 137 | _IntEnum._convert( |
| 138 | 'SSLErrorNumber', __name__, |
| 139 | lambda name: name.startswith('SSL_ERROR_'), |
| 140 | source=_ssl) |
| 141 | |
| 142 | _IntFlag._convert( |
| 143 | 'VerifyFlags', __name__, |
| 144 | lambda name: name.startswith('VERIFY_'), |
| 145 | source=_ssl) |
| 146 | |
| 147 | _IntEnum._convert( |
| 148 | 'VerifyMode', __name__, |
| 149 | lambda name: name.startswith('CERT_'), |
| 150 | source=_ssl) |
| 151 | |
Antoine Pitrou | 58ddc9d | 2013-01-05 21:20:29 +0100 | [diff] [blame] | 152 | |
Christian Heimes | 598894f | 2016-09-05 23:19:05 +0200 | [diff] [blame] | 153 | PROTOCOL_SSLv23 = _SSLMethod.PROTOCOL_SSLv23 = _SSLMethod.PROTOCOL_TLS |
Antoine Pitrou | 172f025 | 2014-04-18 20:33:08 +0200 | [diff] [blame] | 154 | _PROTOCOL_NAMES = {value: name for name, value in _SSLMethod.__members__.items()} |
| 155 | |
Christian Heimes | 3aeacad | 2016-09-10 00:19:35 +0200 | [diff] [blame] | 156 | _SSLv2_IF_EXISTS = getattr(_SSLMethod, 'PROTOCOL_SSLv2', None) |
| 157 | |
Antoine Pitrou | 2463e5f | 2013-03-28 22:24:43 +0100 | [diff] [blame] | 158 | |
Christian Heimes | 46bebee | 2013-06-09 19:03:31 +0200 | [diff] [blame] | 159 | if sys.platform == "win32": |
Christian Heimes | 44109d7 | 2013-11-22 01:51:30 +0100 | [diff] [blame] | 160 | from _ssl import enum_certificates, enum_crls |
Christian Heimes | 46bebee | 2013-06-09 19:03:31 +0200 | [diff] [blame] | 161 | |
Antoine Pitrou | 15399c3 | 2011-04-28 19:23:55 +0200 | [diff] [blame] | 162 | from socket import socket, AF_INET, SOCK_STREAM, create_connection |
Antoine Pitrou | 3e86ba4 | 2013-12-28 17:26:33 +0100 | [diff] [blame] | 163 | from socket import SOL_SOCKET, SO_TYPE |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 164 | import base64 # for DER-to-PEM translation |
Antoine Pitrou | de8cf32 | 2010-04-26 17:29:05 +0000 | [diff] [blame] | 165 | import errno |
Steve Dower | 33bc4a2 | 2016-05-26 12:18:12 -0700 | [diff] [blame] | 166 | import warnings |
Thomas Wouters | 47b49bf | 2007-08-30 22:15:33 +0000 | [diff] [blame] | 167 | |
Andrew Svetlov | 0832af6 | 2012-12-18 23:10:48 +0200 | [diff] [blame] | 168 | |
| 169 | socket_error = OSError # keep that public name in module namespace |
| 170 | |
Antoine Pitrou | d649480 | 2011-07-21 01:11:30 +0200 | [diff] [blame] | 171 | if _ssl.HAS_TLS_UNIQUE: |
| 172 | CHANNEL_BINDING_TYPES = ['tls-unique'] |
| 173 | else: |
| 174 | CHANNEL_BINDING_TYPES = [] |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 175 | |
Christian Heimes | 03d13c0 | 2016-09-06 20:06:47 +0200 | [diff] [blame] | 176 | |
Antoine Pitrou | 8f85f90 | 2012-01-03 22:46:48 +0100 | [diff] [blame] | 177 | # Disable weak or insecure ciphers by default |
| 178 | # (OpenSSL's default setting is 'DEFAULT:!aNULL:!eNULL') |
Donald Stufft | 79ccaa2 | 2014-03-21 21:33:34 -0400 | [diff] [blame] | 179 | # Enable a better set of ciphers by default |
| 180 | # This list has been explicitly chosen to: |
Christian Heimes | cb5b68a | 2017-09-07 18:07:00 -0700 | [diff] [blame] | 181 | # * TLS 1.3 ChaCha20 and AES-GCM cipher suites |
Donald Stufft | 79ccaa2 | 2014-03-21 21:33:34 -0400 | [diff] [blame] | 182 | # * Prefer cipher suites that offer perfect forward secrecy (DHE/ECDHE) |
| 183 | # * Prefer ECDHE over DHE for better performance |
Christian Heimes | 03d13c0 | 2016-09-06 20:06:47 +0200 | [diff] [blame] | 184 | # * Prefer AEAD over CBC for better performance and security |
| 185 | # * Prefer AES-GCM over ChaCha20 because most platforms have AES-NI |
| 186 | # (ChaCha20 needs OpenSSL 1.1.0 or patched 1.0.2) |
| 187 | # * Prefer any AES-GCM and ChaCha20 over any AES-CBC for better |
| 188 | # performance and security |
Donald Stufft | 79ccaa2 | 2014-03-21 21:33:34 -0400 | [diff] [blame] | 189 | # * Then Use HIGH cipher suites as a fallback |
Christian Heimes | 03d13c0 | 2016-09-06 20:06:47 +0200 | [diff] [blame] | 190 | # * Disable NULL authentication, NULL encryption, 3DES and MD5 MACs |
| 191 | # for security reasons |
Donald Stufft | 79ccaa2 | 2014-03-21 21:33:34 -0400 | [diff] [blame] | 192 | _DEFAULT_CIPHERS = ( |
Christian Heimes | cb5b68a | 2017-09-07 18:07:00 -0700 | [diff] [blame] | 193 | 'TLS13-AES-256-GCM-SHA384:TLS13-CHACHA20-POLY1305-SHA256:' |
| 194 | 'TLS13-AES-128-GCM-SHA256:' |
Christian Heimes | 03d13c0 | 2016-09-06 20:06:47 +0200 | [diff] [blame] | 195 | 'ECDH+AESGCM:ECDH+CHACHA20:DH+AESGCM:DH+CHACHA20:ECDH+AES256:DH+AES256:' |
| 196 | 'ECDH+AES128:DH+AES:ECDH+HIGH:DH+HIGH:RSA+AESGCM:RSA+AES:RSA+HIGH:' |
| 197 | '!aNULL:!eNULL:!MD5:!3DES' |
| 198 | ) |
Antoine Pitrou | 8f85f90 | 2012-01-03 22:46:48 +0100 | [diff] [blame] | 199 | |
Donald Stufft | 6a2ba94 | 2014-03-23 19:05:28 -0400 | [diff] [blame] | 200 | # Restricted and more secure ciphers for the server side |
Donald Stufft | 79ccaa2 | 2014-03-21 21:33:34 -0400 | [diff] [blame] | 201 | # This list has been explicitly chosen to: |
Christian Heimes | cb5b68a | 2017-09-07 18:07:00 -0700 | [diff] [blame] | 202 | # * TLS 1.3 ChaCha20 and AES-GCM cipher suites |
Donald Stufft | 79ccaa2 | 2014-03-21 21:33:34 -0400 | [diff] [blame] | 203 | # * Prefer cipher suites that offer perfect forward secrecy (DHE/ECDHE) |
| 204 | # * Prefer ECDHE over DHE for better performance |
Christian Heimes | 03d13c0 | 2016-09-06 20:06:47 +0200 | [diff] [blame] | 205 | # * Prefer AEAD over CBC for better performance and security |
| 206 | # * Prefer AES-GCM over ChaCha20 because most platforms have AES-NI |
| 207 | # * Prefer any AES-GCM and ChaCha20 over any AES-CBC for better |
| 208 | # performance and security |
Donald Stufft | 79ccaa2 | 2014-03-21 21:33:34 -0400 | [diff] [blame] | 209 | # * Then Use HIGH cipher suites as a fallback |
Christian Heimes | 03d13c0 | 2016-09-06 20:06:47 +0200 | [diff] [blame] | 210 | # * Disable NULL authentication, NULL encryption, MD5 MACs, DSS, RC4, and |
| 211 | # 3DES for security reasons |
Donald Stufft | 6a2ba94 | 2014-03-23 19:05:28 -0400 | [diff] [blame] | 212 | _RESTRICTED_SERVER_CIPHERS = ( |
Christian Heimes | cb5b68a | 2017-09-07 18:07:00 -0700 | [diff] [blame] | 213 | 'TLS13-AES-256-GCM-SHA384:TLS13-CHACHA20-POLY1305-SHA256:' |
| 214 | 'TLS13-AES-128-GCM-SHA256:' |
Christian Heimes | 03d13c0 | 2016-09-06 20:06:47 +0200 | [diff] [blame] | 215 | 'ECDH+AESGCM:ECDH+CHACHA20:DH+AESGCM:DH+CHACHA20:ECDH+AES256:DH+AES256:' |
| 216 | 'ECDH+AES128:DH+AES:ECDH+HIGH:DH+HIGH:RSA+AESGCM:RSA+AES:RSA+HIGH:' |
| 217 | '!aNULL:!eNULL:!MD5:!DSS:!RC4:!3DES' |
Donald Stufft | 79ccaa2 | 2014-03-21 21:33:34 -0400 | [diff] [blame] | 218 | ) |
Christian Heimes | 4c05b47 | 2013-11-23 15:58:30 +0100 | [diff] [blame] | 219 | |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 220 | |
Antoine Pitrou | 59fdd67 | 2010-10-08 10:37:08 +0000 | [diff] [blame] | 221 | class CertificateError(ValueError): |
| 222 | pass |
| 223 | |
| 224 | |
Georg Brandl | 72c98d3 | 2013-10-27 07:16:53 +0100 | [diff] [blame] | 225 | def _dnsname_match(dn, hostname, max_wildcards=1): |
| 226 | """Matching according to RFC 6125, section 6.4.3 |
| 227 | |
| 228 | http://tools.ietf.org/html/rfc6125#section-6.4.3 |
| 229 | """ |
Antoine Pitrou | 59fdd67 | 2010-10-08 10:37:08 +0000 | [diff] [blame] | 230 | pats = [] |
Georg Brandl | 72c98d3 | 2013-10-27 07:16:53 +0100 | [diff] [blame] | 231 | if not dn: |
| 232 | return False |
| 233 | |
| 234 | leftmost, *remainder = dn.split(r'.') |
| 235 | |
| 236 | wildcards = leftmost.count('*') |
| 237 | if wildcards > max_wildcards: |
| 238 | # Issue #17980: avoid denials of service by refusing more |
Berker Peksag | f23530f | 2014-10-19 18:04:38 +0300 | [diff] [blame] | 239 | # than one wildcard per fragment. A survey of established |
Georg Brandl | 72c98d3 | 2013-10-27 07:16:53 +0100 | [diff] [blame] | 240 | # policy among SSL implementations showed it to be a |
| 241 | # reasonable choice. |
| 242 | raise CertificateError( |
| 243 | "too many wildcards in certificate DNS name: " + repr(dn)) |
| 244 | |
| 245 | # speed up common case w/o wildcards |
| 246 | if not wildcards: |
| 247 | return dn.lower() == hostname.lower() |
| 248 | |
| 249 | # RFC 6125, section 6.4.3, subitem 1. |
| 250 | # The client SHOULD NOT attempt to match a presented identifier in which |
| 251 | # the wildcard character comprises a label other than the left-most label. |
| 252 | if leftmost == '*': |
| 253 | # When '*' is a fragment by itself, it matches a non-empty dotless |
| 254 | # fragment. |
| 255 | pats.append('[^.]+') |
| 256 | elif leftmost.startswith('xn--') or hostname.startswith('xn--'): |
| 257 | # RFC 6125, section 6.4.3, subitem 3. |
| 258 | # The client SHOULD NOT attempt to match a presented identifier |
| 259 | # where the wildcard character is embedded within an A-label or |
| 260 | # U-label of an internationalized domain name. |
| 261 | pats.append(re.escape(leftmost)) |
| 262 | else: |
| 263 | # Otherwise, '*' matches any dotless string, e.g. www* |
| 264 | pats.append(re.escape(leftmost).replace(r'\*', '[^.]*')) |
| 265 | |
| 266 | # add the remaining fragments, ignore any wildcards |
| 267 | for frag in remainder: |
| 268 | pats.append(re.escape(frag)) |
| 269 | |
| 270 | pat = re.compile(r'\A' + r'\.'.join(pats) + r'\Z', re.IGNORECASE) |
| 271 | return pat.match(hostname) |
Antoine Pitrou | 59fdd67 | 2010-10-08 10:37:08 +0000 | [diff] [blame] | 272 | |
| 273 | |
Antoine Pitrou | c481bfb | 2015-02-15 18:12:20 +0100 | [diff] [blame] | 274 | def _ipaddress_match(ipname, host_ip): |
| 275 | """Exact matching of IP addresses. |
| 276 | |
| 277 | RFC 6125 explicitly doesn't define an algorithm for this |
| 278 | (section 1.7.2 - "Out of Scope"). |
| 279 | """ |
| 280 | # OpenSSL may add a trailing newline to a subjectAltName's IP address |
| 281 | ip = ipaddress.ip_address(ipname.rstrip()) |
| 282 | return ip == host_ip |
| 283 | |
| 284 | |
Antoine Pitrou | 59fdd67 | 2010-10-08 10:37:08 +0000 | [diff] [blame] | 285 | def match_hostname(cert, hostname): |
| 286 | """Verify that *cert* (in decoded format as returned by |
Georg Brandl | 72c98d3 | 2013-10-27 07:16:53 +0100 | [diff] [blame] | 287 | SSLSocket.getpeercert()) matches the *hostname*. RFC 2818 and RFC 6125 |
| 288 | rules are followed, but IP addresses are not accepted for *hostname*. |
Antoine Pitrou | 59fdd67 | 2010-10-08 10:37:08 +0000 | [diff] [blame] | 289 | |
| 290 | CertificateError is raised on failure. On success, the function |
| 291 | returns nothing. |
| 292 | """ |
| 293 | if not cert: |
Christian Heimes | 1aa9a75 | 2013-12-02 02:41:19 +0100 | [diff] [blame] | 294 | raise ValueError("empty or no certificate, match_hostname needs a " |
| 295 | "SSL socket or SSL context with either " |
| 296 | "CERT_OPTIONAL or CERT_REQUIRED") |
Antoine Pitrou | c481bfb | 2015-02-15 18:12:20 +0100 | [diff] [blame] | 297 | try: |
| 298 | host_ip = ipaddress.ip_address(hostname) |
| 299 | except ValueError: |
| 300 | # Not an IP address (common case) |
| 301 | host_ip = None |
Antoine Pitrou | 59fdd67 | 2010-10-08 10:37:08 +0000 | [diff] [blame] | 302 | dnsnames = [] |
| 303 | san = cert.get('subjectAltName', ()) |
| 304 | for key, value in san: |
| 305 | if key == 'DNS': |
Antoine Pitrou | c481bfb | 2015-02-15 18:12:20 +0100 | [diff] [blame] | 306 | if host_ip is None and _dnsname_match(value, hostname): |
| 307 | return |
| 308 | dnsnames.append(value) |
| 309 | elif key == 'IP Address': |
| 310 | if host_ip is not None and _ipaddress_match(value, host_ip): |
Antoine Pitrou | 59fdd67 | 2010-10-08 10:37:08 +0000 | [diff] [blame] | 311 | return |
| 312 | dnsnames.append(value) |
Antoine Pitrou | 1c86b44 | 2011-05-06 15:19:49 +0200 | [diff] [blame] | 313 | if not dnsnames: |
| 314 | # The subject is only checked when there is no dNSName entry |
| 315 | # in subjectAltName |
Antoine Pitrou | 59fdd67 | 2010-10-08 10:37:08 +0000 | [diff] [blame] | 316 | for sub in cert.get('subject', ()): |
| 317 | for key, value in sub: |
| 318 | # XXX according to RFC 2818, the most specific Common Name |
| 319 | # must be used. |
| 320 | if key == 'commonName': |
Georg Brandl | 72c98d3 | 2013-10-27 07:16:53 +0100 | [diff] [blame] | 321 | if _dnsname_match(value, hostname): |
Antoine Pitrou | 59fdd67 | 2010-10-08 10:37:08 +0000 | [diff] [blame] | 322 | return |
| 323 | dnsnames.append(value) |
| 324 | if len(dnsnames) > 1: |
| 325 | raise CertificateError("hostname %r " |
| 326 | "doesn't match either of %s" |
| 327 | % (hostname, ', '.join(map(repr, dnsnames)))) |
| 328 | elif len(dnsnames) == 1: |
| 329 | raise CertificateError("hostname %r " |
| 330 | "doesn't match %r" |
| 331 | % (hostname, dnsnames[0])) |
| 332 | else: |
| 333 | raise CertificateError("no appropriate commonName or " |
| 334 | "subjectAltName fields were found") |
| 335 | |
| 336 | |
Christian Heimes | a6bc95a | 2013-11-17 19:59:14 +0100 | [diff] [blame] | 337 | DefaultVerifyPaths = namedtuple("DefaultVerifyPaths", |
Christian Heimes | 6d7ad13 | 2013-06-09 18:02:55 +0200 | [diff] [blame] | 338 | "cafile capath openssl_cafile_env openssl_cafile openssl_capath_env " |
| 339 | "openssl_capath") |
| 340 | |
| 341 | def get_default_verify_paths(): |
| 342 | """Return paths to default cafile and capath. |
| 343 | """ |
| 344 | parts = _ssl.get_default_verify_paths() |
| 345 | |
| 346 | # environment vars shadow paths |
| 347 | cafile = os.environ.get(parts[0], parts[1]) |
| 348 | capath = os.environ.get(parts[2], parts[3]) |
| 349 | |
| 350 | return DefaultVerifyPaths(cafile if os.path.isfile(cafile) else None, |
| 351 | capath if os.path.isdir(capath) else None, |
| 352 | *parts) |
| 353 | |
| 354 | |
Christian Heimes | a6bc95a | 2013-11-17 19:59:14 +0100 | [diff] [blame] | 355 | class _ASN1Object(namedtuple("_ASN1Object", "nid shortname longname oid")): |
| 356 | """ASN.1 object identifier lookup |
| 357 | """ |
| 358 | __slots__ = () |
| 359 | |
| 360 | def __new__(cls, oid): |
| 361 | return super().__new__(cls, *_txt2obj(oid, name=False)) |
| 362 | |
| 363 | @classmethod |
| 364 | def fromnid(cls, nid): |
| 365 | """Create _ASN1Object from OpenSSL numeric ID |
| 366 | """ |
| 367 | return super().__new__(cls, *_nid2obj(nid)) |
| 368 | |
| 369 | @classmethod |
| 370 | def fromname(cls, name): |
| 371 | """Create _ASN1Object from short name, long name or OID |
| 372 | """ |
| 373 | return super().__new__(cls, *_txt2obj(name, name=True)) |
| 374 | |
| 375 | |
Christian Heimes | 72d2850 | 2013-11-23 13:56:58 +0100 | [diff] [blame] | 376 | class Purpose(_ASN1Object, _Enum): |
| 377 | """SSLContext purpose flags with X509v3 Extended Key Usage objects |
| 378 | """ |
| 379 | SERVER_AUTH = '1.3.6.1.5.5.7.3.1' |
| 380 | CLIENT_AUTH = '1.3.6.1.5.5.7.3.2' |
| 381 | |
| 382 | |
Antoine Pitrou | 152efa2 | 2010-05-16 18:19:27 +0000 | [diff] [blame] | 383 | class SSLContext(_SSLContext): |
| 384 | """An SSLContext holds various SSL-related configuration options and |
| 385 | data, such as certificates and possibly a private key.""" |
Christian Heimes | 72d2850 | 2013-11-23 13:56:58 +0100 | [diff] [blame] | 386 | _windows_cert_stores = ("CA", "ROOT") |
Antoine Pitrou | 152efa2 | 2010-05-16 18:19:27 +0000 | [diff] [blame] | 387 | |
Christian Heimes | 4df60f1 | 2017-09-15 20:26:05 +0200 | [diff] [blame] | 388 | sslsocket_class = None # SSLSocket is assigned later. |
| 389 | sslobject_class = None # SSLObject is assigned later. |
| 390 | |
Christian Heimes | 598894f | 2016-09-05 23:19:05 +0200 | [diff] [blame] | 391 | def __new__(cls, protocol=PROTOCOL_TLS, *args, **kwargs): |
Antoine Pitrou | 8f85f90 | 2012-01-03 22:46:48 +0100 | [diff] [blame] | 392 | self = _SSLContext.__new__(cls, protocol) |
| 393 | if protocol != _SSLv2_IF_EXISTS: |
| 394 | self.set_ciphers(_DEFAULT_CIPHERS) |
| 395 | return self |
Antoine Pitrou | 152efa2 | 2010-05-16 18:19:27 +0000 | [diff] [blame] | 396 | |
Christian Heimes | 598894f | 2016-09-05 23:19:05 +0200 | [diff] [blame] | 397 | def __init__(self, protocol=PROTOCOL_TLS): |
Antoine Pitrou | 152efa2 | 2010-05-16 18:19:27 +0000 | [diff] [blame] | 398 | self.protocol = protocol |
| 399 | |
| 400 | def wrap_socket(self, sock, server_side=False, |
| 401 | do_handshake_on_connect=True, |
Antoine Pitrou | d532321 | 2010-10-22 18:19:07 +0000 | [diff] [blame] | 402 | suppress_ragged_eofs=True, |
Christian Heimes | 99a6570 | 2016-09-10 23:44:53 +0200 | [diff] [blame] | 403 | server_hostname=None, session=None): |
Christian Heimes | 4df60f1 | 2017-09-15 20:26:05 +0200 | [diff] [blame] | 404 | return self.sslsocket_class( |
| 405 | sock=sock, |
| 406 | server_side=server_side, |
| 407 | do_handshake_on_connect=do_handshake_on_connect, |
| 408 | suppress_ragged_eofs=suppress_ragged_eofs, |
| 409 | server_hostname=server_hostname, |
| 410 | _context=self, |
| 411 | _session=session |
| 412 | ) |
Antoine Pitrou | 152efa2 | 2010-05-16 18:19:27 +0000 | [diff] [blame] | 413 | |
Antoine Pitrou | b1fdf47 | 2014-10-05 20:41:53 +0200 | [diff] [blame] | 414 | def wrap_bio(self, incoming, outgoing, server_side=False, |
Christian Heimes | 99a6570 | 2016-09-10 23:44:53 +0200 | [diff] [blame] | 415 | server_hostname=None, session=None): |
Antoine Pitrou | b1fdf47 | 2014-10-05 20:41:53 +0200 | [diff] [blame] | 416 | sslobj = self._wrap_bio(incoming, outgoing, server_side=server_side, |
| 417 | server_hostname=server_hostname) |
Christian Heimes | 4df60f1 | 2017-09-15 20:26:05 +0200 | [diff] [blame] | 418 | return self.sslobject_class(sslobj, session=session) |
Antoine Pitrou | b1fdf47 | 2014-10-05 20:41:53 +0200 | [diff] [blame] | 419 | |
Antoine Pitrou | d5d17eb | 2012-03-22 00:23:03 +0100 | [diff] [blame] | 420 | def set_npn_protocols(self, npn_protocols): |
| 421 | protos = bytearray() |
| 422 | for protocol in npn_protocols: |
| 423 | b = bytes(protocol, 'ascii') |
| 424 | if len(b) == 0 or len(b) > 255: |
| 425 | raise SSLError('NPN protocols must be 1 to 255 in length') |
| 426 | protos.append(len(b)) |
| 427 | protos.extend(b) |
| 428 | |
| 429 | self._set_npn_protocols(protos) |
| 430 | |
Benjamin Peterson | cca2732 | 2015-01-23 16:35:37 -0500 | [diff] [blame] | 431 | def set_alpn_protocols(self, alpn_protocols): |
| 432 | protos = bytearray() |
| 433 | for protocol in alpn_protocols: |
| 434 | b = bytes(protocol, 'ascii') |
| 435 | if len(b) == 0 or len(b) > 255: |
| 436 | raise SSLError('ALPN protocols must be 1 to 255 in length') |
| 437 | protos.append(len(b)) |
| 438 | protos.extend(b) |
| 439 | |
| 440 | self._set_alpn_protocols(protos) |
| 441 | |
Christian Heimes | 72d2850 | 2013-11-23 13:56:58 +0100 | [diff] [blame] | 442 | def _load_windows_store_certs(self, storename, purpose): |
| 443 | certs = bytearray() |
Steve Dower | 33bc4a2 | 2016-05-26 12:18:12 -0700 | [diff] [blame] | 444 | try: |
| 445 | for cert, encoding, trust in enum_certificates(storename): |
| 446 | # CA certs are never PKCS#7 encoded |
| 447 | if encoding == "x509_asn": |
| 448 | if trust is True or purpose.oid in trust: |
| 449 | certs.extend(cert) |
| 450 | except PermissionError: |
| 451 | warnings.warn("unable to enumerate Windows certificate store") |
Steve Dower | 8dd7aeb | 2016-03-17 15:02:39 -0700 | [diff] [blame] | 452 | if certs: |
| 453 | self.load_verify_locations(cadata=certs) |
Christian Heimes | 72d2850 | 2013-11-23 13:56:58 +0100 | [diff] [blame] | 454 | return certs |
| 455 | |
| 456 | def load_default_certs(self, purpose=Purpose.SERVER_AUTH): |
| 457 | if not isinstance(purpose, _ASN1Object): |
| 458 | raise TypeError(purpose) |
| 459 | if sys.platform == "win32": |
| 460 | for storename in self._windows_cert_stores: |
| 461 | self._load_windows_store_certs(storename, purpose) |
Benjamin Peterson | 5915b0f | 2014-10-03 17:27:05 -0400 | [diff] [blame] | 462 | self.set_default_verify_paths() |
Christian Heimes | 72d2850 | 2013-11-23 13:56:58 +0100 | [diff] [blame] | 463 | |
Christian Heimes | 3aeacad | 2016-09-10 00:19:35 +0200 | [diff] [blame] | 464 | @property |
| 465 | def options(self): |
| 466 | return Options(super().options) |
| 467 | |
| 468 | @options.setter |
| 469 | def options(self, value): |
| 470 | super(SSLContext, SSLContext).options.__set__(self, value) |
| 471 | |
| 472 | @property |
| 473 | def verify_flags(self): |
| 474 | return VerifyFlags(super().verify_flags) |
| 475 | |
| 476 | @verify_flags.setter |
| 477 | def verify_flags(self, value): |
| 478 | super(SSLContext, SSLContext).verify_flags.__set__(self, value) |
| 479 | |
| 480 | @property |
| 481 | def verify_mode(self): |
| 482 | value = super().verify_mode |
| 483 | try: |
| 484 | return VerifyMode(value) |
| 485 | except ValueError: |
| 486 | return value |
| 487 | |
| 488 | @verify_mode.setter |
| 489 | def verify_mode(self, value): |
| 490 | super(SSLContext, SSLContext).verify_mode.__set__(self, value) |
| 491 | |
Antoine Pitrou | 152efa2 | 2010-05-16 18:19:27 +0000 | [diff] [blame] | 492 | |
Christian Heimes | 4c05b47 | 2013-11-23 15:58:30 +0100 | [diff] [blame] | 493 | def create_default_context(purpose=Purpose.SERVER_AUTH, *, cafile=None, |
| 494 | capath=None, cadata=None): |
| 495 | """Create a SSLContext object with default settings. |
| 496 | |
| 497 | NOTE: The protocol and settings may change anytime without prior |
| 498 | deprecation. The values represent a fair balance between maximum |
| 499 | compatibility and security. |
| 500 | """ |
| 501 | if not isinstance(purpose, _ASN1Object): |
| 502 | raise TypeError(purpose) |
Donald Stufft | 6a2ba94 | 2014-03-23 19:05:28 -0400 | [diff] [blame] | 503 | |
Christian Heimes | 358cfd4 | 2016-09-10 22:43:48 +0200 | [diff] [blame] | 504 | # SSLContext sets OP_NO_SSLv2, OP_NO_SSLv3, OP_NO_COMPRESSION, |
| 505 | # OP_CIPHER_SERVER_PREFERENCE, OP_SINGLE_DH_USE and OP_SINGLE_ECDH_USE |
| 506 | # by default. |
Christian Heimes | 598894f | 2016-09-05 23:19:05 +0200 | [diff] [blame] | 507 | context = SSLContext(PROTOCOL_TLS) |
Donald Stufft | 6a2ba94 | 2014-03-23 19:05:28 -0400 | [diff] [blame] | 508 | |
Christian Heimes | 4c05b47 | 2013-11-23 15:58:30 +0100 | [diff] [blame] | 509 | if purpose == Purpose.SERVER_AUTH: |
Donald Stufft | 6a2ba94 | 2014-03-23 19:05:28 -0400 | [diff] [blame] | 510 | # verify certs and host name in client mode |
Christian Heimes | 4c05b47 | 2013-11-23 15:58:30 +0100 | [diff] [blame] | 511 | context.verify_mode = CERT_REQUIRED |
Christian Heimes | 1aa9a75 | 2013-12-02 02:41:19 +0100 | [diff] [blame] | 512 | context.check_hostname = True |
Donald Stufft | 6a2ba94 | 2014-03-23 19:05:28 -0400 | [diff] [blame] | 513 | elif purpose == Purpose.CLIENT_AUTH: |
Donald Stufft | 6a2ba94 | 2014-03-23 19:05:28 -0400 | [diff] [blame] | 514 | context.set_ciphers(_RESTRICTED_SERVER_CIPHERS) |
| 515 | |
Christian Heimes | 4c05b47 | 2013-11-23 15:58:30 +0100 | [diff] [blame] | 516 | if cafile or capath or cadata: |
| 517 | context.load_verify_locations(cafile, capath, cadata) |
| 518 | elif context.verify_mode != CERT_NONE: |
| 519 | # no explicit cafile, capath or cadata but the verify mode is |
| 520 | # CERT_OPTIONAL or CERT_REQUIRED. Let's try to load default system |
| 521 | # root CA certificates for the given purpose. This may fail silently. |
| 522 | context.load_default_certs(purpose) |
| 523 | return context |
| 524 | |
Christian Heimes | a170fa1 | 2017-09-15 20:27:30 +0200 | [diff] [blame] | 525 | def _create_unverified_context(protocol=PROTOCOL_TLS, *, cert_reqs=CERT_NONE, |
Christian Heimes | a02c69a | 2013-12-02 20:59:28 +0100 | [diff] [blame] | 526 | check_hostname=False, purpose=Purpose.SERVER_AUTH, |
Christian Heimes | 67986f9 | 2013-11-23 22:43:47 +0100 | [diff] [blame] | 527 | certfile=None, keyfile=None, |
| 528 | cafile=None, capath=None, cadata=None): |
| 529 | """Create a SSLContext object for Python stdlib modules |
| 530 | |
| 531 | All Python stdlib modules shall use this function to create SSLContext |
| 532 | objects in order to keep common settings in one place. The configuration |
| 533 | is less restrict than create_default_context()'s to increase backward |
| 534 | compatibility. |
| 535 | """ |
| 536 | if not isinstance(purpose, _ASN1Object): |
| 537 | raise TypeError(purpose) |
| 538 | |
Christian Heimes | 358cfd4 | 2016-09-10 22:43:48 +0200 | [diff] [blame] | 539 | # SSLContext sets OP_NO_SSLv2, OP_NO_SSLv3, OP_NO_COMPRESSION, |
| 540 | # OP_CIPHER_SERVER_PREFERENCE, OP_SINGLE_DH_USE and OP_SINGLE_ECDH_USE |
| 541 | # by default. |
Christian Heimes | 67986f9 | 2013-11-23 22:43:47 +0100 | [diff] [blame] | 542 | context = SSLContext(protocol) |
Christian Heimes | 67986f9 | 2013-11-23 22:43:47 +0100 | [diff] [blame] | 543 | |
Christian Heimes | a170fa1 | 2017-09-15 20:27:30 +0200 | [diff] [blame] | 544 | if not check_hostname: |
| 545 | context.check_hostname = False |
Christian Heimes | 67986f9 | 2013-11-23 22:43:47 +0100 | [diff] [blame] | 546 | if cert_reqs is not None: |
| 547 | context.verify_mode = cert_reqs |
Christian Heimes | a170fa1 | 2017-09-15 20:27:30 +0200 | [diff] [blame] | 548 | if check_hostname: |
| 549 | context.check_hostname = True |
Christian Heimes | 67986f9 | 2013-11-23 22:43:47 +0100 | [diff] [blame] | 550 | |
| 551 | if keyfile and not certfile: |
| 552 | raise ValueError("certfile must be specified") |
| 553 | if certfile or keyfile: |
| 554 | context.load_cert_chain(certfile, keyfile) |
| 555 | |
| 556 | # load CA root certs |
| 557 | if cafile or capath or cadata: |
| 558 | context.load_verify_locations(cafile, capath, cadata) |
| 559 | elif context.verify_mode != CERT_NONE: |
| 560 | # no explicit cafile, capath or cadata but the verify mode is |
| 561 | # CERT_OPTIONAL or CERT_REQUIRED. Let's try to load default system |
| 562 | # root CA certificates for the given purpose. This may fail silently. |
| 563 | context.load_default_certs(purpose) |
| 564 | |
| 565 | return context |
| 566 | |
Benjamin Peterson | 4ffb075 | 2014-11-03 14:29:33 -0500 | [diff] [blame] | 567 | # Used by http.client if no context is explicitly passed. |
| 568 | _create_default_https_context = create_default_context |
| 569 | |
| 570 | |
| 571 | # Backwards compatibility alias, even though it's not a public name. |
| 572 | _create_stdlib_context = _create_unverified_context |
| 573 | |
Antoine Pitrou | b1fdf47 | 2014-10-05 20:41:53 +0200 | [diff] [blame] | 574 | |
| 575 | class SSLObject: |
| 576 | """This class implements an interface on top of a low-level SSL object as |
| 577 | implemented by OpenSSL. This object captures the state of an SSL connection |
| 578 | but does not provide any network IO itself. IO needs to be performed |
| 579 | through separate "BIO" objects which are OpenSSL's IO abstraction layer. |
| 580 | |
| 581 | This class does not have a public constructor. Instances are returned by |
| 582 | ``SSLContext.wrap_bio``. This class is typically used by framework authors |
| 583 | that want to implement asynchronous IO for SSL through memory buffers. |
| 584 | |
| 585 | When compared to ``SSLSocket``, this object lacks the following features: |
| 586 | |
| 587 | * Any form of network IO incluging methods such as ``recv`` and ``send``. |
| 588 | * The ``do_handshake_on_connect`` and ``suppress_ragged_eofs`` machinery. |
| 589 | """ |
| 590 | |
Christian Heimes | 99a6570 | 2016-09-10 23:44:53 +0200 | [diff] [blame] | 591 | def __init__(self, sslobj, owner=None, session=None): |
Antoine Pitrou | b1fdf47 | 2014-10-05 20:41:53 +0200 | [diff] [blame] | 592 | self._sslobj = sslobj |
| 593 | # Note: _sslobj takes a weak reference to owner |
| 594 | self._sslobj.owner = owner or self |
Christian Heimes | 99a6570 | 2016-09-10 23:44:53 +0200 | [diff] [blame] | 595 | if session is not None: |
| 596 | self._sslobj.session = session |
Antoine Pitrou | b1fdf47 | 2014-10-05 20:41:53 +0200 | [diff] [blame] | 597 | |
| 598 | @property |
| 599 | def context(self): |
| 600 | """The SSLContext that is currently in use.""" |
| 601 | return self._sslobj.context |
| 602 | |
| 603 | @context.setter |
| 604 | def context(self, ctx): |
| 605 | self._sslobj.context = ctx |
| 606 | |
| 607 | @property |
Christian Heimes | 99a6570 | 2016-09-10 23:44:53 +0200 | [diff] [blame] | 608 | def session(self): |
| 609 | """The SSLSession for client socket.""" |
| 610 | return self._sslobj.session |
| 611 | |
| 612 | @session.setter |
| 613 | def session(self, session): |
| 614 | self._sslobj.session = session |
| 615 | |
| 616 | @property |
| 617 | def session_reused(self): |
| 618 | """Was the client session reused during handshake""" |
| 619 | return self._sslobj.session_reused |
| 620 | |
| 621 | @property |
Antoine Pitrou | b1fdf47 | 2014-10-05 20:41:53 +0200 | [diff] [blame] | 622 | def server_side(self): |
| 623 | """Whether this is a server-side socket.""" |
| 624 | return self._sslobj.server_side |
| 625 | |
| 626 | @property |
| 627 | def server_hostname(self): |
| 628 | """The currently set server hostname (for SNI), or ``None`` if no |
| 629 | server hostame is set.""" |
| 630 | return self._sslobj.server_hostname |
| 631 | |
Martin Panter | f6b1d66 | 2016-03-28 00:22:09 +0000 | [diff] [blame] | 632 | def read(self, len=1024, buffer=None): |
Antoine Pitrou | b1fdf47 | 2014-10-05 20:41:53 +0200 | [diff] [blame] | 633 | """Read up to 'len' bytes from the SSL object and return them. |
| 634 | |
| 635 | If 'buffer' is provided, read into this buffer and return the number of |
| 636 | bytes read. |
| 637 | """ |
| 638 | if buffer is not None: |
| 639 | v = self._sslobj.read(len, buffer) |
| 640 | else: |
Martin Panter | f6b1d66 | 2016-03-28 00:22:09 +0000 | [diff] [blame] | 641 | v = self._sslobj.read(len) |
Antoine Pitrou | b1fdf47 | 2014-10-05 20:41:53 +0200 | [diff] [blame] | 642 | return v |
| 643 | |
| 644 | def write(self, data): |
| 645 | """Write 'data' to the SSL object and return the number of bytes |
| 646 | written. |
| 647 | |
| 648 | The 'data' argument must support the buffer interface. |
| 649 | """ |
| 650 | return self._sslobj.write(data) |
| 651 | |
| 652 | def getpeercert(self, binary_form=False): |
| 653 | """Returns a formatted version of the data in the certificate provided |
| 654 | by the other end of the SSL channel. |
| 655 | |
| 656 | Return None if no certificate was provided, {} if a certificate was |
| 657 | provided, but not validated. |
| 658 | """ |
| 659 | return self._sslobj.peer_certificate(binary_form) |
| 660 | |
| 661 | def selected_npn_protocol(self): |
| 662 | """Return the currently selected NPN protocol as a string, or ``None`` |
| 663 | if a next protocol was not negotiated or if NPN is not supported by one |
| 664 | of the peers.""" |
| 665 | if _ssl.HAS_NPN: |
| 666 | return self._sslobj.selected_npn_protocol() |
| 667 | |
Benjamin Peterson | cca2732 | 2015-01-23 16:35:37 -0500 | [diff] [blame] | 668 | def selected_alpn_protocol(self): |
| 669 | """Return the currently selected ALPN protocol as a string, or ``None`` |
| 670 | if a next protocol was not negotiated or if ALPN is not supported by one |
| 671 | of the peers.""" |
| 672 | if _ssl.HAS_ALPN: |
| 673 | return self._sslobj.selected_alpn_protocol() |
| 674 | |
Antoine Pitrou | b1fdf47 | 2014-10-05 20:41:53 +0200 | [diff] [blame] | 675 | def cipher(self): |
| 676 | """Return the currently selected cipher as a 3-tuple ``(name, |
| 677 | ssl_version, secret_bits)``.""" |
| 678 | return self._sslobj.cipher() |
| 679 | |
Benjamin Peterson | 4cb1781 | 2015-01-07 11:14:26 -0600 | [diff] [blame] | 680 | def shared_ciphers(self): |
Benjamin Peterson | c114e7d | 2015-01-11 15:22:07 -0500 | [diff] [blame] | 681 | """Return a list of ciphers shared by the client during the handshake or |
| 682 | None if this is not a valid server connection. |
Benjamin Peterson | 5318c7a | 2015-01-07 11:26:50 -0600 | [diff] [blame] | 683 | """ |
Benjamin Peterson | 4cb1781 | 2015-01-07 11:14:26 -0600 | [diff] [blame] | 684 | return self._sslobj.shared_ciphers() |
| 685 | |
Antoine Pitrou | b1fdf47 | 2014-10-05 20:41:53 +0200 | [diff] [blame] | 686 | def compression(self): |
| 687 | """Return the current compression algorithm in use, or ``None`` if |
| 688 | compression was not negotiated or not supported by one of the peers.""" |
| 689 | return self._sslobj.compression() |
| 690 | |
| 691 | def pending(self): |
| 692 | """Return the number of bytes that can be read immediately.""" |
| 693 | return self._sslobj.pending() |
| 694 | |
Antoine Pitrou | 3cb9379 | 2014-10-06 00:21:09 +0200 | [diff] [blame] | 695 | def do_handshake(self): |
Antoine Pitrou | b1fdf47 | 2014-10-05 20:41:53 +0200 | [diff] [blame] | 696 | """Start the SSL/TLS handshake.""" |
| 697 | self._sslobj.do_handshake() |
| 698 | if self.context.check_hostname: |
| 699 | if not self.server_hostname: |
| 700 | raise ValueError("check_hostname needs server_hostname " |
| 701 | "argument") |
| 702 | match_hostname(self.getpeercert(), self.server_hostname) |
| 703 | |
| 704 | def unwrap(self): |
| 705 | """Start the SSL shutdown handshake.""" |
| 706 | return self._sslobj.shutdown() |
| 707 | |
| 708 | def get_channel_binding(self, cb_type="tls-unique"): |
| 709 | """Get channel binding data for current connection. Raise ValueError |
| 710 | if the requested `cb_type` is not supported. Return bytes of the data |
| 711 | or None if the data is not available (e.g. before the handshake).""" |
| 712 | if cb_type not in CHANNEL_BINDING_TYPES: |
| 713 | raise ValueError("Unsupported channel binding type") |
| 714 | if cb_type != "tls-unique": |
| 715 | raise NotImplementedError( |
| 716 | "{0} channel binding type not implemented" |
| 717 | .format(cb_type)) |
| 718 | return self._sslobj.tls_unique_cb() |
| 719 | |
| 720 | def version(self): |
| 721 | """Return a string identifying the protocol version used by the |
| 722 | current SSL channel. """ |
| 723 | return self._sslobj.version() |
| 724 | |
| 725 | |
Antoine Pitrou | 152efa2 | 2010-05-16 18:19:27 +0000 | [diff] [blame] | 726 | class SSLSocket(socket): |
Thomas Wouters | 47b49bf | 2007-08-30 22:15:33 +0000 | [diff] [blame] | 727 | """This class implements a subtype of socket.socket that wraps |
| 728 | the underlying OS socket in an SSL context when necessary, and |
| 729 | provides read and write methods over that channel.""" |
| 730 | |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 731 | def __init__(self, sock=None, keyfile=None, certfile=None, |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 732 | server_side=False, cert_reqs=CERT_NONE, |
Christian Heimes | 598894f | 2016-09-05 23:19:05 +0200 | [diff] [blame] | 733 | ssl_version=PROTOCOL_TLS, ca_certs=None, |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 734 | do_handshake_on_connect=True, |
| 735 | family=AF_INET, type=SOCK_STREAM, proto=0, fileno=None, |
Antoine Pitrou | d5d17eb | 2012-03-22 00:23:03 +0100 | [diff] [blame] | 736 | suppress_ragged_eofs=True, npn_protocols=None, ciphers=None, |
Antoine Pitrou | d532321 | 2010-10-22 18:19:07 +0000 | [diff] [blame] | 737 | server_hostname=None, |
Christian Heimes | 99a6570 | 2016-09-10 23:44:53 +0200 | [diff] [blame] | 738 | _context=None, _session=None): |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 739 | |
Antoine Pitrou | 152efa2 | 2010-05-16 18:19:27 +0000 | [diff] [blame] | 740 | if _context: |
Antoine Pitrou | 58ddc9d | 2013-01-05 21:20:29 +0100 | [diff] [blame] | 741 | self._context = _context |
Antoine Pitrou | 152efa2 | 2010-05-16 18:19:27 +0000 | [diff] [blame] | 742 | else: |
Giampaolo Rodolà | 745ab38 | 2010-08-29 19:25:49 +0000 | [diff] [blame] | 743 | if server_side and not certfile: |
| 744 | raise ValueError("certfile must be specified for server-side " |
| 745 | "operations") |
Giampaolo Rodolà | 8b7da62 | 2010-08-30 18:28:05 +0000 | [diff] [blame] | 746 | if keyfile and not certfile: |
| 747 | raise ValueError("certfile must be specified") |
Antoine Pitrou | 152efa2 | 2010-05-16 18:19:27 +0000 | [diff] [blame] | 748 | if certfile and not keyfile: |
| 749 | keyfile = certfile |
Antoine Pitrou | 58ddc9d | 2013-01-05 21:20:29 +0100 | [diff] [blame] | 750 | self._context = SSLContext(ssl_version) |
| 751 | self._context.verify_mode = cert_reqs |
Antoine Pitrou | 152efa2 | 2010-05-16 18:19:27 +0000 | [diff] [blame] | 752 | if ca_certs: |
Antoine Pitrou | 58ddc9d | 2013-01-05 21:20:29 +0100 | [diff] [blame] | 753 | self._context.load_verify_locations(ca_certs) |
Antoine Pitrou | 152efa2 | 2010-05-16 18:19:27 +0000 | [diff] [blame] | 754 | if certfile: |
Antoine Pitrou | 58ddc9d | 2013-01-05 21:20:29 +0100 | [diff] [blame] | 755 | self._context.load_cert_chain(certfile, keyfile) |
Antoine Pitrou | d5d17eb | 2012-03-22 00:23:03 +0100 | [diff] [blame] | 756 | if npn_protocols: |
Antoine Pitrou | 58ddc9d | 2013-01-05 21:20:29 +0100 | [diff] [blame] | 757 | self._context.set_npn_protocols(npn_protocols) |
Antoine Pitrou | 152efa2 | 2010-05-16 18:19:27 +0000 | [diff] [blame] | 758 | if ciphers: |
Antoine Pitrou | 58ddc9d | 2013-01-05 21:20:29 +0100 | [diff] [blame] | 759 | self._context.set_ciphers(ciphers) |
Antoine Pitrou | 152efa2 | 2010-05-16 18:19:27 +0000 | [diff] [blame] | 760 | self.keyfile = keyfile |
| 761 | self.certfile = certfile |
| 762 | self.cert_reqs = cert_reqs |
| 763 | self.ssl_version = ssl_version |
| 764 | self.ca_certs = ca_certs |
| 765 | self.ciphers = ciphers |
Antoine Pitrou | 3e86ba4 | 2013-12-28 17:26:33 +0100 | [diff] [blame] | 766 | # Can't use sock.type as other flags (such as SOCK_NONBLOCK) get |
| 767 | # mixed in. |
| 768 | if sock.getsockopt(SOL_SOCKET, SO_TYPE) != SOCK_STREAM: |
| 769 | raise NotImplementedError("only stream sockets are supported") |
Christian Heimes | 99a6570 | 2016-09-10 23:44:53 +0200 | [diff] [blame] | 770 | if server_side: |
| 771 | if server_hostname: |
| 772 | raise ValueError("server_hostname can only be specified " |
| 773 | "in client mode") |
| 774 | if _session is not None: |
| 775 | raise ValueError("session can only be specified in " |
| 776 | "client mode") |
Christian Heimes | 1aa9a75 | 2013-12-02 02:41:19 +0100 | [diff] [blame] | 777 | if self._context.check_hostname and not server_hostname: |
Benjamin Peterson | 7243b57 | 2014-11-23 17:04:34 -0600 | [diff] [blame] | 778 | raise ValueError("check_hostname requires server_hostname") |
Christian Heimes | 99a6570 | 2016-09-10 23:44:53 +0200 | [diff] [blame] | 779 | self._session = _session |
Giampaolo Rodolà | 745ab38 | 2010-08-29 19:25:49 +0000 | [diff] [blame] | 780 | self.server_side = server_side |
Antoine Pitrou | d532321 | 2010-10-22 18:19:07 +0000 | [diff] [blame] | 781 | self.server_hostname = server_hostname |
Antoine Pitrou | 152efa2 | 2010-05-16 18:19:27 +0000 | [diff] [blame] | 782 | self.do_handshake_on_connect = do_handshake_on_connect |
| 783 | self.suppress_ragged_eofs = suppress_ragged_eofs |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 784 | if sock is not None: |
Bill Janssen | 54cc54c | 2007-12-14 22:08:56 +0000 | [diff] [blame] | 785 | socket.__init__(self, |
| 786 | family=sock.family, |
| 787 | type=sock.type, |
| 788 | proto=sock.proto, |
Antoine Pitrou | e43f9d0 | 2010-08-08 23:24:50 +0000 | [diff] [blame] | 789 | fileno=sock.fileno()) |
Antoine Pitrou | 40f0874 | 2010-04-24 22:04:40 +0000 | [diff] [blame] | 790 | self.settimeout(sock.gettimeout()) |
Antoine Pitrou | 6e451df | 2010-08-09 20:39:54 +0000 | [diff] [blame] | 791 | sock.detach() |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 792 | elif fileno is not None: |
| 793 | socket.__init__(self, fileno=fileno) |
| 794 | else: |
| 795 | socket.__init__(self, family=family, type=type, proto=proto) |
| 796 | |
Antoine Pitrou | 242db72 | 2013-05-01 20:52:07 +0200 | [diff] [blame] | 797 | # See if we are connected |
| 798 | try: |
| 799 | self.getpeername() |
| 800 | except OSError as e: |
| 801 | if e.errno != errno.ENOTCONN: |
| 802 | raise |
| 803 | connected = False |
| 804 | else: |
| 805 | connected = True |
| 806 | |
Antoine Pitrou | fa2b938 | 2010-04-26 22:17:47 +0000 | [diff] [blame] | 807 | self._closed = False |
| 808 | self._sslobj = None |
Antoine Pitrou | e93bf7a | 2011-02-26 23:24:06 +0000 | [diff] [blame] | 809 | self._connected = connected |
Antoine Pitrou | fa2b938 | 2010-04-26 22:17:47 +0000 | [diff] [blame] | 810 | if connected: |
| 811 | # create the SSL object |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 812 | try: |
Antoine Pitrou | b1fdf47 | 2014-10-05 20:41:53 +0200 | [diff] [blame] | 813 | sslobj = self._context._wrap_socket(self, server_side, |
| 814 | server_hostname) |
Christian Heimes | 99a6570 | 2016-09-10 23:44:53 +0200 | [diff] [blame] | 815 | self._sslobj = SSLObject(sslobj, owner=self, |
| 816 | session=self._session) |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 817 | if do_handshake_on_connect: |
Bill Janssen | 48dc27c | 2007-12-05 03:38:10 +0000 | [diff] [blame] | 818 | timeout = self.gettimeout() |
| 819 | if timeout == 0.0: |
| 820 | # non-blocking |
| 821 | raise ValueError("do_handshake_on_connect should not be specified for non-blocking sockets") |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 822 | self.do_handshake() |
Bill Janssen | 48dc27c | 2007-12-05 03:38:10 +0000 | [diff] [blame] | 823 | |
Christian Heimes | 1aa9a75 | 2013-12-02 02:41:19 +0100 | [diff] [blame] | 824 | except (OSError, ValueError): |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 825 | self.close() |
Christian Heimes | 1aa9a75 | 2013-12-02 02:41:19 +0100 | [diff] [blame] | 826 | raise |
Antoine Pitrou | 242db72 | 2013-05-01 20:52:07 +0200 | [diff] [blame] | 827 | |
Antoine Pitrou | 58ddc9d | 2013-01-05 21:20:29 +0100 | [diff] [blame] | 828 | @property |
| 829 | def context(self): |
| 830 | return self._context |
| 831 | |
| 832 | @context.setter |
| 833 | def context(self, ctx): |
| 834 | self._context = ctx |
| 835 | self._sslobj.context = ctx |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 836 | |
Christian Heimes | 99a6570 | 2016-09-10 23:44:53 +0200 | [diff] [blame] | 837 | @property |
| 838 | def session(self): |
| 839 | """The SSLSession for client socket.""" |
| 840 | if self._sslobj is not None: |
| 841 | return self._sslobj.session |
| 842 | |
| 843 | @session.setter |
| 844 | def session(self, session): |
| 845 | self._session = session |
| 846 | if self._sslobj is not None: |
| 847 | self._sslobj.session = session |
| 848 | |
| 849 | @property |
| 850 | def session_reused(self): |
| 851 | """Was the client session reused during handshake""" |
| 852 | if self._sslobj is not None: |
| 853 | return self._sslobj.session_reused |
| 854 | |
Guido van Rossum | b7b030e | 2007-11-16 01:28:45 +0000 | [diff] [blame] | 855 | def dup(self): |
| 856 | raise NotImplemented("Can't dup() %s instances" % |
| 857 | self.__class__.__name__) |
| 858 | |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 859 | def _checkClosed(self, msg=None): |
| 860 | # raise an exception here if you wish to check for spurious closes |
| 861 | pass |
| 862 | |
Antoine Pitrou | 242db72 | 2013-05-01 20:52:07 +0200 | [diff] [blame] | 863 | def _check_connected(self): |
| 864 | if not self._connected: |
| 865 | # getpeername() will raise ENOTCONN if the socket is really |
| 866 | # not connected; note that we can be connected even without |
| 867 | # _connected being set, e.g. if connect() first returned |
| 868 | # EAGAIN. |
| 869 | self.getpeername() |
| 870 | |
Martin Panter | f6b1d66 | 2016-03-28 00:22:09 +0000 | [diff] [blame] | 871 | def read(self, len=1024, buffer=None): |
Thomas Wouters | 47b49bf | 2007-08-30 22:15:33 +0000 | [diff] [blame] | 872 | """Read up to LEN bytes and return them. |
| 873 | Return zero-length string on EOF.""" |
| 874 | |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 875 | self._checkClosed() |
Antoine Pitrou | 60a26e0 | 2013-07-20 19:35:16 +0200 | [diff] [blame] | 876 | if not self._sslobj: |
| 877 | raise ValueError("Read on closed or unwrapped SSL socket.") |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 878 | try: |
Antoine Pitrou | b1fdf47 | 2014-10-05 20:41:53 +0200 | [diff] [blame] | 879 | return self._sslobj.read(len, buffer) |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 880 | except SSLError as x: |
| 881 | if x.args[0] == SSL_ERROR_EOF and self.suppress_ragged_eofs: |
Antoine Pitrou | 24e561a | 2010-09-03 18:38:17 +0000 | [diff] [blame] | 882 | if buffer is not None: |
Bill Janssen | 54cc54c | 2007-12-14 22:08:56 +0000 | [diff] [blame] | 883 | return 0 |
| 884 | else: |
| 885 | return b'' |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 886 | else: |
| 887 | raise |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 888 | |
| 889 | def write(self, data): |
Thomas Wouters | 47b49bf | 2007-08-30 22:15:33 +0000 | [diff] [blame] | 890 | """Write DATA to the underlying SSL channel. Returns |
| 891 | number of bytes of DATA actually transmitted.""" |
| 892 | |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 893 | self._checkClosed() |
Antoine Pitrou | 60a26e0 | 2013-07-20 19:35:16 +0200 | [diff] [blame] | 894 | if not self._sslobj: |
| 895 | raise ValueError("Write on closed or unwrapped SSL socket.") |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 896 | return self._sslobj.write(data) |
| 897 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 898 | def getpeercert(self, binary_form=False): |
Thomas Wouters | 47b49bf | 2007-08-30 22:15:33 +0000 | [diff] [blame] | 899 | """Returns a formatted version of the data in the |
| 900 | certificate provided by the other end of the SSL channel. |
| 901 | Return None if no certificate was provided, {} if a |
| 902 | certificate was provided, but not validated.""" |
| 903 | |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 904 | self._checkClosed() |
Antoine Pitrou | 242db72 | 2013-05-01 20:52:07 +0200 | [diff] [blame] | 905 | self._check_connected() |
Antoine Pitrou | b1fdf47 | 2014-10-05 20:41:53 +0200 | [diff] [blame] | 906 | return self._sslobj.getpeercert(binary_form) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 907 | |
Antoine Pitrou | d5d17eb | 2012-03-22 00:23:03 +0100 | [diff] [blame] | 908 | def selected_npn_protocol(self): |
| 909 | self._checkClosed() |
| 910 | if not self._sslobj or not _ssl.HAS_NPN: |
| 911 | return None |
| 912 | else: |
| 913 | return self._sslobj.selected_npn_protocol() |
| 914 | |
Benjamin Peterson | cca2732 | 2015-01-23 16:35:37 -0500 | [diff] [blame] | 915 | def selected_alpn_protocol(self): |
| 916 | self._checkClosed() |
| 917 | if not self._sslobj or not _ssl.HAS_ALPN: |
| 918 | return None |
| 919 | else: |
| 920 | return self._sslobj.selected_alpn_protocol() |
| 921 | |
Guido van Rossum | 5b8b155 | 2007-11-16 00:06:11 +0000 | [diff] [blame] | 922 | def cipher(self): |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 923 | self._checkClosed() |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 924 | if not self._sslobj: |
| 925 | return None |
| 926 | else: |
| 927 | return self._sslobj.cipher() |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 928 | |
Benjamin Peterson | 4cb1781 | 2015-01-07 11:14:26 -0600 | [diff] [blame] | 929 | def shared_ciphers(self): |
| 930 | self._checkClosed() |
| 931 | if not self._sslobj: |
| 932 | return None |
| 933 | return self._sslobj.shared_ciphers() |
| 934 | |
Antoine Pitrou | 8abdb8a | 2011-12-20 10:13:40 +0100 | [diff] [blame] | 935 | def compression(self): |
| 936 | self._checkClosed() |
| 937 | if not self._sslobj: |
| 938 | return None |
| 939 | else: |
| 940 | return self._sslobj.compression() |
| 941 | |
Guido van Rossum | 5b8b155 | 2007-11-16 00:06:11 +0000 | [diff] [blame] | 942 | def send(self, data, flags=0): |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 943 | self._checkClosed() |
Thomas Wouters | 47b49bf | 2007-08-30 22:15:33 +0000 | [diff] [blame] | 944 | if self._sslobj: |
| 945 | if flags != 0: |
| 946 | raise ValueError( |
| 947 | "non-zero flags not allowed in calls to send() on %s" % |
| 948 | self.__class__) |
Antoine Pitrou | b4bebda | 2014-04-29 10:03:28 +0200 | [diff] [blame] | 949 | return self._sslobj.write(data) |
Thomas Wouters | 47b49bf | 2007-08-30 22:15:33 +0000 | [diff] [blame] | 950 | else: |
| 951 | return socket.send(self, data, flags) |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 952 | |
Antoine Pitrou | a468adc | 2010-09-14 14:43:44 +0000 | [diff] [blame] | 953 | def sendto(self, data, flags_or_addr, addr=None): |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 954 | self._checkClosed() |
Thomas Wouters | 47b49bf | 2007-08-30 22:15:33 +0000 | [diff] [blame] | 955 | if self._sslobj: |
Bill Janssen | 980f314 | 2008-06-29 00:05:51 +0000 | [diff] [blame] | 956 | raise ValueError("sendto not allowed on instances of %s" % |
Thomas Wouters | 47b49bf | 2007-08-30 22:15:33 +0000 | [diff] [blame] | 957 | self.__class__) |
Antoine Pitrou | a468adc | 2010-09-14 14:43:44 +0000 | [diff] [blame] | 958 | elif addr is None: |
| 959 | return socket.sendto(self, data, flags_or_addr) |
Thomas Wouters | 47b49bf | 2007-08-30 22:15:33 +0000 | [diff] [blame] | 960 | else: |
Antoine Pitrou | a468adc | 2010-09-14 14:43:44 +0000 | [diff] [blame] | 961 | return socket.sendto(self, data, flags_or_addr, addr) |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 962 | |
Nick Coghlan | 513886a | 2011-08-28 00:00:27 +1000 | [diff] [blame] | 963 | def sendmsg(self, *args, **kwargs): |
| 964 | # Ensure programs don't send data unencrypted if they try to |
| 965 | # use this method. |
| 966 | raise NotImplementedError("sendmsg not allowed on instances of %s" % |
| 967 | self.__class__) |
| 968 | |
Guido van Rossum | 5b8b155 | 2007-11-16 00:06:11 +0000 | [diff] [blame] | 969 | def sendall(self, data, flags=0): |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 970 | self._checkClosed() |
Thomas Wouters | 47b49bf | 2007-08-30 22:15:33 +0000 | [diff] [blame] | 971 | if self._sslobj: |
Giampaolo Rodolà | 374f835 | 2010-08-29 12:08:09 +0000 | [diff] [blame] | 972 | if flags != 0: |
| 973 | raise ValueError( |
| 974 | "non-zero flags not allowed in calls to sendall() on %s" % |
| 975 | self.__class__) |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 976 | count = 0 |
Christian Heimes | 888bbdc | 2017-09-07 14:18:21 -0700 | [diff] [blame] | 977 | with memoryview(data) as view, view.cast("B") as byte_view: |
| 978 | amount = len(byte_view) |
| 979 | while count < amount: |
| 980 | v = self.send(byte_view[count:]) |
| 981 | count += v |
Thomas Wouters | 47b49bf | 2007-08-30 22:15:33 +0000 | [diff] [blame] | 982 | else: |
| 983 | return socket.sendall(self, data, flags) |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 984 | |
Giampaolo Rodola' | 915d141 | 2014-06-11 03:54:30 +0200 | [diff] [blame] | 985 | def sendfile(self, file, offset=0, count=None): |
| 986 | """Send a file, possibly by using os.sendfile() if this is a |
| 987 | clear-text socket. Return the total number of bytes sent. |
| 988 | """ |
| 989 | if self._sslobj is None: |
| 990 | # os.sendfile() works with plain sockets only |
| 991 | return super().sendfile(file, offset, count) |
| 992 | else: |
| 993 | return self._sendfile_use_send(file, offset, count) |
| 994 | |
Guido van Rossum | 5b8b155 | 2007-11-16 00:06:11 +0000 | [diff] [blame] | 995 | def recv(self, buflen=1024, flags=0): |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 996 | self._checkClosed() |
Thomas Wouters | 47b49bf | 2007-08-30 22:15:33 +0000 | [diff] [blame] | 997 | if self._sslobj: |
| 998 | if flags != 0: |
| 999 | raise ValueError( |
Antoine Pitrou | 5733c08 | 2010-03-22 14:49:10 +0000 | [diff] [blame] | 1000 | "non-zero flags not allowed in calls to recv() on %s" % |
| 1001 | self.__class__) |
| 1002 | return self.read(buflen) |
Thomas Wouters | 47b49bf | 2007-08-30 22:15:33 +0000 | [diff] [blame] | 1003 | else: |
| 1004 | return socket.recv(self, buflen, flags) |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 1005 | |
Guido van Rossum | 5b8b155 | 2007-11-16 00:06:11 +0000 | [diff] [blame] | 1006 | def recv_into(self, buffer, nbytes=None, flags=0): |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 1007 | self._checkClosed() |
| 1008 | if buffer and (nbytes is None): |
| 1009 | nbytes = len(buffer) |
| 1010 | elif nbytes is None: |
| 1011 | nbytes = 1024 |
| 1012 | if self._sslobj: |
| 1013 | if flags != 0: |
| 1014 | raise ValueError( |
Guido van Rossum | 5b8b155 | 2007-11-16 00:06:11 +0000 | [diff] [blame] | 1015 | "non-zero flags not allowed in calls to recv_into() on %s" % |
| 1016 | self.__class__) |
Antoine Pitrou | 5733c08 | 2010-03-22 14:49:10 +0000 | [diff] [blame] | 1017 | return self.read(nbytes, buffer) |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 1018 | else: |
| 1019 | return socket.recv_into(self, buffer, nbytes, flags) |
| 1020 | |
Antoine Pitrou | a468adc | 2010-09-14 14:43:44 +0000 | [diff] [blame] | 1021 | def recvfrom(self, buflen=1024, flags=0): |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 1022 | self._checkClosed() |
Thomas Wouters | 47b49bf | 2007-08-30 22:15:33 +0000 | [diff] [blame] | 1023 | if self._sslobj: |
Bill Janssen | 980f314 | 2008-06-29 00:05:51 +0000 | [diff] [blame] | 1024 | raise ValueError("recvfrom not allowed on instances of %s" % |
Thomas Wouters | 47b49bf | 2007-08-30 22:15:33 +0000 | [diff] [blame] | 1025 | self.__class__) |
| 1026 | else: |
Antoine Pitrou | a468adc | 2010-09-14 14:43:44 +0000 | [diff] [blame] | 1027 | return socket.recvfrom(self, buflen, flags) |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 1028 | |
Bill Janssen | 58afe4c | 2008-09-08 16:45:19 +0000 | [diff] [blame] | 1029 | def recvfrom_into(self, buffer, nbytes=None, flags=0): |
| 1030 | self._checkClosed() |
| 1031 | if self._sslobj: |
| 1032 | raise ValueError("recvfrom_into not allowed on instances of %s" % |
| 1033 | self.__class__) |
| 1034 | else: |
| 1035 | return socket.recvfrom_into(self, buffer, nbytes, flags) |
| 1036 | |
Nick Coghlan | 513886a | 2011-08-28 00:00:27 +1000 | [diff] [blame] | 1037 | def recvmsg(self, *args, **kwargs): |
| 1038 | raise NotImplementedError("recvmsg not allowed on instances of %s" % |
| 1039 | self.__class__) |
| 1040 | |
| 1041 | def recvmsg_into(self, *args, **kwargs): |
| 1042 | raise NotImplementedError("recvmsg_into not allowed on instances of " |
| 1043 | "%s" % self.__class__) |
| 1044 | |
Guido van Rossum | 5b8b155 | 2007-11-16 00:06:11 +0000 | [diff] [blame] | 1045 | def pending(self): |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 1046 | self._checkClosed() |
| 1047 | if self._sslobj: |
| 1048 | return self._sslobj.pending() |
| 1049 | else: |
| 1050 | return 0 |
| 1051 | |
Guido van Rossum | 5b8b155 | 2007-11-16 00:06:11 +0000 | [diff] [blame] | 1052 | def shutdown(self, how): |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 1053 | self._checkClosed() |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1054 | self._sslobj = None |
Thomas Wouters | 47b49bf | 2007-08-30 22:15:33 +0000 | [diff] [blame] | 1055 | socket.shutdown(self, how) |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 1056 | |
Ezio Melotti | dc55e67 | 2010-01-18 09:15:14 +0000 | [diff] [blame] | 1057 | def unwrap(self): |
Bill Janssen | 40a0f66 | 2008-08-12 16:56:25 +0000 | [diff] [blame] | 1058 | if self._sslobj: |
Antoine Pitrou | b1fdf47 | 2014-10-05 20:41:53 +0200 | [diff] [blame] | 1059 | s = self._sslobj.unwrap() |
Bill Janssen | 40a0f66 | 2008-08-12 16:56:25 +0000 | [diff] [blame] | 1060 | self._sslobj = None |
| 1061 | return s |
| 1062 | else: |
| 1063 | raise ValueError("No SSL wrapper around " + str(self)) |
| 1064 | |
Guido van Rossum | 5b8b155 | 2007-11-16 00:06:11 +0000 | [diff] [blame] | 1065 | def _real_close(self): |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1066 | self._sslobj = None |
Bill Janssen | 54cc54c | 2007-12-14 22:08:56 +0000 | [diff] [blame] | 1067 | socket._real_close(self) |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 1068 | |
Bill Janssen | 48dc27c | 2007-12-05 03:38:10 +0000 | [diff] [blame] | 1069 | def do_handshake(self, block=False): |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 1070 | """Perform a TLS/SSL handshake.""" |
Antoine Pitrou | 242db72 | 2013-05-01 20:52:07 +0200 | [diff] [blame] | 1071 | self._check_connected() |
Bill Janssen | 48dc27c | 2007-12-05 03:38:10 +0000 | [diff] [blame] | 1072 | timeout = self.gettimeout() |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 1073 | try: |
Bill Janssen | 48dc27c | 2007-12-05 03:38:10 +0000 | [diff] [blame] | 1074 | if timeout == 0.0 and block: |
| 1075 | self.settimeout(None) |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 1076 | self._sslobj.do_handshake() |
Bill Janssen | 48dc27c | 2007-12-05 03:38:10 +0000 | [diff] [blame] | 1077 | finally: |
| 1078 | self.settimeout(timeout) |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 1079 | |
Antoine Pitrou | b4410db | 2011-05-18 18:51:06 +0200 | [diff] [blame] | 1080 | def _real_connect(self, addr, connect_ex): |
Giampaolo Rodolà | 745ab38 | 2010-08-29 19:25:49 +0000 | [diff] [blame] | 1081 | if self.server_side: |
| 1082 | raise ValueError("can't connect in server-side mode") |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 1083 | # Here we assume that the socket is client-side, and not |
| 1084 | # connected at the time of the call. We connect it, then wrap it. |
Antoine Pitrou | e93bf7a | 2011-02-26 23:24:06 +0000 | [diff] [blame] | 1085 | if self._connected: |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1086 | raise ValueError("attempt to connect already-connected SSLSocket!") |
Antoine Pitrou | b1fdf47 | 2014-10-05 20:41:53 +0200 | [diff] [blame] | 1087 | sslobj = self.context._wrap_socket(self, False, self.server_hostname) |
Christian Heimes | 99a6570 | 2016-09-10 23:44:53 +0200 | [diff] [blame] | 1088 | self._sslobj = SSLObject(sslobj, owner=self, |
| 1089 | session=self._session) |
Bill Janssen | 54cc54c | 2007-12-14 22:08:56 +0000 | [diff] [blame] | 1090 | try: |
Antoine Pitrou | b4410db | 2011-05-18 18:51:06 +0200 | [diff] [blame] | 1091 | if connect_ex: |
| 1092 | rc = socket.connect_ex(self, addr) |
Antoine Pitrou | e93bf7a | 2011-02-26 23:24:06 +0000 | [diff] [blame] | 1093 | else: |
Antoine Pitrou | b4410db | 2011-05-18 18:51:06 +0200 | [diff] [blame] | 1094 | rc = None |
| 1095 | socket.connect(self, addr) |
| 1096 | if not rc: |
Antoine Pitrou | 242db72 | 2013-05-01 20:52:07 +0200 | [diff] [blame] | 1097 | self._connected = True |
Antoine Pitrou | b4410db | 2011-05-18 18:51:06 +0200 | [diff] [blame] | 1098 | if self.do_handshake_on_connect: |
| 1099 | self.do_handshake() |
Antoine Pitrou | b4410db | 2011-05-18 18:51:06 +0200 | [diff] [blame] | 1100 | return rc |
Christian Heimes | 1aa9a75 | 2013-12-02 02:41:19 +0100 | [diff] [blame] | 1101 | except (OSError, ValueError): |
Antoine Pitrou | b4410db | 2011-05-18 18:51:06 +0200 | [diff] [blame] | 1102 | self._sslobj = None |
| 1103 | raise |
Antoine Pitrou | e93bf7a | 2011-02-26 23:24:06 +0000 | [diff] [blame] | 1104 | |
| 1105 | def connect(self, addr): |
| 1106 | """Connects to remote ADDR, and then wraps the connection in |
| 1107 | an SSL channel.""" |
| 1108 | self._real_connect(addr, False) |
| 1109 | |
| 1110 | def connect_ex(self, addr): |
| 1111 | """Connects to remote ADDR, and then wraps the connection in |
| 1112 | an SSL channel.""" |
| 1113 | return self._real_connect(addr, True) |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 1114 | |
| 1115 | def accept(self): |
Thomas Wouters | 47b49bf | 2007-08-30 22:15:33 +0000 | [diff] [blame] | 1116 | """Accepts a new connection from a remote client, and returns |
| 1117 | a tuple containing that new connection wrapped with a server-side |
| 1118 | SSL channel, and the address of the remote client.""" |
| 1119 | |
| 1120 | newsock, addr = socket.accept(self) |
Antoine Pitrou | 5c89b4e | 2012-11-11 01:25:36 +0100 | [diff] [blame] | 1121 | newsock = self.context.wrap_socket(newsock, |
| 1122 | do_handshake_on_connect=self.do_handshake_on_connect, |
| 1123 | suppress_ragged_eofs=self.suppress_ragged_eofs, |
| 1124 | server_side=True) |
| 1125 | return newsock, addr |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1126 | |
Antoine Pitrou | d649480 | 2011-07-21 01:11:30 +0200 | [diff] [blame] | 1127 | def get_channel_binding(self, cb_type="tls-unique"): |
| 1128 | """Get channel binding data for current connection. Raise ValueError |
| 1129 | if the requested `cb_type` is not supported. Return bytes of the data |
| 1130 | or None if the data is not available (e.g. before the handshake). |
| 1131 | """ |
Antoine Pitrou | d649480 | 2011-07-21 01:11:30 +0200 | [diff] [blame] | 1132 | if self._sslobj is None: |
| 1133 | return None |
Antoine Pitrou | b1fdf47 | 2014-10-05 20:41:53 +0200 | [diff] [blame] | 1134 | return self._sslobj.get_channel_binding(cb_type) |
Antoine Pitrou | d649480 | 2011-07-21 01:11:30 +0200 | [diff] [blame] | 1135 | |
Antoine Pitrou | 47e4042 | 2014-09-04 21:00:10 +0200 | [diff] [blame] | 1136 | def version(self): |
| 1137 | """ |
| 1138 | Return a string identifying the protocol version used by the |
| 1139 | current SSL channel, or None if there is no established channel. |
| 1140 | """ |
| 1141 | if self._sslobj is None: |
| 1142 | return None |
| 1143 | return self._sslobj.version() |
| 1144 | |
Bill Janssen | 54cc54c | 2007-12-14 22:08:56 +0000 | [diff] [blame] | 1145 | |
Christian Heimes | 4df60f1 | 2017-09-15 20:26:05 +0200 | [diff] [blame] | 1146 | # Python does not support forward declaration of types. |
| 1147 | SSLContext.sslsocket_class = SSLSocket |
| 1148 | SSLContext.sslobject_class = SSLObject |
| 1149 | |
| 1150 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1151 | def wrap_socket(sock, keyfile=None, certfile=None, |
| 1152 | server_side=False, cert_reqs=CERT_NONE, |
Christian Heimes | 598894f | 2016-09-05 23:19:05 +0200 | [diff] [blame] | 1153 | ssl_version=PROTOCOL_TLS, ca_certs=None, |
Bill Janssen | 48dc27c | 2007-12-05 03:38:10 +0000 | [diff] [blame] | 1154 | do_handshake_on_connect=True, |
Antoine Pitrou | d5d17eb | 2012-03-22 00:23:03 +0100 | [diff] [blame] | 1155 | suppress_ragged_eofs=True, |
| 1156 | ciphers=None): |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 1157 | return SSLSocket(sock=sock, keyfile=keyfile, certfile=certfile, |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1158 | server_side=server_side, cert_reqs=cert_reqs, |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 1159 | ssl_version=ssl_version, ca_certs=ca_certs, |
Bill Janssen | 48dc27c | 2007-12-05 03:38:10 +0000 | [diff] [blame] | 1160 | do_handshake_on_connect=do_handshake_on_connect, |
Antoine Pitrou | 2d9cb9c | 2010-04-17 17:40:45 +0000 | [diff] [blame] | 1161 | suppress_ragged_eofs=suppress_ragged_eofs, |
| 1162 | ciphers=ciphers) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1163 | |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 1164 | # some utility functions |
| 1165 | |
| 1166 | def cert_time_to_seconds(cert_time): |
Antoine Pitrou | c695c95 | 2014-04-28 20:57:36 +0200 | [diff] [blame] | 1167 | """Return the time in seconds since the Epoch, given the timestring |
| 1168 | representing the "notBefore" or "notAfter" date from a certificate |
| 1169 | in ``"%b %d %H:%M:%S %Y %Z"`` strptime format (C locale). |
Thomas Wouters | 47b49bf | 2007-08-30 22:15:33 +0000 | [diff] [blame] | 1170 | |
Antoine Pitrou | c695c95 | 2014-04-28 20:57:36 +0200 | [diff] [blame] | 1171 | "notBefore" or "notAfter" dates must use UTC (RFC 5280). |
| 1172 | |
| 1173 | Month is one of: Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec |
| 1174 | UTC should be specified as GMT (see ASN1_TIME_print()) |
| 1175 | """ |
| 1176 | from time import strptime |
| 1177 | from calendar import timegm |
| 1178 | |
| 1179 | months = ( |
| 1180 | "Jan","Feb","Mar","Apr","May","Jun", |
| 1181 | "Jul","Aug","Sep","Oct","Nov","Dec" |
| 1182 | ) |
| 1183 | time_format = ' %d %H:%M:%S %Y GMT' # NOTE: no month, fixed GMT |
| 1184 | try: |
| 1185 | month_number = months.index(cert_time[:3].title()) + 1 |
| 1186 | except ValueError: |
| 1187 | raise ValueError('time data %r does not match ' |
| 1188 | 'format "%%b%s"' % (cert_time, time_format)) |
| 1189 | else: |
| 1190 | # found valid month |
| 1191 | tt = strptime(cert_time[3:], time_format) |
| 1192 | # return an integer, the previous mktime()-based implementation |
| 1193 | # returned a float (fractional seconds are always zero here). |
| 1194 | return timegm((tt[0], month_number) + tt[2:6]) |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 1195 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1196 | PEM_HEADER = "-----BEGIN CERTIFICATE-----" |
| 1197 | PEM_FOOTER = "-----END CERTIFICATE-----" |
| 1198 | |
| 1199 | def DER_cert_to_PEM_cert(der_cert_bytes): |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1200 | """Takes a certificate in binary DER format and returns the |
| 1201 | PEM version of it as a string.""" |
| 1202 | |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 1203 | f = str(base64.standard_b64encode(der_cert_bytes), 'ASCII', 'strict') |
| 1204 | return (PEM_HEADER + '\n' + |
| 1205 | textwrap.fill(f, 64) + '\n' + |
| 1206 | PEM_FOOTER + '\n') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1207 | |
| 1208 | def PEM_cert_to_DER_cert(pem_cert_string): |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1209 | """Takes a certificate in ASCII PEM format and returns the |
| 1210 | DER-encoded version of it as a byte sequence""" |
| 1211 | |
| 1212 | if not pem_cert_string.startswith(PEM_HEADER): |
| 1213 | raise ValueError("Invalid PEM encoding; must start with %s" |
| 1214 | % PEM_HEADER) |
| 1215 | if not pem_cert_string.strip().endswith(PEM_FOOTER): |
| 1216 | raise ValueError("Invalid PEM encoding; must end with %s" |
| 1217 | % PEM_FOOTER) |
| 1218 | d = pem_cert_string.strip()[len(PEM_HEADER):-len(PEM_FOOTER)] |
Georg Brandl | 706824f | 2009-06-04 09:42:55 +0000 | [diff] [blame] | 1219 | return base64.decodebytes(d.encode('ASCII', 'strict')) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1220 | |
Christian Heimes | 598894f | 2016-09-05 23:19:05 +0200 | [diff] [blame] | 1221 | def get_server_certificate(addr, ssl_version=PROTOCOL_TLS, ca_certs=None): |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1222 | """Retrieve the certificate from the server at the specified address, |
| 1223 | and return it as a PEM-encoded string. |
| 1224 | If 'ca_certs' is specified, validate the server cert against it. |
| 1225 | If 'ssl_version' is specified, use it in the connection attempt.""" |
| 1226 | |
| 1227 | host, port = addr |
Christian Heimes | 67986f9 | 2013-11-23 22:43:47 +0100 | [diff] [blame] | 1228 | if ca_certs is not None: |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1229 | cert_reqs = CERT_REQUIRED |
| 1230 | else: |
| 1231 | cert_reqs = CERT_NONE |
Christian Heimes | 67986f9 | 2013-11-23 22:43:47 +0100 | [diff] [blame] | 1232 | context = _create_stdlib_context(ssl_version, |
| 1233 | cert_reqs=cert_reqs, |
| 1234 | cafile=ca_certs) |
| 1235 | with create_connection(addr) as sock: |
| 1236 | with context.wrap_socket(sock) as sslsock: |
| 1237 | dercert = sslsock.getpeercert(True) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1238 | return DER_cert_to_PEM_cert(dercert) |
| 1239 | |
Guido van Rossum | 5b8b155 | 2007-11-16 00:06:11 +0000 | [diff] [blame] | 1240 | def get_protocol_name(protocol_code): |
Victor Stinner | 3de4919 | 2011-05-09 00:42:58 +0200 | [diff] [blame] | 1241 | return _PROTOCOL_NAMES.get(protocol_code, '<unknown>') |