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 |
| 54 | PROTOCOL_TLSv1 |
Antoine Pitrou | 2463e5f | 2013-03-28 22:24:43 +0100 | [diff] [blame] | 55 | PROTOCOL_TLSv1_1 |
| 56 | PROTOCOL_TLSv1_2 |
Antoine Pitrou | 58ddc9d | 2013-01-05 21:20:29 +0100 | [diff] [blame] | 57 | |
| 58 | The following constants identify various SSL alert message descriptions as per |
| 59 | http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-6 |
| 60 | |
| 61 | ALERT_DESCRIPTION_CLOSE_NOTIFY |
| 62 | ALERT_DESCRIPTION_UNEXPECTED_MESSAGE |
| 63 | ALERT_DESCRIPTION_BAD_RECORD_MAC |
| 64 | ALERT_DESCRIPTION_RECORD_OVERFLOW |
| 65 | ALERT_DESCRIPTION_DECOMPRESSION_FAILURE |
| 66 | ALERT_DESCRIPTION_HANDSHAKE_FAILURE |
| 67 | ALERT_DESCRIPTION_BAD_CERTIFICATE |
| 68 | ALERT_DESCRIPTION_UNSUPPORTED_CERTIFICATE |
| 69 | ALERT_DESCRIPTION_CERTIFICATE_REVOKED |
| 70 | ALERT_DESCRIPTION_CERTIFICATE_EXPIRED |
| 71 | ALERT_DESCRIPTION_CERTIFICATE_UNKNOWN |
| 72 | ALERT_DESCRIPTION_ILLEGAL_PARAMETER |
| 73 | ALERT_DESCRIPTION_UNKNOWN_CA |
| 74 | ALERT_DESCRIPTION_ACCESS_DENIED |
| 75 | ALERT_DESCRIPTION_DECODE_ERROR |
| 76 | ALERT_DESCRIPTION_DECRYPT_ERROR |
| 77 | ALERT_DESCRIPTION_PROTOCOL_VERSION |
| 78 | ALERT_DESCRIPTION_INSUFFICIENT_SECURITY |
| 79 | ALERT_DESCRIPTION_INTERNAL_ERROR |
| 80 | ALERT_DESCRIPTION_USER_CANCELLED |
| 81 | ALERT_DESCRIPTION_NO_RENEGOTIATION |
| 82 | ALERT_DESCRIPTION_UNSUPPORTED_EXTENSION |
| 83 | ALERT_DESCRIPTION_CERTIFICATE_UNOBTAINABLE |
| 84 | ALERT_DESCRIPTION_UNRECOGNIZED_NAME |
| 85 | ALERT_DESCRIPTION_BAD_CERTIFICATE_STATUS_RESPONSE |
| 86 | ALERT_DESCRIPTION_BAD_CERTIFICATE_HASH_VALUE |
| 87 | ALERT_DESCRIPTION_UNKNOWN_PSK_IDENTITY |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 88 | """ |
| 89 | |
Christian Heimes | 05e8be1 | 2008-02-23 18:30:17 +0000 | [diff] [blame] | 90 | import textwrap |
Antoine Pitrou | 59fdd67 | 2010-10-08 10:37:08 +0000 | [diff] [blame] | 91 | import re |
Christian Heimes | 46bebee | 2013-06-09 19:03:31 +0200 | [diff] [blame] | 92 | import sys |
Christian Heimes | 6d7ad13 | 2013-06-09 18:02:55 +0200 | [diff] [blame] | 93 | import os |
Christian Heimes | a6bc95a | 2013-11-17 19:59:14 +0100 | [diff] [blame] | 94 | from collections import namedtuple |
Christian Heimes | 72d2850 | 2013-11-23 13:56:58 +0100 | [diff] [blame] | 95 | from enum import Enum as _Enum |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 96 | |
| 97 | import _ssl # if we can't import it, let the error propagate |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 98 | |
Antoine Pitrou | 04f6a32 | 2010-04-05 21:40:07 +0000 | [diff] [blame] | 99 | from _ssl import OPENSSL_VERSION_NUMBER, OPENSSL_VERSION_INFO, OPENSSL_VERSION |
Antoine Pitrou | 41032a6 | 2011-10-27 23:56:55 +0200 | [diff] [blame] | 100 | from _ssl import _SSLContext |
| 101 | from _ssl import ( |
| 102 | SSLError, SSLZeroReturnError, SSLWantReadError, SSLWantWriteError, |
| 103 | SSLSyscallError, SSLEOFError, |
| 104 | ) |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 105 | from _ssl import CERT_NONE, CERT_OPTIONAL, CERT_REQUIRED |
Christian Heimes | 2258779 | 2013-11-21 23:56:13 +0100 | [diff] [blame] | 106 | from _ssl import (VERIFY_DEFAULT, VERIFY_CRL_CHECK_LEAF, VERIFY_CRL_CHECK_CHAIN, |
| 107 | VERIFY_X509_STRICT) |
Christian Heimes | a6bc95a | 2013-11-17 19:59:14 +0100 | [diff] [blame] | 108 | from _ssl import txt2obj as _txt2obj, nid2obj as _nid2obj |
Victor Stinner | 99c8b16 | 2011-05-24 12:05:19 +0200 | [diff] [blame] | 109 | from _ssl import RAND_status, RAND_egd, RAND_add, RAND_bytes, RAND_pseudo_bytes |
Antoine Pitrou | 58ddc9d | 2013-01-05 21:20:29 +0100 | [diff] [blame] | 110 | |
| 111 | def _import_symbols(prefix): |
| 112 | for n in dir(_ssl): |
| 113 | if n.startswith(prefix): |
| 114 | globals()[n] = getattr(_ssl, n) |
| 115 | |
| 116 | _import_symbols('OP_') |
| 117 | _import_symbols('ALERT_DESCRIPTION_') |
| 118 | _import_symbols('SSL_ERROR_') |
| 119 | |
Antoine Pitrou | d5d17eb | 2012-03-22 00:23:03 +0100 | [diff] [blame] | 120 | from _ssl import HAS_SNI, HAS_ECDH, HAS_NPN |
Antoine Pitrou | 58ddc9d | 2013-01-05 21:20:29 +0100 | [diff] [blame] | 121 | |
Antoine Pitrou | 2463e5f | 2013-03-28 22:24:43 +0100 | [diff] [blame] | 122 | from _ssl import PROTOCOL_SSLv3, PROTOCOL_SSLv23, PROTOCOL_TLSv1 |
Antoine Pitrou | b9ac25d | 2011-07-08 18:47:06 +0200 | [diff] [blame] | 123 | from _ssl import _OPENSSL_API_VERSION |
| 124 | |
Antoine Pitrou | 58ddc9d | 2013-01-05 21:20:29 +0100 | [diff] [blame] | 125 | |
Victor Stinner | 3de4919 | 2011-05-09 00:42:58 +0200 | [diff] [blame] | 126 | _PROTOCOL_NAMES = { |
| 127 | PROTOCOL_TLSv1: "TLSv1", |
| 128 | PROTOCOL_SSLv23: "SSLv23", |
| 129 | PROTOCOL_SSLv3: "SSLv3", |
| 130 | } |
| 131 | try: |
| 132 | from _ssl import PROTOCOL_SSLv2 |
Antoine Pitrou | 8f85f90 | 2012-01-03 22:46:48 +0100 | [diff] [blame] | 133 | _SSLv2_IF_EXISTS = PROTOCOL_SSLv2 |
Brett Cannon | cd171c8 | 2013-07-04 17:43:24 -0400 | [diff] [blame] | 134 | except ImportError: |
Antoine Pitrou | 8f85f90 | 2012-01-03 22:46:48 +0100 | [diff] [blame] | 135 | _SSLv2_IF_EXISTS = None |
Victor Stinner | 3de4919 | 2011-05-09 00:42:58 +0200 | [diff] [blame] | 136 | else: |
| 137 | _PROTOCOL_NAMES[PROTOCOL_SSLv2] = "SSLv2" |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 138 | |
Antoine Pitrou | 2463e5f | 2013-03-28 22:24:43 +0100 | [diff] [blame] | 139 | try: |
| 140 | from _ssl import PROTOCOL_TLSv1_1, PROTOCOL_TLSv1_2 |
Brett Cannon | cd171c8 | 2013-07-04 17:43:24 -0400 | [diff] [blame] | 141 | except ImportError: |
Antoine Pitrou | 2463e5f | 2013-03-28 22:24:43 +0100 | [diff] [blame] | 142 | pass |
| 143 | else: |
| 144 | _PROTOCOL_NAMES[PROTOCOL_TLSv1_1] = "TLSv1.1" |
| 145 | _PROTOCOL_NAMES[PROTOCOL_TLSv1_2] = "TLSv1.2" |
| 146 | |
Christian Heimes | 46bebee | 2013-06-09 19:03:31 +0200 | [diff] [blame] | 147 | if sys.platform == "win32": |
Christian Heimes | 44109d7 | 2013-11-22 01:51:30 +0100 | [diff] [blame] | 148 | from _ssl import enum_certificates, enum_crls |
Christian Heimes | 46bebee | 2013-06-09 19:03:31 +0200 | [diff] [blame] | 149 | |
Antoine Pitrou | 15399c3 | 2011-04-28 19:23:55 +0200 | [diff] [blame] | 150 | from socket import socket, AF_INET, SOCK_STREAM, create_connection |
Antoine Pitrou | 3e86ba4 | 2013-12-28 17:26:33 +0100 | [diff] [blame] | 151 | from socket import SOL_SOCKET, SO_TYPE |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 152 | import base64 # for DER-to-PEM translation |
Antoine Pitrou | de8cf32 | 2010-04-26 17:29:05 +0000 | [diff] [blame] | 153 | import errno |
Thomas Wouters | 47b49bf | 2007-08-30 22:15:33 +0000 | [diff] [blame] | 154 | |
Andrew Svetlov | 0832af6 | 2012-12-18 23:10:48 +0200 | [diff] [blame] | 155 | |
| 156 | socket_error = OSError # keep that public name in module namespace |
| 157 | |
Antoine Pitrou | d649480 | 2011-07-21 01:11:30 +0200 | [diff] [blame] | 158 | if _ssl.HAS_TLS_UNIQUE: |
| 159 | CHANNEL_BINDING_TYPES = ['tls-unique'] |
| 160 | else: |
| 161 | CHANNEL_BINDING_TYPES = [] |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 162 | |
Antoine Pitrou | 8f85f90 | 2012-01-03 22:46:48 +0100 | [diff] [blame] | 163 | # Disable weak or insecure ciphers by default |
| 164 | # (OpenSSL's default setting is 'DEFAULT:!aNULL:!eNULL') |
Donald Stufft | 79ccaa2 | 2014-03-21 21:33:34 -0400 | [diff] [blame] | 165 | # Enable a better set of ciphers by default |
| 166 | # This list has been explicitly chosen to: |
| 167 | # * Prefer cipher suites that offer perfect forward secrecy (DHE/ECDHE) |
| 168 | # * Prefer ECDHE over DHE for better performance |
| 169 | # * Prefer any AES-GCM over any AES-CBC for better performance and security |
| 170 | # * Then Use HIGH cipher suites as a fallback |
| 171 | # * Then Use 3DES as fallback which is secure but slow |
| 172 | # * Finally use RC4 as a fallback which is problematic but needed for |
| 173 | # compatibility some times. |
| 174 | # * Disable NULL authentication, NULL encryption, and MD5 MACs for security |
| 175 | # reasons |
| 176 | _DEFAULT_CIPHERS = ( |
| 177 | 'ECDH+AESGCM:DH+AESGCM:ECDH+AES256:DH+AES256:ECDH+AES128:DH+AES:ECDH+HIGH:' |
| 178 | 'DH+HIGH:ECDH+3DES:DH+3DES:RSA+AESGCM:RSA+AES:RSA+HIGH:RSA+3DES:ECDH+RC4:' |
| 179 | 'DH+RC4:RSA+RC4:!aNULL:!eNULL:!MD5' |
| 180 | ) |
Antoine Pitrou | 8f85f90 | 2012-01-03 22:46:48 +0100 | [diff] [blame] | 181 | |
Donald Stufft | 6a2ba94 | 2014-03-23 19:05:28 -0400 | [diff] [blame] | 182 | # Restricted and more secure ciphers for the server side |
Donald Stufft | 79ccaa2 | 2014-03-21 21:33:34 -0400 | [diff] [blame] | 183 | # This list has been explicitly chosen to: |
| 184 | # * Prefer cipher suites that offer perfect forward secrecy (DHE/ECDHE) |
| 185 | # * Prefer ECDHE over DHE for better performance |
| 186 | # * Prefer any AES-GCM over any AES-CBC for better performance and security |
| 187 | # * Then Use HIGH cipher suites as a fallback |
| 188 | # * Then Use 3DES as fallback which is secure but slow |
| 189 | # * Disable NULL authentication, NULL encryption, MD5 MACs, DSS, and RC4 for |
| 190 | # security reasons |
Donald Stufft | 6a2ba94 | 2014-03-23 19:05:28 -0400 | [diff] [blame] | 191 | _RESTRICTED_SERVER_CIPHERS = ( |
Donald Stufft | 79ccaa2 | 2014-03-21 21:33:34 -0400 | [diff] [blame] | 192 | 'ECDH+AESGCM:DH+AESGCM:ECDH+AES256:DH+AES256:ECDH+AES128:DH+AES:ECDH+HIGH:' |
| 193 | 'DH+HIGH:ECDH+3DES:DH+3DES:RSA+AESGCM:RSA+AES:RSA+HIGH:RSA+3DES:!aNULL:' |
| 194 | '!eNULL:!MD5:!DSS:!RC4' |
| 195 | ) |
Christian Heimes | 4c05b47 | 2013-11-23 15:58:30 +0100 | [diff] [blame] | 196 | |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 197 | |
Antoine Pitrou | 59fdd67 | 2010-10-08 10:37:08 +0000 | [diff] [blame] | 198 | class CertificateError(ValueError): |
| 199 | pass |
| 200 | |
| 201 | |
Georg Brandl | 72c98d3 | 2013-10-27 07:16:53 +0100 | [diff] [blame] | 202 | def _dnsname_match(dn, hostname, max_wildcards=1): |
| 203 | """Matching according to RFC 6125, section 6.4.3 |
| 204 | |
| 205 | http://tools.ietf.org/html/rfc6125#section-6.4.3 |
| 206 | """ |
Antoine Pitrou | 59fdd67 | 2010-10-08 10:37:08 +0000 | [diff] [blame] | 207 | pats = [] |
Georg Brandl | 72c98d3 | 2013-10-27 07:16:53 +0100 | [diff] [blame] | 208 | if not dn: |
| 209 | return False |
| 210 | |
| 211 | leftmost, *remainder = dn.split(r'.') |
| 212 | |
| 213 | wildcards = leftmost.count('*') |
| 214 | if wildcards > max_wildcards: |
| 215 | # Issue #17980: avoid denials of service by refusing more |
| 216 | # than one wildcard per fragment. A survery of established |
| 217 | # policy among SSL implementations showed it to be a |
| 218 | # reasonable choice. |
| 219 | raise CertificateError( |
| 220 | "too many wildcards in certificate DNS name: " + repr(dn)) |
| 221 | |
| 222 | # speed up common case w/o wildcards |
| 223 | if not wildcards: |
| 224 | return dn.lower() == hostname.lower() |
| 225 | |
| 226 | # RFC 6125, section 6.4.3, subitem 1. |
| 227 | # The client SHOULD NOT attempt to match a presented identifier in which |
| 228 | # the wildcard character comprises a label other than the left-most label. |
| 229 | if leftmost == '*': |
| 230 | # When '*' is a fragment by itself, it matches a non-empty dotless |
| 231 | # fragment. |
| 232 | pats.append('[^.]+') |
| 233 | elif leftmost.startswith('xn--') or hostname.startswith('xn--'): |
| 234 | # RFC 6125, section 6.4.3, subitem 3. |
| 235 | # The client SHOULD NOT attempt to match a presented identifier |
| 236 | # where the wildcard character is embedded within an A-label or |
| 237 | # U-label of an internationalized domain name. |
| 238 | pats.append(re.escape(leftmost)) |
| 239 | else: |
| 240 | # Otherwise, '*' matches any dotless string, e.g. www* |
| 241 | pats.append(re.escape(leftmost).replace(r'\*', '[^.]*')) |
| 242 | |
| 243 | # add the remaining fragments, ignore any wildcards |
| 244 | for frag in remainder: |
| 245 | pats.append(re.escape(frag)) |
| 246 | |
| 247 | pat = re.compile(r'\A' + r'\.'.join(pats) + r'\Z', re.IGNORECASE) |
| 248 | return pat.match(hostname) |
Antoine Pitrou | 59fdd67 | 2010-10-08 10:37:08 +0000 | [diff] [blame] | 249 | |
| 250 | |
| 251 | def match_hostname(cert, hostname): |
| 252 | """Verify that *cert* (in decoded format as returned by |
Georg Brandl | 72c98d3 | 2013-10-27 07:16:53 +0100 | [diff] [blame] | 253 | SSLSocket.getpeercert()) matches the *hostname*. RFC 2818 and RFC 6125 |
| 254 | rules are followed, but IP addresses are not accepted for *hostname*. |
Antoine Pitrou | 59fdd67 | 2010-10-08 10:37:08 +0000 | [diff] [blame] | 255 | |
| 256 | CertificateError is raised on failure. On success, the function |
| 257 | returns nothing. |
| 258 | """ |
| 259 | if not cert: |
Christian Heimes | 1aa9a75 | 2013-12-02 02:41:19 +0100 | [diff] [blame] | 260 | raise ValueError("empty or no certificate, match_hostname needs a " |
| 261 | "SSL socket or SSL context with either " |
| 262 | "CERT_OPTIONAL or CERT_REQUIRED") |
Antoine Pitrou | 59fdd67 | 2010-10-08 10:37:08 +0000 | [diff] [blame] | 263 | dnsnames = [] |
| 264 | san = cert.get('subjectAltName', ()) |
| 265 | for key, value in san: |
| 266 | if key == 'DNS': |
Georg Brandl | 72c98d3 | 2013-10-27 07:16:53 +0100 | [diff] [blame] | 267 | if _dnsname_match(value, hostname): |
Antoine Pitrou | 59fdd67 | 2010-10-08 10:37:08 +0000 | [diff] [blame] | 268 | return |
| 269 | dnsnames.append(value) |
Antoine Pitrou | 1c86b44 | 2011-05-06 15:19:49 +0200 | [diff] [blame] | 270 | if not dnsnames: |
| 271 | # The subject is only checked when there is no dNSName entry |
| 272 | # in subjectAltName |
Antoine Pitrou | 59fdd67 | 2010-10-08 10:37:08 +0000 | [diff] [blame] | 273 | for sub in cert.get('subject', ()): |
| 274 | for key, value in sub: |
| 275 | # XXX according to RFC 2818, the most specific Common Name |
| 276 | # must be used. |
| 277 | if key == 'commonName': |
Georg Brandl | 72c98d3 | 2013-10-27 07:16:53 +0100 | [diff] [blame] | 278 | if _dnsname_match(value, hostname): |
Antoine Pitrou | 59fdd67 | 2010-10-08 10:37:08 +0000 | [diff] [blame] | 279 | return |
| 280 | dnsnames.append(value) |
| 281 | if len(dnsnames) > 1: |
| 282 | raise CertificateError("hostname %r " |
| 283 | "doesn't match either of %s" |
| 284 | % (hostname, ', '.join(map(repr, dnsnames)))) |
| 285 | elif len(dnsnames) == 1: |
| 286 | raise CertificateError("hostname %r " |
| 287 | "doesn't match %r" |
| 288 | % (hostname, dnsnames[0])) |
| 289 | else: |
| 290 | raise CertificateError("no appropriate commonName or " |
| 291 | "subjectAltName fields were found") |
| 292 | |
| 293 | |
Christian Heimes | a6bc95a | 2013-11-17 19:59:14 +0100 | [diff] [blame] | 294 | DefaultVerifyPaths = namedtuple("DefaultVerifyPaths", |
Christian Heimes | 6d7ad13 | 2013-06-09 18:02:55 +0200 | [diff] [blame] | 295 | "cafile capath openssl_cafile_env openssl_cafile openssl_capath_env " |
| 296 | "openssl_capath") |
| 297 | |
| 298 | def get_default_verify_paths(): |
| 299 | """Return paths to default cafile and capath. |
| 300 | """ |
| 301 | parts = _ssl.get_default_verify_paths() |
| 302 | |
| 303 | # environment vars shadow paths |
| 304 | cafile = os.environ.get(parts[0], parts[1]) |
| 305 | capath = os.environ.get(parts[2], parts[3]) |
| 306 | |
| 307 | return DefaultVerifyPaths(cafile if os.path.isfile(cafile) else None, |
| 308 | capath if os.path.isdir(capath) else None, |
| 309 | *parts) |
| 310 | |
| 311 | |
Christian Heimes | a6bc95a | 2013-11-17 19:59:14 +0100 | [diff] [blame] | 312 | class _ASN1Object(namedtuple("_ASN1Object", "nid shortname longname oid")): |
| 313 | """ASN.1 object identifier lookup |
| 314 | """ |
| 315 | __slots__ = () |
| 316 | |
| 317 | def __new__(cls, oid): |
| 318 | return super().__new__(cls, *_txt2obj(oid, name=False)) |
| 319 | |
| 320 | @classmethod |
| 321 | def fromnid(cls, nid): |
| 322 | """Create _ASN1Object from OpenSSL numeric ID |
| 323 | """ |
| 324 | return super().__new__(cls, *_nid2obj(nid)) |
| 325 | |
| 326 | @classmethod |
| 327 | def fromname(cls, name): |
| 328 | """Create _ASN1Object from short name, long name or OID |
| 329 | """ |
| 330 | return super().__new__(cls, *_txt2obj(name, name=True)) |
| 331 | |
| 332 | |
Christian Heimes | 72d2850 | 2013-11-23 13:56:58 +0100 | [diff] [blame] | 333 | class Purpose(_ASN1Object, _Enum): |
| 334 | """SSLContext purpose flags with X509v3 Extended Key Usage objects |
| 335 | """ |
| 336 | SERVER_AUTH = '1.3.6.1.5.5.7.3.1' |
| 337 | CLIENT_AUTH = '1.3.6.1.5.5.7.3.2' |
| 338 | |
| 339 | |
Antoine Pitrou | 152efa2 | 2010-05-16 18:19:27 +0000 | [diff] [blame] | 340 | class SSLContext(_SSLContext): |
| 341 | """An SSLContext holds various SSL-related configuration options and |
| 342 | data, such as certificates and possibly a private key.""" |
| 343 | |
Antoine Pitrou | 58ddc9d | 2013-01-05 21:20:29 +0100 | [diff] [blame] | 344 | __slots__ = ('protocol', '__weakref__') |
Christian Heimes | 72d2850 | 2013-11-23 13:56:58 +0100 | [diff] [blame] | 345 | _windows_cert_stores = ("CA", "ROOT") |
Antoine Pitrou | 152efa2 | 2010-05-16 18:19:27 +0000 | [diff] [blame] | 346 | |
| 347 | def __new__(cls, protocol, *args, **kwargs): |
Antoine Pitrou | 8f85f90 | 2012-01-03 22:46:48 +0100 | [diff] [blame] | 348 | self = _SSLContext.__new__(cls, protocol) |
| 349 | if protocol != _SSLv2_IF_EXISTS: |
| 350 | self.set_ciphers(_DEFAULT_CIPHERS) |
| 351 | return self |
Antoine Pitrou | 152efa2 | 2010-05-16 18:19:27 +0000 | [diff] [blame] | 352 | |
| 353 | def __init__(self, protocol): |
| 354 | self.protocol = protocol |
| 355 | |
| 356 | def wrap_socket(self, sock, server_side=False, |
| 357 | do_handshake_on_connect=True, |
Antoine Pitrou | d532321 | 2010-10-22 18:19:07 +0000 | [diff] [blame] | 358 | suppress_ragged_eofs=True, |
| 359 | server_hostname=None): |
Antoine Pitrou | 152efa2 | 2010-05-16 18:19:27 +0000 | [diff] [blame] | 360 | return SSLSocket(sock=sock, server_side=server_side, |
| 361 | do_handshake_on_connect=do_handshake_on_connect, |
| 362 | suppress_ragged_eofs=suppress_ragged_eofs, |
Antoine Pitrou | d532321 | 2010-10-22 18:19:07 +0000 | [diff] [blame] | 363 | server_hostname=server_hostname, |
Antoine Pitrou | 152efa2 | 2010-05-16 18:19:27 +0000 | [diff] [blame] | 364 | _context=self) |
| 365 | |
Antoine Pitrou | d5d17eb | 2012-03-22 00:23:03 +0100 | [diff] [blame] | 366 | def set_npn_protocols(self, npn_protocols): |
| 367 | protos = bytearray() |
| 368 | for protocol in npn_protocols: |
| 369 | b = bytes(protocol, 'ascii') |
| 370 | if len(b) == 0 or len(b) > 255: |
| 371 | raise SSLError('NPN protocols must be 1 to 255 in length') |
| 372 | protos.append(len(b)) |
| 373 | protos.extend(b) |
| 374 | |
| 375 | self._set_npn_protocols(protos) |
| 376 | |
Christian Heimes | 72d2850 | 2013-11-23 13:56:58 +0100 | [diff] [blame] | 377 | def _load_windows_store_certs(self, storename, purpose): |
| 378 | certs = bytearray() |
| 379 | for cert, encoding, trust in enum_certificates(storename): |
| 380 | # CA certs are never PKCS#7 encoded |
| 381 | if encoding == "x509_asn": |
| 382 | if trust is True or purpose.oid in trust: |
| 383 | certs.extend(cert) |
| 384 | self.load_verify_locations(cadata=certs) |
| 385 | return certs |
| 386 | |
| 387 | def load_default_certs(self, purpose=Purpose.SERVER_AUTH): |
| 388 | if not isinstance(purpose, _ASN1Object): |
| 389 | raise TypeError(purpose) |
| 390 | if sys.platform == "win32": |
| 391 | for storename in self._windows_cert_stores: |
| 392 | self._load_windows_store_certs(storename, purpose) |
| 393 | else: |
| 394 | self.set_default_verify_paths() |
| 395 | |
Antoine Pitrou | 152efa2 | 2010-05-16 18:19:27 +0000 | [diff] [blame] | 396 | |
Christian Heimes | 4c05b47 | 2013-11-23 15:58:30 +0100 | [diff] [blame] | 397 | def create_default_context(purpose=Purpose.SERVER_AUTH, *, cafile=None, |
| 398 | capath=None, cadata=None): |
| 399 | """Create a SSLContext object with default settings. |
| 400 | |
| 401 | NOTE: The protocol and settings may change anytime without prior |
| 402 | deprecation. The values represent a fair balance between maximum |
| 403 | compatibility and security. |
| 404 | """ |
| 405 | if not isinstance(purpose, _ASN1Object): |
| 406 | raise TypeError(purpose) |
Donald Stufft | 6a2ba94 | 2014-03-23 19:05:28 -0400 | [diff] [blame] | 407 | |
| 408 | context = SSLContext(PROTOCOL_SSLv23) |
| 409 | |
Christian Heimes | 4c05b47 | 2013-11-23 15:58:30 +0100 | [diff] [blame] | 410 | # SSLv2 considered harmful. |
| 411 | context.options |= OP_NO_SSLv2 |
Donald Stufft | 6a2ba94 | 2014-03-23 19:05:28 -0400 | [diff] [blame] | 412 | |
| 413 | # SSLv3 has problematic security and is only required for really old |
| 414 | # clients such as IE6 on Windows XP |
| 415 | context.options |= OP_NO_SSLv3 |
| 416 | |
Christian Heimes | dec813f | 2013-11-28 08:06:54 +0100 | [diff] [blame] | 417 | # disable compression to prevent CRIME attacks (OpenSSL 1.0+) |
| 418 | context.options |= getattr(_ssl, "OP_NO_COMPRESSION", 0) |
Donald Stufft | 6a2ba94 | 2014-03-23 19:05:28 -0400 | [diff] [blame] | 419 | |
Christian Heimes | 4c05b47 | 2013-11-23 15:58:30 +0100 | [diff] [blame] | 420 | if purpose == Purpose.SERVER_AUTH: |
Donald Stufft | 6a2ba94 | 2014-03-23 19:05:28 -0400 | [diff] [blame] | 421 | # verify certs and host name in client mode |
Christian Heimes | 4c05b47 | 2013-11-23 15:58:30 +0100 | [diff] [blame] | 422 | context.verify_mode = CERT_REQUIRED |
Christian Heimes | 1aa9a75 | 2013-12-02 02:41:19 +0100 | [diff] [blame] | 423 | context.check_hostname = True |
Donald Stufft | 6a2ba94 | 2014-03-23 19:05:28 -0400 | [diff] [blame] | 424 | elif purpose == Purpose.CLIENT_AUTH: |
| 425 | # Prefer the server's ciphers by default so that we get stronger |
| 426 | # encryption |
| 427 | context.options |= getattr(_ssl, "OP_CIPHER_SERVER_PREFERENCE", 0) |
| 428 | |
| 429 | # Use single use keys in order to improve forward secrecy |
| 430 | context.options |= getattr(_ssl, "OP_SINGLE_DH_USE", 0) |
| 431 | context.options |= getattr(_ssl, "OP_SINGLE_ECDH_USE", 0) |
| 432 | |
| 433 | # disallow ciphers with known vulnerabilities |
| 434 | context.set_ciphers(_RESTRICTED_SERVER_CIPHERS) |
| 435 | |
Christian Heimes | 4c05b47 | 2013-11-23 15:58:30 +0100 | [diff] [blame] | 436 | if cafile or capath or cadata: |
| 437 | context.load_verify_locations(cafile, capath, cadata) |
| 438 | elif context.verify_mode != CERT_NONE: |
| 439 | # no explicit cafile, capath or cadata but the verify mode is |
| 440 | # CERT_OPTIONAL or CERT_REQUIRED. Let's try to load default system |
| 441 | # root CA certificates for the given purpose. This may fail silently. |
| 442 | context.load_default_certs(purpose) |
| 443 | return context |
| 444 | |
| 445 | |
Christian Heimes | 67986f9 | 2013-11-23 22:43:47 +0100 | [diff] [blame] | 446 | def _create_stdlib_context(protocol=PROTOCOL_SSLv23, *, cert_reqs=None, |
Christian Heimes | a02c69a | 2013-12-02 20:59:28 +0100 | [diff] [blame] | 447 | check_hostname=False, purpose=Purpose.SERVER_AUTH, |
Christian Heimes | 67986f9 | 2013-11-23 22:43:47 +0100 | [diff] [blame] | 448 | certfile=None, keyfile=None, |
| 449 | cafile=None, capath=None, cadata=None): |
| 450 | """Create a SSLContext object for Python stdlib modules |
| 451 | |
| 452 | All Python stdlib modules shall use this function to create SSLContext |
| 453 | objects in order to keep common settings in one place. The configuration |
| 454 | is less restrict than create_default_context()'s to increase backward |
| 455 | compatibility. |
| 456 | """ |
| 457 | if not isinstance(purpose, _ASN1Object): |
| 458 | raise TypeError(purpose) |
| 459 | |
| 460 | context = SSLContext(protocol) |
| 461 | # SSLv2 considered harmful. |
| 462 | context.options |= OP_NO_SSLv2 |
| 463 | |
| 464 | if cert_reqs is not None: |
| 465 | context.verify_mode = cert_reqs |
Christian Heimes | a02c69a | 2013-12-02 20:59:28 +0100 | [diff] [blame] | 466 | context.check_hostname = check_hostname |
Christian Heimes | 67986f9 | 2013-11-23 22:43:47 +0100 | [diff] [blame] | 467 | |
| 468 | if keyfile and not certfile: |
| 469 | raise ValueError("certfile must be specified") |
| 470 | if certfile or keyfile: |
| 471 | context.load_cert_chain(certfile, keyfile) |
| 472 | |
| 473 | # load CA root certs |
| 474 | if cafile or capath or cadata: |
| 475 | context.load_verify_locations(cafile, capath, cadata) |
| 476 | elif context.verify_mode != CERT_NONE: |
| 477 | # no explicit cafile, capath or cadata but the verify mode is |
| 478 | # CERT_OPTIONAL or CERT_REQUIRED. Let's try to load default system |
| 479 | # root CA certificates for the given purpose. This may fail silently. |
| 480 | context.load_default_certs(purpose) |
| 481 | |
| 482 | return context |
| 483 | |
Antoine Pitrou | 152efa2 | 2010-05-16 18:19:27 +0000 | [diff] [blame] | 484 | class SSLSocket(socket): |
Thomas Wouters | 47b49bf | 2007-08-30 22:15:33 +0000 | [diff] [blame] | 485 | """This class implements a subtype of socket.socket that wraps |
| 486 | the underlying OS socket in an SSL context when necessary, and |
| 487 | provides read and write methods over that channel.""" |
| 488 | |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 489 | def __init__(self, sock=None, keyfile=None, certfile=None, |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 490 | server_side=False, cert_reqs=CERT_NONE, |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 491 | ssl_version=PROTOCOL_SSLv23, ca_certs=None, |
| 492 | do_handshake_on_connect=True, |
| 493 | family=AF_INET, type=SOCK_STREAM, proto=0, fileno=None, |
Antoine Pitrou | d5d17eb | 2012-03-22 00:23:03 +0100 | [diff] [blame] | 494 | suppress_ragged_eofs=True, npn_protocols=None, ciphers=None, |
Antoine Pitrou | d532321 | 2010-10-22 18:19:07 +0000 | [diff] [blame] | 495 | server_hostname=None, |
Antoine Pitrou | 152efa2 | 2010-05-16 18:19:27 +0000 | [diff] [blame] | 496 | _context=None): |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 497 | |
Antoine Pitrou | 152efa2 | 2010-05-16 18:19:27 +0000 | [diff] [blame] | 498 | if _context: |
Antoine Pitrou | 58ddc9d | 2013-01-05 21:20:29 +0100 | [diff] [blame] | 499 | self._context = _context |
Antoine Pitrou | 152efa2 | 2010-05-16 18:19:27 +0000 | [diff] [blame] | 500 | else: |
Giampaolo RodolĂ | 745ab38 | 2010-08-29 19:25:49 +0000 | [diff] [blame] | 501 | if server_side and not certfile: |
| 502 | raise ValueError("certfile must be specified for server-side " |
| 503 | "operations") |
Giampaolo RodolĂ | 8b7da62 | 2010-08-30 18:28:05 +0000 | [diff] [blame] | 504 | if keyfile and not certfile: |
| 505 | raise ValueError("certfile must be specified") |
Antoine Pitrou | 152efa2 | 2010-05-16 18:19:27 +0000 | [diff] [blame] | 506 | if certfile and not keyfile: |
| 507 | keyfile = certfile |
Antoine Pitrou | 58ddc9d | 2013-01-05 21:20:29 +0100 | [diff] [blame] | 508 | self._context = SSLContext(ssl_version) |
| 509 | self._context.verify_mode = cert_reqs |
Antoine Pitrou | 152efa2 | 2010-05-16 18:19:27 +0000 | [diff] [blame] | 510 | if ca_certs: |
Antoine Pitrou | 58ddc9d | 2013-01-05 21:20:29 +0100 | [diff] [blame] | 511 | self._context.load_verify_locations(ca_certs) |
Antoine Pitrou | 152efa2 | 2010-05-16 18:19:27 +0000 | [diff] [blame] | 512 | if certfile: |
Antoine Pitrou | 58ddc9d | 2013-01-05 21:20:29 +0100 | [diff] [blame] | 513 | self._context.load_cert_chain(certfile, keyfile) |
Antoine Pitrou | d5d17eb | 2012-03-22 00:23:03 +0100 | [diff] [blame] | 514 | if npn_protocols: |
Antoine Pitrou | 58ddc9d | 2013-01-05 21:20:29 +0100 | [diff] [blame] | 515 | self._context.set_npn_protocols(npn_protocols) |
Antoine Pitrou | 152efa2 | 2010-05-16 18:19:27 +0000 | [diff] [blame] | 516 | if ciphers: |
Antoine Pitrou | 58ddc9d | 2013-01-05 21:20:29 +0100 | [diff] [blame] | 517 | self._context.set_ciphers(ciphers) |
Antoine Pitrou | 152efa2 | 2010-05-16 18:19:27 +0000 | [diff] [blame] | 518 | self.keyfile = keyfile |
| 519 | self.certfile = certfile |
| 520 | self.cert_reqs = cert_reqs |
| 521 | self.ssl_version = ssl_version |
| 522 | self.ca_certs = ca_certs |
| 523 | self.ciphers = ciphers |
Antoine Pitrou | 3e86ba4 | 2013-12-28 17:26:33 +0100 | [diff] [blame] | 524 | # Can't use sock.type as other flags (such as SOCK_NONBLOCK) get |
| 525 | # mixed in. |
| 526 | if sock.getsockopt(SOL_SOCKET, SO_TYPE) != SOCK_STREAM: |
| 527 | raise NotImplementedError("only stream sockets are supported") |
Antoine Pitrou | d532321 | 2010-10-22 18:19:07 +0000 | [diff] [blame] | 528 | if server_side and server_hostname: |
| 529 | raise ValueError("server_hostname can only be specified " |
| 530 | "in client mode") |
Christian Heimes | 1aa9a75 | 2013-12-02 02:41:19 +0100 | [diff] [blame] | 531 | if self._context.check_hostname and not server_hostname: |
| 532 | if HAS_SNI: |
| 533 | raise ValueError("check_hostname requires server_hostname") |
| 534 | else: |
| 535 | raise ValueError("check_hostname requires server_hostname, " |
| 536 | "but it's not supported by your OpenSSL " |
| 537 | "library") |
Giampaolo RodolĂ | 745ab38 | 2010-08-29 19:25:49 +0000 | [diff] [blame] | 538 | self.server_side = server_side |
Antoine Pitrou | d532321 | 2010-10-22 18:19:07 +0000 | [diff] [blame] | 539 | self.server_hostname = server_hostname |
Antoine Pitrou | 152efa2 | 2010-05-16 18:19:27 +0000 | [diff] [blame] | 540 | self.do_handshake_on_connect = do_handshake_on_connect |
| 541 | self.suppress_ragged_eofs = suppress_ragged_eofs |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 542 | if sock is not None: |
Bill Janssen | 54cc54c | 2007-12-14 22:08:56 +0000 | [diff] [blame] | 543 | socket.__init__(self, |
| 544 | family=sock.family, |
| 545 | type=sock.type, |
| 546 | proto=sock.proto, |
Antoine Pitrou | e43f9d0 | 2010-08-08 23:24:50 +0000 | [diff] [blame] | 547 | fileno=sock.fileno()) |
Antoine Pitrou | 40f0874 | 2010-04-24 22:04:40 +0000 | [diff] [blame] | 548 | self.settimeout(sock.gettimeout()) |
Antoine Pitrou | 6e451df | 2010-08-09 20:39:54 +0000 | [diff] [blame] | 549 | sock.detach() |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 550 | elif fileno is not None: |
| 551 | socket.__init__(self, fileno=fileno) |
| 552 | else: |
| 553 | socket.__init__(self, family=family, type=type, proto=proto) |
| 554 | |
Antoine Pitrou | 242db72 | 2013-05-01 20:52:07 +0200 | [diff] [blame] | 555 | # See if we are connected |
| 556 | try: |
| 557 | self.getpeername() |
| 558 | except OSError as e: |
| 559 | if e.errno != errno.ENOTCONN: |
| 560 | raise |
| 561 | connected = False |
| 562 | else: |
| 563 | connected = True |
| 564 | |
Antoine Pitrou | fa2b938 | 2010-04-26 22:17:47 +0000 | [diff] [blame] | 565 | self._closed = False |
| 566 | self._sslobj = None |
Antoine Pitrou | e93bf7a | 2011-02-26 23:24:06 +0000 | [diff] [blame] | 567 | self._connected = connected |
Antoine Pitrou | fa2b938 | 2010-04-26 22:17:47 +0000 | [diff] [blame] | 568 | if connected: |
| 569 | # create the SSL object |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 570 | try: |
Antoine Pitrou | 58ddc9d | 2013-01-05 21:20:29 +0100 | [diff] [blame] | 571 | self._sslobj = self._context._wrap_socket(self, server_side, |
Antoine Pitrou | d532321 | 2010-10-22 18:19:07 +0000 | [diff] [blame] | 572 | server_hostname) |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 573 | if do_handshake_on_connect: |
Bill Janssen | 48dc27c | 2007-12-05 03:38:10 +0000 | [diff] [blame] | 574 | timeout = self.gettimeout() |
| 575 | if timeout == 0.0: |
| 576 | # non-blocking |
| 577 | 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] | 578 | self.do_handshake() |
Bill Janssen | 48dc27c | 2007-12-05 03:38:10 +0000 | [diff] [blame] | 579 | |
Christian Heimes | 1aa9a75 | 2013-12-02 02:41:19 +0100 | [diff] [blame] | 580 | except (OSError, ValueError): |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 581 | self.close() |
Christian Heimes | 1aa9a75 | 2013-12-02 02:41:19 +0100 | [diff] [blame] | 582 | raise |
Antoine Pitrou | 242db72 | 2013-05-01 20:52:07 +0200 | [diff] [blame] | 583 | |
Antoine Pitrou | 58ddc9d | 2013-01-05 21:20:29 +0100 | [diff] [blame] | 584 | @property |
| 585 | def context(self): |
| 586 | return self._context |
| 587 | |
| 588 | @context.setter |
| 589 | def context(self, ctx): |
| 590 | self._context = ctx |
| 591 | self._sslobj.context = ctx |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 592 | |
Guido van Rossum | b7b030e | 2007-11-16 01:28:45 +0000 | [diff] [blame] | 593 | def dup(self): |
| 594 | raise NotImplemented("Can't dup() %s instances" % |
| 595 | self.__class__.__name__) |
| 596 | |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 597 | def _checkClosed(self, msg=None): |
| 598 | # raise an exception here if you wish to check for spurious closes |
| 599 | pass |
| 600 | |
Antoine Pitrou | 242db72 | 2013-05-01 20:52:07 +0200 | [diff] [blame] | 601 | def _check_connected(self): |
| 602 | if not self._connected: |
| 603 | # getpeername() will raise ENOTCONN if the socket is really |
| 604 | # not connected; note that we can be connected even without |
| 605 | # _connected being set, e.g. if connect() first returned |
| 606 | # EAGAIN. |
| 607 | self.getpeername() |
| 608 | |
Bill Janssen | 54cc54c | 2007-12-14 22:08:56 +0000 | [diff] [blame] | 609 | def read(self, len=0, buffer=None): |
Thomas Wouters | 47b49bf | 2007-08-30 22:15:33 +0000 | [diff] [blame] | 610 | """Read up to LEN bytes and return them. |
| 611 | Return zero-length string on EOF.""" |
| 612 | |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 613 | self._checkClosed() |
Antoine Pitrou | 60a26e0 | 2013-07-20 19:35:16 +0200 | [diff] [blame] | 614 | if not self._sslobj: |
| 615 | raise ValueError("Read on closed or unwrapped SSL socket.") |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 616 | try: |
Antoine Pitrou | 24e561a | 2010-09-03 18:38:17 +0000 | [diff] [blame] | 617 | if buffer is not None: |
| 618 | v = self._sslobj.read(len, buffer) |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 619 | else: |
Bill Janssen | 54cc54c | 2007-12-14 22:08:56 +0000 | [diff] [blame] | 620 | v = self._sslobj.read(len or 1024) |
| 621 | return v |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 622 | except SSLError as x: |
| 623 | if x.args[0] == SSL_ERROR_EOF and self.suppress_ragged_eofs: |
Antoine Pitrou | 24e561a | 2010-09-03 18:38:17 +0000 | [diff] [blame] | 624 | if buffer is not None: |
Bill Janssen | 54cc54c | 2007-12-14 22:08:56 +0000 | [diff] [blame] | 625 | return 0 |
| 626 | else: |
| 627 | return b'' |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 628 | else: |
| 629 | raise |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 630 | |
| 631 | def write(self, data): |
Thomas Wouters | 47b49bf | 2007-08-30 22:15:33 +0000 | [diff] [blame] | 632 | """Write DATA to the underlying SSL channel. Returns |
| 633 | number of bytes of DATA actually transmitted.""" |
| 634 | |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 635 | self._checkClosed() |
Antoine Pitrou | 60a26e0 | 2013-07-20 19:35:16 +0200 | [diff] [blame] | 636 | if not self._sslobj: |
| 637 | raise ValueError("Write on closed or unwrapped SSL socket.") |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 638 | return self._sslobj.write(data) |
| 639 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 640 | def getpeercert(self, binary_form=False): |
Thomas Wouters | 47b49bf | 2007-08-30 22:15:33 +0000 | [diff] [blame] | 641 | """Returns a formatted version of the data in the |
| 642 | certificate provided by the other end of the SSL channel. |
| 643 | Return None if no certificate was provided, {} if a |
| 644 | certificate was provided, but not validated.""" |
| 645 | |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 646 | self._checkClosed() |
Antoine Pitrou | 242db72 | 2013-05-01 20:52:07 +0200 | [diff] [blame] | 647 | self._check_connected() |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 648 | return self._sslobj.peer_certificate(binary_form) |
| 649 | |
Antoine Pitrou | d5d17eb | 2012-03-22 00:23:03 +0100 | [diff] [blame] | 650 | def selected_npn_protocol(self): |
| 651 | self._checkClosed() |
| 652 | if not self._sslobj or not _ssl.HAS_NPN: |
| 653 | return None |
| 654 | else: |
| 655 | return self._sslobj.selected_npn_protocol() |
| 656 | |
Guido van Rossum | 5b8b155 | 2007-11-16 00:06:11 +0000 | [diff] [blame] | 657 | def cipher(self): |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 658 | self._checkClosed() |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 659 | if not self._sslobj: |
| 660 | return None |
| 661 | else: |
| 662 | return self._sslobj.cipher() |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 663 | |
Antoine Pitrou | 8abdb8a | 2011-12-20 10:13:40 +0100 | [diff] [blame] | 664 | def compression(self): |
| 665 | self._checkClosed() |
| 666 | if not self._sslobj: |
| 667 | return None |
| 668 | else: |
| 669 | return self._sslobj.compression() |
| 670 | |
Guido van Rossum | 5b8b155 | 2007-11-16 00:06:11 +0000 | [diff] [blame] | 671 | def send(self, data, flags=0): |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 672 | self._checkClosed() |
Thomas Wouters | 47b49bf | 2007-08-30 22:15:33 +0000 | [diff] [blame] | 673 | if self._sslobj: |
| 674 | if flags != 0: |
| 675 | raise ValueError( |
| 676 | "non-zero flags not allowed in calls to send() on %s" % |
| 677 | self.__class__) |
Giampaolo Rodola' | 06d0c1e | 2013-04-03 12:01:44 +0200 | [diff] [blame] | 678 | try: |
| 679 | v = self._sslobj.write(data) |
| 680 | except SSLError as x: |
| 681 | if x.args[0] == SSL_ERROR_WANT_READ: |
| 682 | return 0 |
| 683 | elif x.args[0] == SSL_ERROR_WANT_WRITE: |
| 684 | return 0 |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 685 | else: |
Giampaolo Rodola' | 06d0c1e | 2013-04-03 12:01:44 +0200 | [diff] [blame] | 686 | raise |
| 687 | else: |
| 688 | return v |
Thomas Wouters | 47b49bf | 2007-08-30 22:15:33 +0000 | [diff] [blame] | 689 | else: |
| 690 | return socket.send(self, data, flags) |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 691 | |
Antoine Pitrou | a468adc | 2010-09-14 14:43:44 +0000 | [diff] [blame] | 692 | def sendto(self, data, flags_or_addr, addr=None): |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 693 | self._checkClosed() |
Thomas Wouters | 47b49bf | 2007-08-30 22:15:33 +0000 | [diff] [blame] | 694 | if self._sslobj: |
Bill Janssen | 980f314 | 2008-06-29 00:05:51 +0000 | [diff] [blame] | 695 | raise ValueError("sendto not allowed on instances of %s" % |
Thomas Wouters | 47b49bf | 2007-08-30 22:15:33 +0000 | [diff] [blame] | 696 | self.__class__) |
Antoine Pitrou | a468adc | 2010-09-14 14:43:44 +0000 | [diff] [blame] | 697 | elif addr is None: |
| 698 | return socket.sendto(self, data, flags_or_addr) |
Thomas Wouters | 47b49bf | 2007-08-30 22:15:33 +0000 | [diff] [blame] | 699 | else: |
Antoine Pitrou | a468adc | 2010-09-14 14:43:44 +0000 | [diff] [blame] | 700 | return socket.sendto(self, data, flags_or_addr, addr) |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 701 | |
Nick Coghlan | 513886a | 2011-08-28 00:00:27 +1000 | [diff] [blame] | 702 | def sendmsg(self, *args, **kwargs): |
| 703 | # Ensure programs don't send data unencrypted if they try to |
| 704 | # use this method. |
| 705 | raise NotImplementedError("sendmsg not allowed on instances of %s" % |
| 706 | self.__class__) |
| 707 | |
Guido van Rossum | 5b8b155 | 2007-11-16 00:06:11 +0000 | [diff] [blame] | 708 | def sendall(self, data, flags=0): |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 709 | self._checkClosed() |
Thomas Wouters | 47b49bf | 2007-08-30 22:15:33 +0000 | [diff] [blame] | 710 | if self._sslobj: |
Giampaolo RodolĂ | 374f835 | 2010-08-29 12:08:09 +0000 | [diff] [blame] | 711 | if flags != 0: |
| 712 | raise ValueError( |
| 713 | "non-zero flags not allowed in calls to sendall() on %s" % |
| 714 | self.__class__) |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 715 | amount = len(data) |
| 716 | count = 0 |
| 717 | while (count < amount): |
| 718 | v = self.send(data[count:]) |
| 719 | count += v |
| 720 | return amount |
Thomas Wouters | 47b49bf | 2007-08-30 22:15:33 +0000 | [diff] [blame] | 721 | else: |
| 722 | return socket.sendall(self, data, flags) |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 723 | |
Guido van Rossum | 5b8b155 | 2007-11-16 00:06:11 +0000 | [diff] [blame] | 724 | def recv(self, buflen=1024, flags=0): |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 725 | self._checkClosed() |
Thomas Wouters | 47b49bf | 2007-08-30 22:15:33 +0000 | [diff] [blame] | 726 | if self._sslobj: |
| 727 | if flags != 0: |
| 728 | raise ValueError( |
Antoine Pitrou | 5733c08 | 2010-03-22 14:49:10 +0000 | [diff] [blame] | 729 | "non-zero flags not allowed in calls to recv() on %s" % |
| 730 | self.__class__) |
| 731 | return self.read(buflen) |
Thomas Wouters | 47b49bf | 2007-08-30 22:15:33 +0000 | [diff] [blame] | 732 | else: |
| 733 | return socket.recv(self, buflen, flags) |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 734 | |
Guido van Rossum | 5b8b155 | 2007-11-16 00:06:11 +0000 | [diff] [blame] | 735 | def recv_into(self, buffer, nbytes=None, flags=0): |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 736 | self._checkClosed() |
| 737 | if buffer and (nbytes is None): |
| 738 | nbytes = len(buffer) |
| 739 | elif nbytes is None: |
| 740 | nbytes = 1024 |
| 741 | if self._sslobj: |
| 742 | if flags != 0: |
| 743 | raise ValueError( |
Guido van Rossum | 5b8b155 | 2007-11-16 00:06:11 +0000 | [diff] [blame] | 744 | "non-zero flags not allowed in calls to recv_into() on %s" % |
| 745 | self.__class__) |
Antoine Pitrou | 5733c08 | 2010-03-22 14:49:10 +0000 | [diff] [blame] | 746 | return self.read(nbytes, buffer) |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 747 | else: |
| 748 | return socket.recv_into(self, buffer, nbytes, flags) |
| 749 | |
Antoine Pitrou | a468adc | 2010-09-14 14:43:44 +0000 | [diff] [blame] | 750 | def recvfrom(self, buflen=1024, flags=0): |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 751 | self._checkClosed() |
Thomas Wouters | 47b49bf | 2007-08-30 22:15:33 +0000 | [diff] [blame] | 752 | if self._sslobj: |
Bill Janssen | 980f314 | 2008-06-29 00:05:51 +0000 | [diff] [blame] | 753 | raise ValueError("recvfrom not allowed on instances of %s" % |
Thomas Wouters | 47b49bf | 2007-08-30 22:15:33 +0000 | [diff] [blame] | 754 | self.__class__) |
| 755 | else: |
Antoine Pitrou | a468adc | 2010-09-14 14:43:44 +0000 | [diff] [blame] | 756 | return socket.recvfrom(self, buflen, flags) |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 757 | |
Bill Janssen | 58afe4c | 2008-09-08 16:45:19 +0000 | [diff] [blame] | 758 | def recvfrom_into(self, buffer, nbytes=None, flags=0): |
| 759 | self._checkClosed() |
| 760 | if self._sslobj: |
| 761 | raise ValueError("recvfrom_into not allowed on instances of %s" % |
| 762 | self.__class__) |
| 763 | else: |
| 764 | return socket.recvfrom_into(self, buffer, nbytes, flags) |
| 765 | |
Nick Coghlan | 513886a | 2011-08-28 00:00:27 +1000 | [diff] [blame] | 766 | def recvmsg(self, *args, **kwargs): |
| 767 | raise NotImplementedError("recvmsg not allowed on instances of %s" % |
| 768 | self.__class__) |
| 769 | |
| 770 | def recvmsg_into(self, *args, **kwargs): |
| 771 | raise NotImplementedError("recvmsg_into not allowed on instances of " |
| 772 | "%s" % self.__class__) |
| 773 | |
Guido van Rossum | 5b8b155 | 2007-11-16 00:06:11 +0000 | [diff] [blame] | 774 | def pending(self): |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 775 | self._checkClosed() |
| 776 | if self._sslobj: |
| 777 | return self._sslobj.pending() |
| 778 | else: |
| 779 | return 0 |
| 780 | |
Guido van Rossum | 5b8b155 | 2007-11-16 00:06:11 +0000 | [diff] [blame] | 781 | def shutdown(self, how): |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 782 | self._checkClosed() |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 783 | self._sslobj = None |
Thomas Wouters | 47b49bf | 2007-08-30 22:15:33 +0000 | [diff] [blame] | 784 | socket.shutdown(self, how) |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 785 | |
Ezio Melotti | dc55e67 | 2010-01-18 09:15:14 +0000 | [diff] [blame] | 786 | def unwrap(self): |
Bill Janssen | 40a0f66 | 2008-08-12 16:56:25 +0000 | [diff] [blame] | 787 | if self._sslobj: |
| 788 | s = self._sslobj.shutdown() |
| 789 | self._sslobj = None |
| 790 | return s |
| 791 | else: |
| 792 | raise ValueError("No SSL wrapper around " + str(self)) |
| 793 | |
Guido van Rossum | 5b8b155 | 2007-11-16 00:06:11 +0000 | [diff] [blame] | 794 | def _real_close(self): |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 795 | self._sslobj = None |
Bill Janssen | 54cc54c | 2007-12-14 22:08:56 +0000 | [diff] [blame] | 796 | socket._real_close(self) |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 797 | |
Bill Janssen | 48dc27c | 2007-12-05 03:38:10 +0000 | [diff] [blame] | 798 | def do_handshake(self, block=False): |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 799 | """Perform a TLS/SSL handshake.""" |
Antoine Pitrou | 242db72 | 2013-05-01 20:52:07 +0200 | [diff] [blame] | 800 | self._check_connected() |
Bill Janssen | 48dc27c | 2007-12-05 03:38:10 +0000 | [diff] [blame] | 801 | timeout = self.gettimeout() |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 802 | try: |
Bill Janssen | 48dc27c | 2007-12-05 03:38:10 +0000 | [diff] [blame] | 803 | if timeout == 0.0 and block: |
| 804 | self.settimeout(None) |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 805 | self._sslobj.do_handshake() |
Bill Janssen | 48dc27c | 2007-12-05 03:38:10 +0000 | [diff] [blame] | 806 | finally: |
| 807 | self.settimeout(timeout) |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 808 | |
Christian Heimes | 1aa9a75 | 2013-12-02 02:41:19 +0100 | [diff] [blame] | 809 | if self.context.check_hostname: |
Christian Heimes | 1da3ba8 | 2013-12-04 20:46:20 +0100 | [diff] [blame] | 810 | if not self.server_hostname: |
| 811 | raise ValueError("check_hostname needs server_hostname " |
| 812 | "argument") |
| 813 | match_hostname(self.getpeercert(), self.server_hostname) |
Christian Heimes | 1aa9a75 | 2013-12-02 02:41:19 +0100 | [diff] [blame] | 814 | |
Antoine Pitrou | b4410db | 2011-05-18 18:51:06 +0200 | [diff] [blame] | 815 | def _real_connect(self, addr, connect_ex): |
Giampaolo RodolĂ | 745ab38 | 2010-08-29 19:25:49 +0000 | [diff] [blame] | 816 | if self.server_side: |
| 817 | raise ValueError("can't connect in server-side mode") |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 818 | # Here we assume that the socket is client-side, and not |
| 819 | # 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] | 820 | if self._connected: |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 821 | raise ValueError("attempt to connect already-connected SSLSocket!") |
Antoine Pitrou | d532321 | 2010-10-22 18:19:07 +0000 | [diff] [blame] | 822 | self._sslobj = self.context._wrap_socket(self, False, self.server_hostname) |
Bill Janssen | 54cc54c | 2007-12-14 22:08:56 +0000 | [diff] [blame] | 823 | try: |
Antoine Pitrou | b4410db | 2011-05-18 18:51:06 +0200 | [diff] [blame] | 824 | if connect_ex: |
| 825 | rc = socket.connect_ex(self, addr) |
Antoine Pitrou | e93bf7a | 2011-02-26 23:24:06 +0000 | [diff] [blame] | 826 | else: |
Antoine Pitrou | b4410db | 2011-05-18 18:51:06 +0200 | [diff] [blame] | 827 | rc = None |
| 828 | socket.connect(self, addr) |
| 829 | if not rc: |
Antoine Pitrou | 242db72 | 2013-05-01 20:52:07 +0200 | [diff] [blame] | 830 | self._connected = True |
Antoine Pitrou | b4410db | 2011-05-18 18:51:06 +0200 | [diff] [blame] | 831 | if self.do_handshake_on_connect: |
| 832 | self.do_handshake() |
Antoine Pitrou | b4410db | 2011-05-18 18:51:06 +0200 | [diff] [blame] | 833 | return rc |
Christian Heimes | 1aa9a75 | 2013-12-02 02:41:19 +0100 | [diff] [blame] | 834 | except (OSError, ValueError): |
Antoine Pitrou | b4410db | 2011-05-18 18:51:06 +0200 | [diff] [blame] | 835 | self._sslobj = None |
| 836 | raise |
Antoine Pitrou | e93bf7a | 2011-02-26 23:24:06 +0000 | [diff] [blame] | 837 | |
| 838 | def connect(self, addr): |
| 839 | """Connects to remote ADDR, and then wraps the connection in |
| 840 | an SSL channel.""" |
| 841 | self._real_connect(addr, False) |
| 842 | |
| 843 | def connect_ex(self, addr): |
| 844 | """Connects to remote ADDR, and then wraps the connection in |
| 845 | an SSL channel.""" |
| 846 | return self._real_connect(addr, True) |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 847 | |
| 848 | def accept(self): |
Thomas Wouters | 47b49bf | 2007-08-30 22:15:33 +0000 | [diff] [blame] | 849 | """Accepts a new connection from a remote client, and returns |
| 850 | a tuple containing that new connection wrapped with a server-side |
| 851 | SSL channel, and the address of the remote client.""" |
| 852 | |
| 853 | newsock, addr = socket.accept(self) |
Antoine Pitrou | 5c89b4e | 2012-11-11 01:25:36 +0100 | [diff] [blame] | 854 | newsock = self.context.wrap_socket(newsock, |
| 855 | do_handshake_on_connect=self.do_handshake_on_connect, |
| 856 | suppress_ragged_eofs=self.suppress_ragged_eofs, |
| 857 | server_side=True) |
| 858 | return newsock, addr |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 859 | |
Antoine Pitrou | d649480 | 2011-07-21 01:11:30 +0200 | [diff] [blame] | 860 | def get_channel_binding(self, cb_type="tls-unique"): |
| 861 | """Get channel binding data for current connection. Raise ValueError |
| 862 | if the requested `cb_type` is not supported. Return bytes of the data |
| 863 | or None if the data is not available (e.g. before the handshake). |
| 864 | """ |
| 865 | if cb_type not in CHANNEL_BINDING_TYPES: |
| 866 | raise ValueError("Unsupported channel binding type") |
| 867 | if cb_type != "tls-unique": |
| 868 | raise NotImplementedError( |
| 869 | "{0} channel binding type not implemented" |
| 870 | .format(cb_type)) |
| 871 | if self._sslobj is None: |
| 872 | return None |
| 873 | return self._sslobj.tls_unique_cb() |
| 874 | |
Bill Janssen | 54cc54c | 2007-12-14 22:08:56 +0000 | [diff] [blame] | 875 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 876 | def wrap_socket(sock, keyfile=None, certfile=None, |
| 877 | server_side=False, cert_reqs=CERT_NONE, |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 878 | ssl_version=PROTOCOL_SSLv23, ca_certs=None, |
Bill Janssen | 48dc27c | 2007-12-05 03:38:10 +0000 | [diff] [blame] | 879 | do_handshake_on_connect=True, |
Antoine Pitrou | d5d17eb | 2012-03-22 00:23:03 +0100 | [diff] [blame] | 880 | suppress_ragged_eofs=True, |
| 881 | ciphers=None): |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 882 | |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 883 | return SSLSocket(sock=sock, keyfile=keyfile, certfile=certfile, |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 884 | server_side=server_side, cert_reqs=cert_reqs, |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 885 | ssl_version=ssl_version, ca_certs=ca_certs, |
Bill Janssen | 48dc27c | 2007-12-05 03:38:10 +0000 | [diff] [blame] | 886 | do_handshake_on_connect=do_handshake_on_connect, |
Antoine Pitrou | 2d9cb9c | 2010-04-17 17:40:45 +0000 | [diff] [blame] | 887 | suppress_ragged_eofs=suppress_ragged_eofs, |
| 888 | ciphers=ciphers) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 889 | |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 890 | # some utility functions |
| 891 | |
| 892 | def cert_time_to_seconds(cert_time): |
Thomas Wouters | 47b49bf | 2007-08-30 22:15:33 +0000 | [diff] [blame] | 893 | """Takes a date-time string in standard ASN1_print form |
| 894 | ("MON DAY 24HOUR:MINUTE:SEC YEAR TIMEZONE") and return |
| 895 | a Python time value in seconds past the epoch.""" |
| 896 | |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 897 | import time |
| 898 | return time.mktime(time.strptime(cert_time, "%b %d %H:%M:%S %Y GMT")) |
| 899 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 900 | PEM_HEADER = "-----BEGIN CERTIFICATE-----" |
| 901 | PEM_FOOTER = "-----END CERTIFICATE-----" |
| 902 | |
| 903 | def DER_cert_to_PEM_cert(der_cert_bytes): |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 904 | """Takes a certificate in binary DER format and returns the |
| 905 | PEM version of it as a string.""" |
| 906 | |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 907 | f = str(base64.standard_b64encode(der_cert_bytes), 'ASCII', 'strict') |
| 908 | return (PEM_HEADER + '\n' + |
| 909 | textwrap.fill(f, 64) + '\n' + |
| 910 | PEM_FOOTER + '\n') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 911 | |
| 912 | def PEM_cert_to_DER_cert(pem_cert_string): |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 913 | """Takes a certificate in ASCII PEM format and returns the |
| 914 | DER-encoded version of it as a byte sequence""" |
| 915 | |
| 916 | if not pem_cert_string.startswith(PEM_HEADER): |
| 917 | raise ValueError("Invalid PEM encoding; must start with %s" |
| 918 | % PEM_HEADER) |
| 919 | if not pem_cert_string.strip().endswith(PEM_FOOTER): |
| 920 | raise ValueError("Invalid PEM encoding; must end with %s" |
| 921 | % PEM_FOOTER) |
| 922 | d = pem_cert_string.strip()[len(PEM_HEADER):-len(PEM_FOOTER)] |
Georg Brandl | 706824f | 2009-06-04 09:42:55 +0000 | [diff] [blame] | 923 | return base64.decodebytes(d.encode('ASCII', 'strict')) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 924 | |
Guido van Rossum | 5b8b155 | 2007-11-16 00:06:11 +0000 | [diff] [blame] | 925 | def get_server_certificate(addr, ssl_version=PROTOCOL_SSLv3, ca_certs=None): |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 926 | """Retrieve the certificate from the server at the specified address, |
| 927 | and return it as a PEM-encoded string. |
| 928 | If 'ca_certs' is specified, validate the server cert against it. |
| 929 | If 'ssl_version' is specified, use it in the connection attempt.""" |
| 930 | |
| 931 | host, port = addr |
Christian Heimes | 67986f9 | 2013-11-23 22:43:47 +0100 | [diff] [blame] | 932 | if ca_certs is not None: |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 933 | cert_reqs = CERT_REQUIRED |
| 934 | else: |
| 935 | cert_reqs = CERT_NONE |
Christian Heimes | 67986f9 | 2013-11-23 22:43:47 +0100 | [diff] [blame] | 936 | context = _create_stdlib_context(ssl_version, |
| 937 | cert_reqs=cert_reqs, |
| 938 | cafile=ca_certs) |
| 939 | with create_connection(addr) as sock: |
| 940 | with context.wrap_socket(sock) as sslsock: |
| 941 | dercert = sslsock.getpeercert(True) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 942 | return DER_cert_to_PEM_cert(dercert) |
| 943 | |
Guido van Rossum | 5b8b155 | 2007-11-16 00:06:11 +0000 | [diff] [blame] | 944 | def get_protocol_name(protocol_code): |
Victor Stinner | 3de4919 | 2011-05-09 00:42:58 +0200 | [diff] [blame] | 945 | return _PROTOCOL_NAMES.get(protocol_code, '<unknown>') |