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