Home | History | Annotate | Download | only in Modules
      1 /* SSL socket module
      2 
      3    SSL support based on patches by Brian E Gallew and Laszlo Kovacs.
      4    Re-worked a bit by Bill Janssen to add server-side support and
      5    certificate decoding.  Chris Stawarz contributed some non-blocking
      6    patches.
      7 
      8    This module is imported by ssl.py. It should *not* be used
      9    directly.
     10 
     11    XXX should partial writes be enabled, SSL_MODE_ENABLE_PARTIAL_WRITE?
     12 
     13    XXX integrate several "shutdown modes" as suggested in
     14        http://bugs.python.org/issue8108#msg102867 ?
     15 */
     16 
     17 #define PY_SSIZE_T_CLEAN
     18 
     19 #include "Python.h"
     20 
     21 #include "pythread.h"
     22 
     23 /* Redefined below for Windows debug builds after important #includes */
     24 #define _PySSL_FIX_ERRNO
     25 
     26 #define PySSL_BEGIN_ALLOW_THREADS_S(save) \
     27     do { if (_ssl_locks_count>0) { (save) = PyEval_SaveThread(); } } while (0)
     28 #define PySSL_END_ALLOW_THREADS_S(save) \
     29     do { if (_ssl_locks_count>0) { PyEval_RestoreThread(save); } _PySSL_FIX_ERRNO; } while (0)
     30 #define PySSL_BEGIN_ALLOW_THREADS { \
     31             PyThreadState *_save = NULL;  \
     32             PySSL_BEGIN_ALLOW_THREADS_S(_save);
     33 #define PySSL_BLOCK_THREADS     PySSL_END_ALLOW_THREADS_S(_save);
     34 #define PySSL_UNBLOCK_THREADS   PySSL_BEGIN_ALLOW_THREADS_S(_save);
     35 #define PySSL_END_ALLOW_THREADS PySSL_END_ALLOW_THREADS_S(_save); }
     36 
     37 /* Include symbols from _socket module */
     38 #include "socketmodule.h"
     39 
     40 static PySocketModule_APIObject PySocketModule;
     41 
     42 #if defined(HAVE_POLL_H)
     43 #include <poll.h>
     44 #elif defined(HAVE_SYS_POLL_H)
     45 #include <sys/poll.h>
     46 #endif
     47 
     48 /* Don't warn about deprecated functions */
     49 #ifdef __GNUC__
     50 #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
     51 #endif
     52 #ifdef __clang__
     53 #pragma clang diagnostic ignored "-Wdeprecated-declarations"
     54 #endif
     55 
     56 /* Include OpenSSL header files */
     57 #include "openssl/rsa.h"
     58 #include "openssl/crypto.h"
     59 #include "openssl/x509.h"
     60 #include "openssl/x509v3.h"
     61 #include "openssl/pem.h"
     62 #include "openssl/ssl.h"
     63 #include "openssl/err.h"
     64 #include "openssl/rand.h"
     65 #include "openssl/bio.h"
     66 #include "openssl/dh.h"
     67 
     68 #ifndef HAVE_X509_VERIFY_PARAM_SET1_HOST
     69 #  ifdef LIBRESSL_VERSION_NUMBER
     70 #    error "LibreSSL is missing X509_VERIFY_PARAM_set1_host(), see https://github.com/libressl-portable/portable/issues/381"
     71 #  elif OPENSSL_VERSION_NUMBER > 0x1000200fL
     72 #    define HAVE_X509_VERIFY_PARAM_SET1_HOST
     73 #  else
     74 #    error "libssl is too old and does not support X509_VERIFY_PARAM_set1_host()"
     75 #  endif
     76 #endif
     77 
     78 /* SSL error object */
     79 static PyObject *PySSLErrorObject;
     80 static PyObject *PySSLCertVerificationErrorObject;
     81 static PyObject *PySSLZeroReturnErrorObject;
     82 static PyObject *PySSLWantReadErrorObject;
     83 static PyObject *PySSLWantWriteErrorObject;
     84 static PyObject *PySSLSyscallErrorObject;
     85 static PyObject *PySSLEOFErrorObject;
     86 
     87 /* Error mappings */
     88 static PyObject *err_codes_to_names;
     89 static PyObject *err_names_to_codes;
     90 static PyObject *lib_codes_to_names;
     91 
     92 struct py_ssl_error_code {
     93     const char *mnemonic;
     94     int library, reason;
     95 };
     96 struct py_ssl_library_code {
     97     const char *library;
     98     int code;
     99 };
    100 
    101 #if defined(MS_WINDOWS) && defined(Py_DEBUG)
    102 /* Debug builds on Windows rely on getting errno directly from OpenSSL.
    103  * However, because it uses a different CRT, we need to transfer the
    104  * value of errno from OpenSSL into our debug CRT.
    105  *
    106  * Don't be fooled - this is horribly ugly code. The only reasonable
    107  * alternative is to do both debug and release builds of OpenSSL, which
    108  * requires much uglier code to transform their automatically generated
    109  * makefile. This is the lesser of all the evils.
    110  */
    111 
    112 static void _PySSLFixErrno(void) {
    113     HMODULE ucrtbase = GetModuleHandleW(L"ucrtbase.dll");
    114     if (!ucrtbase) {
    115         /* If ucrtbase.dll is not loaded but the SSL DLLs are, we likely
    116          * have a catastrophic failure, but this function is not the
    117          * place to raise it. */
    118         return;
    119     }
    120 
    121     typedef int *(__stdcall *errno_func)(void);
    122     errno_func ssl_errno = (errno_func)GetProcAddress(ucrtbase, "_errno");
    123     if (ssl_errno) {
    124         errno = *ssl_errno();
    125         *ssl_errno() = 0;
    126     } else {
    127         errno = ENOTRECOVERABLE;
    128     }
    129 }
    130 
    131 #undef _PySSL_FIX_ERRNO
    132 #define _PySSL_FIX_ERRNO _PySSLFixErrno()
    133 #endif
    134 
    135 /* Include generated data (error codes) */
    136 #include "_ssl_data.h"
    137 
    138 #if (OPENSSL_VERSION_NUMBER >= 0x10100000L) && !defined(LIBRESSL_VERSION_NUMBER)
    139 #  define OPENSSL_VERSION_1_1 1
    140 #  define PY_OPENSSL_1_1_API 1
    141 #endif
    142 
    143 /* LibreSSL 2.7.0 provides necessary OpenSSL 1.1.0 APIs */
    144 #if defined(LIBRESSL_VERSION_NUMBER) && LIBRESSL_VERSION_NUMBER >= 0x2070000fL
    145 #  define PY_OPENSSL_1_1_API 1
    146 #endif
    147 
    148 /* Openssl comes with TLSv1.1 and TLSv1.2 between 1.0.0h and 1.0.1
    149     http://www.openssl.org/news/changelog.html
    150  */
    151 #if OPENSSL_VERSION_NUMBER >= 0x10001000L
    152 # define HAVE_TLSv1_2 1
    153 #else
    154 # define HAVE_TLSv1_2 0
    155 #endif
    156 
    157 /* SNI support (client- and server-side) appeared in OpenSSL 1.0.0 and 0.9.8f
    158  * This includes the SSL_set_SSL_CTX() function.
    159  */
    160 #ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
    161 # define HAVE_SNI 1
    162 #else
    163 # define HAVE_SNI 0
    164 #endif
    165 
    166 #ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
    167 # define HAVE_ALPN 1
    168 #else
    169 # define HAVE_ALPN 0
    170 #endif
    171 
    172 /* We cannot rely on OPENSSL_NO_NEXTPROTONEG because LibreSSL 2.6.1 dropped
    173  * NPN support but did not set OPENSSL_NO_NEXTPROTONEG for compatibility
    174  * reasons. The check for TLSEXT_TYPE_next_proto_neg works with
    175  * OpenSSL 1.0.1+ and LibreSSL.
    176  * OpenSSL 1.1.1-pre1 dropped NPN but still has TLSEXT_TYPE_next_proto_neg.
    177  */
    178 #ifdef OPENSSL_NO_NEXTPROTONEG
    179 # define HAVE_NPN 0
    180 #elif (OPENSSL_VERSION_NUMBER >= 0x10101000L) && !defined(LIBRESSL_VERSION_NUMBER)
    181 # define HAVE_NPN 0
    182 #elif defined(TLSEXT_TYPE_next_proto_neg)
    183 # define HAVE_NPN 1
    184 #else
    185 # define HAVE_NPN 0
    186 #endif
    187 
    188 #ifndef INVALID_SOCKET /* MS defines this */
    189 #define INVALID_SOCKET (-1)
    190 #endif
    191 
    192 /* OpenSSL 1.0.2 and LibreSSL needs extra code for locking */
    193 #ifndef OPENSSL_VERSION_1_1
    194 #define HAVE_OPENSSL_CRYPTO_LOCK
    195 #endif
    196 
    197 #if defined(OPENSSL_VERSION_1_1) && !defined(OPENSSL_NO_SSL2)
    198 #define OPENSSL_NO_SSL2
    199 #endif
    200 
    201 #ifndef PY_OPENSSL_1_1_API
    202 /* OpenSSL 1.1 API shims for OpenSSL < 1.1.0 and LibreSSL < 2.7.0 */
    203 
    204 #define TLS_method SSLv23_method
    205 #define TLS_client_method SSLv23_client_method
    206 #define TLS_server_method SSLv23_server_method
    207 
    208 static int X509_NAME_ENTRY_set(const X509_NAME_ENTRY *ne)
    209 {
    210     return ne->set;
    211 }
    212 
    213 #ifndef OPENSSL_NO_COMP
    214 /* LCOV_EXCL_START */
    215 static int COMP_get_type(const COMP_METHOD *meth)
    216 {
    217     return meth->type;
    218 }
    219 /* LCOV_EXCL_STOP */
    220 #endif
    221 
    222 static pem_password_cb *SSL_CTX_get_default_passwd_cb(SSL_CTX *ctx)
    223 {
    224     return ctx->default_passwd_callback;
    225 }
    226 
    227 static void *SSL_CTX_get_default_passwd_cb_userdata(SSL_CTX *ctx)
    228 {
    229     return ctx->default_passwd_callback_userdata;
    230 }
    231 
    232 static int X509_OBJECT_get_type(X509_OBJECT *x)
    233 {
    234     return x->type;
    235 }
    236 
    237 static X509 *X509_OBJECT_get0_X509(X509_OBJECT *x)
    238 {
    239     return x->data.x509;
    240 }
    241 
    242 static int BIO_up_ref(BIO *b)
    243 {
    244     CRYPTO_add(&b->references, 1, CRYPTO_LOCK_BIO);
    245     return 1;
    246 }
    247 
    248 static STACK_OF(X509_OBJECT) *X509_STORE_get0_objects(X509_STORE *store) {
    249     return store->objs;
    250 }
    251 
    252 static int
    253 SSL_SESSION_has_ticket(const SSL_SESSION *s)
    254 {
    255     return (s->tlsext_ticklen > 0) ? 1 : 0;
    256 }
    257 
    258 static unsigned long
    259 SSL_SESSION_get_ticket_lifetime_hint(const SSL_SESSION *s)
    260 {
    261     return s->tlsext_tick_lifetime_hint;
    262 }
    263 
    264 #endif /* OpenSSL < 1.1.0 or LibreSSL < 2.7.0 */
    265 
    266 /* Default cipher suites */
    267 #ifndef PY_SSL_DEFAULT_CIPHERS
    268 #define PY_SSL_DEFAULT_CIPHERS 1
    269 #endif
    270 
    271 #if PY_SSL_DEFAULT_CIPHERS == 0
    272   #ifndef PY_SSL_DEFAULT_CIPHER_STRING
    273      #error "Py_SSL_DEFAULT_CIPHERS 0 needs Py_SSL_DEFAULT_CIPHER_STRING"
    274   #endif
    275 #elif PY_SSL_DEFAULT_CIPHERS == 1
    276 /* Python custom selection of sensible cipher suites
    277  * DEFAULT: OpenSSL's default cipher list. Since 1.0.2 the list is in sensible order.
    278  * !aNULL:!eNULL: really no NULL ciphers
    279  * !MD5:!3DES:!DES:!RC4:!IDEA:!SEED: no weak or broken algorithms on old OpenSSL versions.
    280  * !aDSS: no authentication with discrete logarithm DSA algorithm
    281  * !SRP:!PSK: no secure remote password or pre-shared key authentication
    282  */
    283   #define PY_SSL_DEFAULT_CIPHER_STRING "DEFAULT:!aNULL:!eNULL:!MD5:!3DES:!DES:!RC4:!IDEA:!SEED:!aDSS:!SRP:!PSK"
    284 #elif PY_SSL_DEFAULT_CIPHERS == 2
    285 /* Ignored in SSLContext constructor, only used to as _ssl.DEFAULT_CIPHER_STRING */
    286   #define PY_SSL_DEFAULT_CIPHER_STRING SSL_DEFAULT_CIPHER_LIST
    287 #else
    288   #error "Unsupported PY_SSL_DEFAULT_CIPHERS"
    289 #endif
    290 
    291 
    292 enum py_ssl_error {
    293     /* these mirror ssl.h */
    294     PY_SSL_ERROR_NONE,
    295     PY_SSL_ERROR_SSL,
    296     PY_SSL_ERROR_WANT_READ,
    297     PY_SSL_ERROR_WANT_WRITE,
    298     PY_SSL_ERROR_WANT_X509_LOOKUP,
    299     PY_SSL_ERROR_SYSCALL,     /* look at error stack/return value/errno */
    300     PY_SSL_ERROR_ZERO_RETURN,
    301     PY_SSL_ERROR_WANT_CONNECT,
    302     /* start of non ssl.h errorcodes */
    303     PY_SSL_ERROR_EOF,         /* special case of SSL_ERROR_SYSCALL */
    304     PY_SSL_ERROR_NO_SOCKET,   /* socket has been GC'd */
    305     PY_SSL_ERROR_INVALID_ERROR_CODE
    306 };
    307 
    308 enum py_ssl_server_or_client {
    309     PY_SSL_CLIENT,
    310     PY_SSL_SERVER
    311 };
    312 
    313 enum py_ssl_cert_requirements {
    314     PY_SSL_CERT_NONE,
    315     PY_SSL_CERT_OPTIONAL,
    316     PY_SSL_CERT_REQUIRED
    317 };
    318 
    319 enum py_ssl_version {
    320     PY_SSL_VERSION_SSL2,
    321     PY_SSL_VERSION_SSL3=1,
    322     PY_SSL_VERSION_TLS, /* SSLv23 */
    323 #if HAVE_TLSv1_2
    324     PY_SSL_VERSION_TLS1,
    325     PY_SSL_VERSION_TLS1_1,
    326     PY_SSL_VERSION_TLS1_2,
    327 #else
    328     PY_SSL_VERSION_TLS1,
    329 #endif
    330     PY_SSL_VERSION_TLS_CLIENT=0x10,
    331     PY_SSL_VERSION_TLS_SERVER,
    332 };
    333 
    334 enum py_proto_version {
    335     PY_PROTO_MINIMUM_SUPPORTED = -2,
    336     PY_PROTO_SSLv3 = SSL3_VERSION,
    337     PY_PROTO_TLSv1 = TLS1_VERSION,
    338     PY_PROTO_TLSv1_1 = TLS1_1_VERSION,
    339     PY_PROTO_TLSv1_2 = TLS1_2_VERSION,
    340 #ifdef TLS1_3_VERSION
    341     PY_PROTO_TLSv1_3 = TLS1_3_VERSION,
    342 #else
    343     PY_PROTO_TLSv1_3 = 0x304,
    344 #endif
    345     PY_PROTO_MAXIMUM_SUPPORTED = -1,
    346 
    347 /* OpenSSL has no dedicated API to set the minimum version to the maximum
    348  * available version, and the other way around. We have to figure out the
    349  * minimum and maximum available version on our own and hope for the best.
    350  */
    351 #if defined(SSL3_VERSION) && !defined(OPENSSL_NO_SSL3)
    352     PY_PROTO_MINIMUM_AVAILABLE = PY_PROTO_SSLv3,
    353 #elif defined(TLS1_VERSION) && !defined(OPENSSL_NO_TLS1)
    354     PY_PROTO_MINIMUM_AVAILABLE = PY_PROTO_TLSv1,
    355 #elif defined(TLS1_1_VERSION) && !defined(OPENSSL_NO_TLS1_1)
    356     PY_PROTO_MINIMUM_AVAILABLE = PY_PROTO_TLSv1_1,
    357 #elif defined(TLS1_2_VERSION) && !defined(OPENSSL_NO_TLS1_2)
    358     PY_PROTO_MINIMUM_AVAILABLE = PY_PROTO_TLSv1_2,
    359 #elif defined(TLS1_3_VERSION) && !defined(OPENSSL_NO_TLS1_3)
    360     PY_PROTO_MINIMUM_AVAILABLE = PY_PROTO_TLSv1_3,
    361 #else
    362     #error "PY_PROTO_MINIMUM_AVAILABLE not found"
    363 #endif
    364 
    365 #if defined(TLS1_3_VERSION) && !defined(OPENSSL_NO_TLS1_3)
    366     PY_PROTO_MAXIMUM_AVAILABLE = PY_PROTO_TLSv1_3,
    367 #elif defined(TLS1_2_VERSION) && !defined(OPENSSL_NO_TLS1_2)
    368     PY_PROTO_MAXIMUM_AVAILABLE = PY_PROTO_TLSv1_2,
    369 #elif defined(TLS1_1_VERSION) && !defined(OPENSSL_NO_TLS1_1)
    370     PY_PROTO_MAXIMUM_AVAILABLE = PY_PROTO_TLSv1_1,
    371 #elif defined(TLS1_VERSION) && !defined(OPENSSL_NO_TLS1)
    372     PY_PROTO_MAXIMUM_AVAILABLE = PY_PROTO_TLSv1,
    373 #elif defined(SSL3_VERSION) && !defined(OPENSSL_NO_SSL3)
    374     PY_PROTO_MAXIMUM_AVAILABLE = PY_PROTO_SSLv3,
    375 #else
    376     #error "PY_PROTO_MAXIMUM_AVAILABLE not found"
    377 #endif
    378 };
    379 
    380 
    381 /* serves as a flag to see whether we've initialized the SSL thread support. */
    382 /* 0 means no, greater than 0 means yes */
    383 
    384 static unsigned int _ssl_locks_count = 0;
    385 
    386 /* SSL socket object */
    387 
    388 #define X509_NAME_MAXLEN 256
    389 
    390 /* SSL_CTX_clear_options() and SSL_clear_options() were first added in
    391  * OpenSSL 0.9.8m but do not appear in some 0.9.9-dev versions such the
    392  * 0.9.9 from "May 2008" that NetBSD 5.0 uses. */
    393 #if OPENSSL_VERSION_NUMBER >= 0x009080dfL && OPENSSL_VERSION_NUMBER != 0x00909000L
    394 # define HAVE_SSL_CTX_CLEAR_OPTIONS
    395 #else
    396 # undef HAVE_SSL_CTX_CLEAR_OPTIONS
    397 #endif
    398 
    399 /* In case of 'tls-unique' it will be 12 bytes for TLS, 36 bytes for
    400  * older SSL, but let's be safe */
    401 #define PySSL_CB_MAXLEN 128
    402 
    403 
    404 typedef struct {
    405     PyObject_HEAD
    406     SSL_CTX *ctx;
    407 #if HAVE_NPN
    408     unsigned char *npn_protocols;
    409     int npn_protocols_len;
    410 #endif
    411 #if HAVE_ALPN
    412     unsigned char *alpn_protocols;
    413     unsigned int alpn_protocols_len;
    414 #endif
    415 #ifndef OPENSSL_NO_TLSEXT
    416     PyObject *set_sni_cb;
    417 #endif
    418     int check_hostname;
    419     /* OpenSSL has no API to get hostflags from X509_VERIFY_PARAM* struct.
    420      * We have to maintain our own copy. OpenSSL's hostflags default to 0.
    421      */
    422     unsigned int hostflags;
    423     int protocol;
    424 #ifdef TLS1_3_VERSION
    425     int post_handshake_auth;
    426 #endif
    427 } PySSLContext;
    428 
    429 typedef struct {
    430     int ssl; /* last seen error from SSL */
    431     int c; /* last seen error from libc */
    432 #ifdef MS_WINDOWS
    433     int ws; /* last seen error from winsock */
    434 #endif
    435 } _PySSLError;
    436 
    437 typedef struct {
    438     PyObject_HEAD
    439     PyObject *Socket; /* weakref to socket on which we're layered */
    440     SSL *ssl;
    441     PySSLContext *ctx; /* weakref to SSL context */
    442     char shutdown_seen_zero;
    443     enum py_ssl_server_or_client socket_type;
    444     PyObject *owner; /* Python level "owner" passed to servername callback */
    445     PyObject *server_hostname;
    446     _PySSLError err; /* last seen error from various sources */
    447 } PySSLSocket;
    448 
    449 typedef struct {
    450     PyObject_HEAD
    451     BIO *bio;
    452     int eof_written;
    453 } PySSLMemoryBIO;
    454 
    455 typedef struct {
    456     PyObject_HEAD
    457     SSL_SESSION *session;
    458     PySSLContext *ctx;
    459 } PySSLSession;
    460 
    461 static PyTypeObject PySSLContext_Type;
    462 static PyTypeObject PySSLSocket_Type;
    463 static PyTypeObject PySSLMemoryBIO_Type;
    464 static PyTypeObject PySSLSession_Type;
    465 
    466 static inline _PySSLError _PySSL_errno(int failed, const SSL *ssl, int retcode)
    467 {
    468     _PySSLError err = { 0 };
    469     if (failed) {
    470 #ifdef MS_WINDOWS
    471         err.ws = WSAGetLastError();
    472         _PySSL_FIX_ERRNO;
    473 #endif
    474         err.c = errno;
    475         err.ssl = SSL_get_error(ssl, retcode);
    476     }
    477     return err;
    478 }
    479 
    480 /*[clinic input]
    481 module _ssl
    482 class _ssl._SSLContext "PySSLContext *" "&PySSLContext_Type"
    483 class _ssl._SSLSocket "PySSLSocket *" "&PySSLSocket_Type"
    484 class _ssl.MemoryBIO "PySSLMemoryBIO *" "&PySSLMemoryBIO_Type"
    485 class _ssl.SSLSession "PySSLSession *" "&PySSLSession_Type"
    486 [clinic start generated code]*/
    487 /*[clinic end generated code: output=da39a3ee5e6b4b0d input=bdc67fafeeaa8109]*/
    488 
    489 #include "clinic/_ssl.c.h"
    490 
    491 static int PySSL_select(PySocketSockObject *s, int writing, _PyTime_t timeout);
    492 
    493 static int PySSL_set_owner(PySSLSocket *, PyObject *, void *);
    494 static int PySSL_set_session(PySSLSocket *, PyObject *, void *);
    495 #define PySSLSocket_Check(v)    (Py_TYPE(v) == &PySSLSocket_Type)
    496 #define PySSLMemoryBIO_Check(v)    (Py_TYPE(v) == &PySSLMemoryBIO_Type)
    497 #define PySSLSession_Check(v)   (Py_TYPE(v) == &PySSLSession_Type)
    498 
    499 typedef enum {
    500     SOCKET_IS_NONBLOCKING,
    501     SOCKET_IS_BLOCKING,
    502     SOCKET_HAS_TIMED_OUT,
    503     SOCKET_HAS_BEEN_CLOSED,
    504     SOCKET_TOO_LARGE_FOR_SELECT,
    505     SOCKET_OPERATION_OK
    506 } timeout_state;
    507 
    508 /* Wrap error strings with filename and line # */
    509 #define ERRSTR1(x,y,z) (x ":" y ": " z)
    510 #define ERRSTR(x) ERRSTR1("_ssl.c", Py_STRINGIFY(__LINE__), x)
    511 
    512 /* Get the socket from a PySSLSocket, if it has one */
    513 #define GET_SOCKET(obj) ((obj)->Socket ? \
    514     (PySocketSockObject *) PyWeakref_GetObject((obj)->Socket) : NULL)
    515 
    516 /* If sock is NULL, use a timeout of 0 second */
    517 #define GET_SOCKET_TIMEOUT(sock) \
    518     ((sock != NULL) ? (sock)->sock_timeout : 0)
    519 
    520 /*
    521  * SSL errors.
    522  */
    523 
    524 PyDoc_STRVAR(SSLError_doc,
    525 "An error occurred in the SSL implementation.");
    526 
    527 PyDoc_STRVAR(SSLCertVerificationError_doc,
    528 "A certificate could not be verified.");
    529 
    530 PyDoc_STRVAR(SSLZeroReturnError_doc,
    531 "SSL/TLS session closed cleanly.");
    532 
    533 PyDoc_STRVAR(SSLWantReadError_doc,
    534 "Non-blocking SSL socket needs to read more data\n"
    535 "before the requested operation can be completed.");
    536 
    537 PyDoc_STRVAR(SSLWantWriteError_doc,
    538 "Non-blocking SSL socket needs to write more data\n"
    539 "before the requested operation can be completed.");
    540 
    541 PyDoc_STRVAR(SSLSyscallError_doc,
    542 "System error when attempting SSL operation.");
    543 
    544 PyDoc_STRVAR(SSLEOFError_doc,
    545 "SSL/TLS connection terminated abruptly.");
    546 
    547 static PyObject *
    548 SSLError_str(PyOSErrorObject *self)
    549 {
    550     if (self->strerror != NULL && PyUnicode_Check(self->strerror)) {
    551         Py_INCREF(self->strerror);
    552         return self->strerror;
    553     }
    554     else
    555         return PyObject_Str(self->args);
    556 }
    557 
    558 static PyType_Slot sslerror_type_slots[] = {
    559     {Py_tp_base, NULL},  /* Filled out in module init as it's not a constant */
    560     {Py_tp_doc, SSLError_doc},
    561     {Py_tp_str, SSLError_str},
    562     {0, 0},
    563 };
    564 
    565 static PyType_Spec sslerror_type_spec = {
    566     "ssl.SSLError",
    567     sizeof(PyOSErrorObject),
    568     0,
    569     Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
    570     sslerror_type_slots
    571 };
    572 
    573 static void
    574 fill_and_set_sslerror(PySSLSocket *sslsock, PyObject *type, int ssl_errno,
    575                       const char *errstr, int lineno, unsigned long errcode)
    576 {
    577     PyObject *err_value = NULL, *reason_obj = NULL, *lib_obj = NULL;
    578     PyObject *verify_obj = NULL, *verify_code_obj = NULL;
    579     PyObject *init_value, *msg, *key;
    580     _Py_IDENTIFIER(reason);
    581     _Py_IDENTIFIER(library);
    582     _Py_IDENTIFIER(verify_message);
    583     _Py_IDENTIFIER(verify_code);
    584 
    585     if (errcode != 0) {
    586         int lib, reason;
    587 
    588         lib = ERR_GET_LIB(errcode);
    589         reason = ERR_GET_REASON(errcode);
    590         key = Py_BuildValue("ii", lib, reason);
    591         if (key == NULL)
    592             goto fail;
    593         reason_obj = PyDict_GetItem(err_codes_to_names, key);
    594         Py_DECREF(key);
    595         if (reason_obj == NULL) {
    596             /* XXX if reason < 100, it might reflect a library number (!!) */
    597             PyErr_Clear();
    598         }
    599         key = PyLong_FromLong(lib);
    600         if (key == NULL)
    601             goto fail;
    602         lib_obj = PyDict_GetItem(lib_codes_to_names, key);
    603         Py_DECREF(key);
    604         if (lib_obj == NULL) {
    605             PyErr_Clear();
    606         }
    607         if (errstr == NULL)
    608             errstr = ERR_reason_error_string(errcode);
    609     }
    610     if (errstr == NULL)
    611         errstr = "unknown error";
    612 
    613     /* verify code for cert validation error */
    614     if ((sslsock != NULL) && (type == PySSLCertVerificationErrorObject)) {
    615         const char *verify_str = NULL;
    616         long verify_code;
    617 
    618         verify_code = SSL_get_verify_result(sslsock->ssl);
    619         verify_code_obj = PyLong_FromLong(verify_code);
    620         if (verify_code_obj == NULL) {
    621             goto fail;
    622         }
    623 
    624         switch (verify_code) {
    625 #ifdef X509_V_ERR_HOSTNAME_MISMATCH
    626         /* OpenSSL >= 1.0.2, LibreSSL >= 2.5.3 */
    627         case X509_V_ERR_HOSTNAME_MISMATCH:
    628             verify_obj = PyUnicode_FromFormat(
    629                 "Hostname mismatch, certificate is not valid for '%S'.",
    630                 sslsock->server_hostname
    631             );
    632             break;
    633 #endif
    634 #ifdef X509_V_ERR_IP_ADDRESS_MISMATCH
    635         case X509_V_ERR_IP_ADDRESS_MISMATCH:
    636             verify_obj = PyUnicode_FromFormat(
    637                 "IP address mismatch, certificate is not valid for '%S'.",
    638                 sslsock->server_hostname
    639             );
    640             break;
    641 #endif
    642         default:
    643             verify_str = X509_verify_cert_error_string(verify_code);
    644             if (verify_str != NULL) {
    645                 verify_obj = PyUnicode_FromString(verify_str);
    646             } else {
    647                 verify_obj = Py_None;
    648                 Py_INCREF(verify_obj);
    649             }
    650             break;
    651         }
    652         if (verify_obj == NULL) {
    653             goto fail;
    654         }
    655     }
    656 
    657     if (verify_obj && reason_obj && lib_obj)
    658         msg = PyUnicode_FromFormat("[%S: %S] %s: %S (_ssl.c:%d)",
    659                                    lib_obj, reason_obj, errstr, verify_obj,
    660                                    lineno);
    661     else if (reason_obj && lib_obj)
    662         msg = PyUnicode_FromFormat("[%S: %S] %s (_ssl.c:%d)",
    663                                    lib_obj, reason_obj, errstr, lineno);
    664     else if (lib_obj)
    665         msg = PyUnicode_FromFormat("[%S] %s (_ssl.c:%d)",
    666                                    lib_obj, errstr, lineno);
    667     else
    668         msg = PyUnicode_FromFormat("%s (_ssl.c:%d)", errstr, lineno);
    669     if (msg == NULL)
    670         goto fail;
    671 
    672     init_value = Py_BuildValue("iN", ssl_errno, msg);
    673     if (init_value == NULL)
    674         goto fail;
    675 
    676     err_value = PyObject_CallObject(type, init_value);
    677     Py_DECREF(init_value);
    678     if (err_value == NULL)
    679         goto fail;
    680 
    681     if (reason_obj == NULL)
    682         reason_obj = Py_None;
    683     if (_PyObject_SetAttrId(err_value, &PyId_reason, reason_obj))
    684         goto fail;
    685 
    686     if (lib_obj == NULL)
    687         lib_obj = Py_None;
    688     if (_PyObject_SetAttrId(err_value, &PyId_library, lib_obj))
    689         goto fail;
    690 
    691     if ((sslsock != NULL) && (type == PySSLCertVerificationErrorObject)) {
    692         /* Only set verify code / message for SSLCertVerificationError */
    693         if (_PyObject_SetAttrId(err_value, &PyId_verify_code,
    694                                 verify_code_obj))
    695             goto fail;
    696         if (_PyObject_SetAttrId(err_value, &PyId_verify_message, verify_obj))
    697             goto fail;
    698     }
    699 
    700     PyErr_SetObject(type, err_value);
    701 fail:
    702     Py_XDECREF(err_value);
    703     Py_XDECREF(verify_code_obj);
    704     Py_XDECREF(verify_obj);
    705 }
    706 
    707 static PyObject *
    708 PySSL_SetError(PySSLSocket *sslsock, int ret, const char *filename, int lineno)
    709 {
    710     PyObject *type = PySSLErrorObject;
    711     char *errstr = NULL;
    712     _PySSLError err;
    713     enum py_ssl_error p = PY_SSL_ERROR_NONE;
    714     unsigned long e = 0;
    715 
    716     assert(ret <= 0);
    717     e = ERR_peek_last_error();
    718 
    719     if (sslsock->ssl != NULL) {
    720         err = sslsock->err;
    721 
    722         switch (err.ssl) {
    723         case SSL_ERROR_ZERO_RETURN:
    724             errstr = "TLS/SSL connection has been closed (EOF)";
    725             type = PySSLZeroReturnErrorObject;
    726             p = PY_SSL_ERROR_ZERO_RETURN;
    727             break;
    728         case SSL_ERROR_WANT_READ:
    729             errstr = "The operation did not complete (read)";
    730             type = PySSLWantReadErrorObject;
    731             p = PY_SSL_ERROR_WANT_READ;
    732             break;
    733         case SSL_ERROR_WANT_WRITE:
    734             p = PY_SSL_ERROR_WANT_WRITE;
    735             type = PySSLWantWriteErrorObject;
    736             errstr = "The operation did not complete (write)";
    737             break;
    738         case SSL_ERROR_WANT_X509_LOOKUP:
    739             p = PY_SSL_ERROR_WANT_X509_LOOKUP;
    740             errstr = "The operation did not complete (X509 lookup)";
    741             break;
    742         case SSL_ERROR_WANT_CONNECT:
    743             p = PY_SSL_ERROR_WANT_CONNECT;
    744             errstr = "The operation did not complete (connect)";
    745             break;
    746         case SSL_ERROR_SYSCALL:
    747         {
    748             if (e == 0) {
    749                 PySocketSockObject *s = GET_SOCKET(sslsock);
    750                 if (ret == 0 || (((PyObject *)s) == Py_None)) {
    751                     p = PY_SSL_ERROR_EOF;
    752                     type = PySSLEOFErrorObject;
    753                     errstr = "EOF occurred in violation of protocol";
    754                 } else if (s && ret == -1) {
    755                     /* underlying BIO reported an I/O error */
    756                     ERR_clear_error();
    757 #ifdef MS_WINDOWS
    758                     if (err.ws) {
    759                         return PyErr_SetFromWindowsErr(err.ws);
    760                     }
    761 #endif
    762                     if (err.c) {
    763                         errno = err.c;
    764                         return PyErr_SetFromErrno(PyExc_OSError);
    765                     }
    766                     Py_INCREF(s);
    767                     s->errorhandler();
    768                     Py_DECREF(s);
    769                     return NULL;
    770                 } else { /* possible? */
    771                     p = PY_SSL_ERROR_SYSCALL;
    772                     type = PySSLSyscallErrorObject;
    773                     errstr = "Some I/O error occurred";
    774                 }
    775             } else {
    776                 p = PY_SSL_ERROR_SYSCALL;
    777             }
    778             break;
    779         }
    780         case SSL_ERROR_SSL:
    781         {
    782             p = PY_SSL_ERROR_SSL;
    783             if (e == 0) {
    784                 /* possible? */
    785                 errstr = "A failure in the SSL library occurred";
    786             }
    787             if (ERR_GET_LIB(e) == ERR_LIB_SSL &&
    788                     ERR_GET_REASON(e) == SSL_R_CERTIFICATE_VERIFY_FAILED) {
    789                 type = PySSLCertVerificationErrorObject;
    790             }
    791             break;
    792         }
    793         default:
    794             p = PY_SSL_ERROR_INVALID_ERROR_CODE;
    795             errstr = "Invalid error code";
    796         }
    797     }
    798     fill_and_set_sslerror(sslsock, type, p, errstr, lineno, e);
    799     ERR_clear_error();
    800     return NULL;
    801 }
    802 
    803 static PyObject *
    804 _setSSLError (const char *errstr, int errcode, const char *filename, int lineno) {
    805 
    806     if (errstr == NULL)
    807         errcode = ERR_peek_last_error();
    808     else
    809         errcode = 0;
    810     fill_and_set_sslerror(NULL, PySSLErrorObject, errcode, errstr, lineno, errcode);
    811     ERR_clear_error();
    812     return NULL;
    813 }
    814 
    815 /*
    816  * SSL objects
    817  */
    818 
    819 static int
    820 _ssl_configure_hostname(PySSLSocket *self, const char* server_hostname)
    821 {
    822     int retval = -1;
    823     ASN1_OCTET_STRING *ip;
    824     PyObject *hostname;
    825     size_t len;
    826 
    827     assert(server_hostname);
    828 
    829     /* Disable OpenSSL's special mode with leading dot in hostname:
    830      * When name starts with a dot (e.g ".example.com"), it will be
    831      * matched by a certificate valid for any sub-domain of name.
    832      */
    833     len = strlen(server_hostname);
    834     if (len == 0 || *server_hostname == '.') {
    835         PyErr_SetString(
    836             PyExc_ValueError,
    837             "server_hostname cannot be an empty string or start with a "
    838             "leading dot.");
    839         return retval;
    840     }
    841 
    842     /* inet_pton is not available on all platforms. */
    843     ip = a2i_IPADDRESS(server_hostname);
    844     if (ip == NULL) {
    845         ERR_clear_error();
    846     }
    847 
    848     hostname = PyUnicode_Decode(server_hostname, len, "ascii", "strict");
    849     if (hostname == NULL) {
    850         goto error;
    851     }
    852     self->server_hostname = hostname;
    853 
    854     /* Only send SNI extension for non-IP hostnames */
    855     if (ip == NULL) {
    856         if (!SSL_set_tlsext_host_name(self->ssl, server_hostname)) {
    857             _setSSLError(NULL, 0, __FILE__, __LINE__);
    858         }
    859     }
    860     if (self->ctx->check_hostname) {
    861         X509_VERIFY_PARAM *param = SSL_get0_param(self->ssl);
    862         if (ip == NULL) {
    863             if (!X509_VERIFY_PARAM_set1_host(param, server_hostname,
    864                                              strlen(server_hostname))) {
    865                 _setSSLError(NULL, 0, __FILE__, __LINE__);
    866                 goto error;
    867             }
    868         } else {
    869             if (!X509_VERIFY_PARAM_set1_ip(param, ASN1_STRING_data(ip),
    870                                            ASN1_STRING_length(ip))) {
    871                 _setSSLError(NULL, 0, __FILE__, __LINE__);
    872                 goto error;
    873             }
    874         }
    875     }
    876     retval = 0;
    877   error:
    878     if (ip != NULL) {
    879         ASN1_OCTET_STRING_free(ip);
    880     }
    881     return retval;
    882 }
    883 
    884 static PySSLSocket *
    885 newPySSLSocket(PySSLContext *sslctx, PySocketSockObject *sock,
    886                enum py_ssl_server_or_client socket_type,
    887                char *server_hostname,
    888                PyObject *owner, PyObject *session,
    889                PySSLMemoryBIO *inbio, PySSLMemoryBIO *outbio)
    890 {
    891     PySSLSocket *self;
    892     SSL_CTX *ctx = sslctx->ctx;
    893     _PySSLError err = { 0 };
    894 
    895     self = PyObject_New(PySSLSocket, &PySSLSocket_Type);
    896     if (self == NULL)
    897         return NULL;
    898 
    899     self->ssl = NULL;
    900     self->Socket = NULL;
    901     self->ctx = sslctx;
    902     Py_INCREF(sslctx);
    903     self->shutdown_seen_zero = 0;
    904     self->owner = NULL;
    905     self->server_hostname = NULL;
    906     self->err = err;
    907 
    908     /* Make sure the SSL error state is initialized */
    909     (void) ERR_get_state();
    910     ERR_clear_error();
    911 
    912     PySSL_BEGIN_ALLOW_THREADS
    913     self->ssl = SSL_new(ctx);
    914     PySSL_END_ALLOW_THREADS
    915     if (self->ssl == NULL) {
    916         Py_DECREF(self);
    917         _setSSLError(NULL, 0, __FILE__, __LINE__);
    918         return NULL;
    919     }
    920     SSL_set_app_data(self->ssl, self);
    921     if (sock) {
    922         SSL_set_fd(self->ssl, Py_SAFE_DOWNCAST(sock->sock_fd, SOCKET_T, int));
    923     } else {
    924         /* BIOs are reference counted and SSL_set_bio borrows our reference.
    925          * To prevent a double free in memory_bio_dealloc() we need to take an
    926          * extra reference here. */
    927         BIO_up_ref(inbio->bio);
    928         BIO_up_ref(outbio->bio);
    929         SSL_set_bio(self->ssl, inbio->bio, outbio->bio);
    930     }
    931     SSL_set_mode(self->ssl,
    932                  SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER | SSL_MODE_AUTO_RETRY);
    933 
    934     if (server_hostname != NULL) {
    935         if (_ssl_configure_hostname(self, server_hostname) < 0) {
    936             Py_DECREF(self);
    937             return NULL;
    938         }
    939     }
    940     /* If the socket is in non-blocking mode or timeout mode, set the BIO
    941      * to non-blocking mode (blocking is the default)
    942      */
    943     if (sock && sock->sock_timeout >= 0) {
    944         BIO_set_nbio(SSL_get_rbio(self->ssl), 1);
    945         BIO_set_nbio(SSL_get_wbio(self->ssl), 1);
    946     }
    947 
    948     PySSL_BEGIN_ALLOW_THREADS
    949     if (socket_type == PY_SSL_CLIENT)
    950         SSL_set_connect_state(self->ssl);
    951     else
    952         SSL_set_accept_state(self->ssl);
    953     PySSL_END_ALLOW_THREADS
    954 
    955     self->socket_type = socket_type;
    956     if (sock != NULL) {
    957         self->Socket = PyWeakref_NewRef((PyObject *) sock, NULL);
    958         if (self->Socket == NULL) {
    959             Py_DECREF(self);
    960             return NULL;
    961         }
    962     }
    963     if (owner && owner != Py_None) {
    964         if (PySSL_set_owner(self, owner, NULL) == -1) {
    965             Py_DECREF(self);
    966             return NULL;
    967         }
    968     }
    969     if (session && session != Py_None) {
    970         if (PySSL_set_session(self, session, NULL) == -1) {
    971             Py_DECREF(self);
    972             return NULL;
    973         }
    974     }
    975     return self;
    976 }
    977 
    978 /* SSL object methods */
    979 
    980 /*[clinic input]
    981 _ssl._SSLSocket.do_handshake
    982 [clinic start generated code]*/
    983 
    984 static PyObject *
    985 _ssl__SSLSocket_do_handshake_impl(PySSLSocket *self)
    986 /*[clinic end generated code: output=6c0898a8936548f6 input=d2d737de3df018c8]*/
    987 {
    988     int ret;
    989     _PySSLError err;
    990     int sockstate, nonblocking;
    991     PySocketSockObject *sock = GET_SOCKET(self);
    992     _PyTime_t timeout, deadline = 0;
    993     int has_timeout;
    994 
    995     if (sock) {
    996         if (((PyObject*)sock) == Py_None) {
    997             _setSSLError("Underlying socket connection gone",
    998                          PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
    999             return NULL;
   1000         }
   1001         Py_INCREF(sock);
   1002 
   1003         /* just in case the blocking state of the socket has been changed */
   1004         nonblocking = (sock->sock_timeout >= 0);
   1005         BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
   1006         BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
   1007     }
   1008 
   1009     timeout = GET_SOCKET_TIMEOUT(sock);
   1010     has_timeout = (timeout > 0);
   1011     if (has_timeout)
   1012         deadline = _PyTime_GetMonotonicClock() + timeout;
   1013 
   1014     /* Actually negotiate SSL connection */
   1015     /* XXX If SSL_do_handshake() returns 0, it's also a failure. */
   1016     do {
   1017         PySSL_BEGIN_ALLOW_THREADS
   1018         ret = SSL_do_handshake(self->ssl);
   1019         err = _PySSL_errno(ret < 1, self->ssl, ret);
   1020         PySSL_END_ALLOW_THREADS
   1021         self->err = err;
   1022 
   1023         if (PyErr_CheckSignals())
   1024             goto error;
   1025 
   1026         if (has_timeout)
   1027             timeout = deadline - _PyTime_GetMonotonicClock();
   1028 
   1029         if (err.ssl == SSL_ERROR_WANT_READ) {
   1030             sockstate = PySSL_select(sock, 0, timeout);
   1031         } else if (err.ssl == SSL_ERROR_WANT_WRITE) {
   1032             sockstate = PySSL_select(sock, 1, timeout);
   1033         } else {
   1034             sockstate = SOCKET_OPERATION_OK;
   1035         }
   1036 
   1037         if (sockstate == SOCKET_HAS_TIMED_OUT) {
   1038             PyErr_SetString(PySocketModule.timeout_error,
   1039                             ERRSTR("The handshake operation timed out"));
   1040             goto error;
   1041         } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
   1042             PyErr_SetString(PySSLErrorObject,
   1043                             ERRSTR("Underlying socket has been closed."));
   1044             goto error;
   1045         } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
   1046             PyErr_SetString(PySSLErrorObject,
   1047                             ERRSTR("Underlying socket too large for select()."));
   1048             goto error;
   1049         } else if (sockstate == SOCKET_IS_NONBLOCKING) {
   1050             break;
   1051         }
   1052     } while (err.ssl == SSL_ERROR_WANT_READ ||
   1053              err.ssl == SSL_ERROR_WANT_WRITE);
   1054     Py_XDECREF(sock);
   1055     if (ret < 1)
   1056         return PySSL_SetError(self, ret, __FILE__, __LINE__);
   1057 
   1058     Py_RETURN_NONE;
   1059 
   1060 error:
   1061     Py_XDECREF(sock);
   1062     return NULL;
   1063 }
   1064 
   1065 static PyObject *
   1066 _asn1obj2py(const ASN1_OBJECT *name, int no_name)
   1067 {
   1068     char buf[X509_NAME_MAXLEN];
   1069     char *namebuf = buf;
   1070     int buflen;
   1071     PyObject *name_obj = NULL;
   1072 
   1073     buflen = OBJ_obj2txt(namebuf, X509_NAME_MAXLEN, name, no_name);
   1074     if (buflen < 0) {
   1075         _setSSLError(NULL, 0, __FILE__, __LINE__);
   1076         return NULL;
   1077     }
   1078     /* initial buffer is too small for oid + terminating null byte */
   1079     if (buflen > X509_NAME_MAXLEN - 1) {
   1080         /* make OBJ_obj2txt() calculate the required buflen */
   1081         buflen = OBJ_obj2txt(NULL, 0, name, no_name);
   1082         /* allocate len + 1 for terminating NULL byte */
   1083         namebuf = PyMem_Malloc(buflen + 1);
   1084         if (namebuf == NULL) {
   1085             PyErr_NoMemory();
   1086             return NULL;
   1087         }
   1088         buflen = OBJ_obj2txt(namebuf, buflen + 1, name, no_name);
   1089         if (buflen < 0) {
   1090             _setSSLError(NULL, 0, __FILE__, __LINE__);
   1091             goto done;
   1092         }
   1093     }
   1094     if (!buflen && no_name) {
   1095         Py_INCREF(Py_None);
   1096         name_obj = Py_None;
   1097     }
   1098     else {
   1099         name_obj = PyUnicode_FromStringAndSize(namebuf, buflen);
   1100     }
   1101 
   1102   done:
   1103     if (buf != namebuf) {
   1104         PyMem_Free(namebuf);
   1105     }
   1106     return name_obj;
   1107 }
   1108 
   1109 static PyObject *
   1110 _create_tuple_for_attribute(ASN1_OBJECT *name, ASN1_STRING *value)
   1111 {
   1112     Py_ssize_t buflen;
   1113     unsigned char *valuebuf = NULL;
   1114     PyObject *attr;
   1115 
   1116     buflen = ASN1_STRING_to_UTF8(&valuebuf, value);
   1117     if (buflen < 0) {
   1118         _setSSLError(NULL, 0, __FILE__, __LINE__);
   1119         return NULL;
   1120     }
   1121     attr = Py_BuildValue("Ns#", _asn1obj2py(name, 0), valuebuf, buflen);
   1122     OPENSSL_free(valuebuf);
   1123     return attr;
   1124 }
   1125 
   1126 static PyObject *
   1127 _create_tuple_for_X509_NAME (X509_NAME *xname)
   1128 {
   1129     PyObject *dn = NULL;    /* tuple which represents the "distinguished name" */
   1130     PyObject *rdn = NULL;   /* tuple to hold a "relative distinguished name" */
   1131     PyObject *rdnt;
   1132     PyObject *attr = NULL;   /* tuple to hold an attribute */
   1133     int entry_count = X509_NAME_entry_count(xname);
   1134     X509_NAME_ENTRY *entry;
   1135     ASN1_OBJECT *name;
   1136     ASN1_STRING *value;
   1137     int index_counter;
   1138     int rdn_level = -1;
   1139     int retcode;
   1140 
   1141     dn = PyList_New(0);
   1142     if (dn == NULL)
   1143         return NULL;
   1144     /* now create another tuple to hold the top-level RDN */
   1145     rdn = PyList_New(0);
   1146     if (rdn == NULL)
   1147         goto fail0;
   1148 
   1149     for (index_counter = 0;
   1150          index_counter < entry_count;
   1151          index_counter++)
   1152     {
   1153         entry = X509_NAME_get_entry(xname, index_counter);
   1154 
   1155         /* check to see if we've gotten to a new RDN */
   1156         if (rdn_level >= 0) {
   1157             if (rdn_level != X509_NAME_ENTRY_set(entry)) {
   1158                 /* yes, new RDN */
   1159                 /* add old RDN to DN */
   1160                 rdnt = PyList_AsTuple(rdn);
   1161                 Py_DECREF(rdn);
   1162                 if (rdnt == NULL)
   1163                     goto fail0;
   1164                 retcode = PyList_Append(dn, rdnt);
   1165                 Py_DECREF(rdnt);
   1166                 if (retcode < 0)
   1167                     goto fail0;
   1168                 /* create new RDN */
   1169                 rdn = PyList_New(0);
   1170                 if (rdn == NULL)
   1171                     goto fail0;
   1172             }
   1173         }
   1174         rdn_level = X509_NAME_ENTRY_set(entry);
   1175 
   1176         /* now add this attribute to the current RDN */
   1177         name = X509_NAME_ENTRY_get_object(entry);
   1178         value = X509_NAME_ENTRY_get_data(entry);
   1179         attr = _create_tuple_for_attribute(name, value);
   1180         /*
   1181         fprintf(stderr, "RDN level %d, attribute %s: %s\n",
   1182             entry->set,
   1183             PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 0)),
   1184             PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 1)));
   1185         */
   1186         if (attr == NULL)
   1187             goto fail1;
   1188         retcode = PyList_Append(rdn, attr);
   1189         Py_DECREF(attr);
   1190         if (retcode < 0)
   1191             goto fail1;
   1192     }
   1193     /* now, there's typically a dangling RDN */
   1194     if (rdn != NULL) {
   1195         if (PyList_GET_SIZE(rdn) > 0) {
   1196             rdnt = PyList_AsTuple(rdn);
   1197             Py_DECREF(rdn);
   1198             if (rdnt == NULL)
   1199                 goto fail0;
   1200             retcode = PyList_Append(dn, rdnt);
   1201             Py_DECREF(rdnt);
   1202             if (retcode < 0)
   1203                 goto fail0;
   1204         }
   1205         else {
   1206             Py_DECREF(rdn);
   1207         }
   1208     }
   1209 
   1210     /* convert list to tuple */
   1211     rdnt = PyList_AsTuple(dn);
   1212     Py_DECREF(dn);
   1213     if (rdnt == NULL)
   1214         return NULL;
   1215     return rdnt;
   1216 
   1217   fail1:
   1218     Py_XDECREF(rdn);
   1219 
   1220   fail0:
   1221     Py_XDECREF(dn);
   1222     return NULL;
   1223 }
   1224 
   1225 static PyObject *
   1226 _get_peer_alt_names (X509 *certificate) {
   1227 
   1228     /* this code follows the procedure outlined in
   1229        OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print()
   1230        function to extract the STACK_OF(GENERAL_NAME),
   1231        then iterates through the stack to add the
   1232        names. */
   1233 
   1234     int j;
   1235     PyObject *peer_alt_names = Py_None;
   1236     PyObject *v = NULL, *t;
   1237     GENERAL_NAMES *names = NULL;
   1238     GENERAL_NAME *name;
   1239     BIO *biobuf = NULL;
   1240     char buf[2048];
   1241     char *vptr;
   1242     int len;
   1243 
   1244     if (certificate == NULL)
   1245         return peer_alt_names;
   1246 
   1247     /* get a memory buffer */
   1248     biobuf = BIO_new(BIO_s_mem());
   1249     if (biobuf == NULL) {
   1250         PyErr_SetString(PySSLErrorObject, "failed to allocate BIO");
   1251         return NULL;
   1252     }
   1253 
   1254     names = (GENERAL_NAMES *)X509_get_ext_d2i(
   1255         certificate, NID_subject_alt_name, NULL, NULL);
   1256     if (names != NULL) {
   1257         if (peer_alt_names == Py_None) {
   1258             peer_alt_names = PyList_New(0);
   1259             if (peer_alt_names == NULL)
   1260                 goto fail;
   1261         }
   1262 
   1263         for(j = 0; j < sk_GENERAL_NAME_num(names); j++) {
   1264             /* get a rendering of each name in the set of names */
   1265             int gntype;
   1266             ASN1_STRING *as = NULL;
   1267 
   1268             name = sk_GENERAL_NAME_value(names, j);
   1269             gntype = name->type;
   1270             switch (gntype) {
   1271             case GEN_DIRNAME:
   1272                 /* we special-case DirName as a tuple of
   1273                    tuples of attributes */
   1274 
   1275                 t = PyTuple_New(2);
   1276                 if (t == NULL) {
   1277                     goto fail;
   1278                 }
   1279 
   1280                 v = PyUnicode_FromString("DirName");
   1281                 if (v == NULL) {
   1282                     Py_DECREF(t);
   1283                     goto fail;
   1284                 }
   1285                 PyTuple_SET_ITEM(t, 0, v);
   1286 
   1287                 v = _create_tuple_for_X509_NAME (name->d.dirn);
   1288                 if (v == NULL) {
   1289                     Py_DECREF(t);
   1290                     goto fail;
   1291                 }
   1292                 PyTuple_SET_ITEM(t, 1, v);
   1293                 break;
   1294 
   1295             case GEN_EMAIL:
   1296             case GEN_DNS:
   1297             case GEN_URI:
   1298                 /* GENERAL_NAME_print() doesn't handle NULL bytes in ASN1_string
   1299                    correctly, CVE-2013-4238 */
   1300                 t = PyTuple_New(2);
   1301                 if (t == NULL)
   1302                     goto fail;
   1303                 switch (gntype) {
   1304                 case GEN_EMAIL:
   1305                     v = PyUnicode_FromString("email");
   1306                     as = name->d.rfc822Name;
   1307                     break;
   1308                 case GEN_DNS:
   1309                     v = PyUnicode_FromString("DNS");
   1310                     as = name->d.dNSName;
   1311                     break;
   1312                 case GEN_URI:
   1313                     v = PyUnicode_FromString("URI");
   1314                     as = name->d.uniformResourceIdentifier;
   1315                     break;
   1316                 }
   1317                 if (v == NULL) {
   1318                     Py_DECREF(t);
   1319                     goto fail;
   1320                 }
   1321                 PyTuple_SET_ITEM(t, 0, v);
   1322                 v = PyUnicode_FromStringAndSize((char *)ASN1_STRING_data(as),
   1323                                                 ASN1_STRING_length(as));
   1324                 if (v == NULL) {
   1325                     Py_DECREF(t);
   1326                     goto fail;
   1327                 }
   1328                 PyTuple_SET_ITEM(t, 1, v);
   1329                 break;
   1330 
   1331             case GEN_RID:
   1332                 t = PyTuple_New(2);
   1333                 if (t == NULL)
   1334                     goto fail;
   1335 
   1336                 v = PyUnicode_FromString("Registered ID");
   1337                 if (v == NULL) {
   1338                     Py_DECREF(t);
   1339                     goto fail;
   1340                 }
   1341                 PyTuple_SET_ITEM(t, 0, v);
   1342 
   1343                 len = i2t_ASN1_OBJECT(buf, sizeof(buf)-1, name->d.rid);
   1344                 if (len < 0) {
   1345                     Py_DECREF(t);
   1346                     _setSSLError(NULL, 0, __FILE__, __LINE__);
   1347                     goto fail;
   1348                 } else if (len >= (int)sizeof(buf)) {
   1349                     v = PyUnicode_FromString("<INVALID>");
   1350                 } else {
   1351                     v = PyUnicode_FromStringAndSize(buf, len);
   1352                 }
   1353                 if (v == NULL) {
   1354                     Py_DECREF(t);
   1355                     goto fail;
   1356                 }
   1357                 PyTuple_SET_ITEM(t, 1, v);
   1358                 break;
   1359 
   1360             default:
   1361                 /* for everything else, we use the OpenSSL print form */
   1362                 switch (gntype) {
   1363                     /* check for new general name type */
   1364                     case GEN_OTHERNAME:
   1365                     case GEN_X400:
   1366                     case GEN_EDIPARTY:
   1367                     case GEN_IPADD:
   1368                     case GEN_RID:
   1369                         break;
   1370                     default:
   1371                         if (PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
   1372                                              "Unknown general name type %d",
   1373                                              gntype) == -1) {
   1374                             goto fail;
   1375                         }
   1376                         break;
   1377                 }
   1378                 (void) BIO_reset(biobuf);
   1379                 GENERAL_NAME_print(biobuf, name);
   1380                 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
   1381                 if (len < 0) {
   1382                     _setSSLError(NULL, 0, __FILE__, __LINE__);
   1383                     goto fail;
   1384                 }
   1385                 vptr = strchr(buf, ':');
   1386                 if (vptr == NULL) {
   1387                     PyErr_Format(PyExc_ValueError,
   1388                                  "Invalid value %.200s",
   1389                                  buf);
   1390                     goto fail;
   1391                 }
   1392                 t = PyTuple_New(2);
   1393                 if (t == NULL)
   1394                     goto fail;
   1395                 v = PyUnicode_FromStringAndSize(buf, (vptr - buf));
   1396                 if (v == NULL) {
   1397                     Py_DECREF(t);
   1398                     goto fail;
   1399                 }
   1400                 PyTuple_SET_ITEM(t, 0, v);
   1401                 v = PyUnicode_FromStringAndSize((vptr + 1),
   1402                                                 (len - (vptr - buf + 1)));
   1403                 if (v == NULL) {
   1404                     Py_DECREF(t);
   1405                     goto fail;
   1406                 }
   1407                 PyTuple_SET_ITEM(t, 1, v);
   1408                 break;
   1409             }
   1410 
   1411             /* and add that rendering to the list */
   1412 
   1413             if (PyList_Append(peer_alt_names, t) < 0) {
   1414                 Py_DECREF(t);
   1415                 goto fail;
   1416             }
   1417             Py_DECREF(t);
   1418         }
   1419         sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
   1420     }
   1421     BIO_free(biobuf);
   1422     if (peer_alt_names != Py_None) {
   1423         v = PyList_AsTuple(peer_alt_names);
   1424         Py_DECREF(peer_alt_names);
   1425         return v;
   1426     } else {
   1427         return peer_alt_names;
   1428     }
   1429 
   1430 
   1431   fail:
   1432     if (biobuf != NULL)
   1433         BIO_free(biobuf);
   1434 
   1435     if (peer_alt_names != Py_None) {
   1436         Py_XDECREF(peer_alt_names);
   1437     }
   1438 
   1439     return NULL;
   1440 }
   1441 
   1442 static PyObject *
   1443 _get_aia_uri(X509 *certificate, int nid) {
   1444     PyObject *lst = NULL, *ostr = NULL;
   1445     int i, result;
   1446     AUTHORITY_INFO_ACCESS *info;
   1447 
   1448     info = X509_get_ext_d2i(certificate, NID_info_access, NULL, NULL);
   1449     if (info == NULL)
   1450         return Py_None;
   1451     if (sk_ACCESS_DESCRIPTION_num(info) == 0) {
   1452         AUTHORITY_INFO_ACCESS_free(info);
   1453         return Py_None;
   1454     }
   1455 
   1456     if ((lst = PyList_New(0)) == NULL) {
   1457         goto fail;
   1458     }
   1459 
   1460     for (i = 0; i < sk_ACCESS_DESCRIPTION_num(info); i++) {
   1461         ACCESS_DESCRIPTION *ad = sk_ACCESS_DESCRIPTION_value(info, i);
   1462         ASN1_IA5STRING *uri;
   1463 
   1464         if ((OBJ_obj2nid(ad->method) != nid) ||
   1465                 (ad->location->type != GEN_URI)) {
   1466             continue;
   1467         }
   1468         uri = ad->location->d.uniformResourceIdentifier;
   1469         ostr = PyUnicode_FromStringAndSize((char *)uri->data,
   1470                                            uri->length);
   1471         if (ostr == NULL) {
   1472             goto fail;
   1473         }
   1474         result = PyList_Append(lst, ostr);
   1475         Py_DECREF(ostr);
   1476         if (result < 0) {
   1477             goto fail;
   1478         }
   1479     }
   1480     AUTHORITY_INFO_ACCESS_free(info);
   1481 
   1482     /* convert to tuple or None */
   1483     if (PyList_Size(lst) == 0) {
   1484         Py_DECREF(lst);
   1485         return Py_None;
   1486     } else {
   1487         PyObject *tup;
   1488         tup = PyList_AsTuple(lst);
   1489         Py_DECREF(lst);
   1490         return tup;
   1491     }
   1492 
   1493   fail:
   1494     AUTHORITY_INFO_ACCESS_free(info);
   1495     Py_XDECREF(lst);
   1496     return NULL;
   1497 }
   1498 
   1499 static PyObject *
   1500 _get_crl_dp(X509 *certificate) {
   1501     STACK_OF(DIST_POINT) *dps;
   1502     int i, j;
   1503     PyObject *lst, *res = NULL;
   1504 
   1505     dps = X509_get_ext_d2i(certificate, NID_crl_distribution_points, NULL, NULL);
   1506 
   1507     if (dps == NULL)
   1508         return Py_None;
   1509 
   1510     lst = PyList_New(0);
   1511     if (lst == NULL)
   1512         goto done;
   1513 
   1514     for (i=0; i < sk_DIST_POINT_num(dps); i++) {
   1515         DIST_POINT *dp;
   1516         STACK_OF(GENERAL_NAME) *gns;
   1517 
   1518         dp = sk_DIST_POINT_value(dps, i);
   1519         if (dp->distpoint == NULL) {
   1520             /* Ignore empty DP value, CVE-2019-5010 */
   1521             continue;
   1522         }
   1523         gns = dp->distpoint->name.fullname;
   1524 
   1525         for (j=0; j < sk_GENERAL_NAME_num(gns); j++) {
   1526             GENERAL_NAME *gn;
   1527             ASN1_IA5STRING *uri;
   1528             PyObject *ouri;
   1529             int err;
   1530 
   1531             gn = sk_GENERAL_NAME_value(gns, j);
   1532             if (gn->type != GEN_URI) {
   1533                 continue;
   1534             }
   1535             uri = gn->d.uniformResourceIdentifier;
   1536             ouri = PyUnicode_FromStringAndSize((char *)uri->data,
   1537                                                uri->length);
   1538             if (ouri == NULL)
   1539                 goto done;
   1540 
   1541             err = PyList_Append(lst, ouri);
   1542             Py_DECREF(ouri);
   1543             if (err < 0)
   1544                 goto done;
   1545         }
   1546     }
   1547 
   1548     /* Convert to tuple. */
   1549     res = (PyList_GET_SIZE(lst) > 0) ? PyList_AsTuple(lst) : Py_None;
   1550 
   1551   done:
   1552     Py_XDECREF(lst);
   1553     CRL_DIST_POINTS_free(dps);
   1554     return res;
   1555 }
   1556 
   1557 static PyObject *
   1558 _decode_certificate(X509 *certificate) {
   1559 
   1560     PyObject *retval = NULL;
   1561     BIO *biobuf = NULL;
   1562     PyObject *peer;
   1563     PyObject *peer_alt_names = NULL;
   1564     PyObject *issuer;
   1565     PyObject *version;
   1566     PyObject *sn_obj;
   1567     PyObject *obj;
   1568     ASN1_INTEGER *serialNumber;
   1569     char buf[2048];
   1570     int len, result;
   1571     ASN1_TIME *notBefore, *notAfter;
   1572     PyObject *pnotBefore, *pnotAfter;
   1573 
   1574     retval = PyDict_New();
   1575     if (retval == NULL)
   1576         return NULL;
   1577 
   1578     peer = _create_tuple_for_X509_NAME(
   1579         X509_get_subject_name(certificate));
   1580     if (peer == NULL)
   1581         goto fail0;
   1582     if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) {
   1583         Py_DECREF(peer);
   1584         goto fail0;
   1585     }
   1586     Py_DECREF(peer);
   1587 
   1588     issuer = _create_tuple_for_X509_NAME(
   1589         X509_get_issuer_name(certificate));
   1590     if (issuer == NULL)
   1591         goto fail0;
   1592     if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) {
   1593         Py_DECREF(issuer);
   1594         goto fail0;
   1595     }
   1596     Py_DECREF(issuer);
   1597 
   1598     version = PyLong_FromLong(X509_get_version(certificate) + 1);
   1599     if (version == NULL)
   1600         goto fail0;
   1601     if (PyDict_SetItemString(retval, "version", version) < 0) {
   1602         Py_DECREF(version);
   1603         goto fail0;
   1604     }
   1605     Py_DECREF(version);
   1606 
   1607     /* get a memory buffer */
   1608     biobuf = BIO_new(BIO_s_mem());
   1609     if (biobuf == NULL) {
   1610         PyErr_SetString(PySSLErrorObject, "failed to allocate BIO");
   1611         goto fail0;
   1612     }
   1613 
   1614     (void) BIO_reset(biobuf);
   1615     serialNumber = X509_get_serialNumber(certificate);
   1616     /* should not exceed 20 octets, 160 bits, so buf is big enough */
   1617     i2a_ASN1_INTEGER(biobuf, serialNumber);
   1618     len = BIO_gets(biobuf, buf, sizeof(buf)-1);
   1619     if (len < 0) {
   1620         _setSSLError(NULL, 0, __FILE__, __LINE__);
   1621         goto fail1;
   1622     }
   1623     sn_obj = PyUnicode_FromStringAndSize(buf, len);
   1624     if (sn_obj == NULL)
   1625         goto fail1;
   1626     if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) {
   1627         Py_DECREF(sn_obj);
   1628         goto fail1;
   1629     }
   1630     Py_DECREF(sn_obj);
   1631 
   1632     (void) BIO_reset(biobuf);
   1633     notBefore = X509_get_notBefore(certificate);
   1634     ASN1_TIME_print(biobuf, notBefore);
   1635     len = BIO_gets(biobuf, buf, sizeof(buf)-1);
   1636     if (len < 0) {
   1637         _setSSLError(NULL, 0, __FILE__, __LINE__);
   1638         goto fail1;
   1639     }
   1640     pnotBefore = PyUnicode_FromStringAndSize(buf, len);
   1641     if (pnotBefore == NULL)
   1642         goto fail1;
   1643     if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) {
   1644         Py_DECREF(pnotBefore);
   1645         goto fail1;
   1646     }
   1647     Py_DECREF(pnotBefore);
   1648 
   1649     (void) BIO_reset(biobuf);
   1650     notAfter = X509_get_notAfter(certificate);
   1651     ASN1_TIME_print(biobuf, notAfter);
   1652     len = BIO_gets(biobuf, buf, sizeof(buf)-1);
   1653     if (len < 0) {
   1654         _setSSLError(NULL, 0, __FILE__, __LINE__);
   1655         goto fail1;
   1656     }
   1657     pnotAfter = PyUnicode_FromStringAndSize(buf, len);
   1658     if (pnotAfter == NULL)
   1659         goto fail1;
   1660     if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) {
   1661         Py_DECREF(pnotAfter);
   1662         goto fail1;
   1663     }
   1664     Py_DECREF(pnotAfter);
   1665 
   1666     /* Now look for subjectAltName */
   1667 
   1668     peer_alt_names = _get_peer_alt_names(certificate);
   1669     if (peer_alt_names == NULL)
   1670         goto fail1;
   1671     else if (peer_alt_names != Py_None) {
   1672         if (PyDict_SetItemString(retval, "subjectAltName",
   1673                                  peer_alt_names) < 0) {
   1674             Py_DECREF(peer_alt_names);
   1675             goto fail1;
   1676         }
   1677         Py_DECREF(peer_alt_names);
   1678     }
   1679 
   1680     /* Authority Information Access: OCSP URIs */
   1681     obj = _get_aia_uri(certificate, NID_ad_OCSP);
   1682     if (obj == NULL) {
   1683         goto fail1;
   1684     } else if (obj != Py_None) {
   1685         result = PyDict_SetItemString(retval, "OCSP", obj);
   1686         Py_DECREF(obj);
   1687         if (result < 0) {
   1688             goto fail1;
   1689         }
   1690     }
   1691 
   1692     obj = _get_aia_uri(certificate, NID_ad_ca_issuers);
   1693     if (obj == NULL) {
   1694         goto fail1;
   1695     } else if (obj != Py_None) {
   1696         result = PyDict_SetItemString(retval, "caIssuers", obj);
   1697         Py_DECREF(obj);
   1698         if (result < 0) {
   1699             goto fail1;
   1700         }
   1701     }
   1702 
   1703     /* CDP (CRL distribution points) */
   1704     obj = _get_crl_dp(certificate);
   1705     if (obj == NULL) {
   1706         goto fail1;
   1707     } else if (obj != Py_None) {
   1708         result = PyDict_SetItemString(retval, "crlDistributionPoints", obj);
   1709         Py_DECREF(obj);
   1710         if (result < 0) {
   1711             goto fail1;
   1712         }
   1713     }
   1714 
   1715     BIO_free(biobuf);
   1716     return retval;
   1717 
   1718   fail1:
   1719     if (biobuf != NULL)
   1720         BIO_free(biobuf);
   1721   fail0:
   1722     Py_XDECREF(retval);
   1723     return NULL;
   1724 }
   1725 
   1726 static PyObject *
   1727 _certificate_to_der(X509 *certificate)
   1728 {
   1729     unsigned char *bytes_buf = NULL;
   1730     int len;
   1731     PyObject *retval;
   1732 
   1733     bytes_buf = NULL;
   1734     len = i2d_X509(certificate, &bytes_buf);
   1735     if (len < 0) {
   1736         _setSSLError(NULL, 0, __FILE__, __LINE__);
   1737         return NULL;
   1738     }
   1739     /* this is actually an immutable bytes sequence */
   1740     retval = PyBytes_FromStringAndSize((const char *) bytes_buf, len);
   1741     OPENSSL_free(bytes_buf);
   1742     return retval;
   1743 }
   1744 
   1745 /*[clinic input]
   1746 _ssl._test_decode_cert
   1747     path: object(converter="PyUnicode_FSConverter")
   1748     /
   1749 
   1750 [clinic start generated code]*/
   1751 
   1752 static PyObject *
   1753 _ssl__test_decode_cert_impl(PyObject *module, PyObject *path)
   1754 /*[clinic end generated code: output=96becb9abb23c091 input=cdeaaf02d4346628]*/
   1755 {
   1756     PyObject *retval = NULL;
   1757     X509 *x=NULL;
   1758     BIO *cert;
   1759 
   1760     if ((cert=BIO_new(BIO_s_file())) == NULL) {
   1761         PyErr_SetString(PySSLErrorObject,
   1762                         "Can't malloc memory to read file");
   1763         goto fail0;
   1764     }
   1765 
   1766     if (BIO_read_filename(cert, PyBytes_AsString(path)) <= 0) {
   1767         PyErr_SetString(PySSLErrorObject,
   1768                         "Can't open file");
   1769         goto fail0;
   1770     }
   1771 
   1772     x = PEM_read_bio_X509_AUX(cert,NULL, NULL, NULL);
   1773     if (x == NULL) {
   1774         PyErr_SetString(PySSLErrorObject,
   1775                         "Error decoding PEM-encoded file");
   1776         goto fail0;
   1777     }
   1778 
   1779     retval = _decode_certificate(x);
   1780     X509_free(x);
   1781 
   1782   fail0:
   1783     Py_DECREF(path);
   1784     if (cert != NULL) BIO_free(cert);
   1785     return retval;
   1786 }
   1787 
   1788 
   1789 /*[clinic input]
   1790 _ssl._SSLSocket.getpeercert
   1791     der as binary_mode: bool = False
   1792     /
   1793 
   1794 Returns the certificate for the peer.
   1795 
   1796 If no certificate was provided, returns None.  If a certificate was
   1797 provided, but not validated, returns an empty dictionary.  Otherwise
   1798 returns a dict containing information about the peer certificate.
   1799 
   1800 If the optional argument is True, returns a DER-encoded copy of the
   1801 peer certificate, or None if no certificate was provided.  This will
   1802 return the certificate even if it wasn't validated.
   1803 [clinic start generated code]*/
   1804 
   1805 static PyObject *
   1806 _ssl__SSLSocket_getpeercert_impl(PySSLSocket *self, int binary_mode)
   1807 /*[clinic end generated code: output=1f0ab66dfb693c88 input=c0fbe802e57629b7]*/
   1808 {
   1809     int verification;
   1810     X509 *peer_cert;
   1811     PyObject *result;
   1812 
   1813     if (!SSL_is_init_finished(self->ssl)) {
   1814         PyErr_SetString(PyExc_ValueError,
   1815                         "handshake not done yet");
   1816         return NULL;
   1817     }
   1818     peer_cert = SSL_get_peer_certificate(self->ssl);
   1819     if (peer_cert == NULL)
   1820         Py_RETURN_NONE;
   1821 
   1822     if (binary_mode) {
   1823         /* return cert in DER-encoded format */
   1824         result = _certificate_to_der(peer_cert);
   1825     } else {
   1826         verification = SSL_CTX_get_verify_mode(SSL_get_SSL_CTX(self->ssl));
   1827         if ((verification & SSL_VERIFY_PEER) == 0)
   1828             result = PyDict_New();
   1829         else
   1830             result = _decode_certificate(peer_cert);
   1831     }
   1832     X509_free(peer_cert);
   1833     return result;
   1834 }
   1835 
   1836 static PyObject *
   1837 cipher_to_tuple(const SSL_CIPHER *cipher)
   1838 {
   1839     const char *cipher_name, *cipher_protocol;
   1840     PyObject *v, *retval = PyTuple_New(3);
   1841     if (retval == NULL)
   1842         return NULL;
   1843 
   1844     cipher_name = SSL_CIPHER_get_name(cipher);
   1845     if (cipher_name == NULL) {
   1846         Py_INCREF(Py_None);
   1847         PyTuple_SET_ITEM(retval, 0, Py_None);
   1848     } else {
   1849         v = PyUnicode_FromString(cipher_name);
   1850         if (v == NULL)
   1851             goto fail;
   1852         PyTuple_SET_ITEM(retval, 0, v);
   1853     }
   1854 
   1855     cipher_protocol = SSL_CIPHER_get_version(cipher);
   1856     if (cipher_protocol == NULL) {
   1857         Py_INCREF(Py_None);
   1858         PyTuple_SET_ITEM(retval, 1, Py_None);
   1859     } else {
   1860         v = PyUnicode_FromString(cipher_protocol);
   1861         if (v == NULL)
   1862             goto fail;
   1863         PyTuple_SET_ITEM(retval, 1, v);
   1864     }
   1865 
   1866     v = PyLong_FromLong(SSL_CIPHER_get_bits(cipher, NULL));
   1867     if (v == NULL)
   1868         goto fail;
   1869     PyTuple_SET_ITEM(retval, 2, v);
   1870 
   1871     return retval;
   1872 
   1873   fail:
   1874     Py_DECREF(retval);
   1875     return NULL;
   1876 }
   1877 
   1878 #if OPENSSL_VERSION_NUMBER >= 0x10002000UL
   1879 static PyObject *
   1880 cipher_to_dict(const SSL_CIPHER *cipher)
   1881 {
   1882     const char *cipher_name, *cipher_protocol;
   1883 
   1884     unsigned long cipher_id;
   1885     int alg_bits, strength_bits, len;
   1886     char buf[512] = {0};
   1887 #if OPENSSL_VERSION_1_1
   1888     int aead, nid;
   1889     const char *skcipher = NULL, *digest = NULL, *kx = NULL, *auth = NULL;
   1890 #endif
   1891 
   1892     /* can be NULL */
   1893     cipher_name = SSL_CIPHER_get_name(cipher);
   1894     cipher_protocol = SSL_CIPHER_get_version(cipher);
   1895     cipher_id = SSL_CIPHER_get_id(cipher);
   1896     SSL_CIPHER_description(cipher, buf, sizeof(buf) - 1);
   1897     /* Downcast to avoid a warning. Safe since buf is always 512 bytes */
   1898     len = (int)strlen(buf);
   1899     if (len > 1 && buf[len-1] == '\n')
   1900         buf[len-1] = '\0';
   1901     strength_bits = SSL_CIPHER_get_bits(cipher, &alg_bits);
   1902 
   1903 #if OPENSSL_VERSION_1_1
   1904     aead = SSL_CIPHER_is_aead(cipher);
   1905     nid = SSL_CIPHER_get_cipher_nid(cipher);
   1906     skcipher = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
   1907     nid = SSL_CIPHER_get_digest_nid(cipher);
   1908     digest = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
   1909     nid = SSL_CIPHER_get_kx_nid(cipher);
   1910     kx = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
   1911     nid = SSL_CIPHER_get_auth_nid(cipher);
   1912     auth = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
   1913 #endif
   1914 
   1915     return Py_BuildValue(
   1916         "{sksssssssisi"
   1917 #if OPENSSL_VERSION_1_1
   1918         "sOssssssss"
   1919 #endif
   1920         "}",
   1921         "id", cipher_id,
   1922         "name", cipher_name,
   1923         "protocol", cipher_protocol,
   1924         "description", buf,
   1925         "strength_bits", strength_bits,
   1926         "alg_bits", alg_bits
   1927 #if OPENSSL_VERSION_1_1
   1928         ,"aead", aead ? Py_True : Py_False,
   1929         "symmetric", skcipher,
   1930         "digest", digest,
   1931         "kea", kx,
   1932         "auth", auth
   1933 #endif
   1934        );
   1935 }
   1936 #endif
   1937 
   1938 /*[clinic input]
   1939 _ssl._SSLSocket.shared_ciphers
   1940 [clinic start generated code]*/
   1941 
   1942 static PyObject *
   1943 _ssl__SSLSocket_shared_ciphers_impl(PySSLSocket *self)
   1944 /*[clinic end generated code: output=3d174ead2e42c4fd input=0bfe149da8fe6306]*/
   1945 {
   1946     STACK_OF(SSL_CIPHER) *ciphers;
   1947     int i;
   1948     PyObject *res;
   1949 
   1950     ciphers = SSL_get_ciphers(self->ssl);
   1951     if (!ciphers)
   1952         Py_RETURN_NONE;
   1953     res = PyList_New(sk_SSL_CIPHER_num(ciphers));
   1954     if (!res)
   1955         return NULL;
   1956     for (i = 0; i < sk_SSL_CIPHER_num(ciphers); i++) {
   1957         PyObject *tup = cipher_to_tuple(sk_SSL_CIPHER_value(ciphers, i));
   1958         if (!tup) {
   1959             Py_DECREF(res);
   1960             return NULL;
   1961         }
   1962         PyList_SET_ITEM(res, i, tup);
   1963     }
   1964     return res;
   1965 }
   1966 
   1967 /*[clinic input]
   1968 _ssl._SSLSocket.cipher
   1969 [clinic start generated code]*/
   1970 
   1971 static PyObject *
   1972 _ssl__SSLSocket_cipher_impl(PySSLSocket *self)
   1973 /*[clinic end generated code: output=376417c16d0e5815 input=548fb0e27243796d]*/
   1974 {
   1975     const SSL_CIPHER *current;
   1976 
   1977     if (self->ssl == NULL)
   1978         Py_RETURN_NONE;
   1979     current = SSL_get_current_cipher(self->ssl);
   1980     if (current == NULL)
   1981         Py_RETURN_NONE;
   1982     return cipher_to_tuple(current);
   1983 }
   1984 
   1985 /*[clinic input]
   1986 _ssl._SSLSocket.version
   1987 [clinic start generated code]*/
   1988 
   1989 static PyObject *
   1990 _ssl__SSLSocket_version_impl(PySSLSocket *self)
   1991 /*[clinic end generated code: output=178aed33193b2cdb input=900186a503436fd6]*/
   1992 {
   1993     const char *version;
   1994 
   1995     if (self->ssl == NULL)
   1996         Py_RETURN_NONE;
   1997     if (!SSL_is_init_finished(self->ssl)) {
   1998         /* handshake not finished */
   1999         Py_RETURN_NONE;
   2000     }
   2001     version = SSL_get_version(self->ssl);
   2002     if (!strcmp(version, "unknown"))
   2003         Py_RETURN_NONE;
   2004     return PyUnicode_FromString(version);
   2005 }
   2006 
   2007 #if HAVE_NPN
   2008 /*[clinic input]
   2009 _ssl._SSLSocket.selected_npn_protocol
   2010 [clinic start generated code]*/
   2011 
   2012 static PyObject *
   2013 _ssl__SSLSocket_selected_npn_protocol_impl(PySSLSocket *self)
   2014 /*[clinic end generated code: output=b91d494cd207ecf6 input=c28fde139204b826]*/
   2015 {
   2016     const unsigned char *out;
   2017     unsigned int outlen;
   2018 
   2019     SSL_get0_next_proto_negotiated(self->ssl,
   2020                                    &out, &outlen);
   2021 
   2022     if (out == NULL)
   2023         Py_RETURN_NONE;
   2024     return PyUnicode_FromStringAndSize((char *)out, outlen);
   2025 }
   2026 #endif
   2027 
   2028 #if HAVE_ALPN
   2029 /*[clinic input]
   2030 _ssl._SSLSocket.selected_alpn_protocol
   2031 [clinic start generated code]*/
   2032 
   2033 static PyObject *
   2034 _ssl__SSLSocket_selected_alpn_protocol_impl(PySSLSocket *self)
   2035 /*[clinic end generated code: output=ec33688b303d250f input=442de30e35bc2913]*/
   2036 {
   2037     const unsigned char *out;
   2038     unsigned int outlen;
   2039 
   2040     SSL_get0_alpn_selected(self->ssl, &out, &outlen);
   2041 
   2042     if (out == NULL)
   2043         Py_RETURN_NONE;
   2044     return PyUnicode_FromStringAndSize((char *)out, outlen);
   2045 }
   2046 #endif
   2047 
   2048 /*[clinic input]
   2049 _ssl._SSLSocket.compression
   2050 [clinic start generated code]*/
   2051 
   2052 static PyObject *
   2053 _ssl__SSLSocket_compression_impl(PySSLSocket *self)
   2054 /*[clinic end generated code: output=bd16cb1bb4646ae7 input=5d059d0a2bbc32c8]*/
   2055 {
   2056 #ifdef OPENSSL_NO_COMP
   2057     Py_RETURN_NONE;
   2058 #else
   2059     const COMP_METHOD *comp_method;
   2060     const char *short_name;
   2061 
   2062     if (self->ssl == NULL)
   2063         Py_RETURN_NONE;
   2064     comp_method = SSL_get_current_compression(self->ssl);
   2065     if (comp_method == NULL || COMP_get_type(comp_method) == NID_undef)
   2066         Py_RETURN_NONE;
   2067     short_name = OBJ_nid2sn(COMP_get_type(comp_method));
   2068     if (short_name == NULL)
   2069         Py_RETURN_NONE;
   2070     return PyUnicode_DecodeFSDefault(short_name);
   2071 #endif
   2072 }
   2073 
   2074 static PySSLContext *PySSL_get_context(PySSLSocket *self, void *closure) {
   2075     Py_INCREF(self->ctx);
   2076     return self->ctx;
   2077 }
   2078 
   2079 static int PySSL_set_context(PySSLSocket *self, PyObject *value,
   2080                                    void *closure) {
   2081 
   2082     if (PyObject_TypeCheck(value, &PySSLContext_Type)) {
   2083 #if !HAVE_SNI
   2084         PyErr_SetString(PyExc_NotImplementedError, "setting a socket's "
   2085                         "context is not supported by your OpenSSL library");
   2086         return -1;
   2087 #else
   2088         Py_INCREF(value);
   2089         Py_SETREF(self->ctx, (PySSLContext *)value);
   2090         SSL_set_SSL_CTX(self->ssl, self->ctx->ctx);
   2091 #endif
   2092     } else {
   2093         PyErr_SetString(PyExc_TypeError, "The value must be a SSLContext");
   2094         return -1;
   2095     }
   2096 
   2097     return 0;
   2098 }
   2099 
   2100 PyDoc_STRVAR(PySSL_set_context_doc,
   2101 "_setter_context(ctx)\n\
   2102 \
   2103 This changes the context associated with the SSLSocket. This is typically\n\
   2104 used from within a callback function set by the sni_callback\n\
   2105 on the SSLContext to change the certificate information associated with the\n\
   2106 SSLSocket before the cryptographic exchange handshake messages\n");
   2107 
   2108 
   2109 static PyObject *
   2110 PySSL_get_server_side(PySSLSocket *self, void *c)
   2111 {
   2112     return PyBool_FromLong(self->socket_type == PY_SSL_SERVER);
   2113 }
   2114 
   2115 PyDoc_STRVAR(PySSL_get_server_side_doc,
   2116 "Whether this is a server-side socket.");
   2117 
   2118 static PyObject *
   2119 PySSL_get_server_hostname(PySSLSocket *self, void *c)
   2120 {
   2121     if (self->server_hostname == NULL)
   2122         Py_RETURN_NONE;
   2123     Py_INCREF(self->server_hostname);
   2124     return self->server_hostname;
   2125 }
   2126 
   2127 PyDoc_STRVAR(PySSL_get_server_hostname_doc,
   2128 "The currently set server hostname (for SNI).");
   2129 
   2130 static PyObject *
   2131 PySSL_get_owner(PySSLSocket *self, void *c)
   2132 {
   2133     PyObject *owner;
   2134 
   2135     if (self->owner == NULL)
   2136         Py_RETURN_NONE;
   2137 
   2138     owner = PyWeakref_GetObject(self->owner);
   2139     Py_INCREF(owner);
   2140     return owner;
   2141 }
   2142 
   2143 static int
   2144 PySSL_set_owner(PySSLSocket *self, PyObject *value, void *c)
   2145 {
   2146     Py_XSETREF(self->owner, PyWeakref_NewRef(value, NULL));
   2147     if (self->owner == NULL)
   2148         return -1;
   2149     return 0;
   2150 }
   2151 
   2152 PyDoc_STRVAR(PySSL_get_owner_doc,
   2153 "The Python-level owner of this object.\
   2154 Passed as \"self\" in servername callback.");
   2155 
   2156 
   2157 static void PySSL_dealloc(PySSLSocket *self)
   2158 {
   2159     if (self->ssl)
   2160         SSL_free(self->ssl);
   2161     Py_XDECREF(self->Socket);
   2162     Py_XDECREF(self->ctx);
   2163     Py_XDECREF(self->server_hostname);
   2164     Py_XDECREF(self->owner);
   2165     PyObject_Del(self);
   2166 }
   2167 
   2168 /* If the socket has a timeout, do a select()/poll() on the socket.
   2169    The argument writing indicates the direction.
   2170    Returns one of the possibilities in the timeout_state enum (above).
   2171  */
   2172 
   2173 static int
   2174 PySSL_select(PySocketSockObject *s, int writing, _PyTime_t timeout)
   2175 {
   2176     int rc;
   2177 #ifdef HAVE_POLL
   2178     struct pollfd pollfd;
   2179     _PyTime_t ms;
   2180 #else
   2181     int nfds;
   2182     fd_set fds;
   2183     struct timeval tv;
   2184 #endif
   2185 
   2186     /* Nothing to do unless we're in timeout mode (not non-blocking) */
   2187     if ((s == NULL) || (timeout == 0))
   2188         return SOCKET_IS_NONBLOCKING;
   2189     else if (timeout < 0) {
   2190         if (s->sock_timeout > 0)
   2191             return SOCKET_HAS_TIMED_OUT;
   2192         else
   2193             return SOCKET_IS_BLOCKING;
   2194     }
   2195 
   2196     /* Guard against closed socket */
   2197     if (s->sock_fd == INVALID_SOCKET)
   2198         return SOCKET_HAS_BEEN_CLOSED;
   2199 
   2200     /* Prefer poll, if available, since you can poll() any fd
   2201      * which can't be done with select(). */
   2202 #ifdef HAVE_POLL
   2203     pollfd.fd = s->sock_fd;
   2204     pollfd.events = writing ? POLLOUT : POLLIN;
   2205 
   2206     /* timeout is in seconds, poll() uses milliseconds */
   2207     ms = (int)_PyTime_AsMilliseconds(timeout, _PyTime_ROUND_CEILING);
   2208     assert(ms <= INT_MAX);
   2209 
   2210     PySSL_BEGIN_ALLOW_THREADS
   2211     rc = poll(&pollfd, 1, (int)ms);
   2212     PySSL_END_ALLOW_THREADS
   2213 #else
   2214     /* Guard against socket too large for select*/
   2215     if (!_PyIsSelectable_fd(s->sock_fd))
   2216         return SOCKET_TOO_LARGE_FOR_SELECT;
   2217 
   2218     _PyTime_AsTimeval_noraise(timeout, &tv, _PyTime_ROUND_CEILING);
   2219 
   2220     FD_ZERO(&fds);
   2221     FD_SET(s->sock_fd, &fds);
   2222 
   2223     /* Wait until the socket becomes ready */
   2224     PySSL_BEGIN_ALLOW_THREADS
   2225     nfds = Py_SAFE_DOWNCAST(s->sock_fd+1, SOCKET_T, int);
   2226     if (writing)
   2227         rc = select(nfds, NULL, &fds, NULL, &tv);
   2228     else
   2229         rc = select(nfds, &fds, NULL, NULL, &tv);
   2230     PySSL_END_ALLOW_THREADS
   2231 #endif
   2232 
   2233     /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
   2234        (when we are able to write or when there's something to read) */
   2235     return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
   2236 }
   2237 
   2238 /*[clinic input]
   2239 _ssl._SSLSocket.write
   2240     b: Py_buffer
   2241     /
   2242 
   2243 Writes the bytes-like object b into the SSL object.
   2244 
   2245 Returns the number of bytes written.
   2246 [clinic start generated code]*/
   2247 
   2248 static PyObject *
   2249 _ssl__SSLSocket_write_impl(PySSLSocket *self, Py_buffer *b)
   2250 /*[clinic end generated code: output=aa7a6be5527358d8 input=77262d994fe5100a]*/
   2251 {
   2252     int len;
   2253     int sockstate;
   2254     _PySSLError err;
   2255     int nonblocking;
   2256     PySocketSockObject *sock = GET_SOCKET(self);
   2257     _PyTime_t timeout, deadline = 0;
   2258     int has_timeout;
   2259 
   2260     if (sock != NULL) {
   2261         if (((PyObject*)sock) == Py_None) {
   2262             _setSSLError("Underlying socket connection gone",
   2263                          PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
   2264             return NULL;
   2265         }
   2266         Py_INCREF(sock);
   2267     }
   2268 
   2269     if (b->len > INT_MAX) {
   2270         PyErr_Format(PyExc_OverflowError,
   2271                      "string longer than %d bytes", INT_MAX);
   2272         goto error;
   2273     }
   2274 
   2275     if (sock != NULL) {
   2276         /* just in case the blocking state of the socket has been changed */
   2277         nonblocking = (sock->sock_timeout >= 0);
   2278         BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
   2279         BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
   2280     }
   2281 
   2282     timeout = GET_SOCKET_TIMEOUT(sock);
   2283     has_timeout = (timeout > 0);
   2284     if (has_timeout)
   2285         deadline = _PyTime_GetMonotonicClock() + timeout;
   2286 
   2287     sockstate = PySSL_select(sock, 1, timeout);
   2288     if (sockstate == SOCKET_HAS_TIMED_OUT) {
   2289         PyErr_SetString(PySocketModule.timeout_error,
   2290                         "The write operation timed out");
   2291         goto error;
   2292     } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
   2293         PyErr_SetString(PySSLErrorObject,
   2294                         "Underlying socket has been closed.");
   2295         goto error;
   2296     } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
   2297         PyErr_SetString(PySSLErrorObject,
   2298                         "Underlying socket too large for select().");
   2299         goto error;
   2300     }
   2301 
   2302     do {
   2303         PySSL_BEGIN_ALLOW_THREADS
   2304         len = SSL_write(self->ssl, b->buf, (int)b->len);
   2305         err = _PySSL_errno(len <= 0, self->ssl, len);
   2306         PySSL_END_ALLOW_THREADS
   2307         self->err = err;
   2308 
   2309         if (PyErr_CheckSignals())
   2310             goto error;
   2311 
   2312         if (has_timeout)
   2313             timeout = deadline - _PyTime_GetMonotonicClock();
   2314 
   2315         if (err.ssl == SSL_ERROR_WANT_READ) {
   2316             sockstate = PySSL_select(sock, 0, timeout);
   2317         } else if (err.ssl == SSL_ERROR_WANT_WRITE) {
   2318             sockstate = PySSL_select(sock, 1, timeout);
   2319         } else {
   2320             sockstate = SOCKET_OPERATION_OK;
   2321         }
   2322 
   2323         if (sockstate == SOCKET_HAS_TIMED_OUT) {
   2324             PyErr_SetString(PySocketModule.timeout_error,
   2325                             "The write operation timed out");
   2326             goto error;
   2327         } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
   2328             PyErr_SetString(PySSLErrorObject,
   2329                             "Underlying socket has been closed.");
   2330             goto error;
   2331         } else if (sockstate == SOCKET_IS_NONBLOCKING) {
   2332             break;
   2333         }
   2334     } while (err.ssl == SSL_ERROR_WANT_READ ||
   2335              err.ssl == SSL_ERROR_WANT_WRITE);
   2336 
   2337     Py_XDECREF(sock);
   2338     if (len > 0)
   2339         return PyLong_FromLong(len);
   2340     else
   2341         return PySSL_SetError(self, len, __FILE__, __LINE__);
   2342 
   2343 error:
   2344     Py_XDECREF(sock);
   2345     return NULL;
   2346 }
   2347 
   2348 /*[clinic input]
   2349 _ssl._SSLSocket.pending
   2350 
   2351 Returns the number of already decrypted bytes available for read, pending on the connection.
   2352 [clinic start generated code]*/
   2353 
   2354 static PyObject *
   2355 _ssl__SSLSocket_pending_impl(PySSLSocket *self)
   2356 /*[clinic end generated code: output=983d9fecdc308a83 input=2b77487d6dfd597f]*/
   2357 {
   2358     int count = 0;
   2359     _PySSLError err;
   2360 
   2361     PySSL_BEGIN_ALLOW_THREADS
   2362     count = SSL_pending(self->ssl);
   2363     err = _PySSL_errno(count < 0, self->ssl, count);
   2364     PySSL_END_ALLOW_THREADS
   2365     self->err = err;
   2366 
   2367     if (count < 0)
   2368         return PySSL_SetError(self, count, __FILE__, __LINE__);
   2369     else
   2370         return PyLong_FromLong(count);
   2371 }
   2372 
   2373 /*[clinic input]
   2374 _ssl._SSLSocket.read
   2375     size as len: int
   2376     [
   2377     buffer: Py_buffer(accept={rwbuffer})
   2378     ]
   2379     /
   2380 
   2381 Read up to size bytes from the SSL socket.
   2382 [clinic start generated code]*/
   2383 
   2384 static PyObject *
   2385 _ssl__SSLSocket_read_impl(PySSLSocket *self, int len, int group_right_1,
   2386                           Py_buffer *buffer)
   2387 /*[clinic end generated code: output=00097776cec2a0af input=ff157eb918d0905b]*/
   2388 {
   2389     PyObject *dest = NULL;
   2390     char *mem;
   2391     int count;
   2392     int sockstate;
   2393     _PySSLError err;
   2394     int nonblocking;
   2395     PySocketSockObject *sock = GET_SOCKET(self);
   2396     _PyTime_t timeout, deadline = 0;
   2397     int has_timeout;
   2398 
   2399     if (!group_right_1 && len < 0) {
   2400         PyErr_SetString(PyExc_ValueError, "size should not be negative");
   2401         return NULL;
   2402     }
   2403 
   2404     if (sock != NULL) {
   2405         if (((PyObject*)sock) == Py_None) {
   2406             _setSSLError("Underlying socket connection gone",
   2407                          PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
   2408             return NULL;
   2409         }
   2410         Py_INCREF(sock);
   2411     }
   2412 
   2413     if (!group_right_1) {
   2414         dest = PyBytes_FromStringAndSize(NULL, len);
   2415         if (dest == NULL)
   2416             goto error;
   2417         if (len == 0) {
   2418             Py_XDECREF(sock);
   2419             return dest;
   2420         }
   2421         mem = PyBytes_AS_STRING(dest);
   2422     }
   2423     else {
   2424         mem = buffer->buf;
   2425         if (len <= 0 || len > buffer->len) {
   2426             len = (int) buffer->len;
   2427             if (buffer->len != len) {
   2428                 PyErr_SetString(PyExc_OverflowError,
   2429                                 "maximum length can't fit in a C 'int'");
   2430                 goto error;
   2431             }
   2432             if (len == 0) {
   2433                 count = 0;
   2434                 goto done;
   2435             }
   2436         }
   2437     }
   2438 
   2439     if (sock != NULL) {
   2440         /* just in case the blocking state of the socket has been changed */
   2441         nonblocking = (sock->sock_timeout >= 0);
   2442         BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
   2443         BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
   2444     }
   2445 
   2446     timeout = GET_SOCKET_TIMEOUT(sock);
   2447     has_timeout = (timeout > 0);
   2448     if (has_timeout)
   2449         deadline = _PyTime_GetMonotonicClock() + timeout;
   2450 
   2451     do {
   2452         PySSL_BEGIN_ALLOW_THREADS
   2453         count = SSL_read(self->ssl, mem, len);
   2454         err = _PySSL_errno(count <= 0, self->ssl, count);
   2455         PySSL_END_ALLOW_THREADS
   2456         self->err = err;
   2457 
   2458         if (PyErr_CheckSignals())
   2459             goto error;
   2460 
   2461         if (has_timeout)
   2462             timeout = deadline - _PyTime_GetMonotonicClock();
   2463 
   2464         if (err.ssl == SSL_ERROR_WANT_READ) {
   2465             sockstate = PySSL_select(sock, 0, timeout);
   2466         } else if (err.ssl == SSL_ERROR_WANT_WRITE) {
   2467             sockstate = PySSL_select(sock, 1, timeout);
   2468         } else if (err.ssl == SSL_ERROR_ZERO_RETURN &&
   2469                    SSL_get_shutdown(self->ssl) == SSL_RECEIVED_SHUTDOWN)
   2470         {
   2471             count = 0;
   2472             goto done;
   2473         }
   2474         else
   2475             sockstate = SOCKET_OPERATION_OK;
   2476 
   2477         if (sockstate == SOCKET_HAS_TIMED_OUT) {
   2478             PyErr_SetString(PySocketModule.timeout_error,
   2479                             "The read operation timed out");
   2480             goto error;
   2481         } else if (sockstate == SOCKET_IS_NONBLOCKING) {
   2482             break;
   2483         }
   2484     } while (err.ssl == SSL_ERROR_WANT_READ ||
   2485              err.ssl == SSL_ERROR_WANT_WRITE);
   2486 
   2487     if (count <= 0) {
   2488         PySSL_SetError(self, count, __FILE__, __LINE__);
   2489         goto error;
   2490     }
   2491 
   2492 done:
   2493     Py_XDECREF(sock);
   2494     if (!group_right_1) {
   2495         _PyBytes_Resize(&dest, count);
   2496         return dest;
   2497     }
   2498     else {
   2499         return PyLong_FromLong(count);
   2500     }
   2501 
   2502 error:
   2503     Py_XDECREF(sock);
   2504     if (!group_right_1)
   2505         Py_XDECREF(dest);
   2506     return NULL;
   2507 }
   2508 
   2509 /*[clinic input]
   2510 _ssl._SSLSocket.shutdown
   2511 
   2512 Does the SSL shutdown handshake with the remote end.
   2513 [clinic start generated code]*/
   2514 
   2515 static PyObject *
   2516 _ssl__SSLSocket_shutdown_impl(PySSLSocket *self)
   2517 /*[clinic end generated code: output=ca1aa7ed9d25ca42 input=11d39e69b0a2bf4a]*/
   2518 {
   2519     _PySSLError err;
   2520     int sockstate, nonblocking, ret;
   2521     int zeros = 0;
   2522     PySocketSockObject *sock = GET_SOCKET(self);
   2523     _PyTime_t timeout, deadline = 0;
   2524     int has_timeout;
   2525 
   2526     if (sock != NULL) {
   2527         /* Guard against closed socket */
   2528         if ((((PyObject*)sock) == Py_None) || (sock->sock_fd == INVALID_SOCKET)) {
   2529             _setSSLError("Underlying socket connection gone",
   2530                          PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
   2531             return NULL;
   2532         }
   2533         Py_INCREF(sock);
   2534 
   2535         /* Just in case the blocking state of the socket has been changed */
   2536         nonblocking = (sock->sock_timeout >= 0);
   2537         BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
   2538         BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
   2539     }
   2540 
   2541     timeout = GET_SOCKET_TIMEOUT(sock);
   2542     has_timeout = (timeout > 0);
   2543     if (has_timeout)
   2544         deadline = _PyTime_GetMonotonicClock() + timeout;
   2545 
   2546     while (1) {
   2547         PySSL_BEGIN_ALLOW_THREADS
   2548         /* Disable read-ahead so that unwrap can work correctly.
   2549          * Otherwise OpenSSL might read in too much data,
   2550          * eating clear text data that happens to be
   2551          * transmitted after the SSL shutdown.
   2552          * Should be safe to call repeatedly every time this
   2553          * function is used and the shutdown_seen_zero != 0
   2554          * condition is met.
   2555          */
   2556         if (self->shutdown_seen_zero)
   2557             SSL_set_read_ahead(self->ssl, 0);
   2558         ret = SSL_shutdown(self->ssl);
   2559         err = _PySSL_errno(ret < 0, self->ssl, ret);
   2560         PySSL_END_ALLOW_THREADS
   2561         self->err = err;
   2562 
   2563         /* If err == 1, a secure shutdown with SSL_shutdown() is complete */
   2564         if (ret > 0)
   2565             break;
   2566         if (ret == 0) {
   2567             /* Don't loop endlessly; instead preserve legacy
   2568                behaviour of trying SSL_shutdown() only twice.
   2569                This looks necessary for OpenSSL < 0.9.8m */
   2570             if (++zeros > 1)
   2571                 break;
   2572             /* Shutdown was sent, now try receiving */
   2573             self->shutdown_seen_zero = 1;
   2574             continue;
   2575         }
   2576 
   2577         if (has_timeout)
   2578             timeout = deadline - _PyTime_GetMonotonicClock();
   2579 
   2580         /* Possibly retry shutdown until timeout or failure */
   2581         if (err.ssl == SSL_ERROR_WANT_READ)
   2582             sockstate = PySSL_select(sock, 0, timeout);
   2583         else if (err.ssl == SSL_ERROR_WANT_WRITE)
   2584             sockstate = PySSL_select(sock, 1, timeout);
   2585         else
   2586             break;
   2587 
   2588         if (sockstate == SOCKET_HAS_TIMED_OUT) {
   2589             if (err.ssl == SSL_ERROR_WANT_READ)
   2590                 PyErr_SetString(PySocketModule.timeout_error,
   2591                                 "The read operation timed out");
   2592             else
   2593                 PyErr_SetString(PySocketModule.timeout_error,
   2594                                 "The write operation timed out");
   2595             goto error;
   2596         }
   2597         else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
   2598             PyErr_SetString(PySSLErrorObject,
   2599                             "Underlying socket too large for select().");
   2600             goto error;
   2601         }
   2602         else if (sockstate != SOCKET_OPERATION_OK)
   2603             /* Retain the SSL error code */
   2604             break;
   2605     }
   2606 
   2607     if (ret < 0) {
   2608         Py_XDECREF(sock);
   2609         return PySSL_SetError(self, ret, __FILE__, __LINE__);
   2610     }
   2611     if (sock)
   2612         /* It's already INCREF'ed */
   2613         return (PyObject *) sock;
   2614     else
   2615         Py_RETURN_NONE;
   2616 
   2617 error:
   2618     Py_XDECREF(sock);
   2619     return NULL;
   2620 }
   2621 
   2622 /*[clinic input]
   2623 _ssl._SSLSocket.get_channel_binding
   2624    cb_type: str = "tls-unique"
   2625 
   2626 Get channel binding data for current connection.
   2627 
   2628 Raise ValueError if the requested `cb_type` is not supported.  Return bytes
   2629 of the data or None if the data is not available (e.g. before the handshake).
   2630 Only 'tls-unique' channel binding data from RFC 5929 is supported.
   2631 [clinic start generated code]*/
   2632 
   2633 static PyObject *
   2634 _ssl__SSLSocket_get_channel_binding_impl(PySSLSocket *self,
   2635                                          const char *cb_type)
   2636 /*[clinic end generated code: output=34bac9acb6a61d31 input=08b7e43b99c17d41]*/
   2637 {
   2638     char buf[PySSL_CB_MAXLEN];
   2639     size_t len;
   2640 
   2641     if (strcmp(cb_type, "tls-unique") == 0) {
   2642         if (SSL_session_reused(self->ssl) ^ !self->socket_type) {
   2643             /* if session is resumed XOR we are the client */
   2644             len = SSL_get_finished(self->ssl, buf, PySSL_CB_MAXLEN);
   2645         }
   2646         else {
   2647             /* if a new session XOR we are the server */
   2648             len = SSL_get_peer_finished(self->ssl, buf, PySSL_CB_MAXLEN);
   2649         }
   2650     }
   2651     else {
   2652         PyErr_Format(
   2653             PyExc_ValueError,
   2654             "'%s' channel binding type not implemented",
   2655             cb_type
   2656         );
   2657         return NULL;
   2658     }
   2659 
   2660     /* It cannot be negative in current OpenSSL version as of July 2011 */
   2661     if (len == 0)
   2662         Py_RETURN_NONE;
   2663 
   2664     return PyBytes_FromStringAndSize(buf, len);
   2665 }
   2666 
   2667 /*[clinic input]
   2668 _ssl._SSLSocket.verify_client_post_handshake
   2669 
   2670 Initiate TLS 1.3 post-handshake authentication
   2671 [clinic start generated code]*/
   2672 
   2673 static PyObject *
   2674 _ssl__SSLSocket_verify_client_post_handshake_impl(PySSLSocket *self)
   2675 /*[clinic end generated code: output=532147f3b1341425 input=6bfa874810a3d889]*/
   2676 {
   2677 #ifdef TLS1_3_VERSION
   2678     int err = SSL_verify_client_post_handshake(self->ssl);
   2679     if (err == 0)
   2680         return _setSSLError(NULL, 0, __FILE__, __LINE__);
   2681     else
   2682         Py_RETURN_NONE;
   2683 #else
   2684     PyErr_SetString(PyExc_NotImplementedError,
   2685                     "Post-handshake auth is not supported by your "
   2686                     "OpenSSL version.");
   2687     return NULL;
   2688 #endif
   2689 }
   2690 
   2691 #ifdef OPENSSL_VERSION_1_1
   2692 
   2693 static SSL_SESSION*
   2694 _ssl_session_dup(SSL_SESSION *session) {
   2695     SSL_SESSION *newsession = NULL;
   2696     int slen;
   2697     unsigned char *senc = NULL, *p;
   2698     const unsigned char *const_p;
   2699 
   2700     if (session == NULL) {
   2701         PyErr_SetString(PyExc_ValueError, "Invalid session");
   2702         goto error;
   2703     }
   2704 
   2705     /* get length */
   2706     slen = i2d_SSL_SESSION(session, NULL);
   2707     if (slen == 0 || slen > 0xFF00) {
   2708         PyErr_SetString(PyExc_ValueError, "i2d() failed.");
   2709         goto error;
   2710     }
   2711     if ((senc = PyMem_Malloc(slen)) == NULL) {
   2712         PyErr_NoMemory();
   2713         goto error;
   2714     }
   2715     p = senc;
   2716     if (!i2d_SSL_SESSION(session, &p)) {
   2717         PyErr_SetString(PyExc_ValueError, "i2d() failed.");
   2718         goto error;
   2719     }
   2720     const_p = senc;
   2721     newsession = d2i_SSL_SESSION(NULL, &const_p, slen);
   2722     if (session == NULL) {
   2723         goto error;
   2724     }
   2725     PyMem_Free(senc);
   2726     return newsession;
   2727   error:
   2728     if (senc != NULL) {
   2729         PyMem_Free(senc);
   2730     }
   2731     return NULL;
   2732 }
   2733 #endif
   2734 
   2735 static PyObject *
   2736 PySSL_get_session(PySSLSocket *self, void *closure) {
   2737     /* get_session can return sessions from a server-side connection,
   2738      * it does not check for handshake done or client socket. */
   2739     PySSLSession *pysess;
   2740     SSL_SESSION *session;
   2741 
   2742 #ifdef OPENSSL_VERSION_1_1
   2743     /* duplicate session as workaround for session bug in OpenSSL 1.1.0,
   2744      * https://github.com/openssl/openssl/issues/1550 */
   2745     session = SSL_get0_session(self->ssl);  /* borrowed reference */
   2746     if (session == NULL) {
   2747         Py_RETURN_NONE;
   2748     }
   2749     if ((session = _ssl_session_dup(session)) == NULL) {
   2750         return NULL;
   2751     }
   2752 #else
   2753     session = SSL_get1_session(self->ssl);
   2754     if (session == NULL) {
   2755         Py_RETURN_NONE;
   2756     }
   2757 #endif
   2758     pysess = PyObject_GC_New(PySSLSession, &PySSLSession_Type);
   2759     if (pysess == NULL) {
   2760         SSL_SESSION_free(session);
   2761         return NULL;
   2762     }
   2763 
   2764     assert(self->ctx);
   2765     pysess->ctx = self->ctx;
   2766     Py_INCREF(pysess->ctx);
   2767     pysess->session = session;
   2768     PyObject_GC_Track(pysess);
   2769     return (PyObject *)pysess;
   2770 }
   2771 
   2772 static int PySSL_set_session(PySSLSocket *self, PyObject *value,
   2773                              void *closure)
   2774                               {
   2775     PySSLSession *pysess;
   2776 #ifdef OPENSSL_VERSION_1_1
   2777     SSL_SESSION *session;
   2778 #endif
   2779     int result;
   2780 
   2781     if (!PySSLSession_Check(value)) {
   2782         PyErr_SetString(PyExc_TypeError, "Value is not a SSLSession.");
   2783         return -1;
   2784     }
   2785     pysess = (PySSLSession *)value;
   2786 
   2787     if (self->ctx->ctx != pysess->ctx->ctx) {
   2788         PyErr_SetString(PyExc_ValueError,
   2789                         "Session refers to a different SSLContext.");
   2790         return -1;
   2791     }
   2792     if (self->socket_type != PY_SSL_CLIENT) {
   2793         PyErr_SetString(PyExc_ValueError,
   2794                         "Cannot set session for server-side SSLSocket.");
   2795         return -1;
   2796     }
   2797     if (SSL_is_init_finished(self->ssl)) {
   2798         PyErr_SetString(PyExc_ValueError,
   2799                         "Cannot set session after handshake.");
   2800         return -1;
   2801     }
   2802 #ifdef OPENSSL_VERSION_1_1
   2803     /* duplicate session */
   2804     if ((session = _ssl_session_dup(pysess->session)) == NULL) {
   2805         return -1;
   2806     }
   2807     result = SSL_set_session(self->ssl, session);
   2808     /* free duplicate, SSL_set_session() bumps ref count */
   2809     SSL_SESSION_free(session);
   2810 #else
   2811     result = SSL_set_session(self->ssl, pysess->session);
   2812 #endif
   2813     if (result == 0) {
   2814         _setSSLError(NULL, 0, __FILE__, __LINE__);
   2815         return -1;
   2816     }
   2817     return 0;
   2818 }
   2819 
   2820 PyDoc_STRVAR(PySSL_set_session_doc,
   2821 "_setter_session(session)\n\
   2822 \
   2823 Get / set SSLSession.");
   2824 
   2825 static PyObject *
   2826 PySSL_get_session_reused(PySSLSocket *self, void *closure) {
   2827     if (SSL_session_reused(self->ssl)) {
   2828         Py_RETURN_TRUE;
   2829     } else {
   2830         Py_RETURN_FALSE;
   2831     }
   2832 }
   2833 
   2834 PyDoc_STRVAR(PySSL_get_session_reused_doc,
   2835 "Was the client session reused during handshake?");
   2836 
   2837 static PyGetSetDef ssl_getsetlist[] = {
   2838     {"context", (getter) PySSL_get_context,
   2839                 (setter) PySSL_set_context, PySSL_set_context_doc},
   2840     {"server_side", (getter) PySSL_get_server_side, NULL,
   2841                     PySSL_get_server_side_doc},
   2842     {"server_hostname", (getter) PySSL_get_server_hostname, NULL,
   2843                         PySSL_get_server_hostname_doc},
   2844     {"owner", (getter) PySSL_get_owner, (setter) PySSL_set_owner,
   2845               PySSL_get_owner_doc},
   2846     {"session", (getter) PySSL_get_session,
   2847                 (setter) PySSL_set_session, PySSL_set_session_doc},
   2848     {"session_reused", (getter) PySSL_get_session_reused, NULL,
   2849               PySSL_get_session_reused_doc},
   2850     {NULL},            /* sentinel */
   2851 };
   2852 
   2853 static PyMethodDef PySSLMethods[] = {
   2854     _SSL__SSLSOCKET_DO_HANDSHAKE_METHODDEF
   2855     _SSL__SSLSOCKET_WRITE_METHODDEF
   2856     _SSL__SSLSOCKET_READ_METHODDEF
   2857     _SSL__SSLSOCKET_PENDING_METHODDEF
   2858     _SSL__SSLSOCKET_GETPEERCERT_METHODDEF
   2859     _SSL__SSLSOCKET_GET_CHANNEL_BINDING_METHODDEF
   2860     _SSL__SSLSOCKET_CIPHER_METHODDEF
   2861     _SSL__SSLSOCKET_SHARED_CIPHERS_METHODDEF
   2862     _SSL__SSLSOCKET_VERSION_METHODDEF
   2863     _SSL__SSLSOCKET_SELECTED_NPN_PROTOCOL_METHODDEF
   2864     _SSL__SSLSOCKET_SELECTED_ALPN_PROTOCOL_METHODDEF
   2865     _SSL__SSLSOCKET_COMPRESSION_METHODDEF
   2866     _SSL__SSLSOCKET_SHUTDOWN_METHODDEF
   2867     _SSL__SSLSOCKET_VERIFY_CLIENT_POST_HANDSHAKE_METHODDEF
   2868     {NULL, NULL}
   2869 };
   2870 
   2871 static PyTypeObject PySSLSocket_Type = {
   2872     PyVarObject_HEAD_INIT(NULL, 0)
   2873     "_ssl._SSLSocket",                  /*tp_name*/
   2874     sizeof(PySSLSocket),                /*tp_basicsize*/
   2875     0,                                  /*tp_itemsize*/
   2876     /* methods */
   2877     (destructor)PySSL_dealloc,          /*tp_dealloc*/
   2878     0,                                  /*tp_print*/
   2879     0,                                  /*tp_getattr*/
   2880     0,                                  /*tp_setattr*/
   2881     0,                                  /*tp_reserved*/
   2882     0,                                  /*tp_repr*/
   2883     0,                                  /*tp_as_number*/
   2884     0,                                  /*tp_as_sequence*/
   2885     0,                                  /*tp_as_mapping*/
   2886     0,                                  /*tp_hash*/
   2887     0,                                  /*tp_call*/
   2888     0,                                  /*tp_str*/
   2889     0,                                  /*tp_getattro*/
   2890     0,                                  /*tp_setattro*/
   2891     0,                                  /*tp_as_buffer*/
   2892     Py_TPFLAGS_DEFAULT,                 /*tp_flags*/
   2893     0,                                  /*tp_doc*/
   2894     0,                                  /*tp_traverse*/
   2895     0,                                  /*tp_clear*/
   2896     0,                                  /*tp_richcompare*/
   2897     0,                                  /*tp_weaklistoffset*/
   2898     0,                                  /*tp_iter*/
   2899     0,                                  /*tp_iternext*/
   2900     PySSLMethods,                       /*tp_methods*/
   2901     0,                                  /*tp_members*/
   2902     ssl_getsetlist,                     /*tp_getset*/
   2903 };
   2904 
   2905 
   2906 /*
   2907  * _SSLContext objects
   2908  */
   2909 
   2910 static int
   2911 _set_verify_mode(PySSLContext *self, enum py_ssl_cert_requirements n)
   2912 {
   2913     int mode;
   2914     int (*verify_cb)(int, X509_STORE_CTX *) = NULL;
   2915 
   2916     switch(n) {
   2917     case PY_SSL_CERT_NONE:
   2918         mode = SSL_VERIFY_NONE;
   2919         break;
   2920     case PY_SSL_CERT_OPTIONAL:
   2921         mode = SSL_VERIFY_PEER;
   2922         break;
   2923     case PY_SSL_CERT_REQUIRED:
   2924         mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
   2925         break;
   2926     default:
   2927          PyErr_SetString(PyExc_ValueError,
   2928                         "invalid value for verify_mode");
   2929         return -1;
   2930     }
   2931 #ifdef TLS1_3_VERSION
   2932     if (self->post_handshake_auth)
   2933         mode |= SSL_VERIFY_POST_HANDSHAKE;
   2934 #endif
   2935     /* keep current verify cb */
   2936     verify_cb = SSL_CTX_get_verify_callback(self->ctx);
   2937     SSL_CTX_set_verify(self->ctx, mode, verify_cb);
   2938     return 0;
   2939 }
   2940 
   2941 /*[clinic input]
   2942 @classmethod
   2943 _ssl._SSLContext.__new__
   2944     protocol as proto_version: int
   2945     /
   2946 [clinic start generated code]*/
   2947 
   2948 static PyObject *
   2949 _ssl__SSLContext_impl(PyTypeObject *type, int proto_version)
   2950 /*[clinic end generated code: output=2cf0d7a0741b6bd1 input=8d58a805b95fc534]*/
   2951 {
   2952     PySSLContext *self;
   2953     long options;
   2954     SSL_CTX *ctx = NULL;
   2955     X509_VERIFY_PARAM *params;
   2956     int result;
   2957 #if defined(SSL_MODE_RELEASE_BUFFERS)
   2958     unsigned long libver;
   2959 #endif
   2960 
   2961     PySSL_BEGIN_ALLOW_THREADS
   2962     if (proto_version == PY_SSL_VERSION_TLS1)
   2963         ctx = SSL_CTX_new(TLSv1_method());
   2964 #if HAVE_TLSv1_2
   2965     else if (proto_version == PY_SSL_VERSION_TLS1_1)
   2966         ctx = SSL_CTX_new(TLSv1_1_method());
   2967     else if (proto_version == PY_SSL_VERSION_TLS1_2)
   2968         ctx = SSL_CTX_new(TLSv1_2_method());
   2969 #endif
   2970 #ifndef OPENSSL_NO_SSL3
   2971     else if (proto_version == PY_SSL_VERSION_SSL3)
   2972         ctx = SSL_CTX_new(SSLv3_method());
   2973 #endif
   2974 #ifndef OPENSSL_NO_SSL2
   2975     else if (proto_version == PY_SSL_VERSION_SSL2)
   2976         ctx = SSL_CTX_new(SSLv2_method());
   2977 #endif
   2978     else if (proto_version == PY_SSL_VERSION_TLS) /* SSLv23 */
   2979         ctx = SSL_CTX_new(TLS_method());
   2980     else if (proto_version == PY_SSL_VERSION_TLS_CLIENT)
   2981         ctx = SSL_CTX_new(TLS_client_method());
   2982     else if (proto_version == PY_SSL_VERSION_TLS_SERVER)
   2983         ctx = SSL_CTX_new(TLS_server_method());
   2984     else
   2985         proto_version = -1;
   2986     PySSL_END_ALLOW_THREADS
   2987 
   2988     if (proto_version == -1) {
   2989         PyErr_SetString(PyExc_ValueError,
   2990                         "invalid protocol version");
   2991         return NULL;
   2992     }
   2993     if (ctx == NULL) {
   2994         _setSSLError(NULL, 0, __FILE__, __LINE__);
   2995         return NULL;
   2996     }
   2997 
   2998     assert(type != NULL && type->tp_alloc != NULL);
   2999     self = (PySSLContext *) type->tp_alloc(type, 0);
   3000     if (self == NULL) {
   3001         SSL_CTX_free(ctx);
   3002         return NULL;
   3003     }
   3004     self->ctx = ctx;
   3005     self->hostflags = X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS;
   3006     self->protocol = proto_version;
   3007 #if HAVE_NPN
   3008     self->npn_protocols = NULL;
   3009 #endif
   3010 #if HAVE_ALPN
   3011     self->alpn_protocols = NULL;
   3012 #endif
   3013 #ifndef OPENSSL_NO_TLSEXT
   3014     self->set_sni_cb = NULL;
   3015 #endif
   3016     /* Don't check host name by default */
   3017     if (proto_version == PY_SSL_VERSION_TLS_CLIENT) {
   3018         self->check_hostname = 1;
   3019         if (_set_verify_mode(self, PY_SSL_CERT_REQUIRED) == -1) {
   3020             Py_DECREF(self);
   3021             return NULL;
   3022         }
   3023     } else {
   3024         self->check_hostname = 0;
   3025         if (_set_verify_mode(self, PY_SSL_CERT_NONE) == -1) {
   3026             Py_DECREF(self);
   3027             return NULL;
   3028         }
   3029     }
   3030     /* Defaults */
   3031     options = SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
   3032     if (proto_version != PY_SSL_VERSION_SSL2)
   3033         options |= SSL_OP_NO_SSLv2;
   3034     if (proto_version != PY_SSL_VERSION_SSL3)
   3035         options |= SSL_OP_NO_SSLv3;
   3036     /* Minimal security flags for server and client side context.
   3037      * Client sockets ignore server-side parameters. */
   3038 #ifdef SSL_OP_NO_COMPRESSION
   3039     options |= SSL_OP_NO_COMPRESSION;
   3040 #endif
   3041 #ifdef SSL_OP_CIPHER_SERVER_PREFERENCE
   3042     options |= SSL_OP_CIPHER_SERVER_PREFERENCE;
   3043 #endif
   3044 #ifdef SSL_OP_SINGLE_DH_USE
   3045     options |= SSL_OP_SINGLE_DH_USE;
   3046 #endif
   3047 #ifdef SSL_OP_SINGLE_ECDH_USE
   3048     options |= SSL_OP_SINGLE_ECDH_USE;
   3049 #endif
   3050     SSL_CTX_set_options(self->ctx, options);
   3051 
   3052     /* A bare minimum cipher list without completely broken cipher suites.
   3053      * It's far from perfect but gives users a better head start. */
   3054     if (proto_version != PY_SSL_VERSION_SSL2) {
   3055 #if PY_SSL_DEFAULT_CIPHERS == 2
   3056         /* stick to OpenSSL's default settings */
   3057         result = 1;
   3058 #else
   3059         result = SSL_CTX_set_cipher_list(ctx, PY_SSL_DEFAULT_CIPHER_STRING);
   3060 #endif
   3061     } else {
   3062         /* SSLv2 needs MD5 */
   3063         result = SSL_CTX_set_cipher_list(ctx, "HIGH:!aNULL:!eNULL");
   3064     }
   3065     if (result == 0) {
   3066         Py_DECREF(self);
   3067         ERR_clear_error();
   3068         PyErr_SetString(PySSLErrorObject,
   3069                         "No cipher can be selected.");
   3070         return NULL;
   3071     }
   3072 
   3073 #if defined(SSL_MODE_RELEASE_BUFFERS)
   3074     /* Set SSL_MODE_RELEASE_BUFFERS. This potentially greatly reduces memory
   3075        usage for no cost at all. However, don't do this for OpenSSL versions
   3076        between 1.0.1 and 1.0.1h or 1.0.0 and 1.0.0m, which are affected by CVE
   3077        2014-0198. I can't find exactly which beta fixed this CVE, so be
   3078        conservative and assume it wasn't fixed until release. We do this check
   3079        at runtime to avoid problems from the dynamic linker.
   3080        See #25672 for more on this. */
   3081     libver = SSLeay();
   3082     if (!(libver >= 0x10001000UL && libver < 0x1000108fUL) &&
   3083         !(libver >= 0x10000000UL && libver < 0x100000dfUL)) {
   3084         SSL_CTX_set_mode(self->ctx, SSL_MODE_RELEASE_BUFFERS);
   3085     }
   3086 #endif
   3087 
   3088 
   3089 #if !defined(OPENSSL_NO_ECDH) && !defined(OPENSSL_VERSION_1_1)
   3090     /* Allow automatic ECDH curve selection (on OpenSSL 1.0.2+), or use
   3091        prime256v1 by default.  This is Apache mod_ssl's initialization
   3092        policy, so we should be safe. OpenSSL 1.1 has it enabled by default.
   3093      */
   3094 #if defined(SSL_CTX_set_ecdh_auto)
   3095     SSL_CTX_set_ecdh_auto(self->ctx, 1);
   3096 #else
   3097     {
   3098         EC_KEY *key = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
   3099         SSL_CTX_set_tmp_ecdh(self->ctx, key);
   3100         EC_KEY_free(key);
   3101     }
   3102 #endif
   3103 #endif
   3104 
   3105 #define SID_CTX "Python"
   3106     SSL_CTX_set_session_id_context(self->ctx, (const unsigned char *) SID_CTX,
   3107                                    sizeof(SID_CTX));
   3108 #undef SID_CTX
   3109 
   3110     params = SSL_CTX_get0_param(self->ctx);
   3111 #ifdef X509_V_FLAG_TRUSTED_FIRST
   3112     /* Improve trust chain building when cross-signed intermediate
   3113        certificates are present. See https://bugs.python.org/issue23476. */
   3114     X509_VERIFY_PARAM_set_flags(params, X509_V_FLAG_TRUSTED_FIRST);
   3115 #endif
   3116     X509_VERIFY_PARAM_set_hostflags(params, self->hostflags);
   3117 
   3118 #ifdef TLS1_3_VERSION
   3119     self->post_handshake_auth = 0;
   3120     SSL_CTX_set_post_handshake_auth(self->ctx, self->post_handshake_auth);
   3121 #endif
   3122 
   3123     return (PyObject *)self;
   3124 }
   3125 
   3126 static int
   3127 context_traverse(PySSLContext *self, visitproc visit, void *arg)
   3128 {
   3129 #ifndef OPENSSL_NO_TLSEXT
   3130     Py_VISIT(self->set_sni_cb);
   3131 #endif
   3132     return 0;
   3133 }
   3134 
   3135 static int
   3136 context_clear(PySSLContext *self)
   3137 {
   3138 #ifndef OPENSSL_NO_TLSEXT
   3139     Py_CLEAR(self->set_sni_cb);
   3140 #endif
   3141     return 0;
   3142 }
   3143 
   3144 static void
   3145 context_dealloc(PySSLContext *self)
   3146 {
   3147     /* bpo-31095: UnTrack is needed before calling any callbacks */
   3148     PyObject_GC_UnTrack(self);
   3149     context_clear(self);
   3150     SSL_CTX_free(self->ctx);
   3151 #if HAVE_NPN
   3152     PyMem_FREE(self->npn_protocols);
   3153 #endif
   3154 #if HAVE_ALPN
   3155     PyMem_FREE(self->alpn_protocols);
   3156 #endif
   3157     Py_TYPE(self)->tp_free(self);
   3158 }
   3159 
   3160 /*[clinic input]
   3161 _ssl._SSLContext.set_ciphers
   3162     cipherlist: str
   3163     /
   3164 [clinic start generated code]*/
   3165 
   3166 static PyObject *
   3167 _ssl__SSLContext_set_ciphers_impl(PySSLContext *self, const char *cipherlist)
   3168 /*[clinic end generated code: output=3a3162f3557c0f3f input=a7ac931b9f3ca7fc]*/
   3169 {
   3170     int ret = SSL_CTX_set_cipher_list(self->ctx, cipherlist);
   3171     if (ret == 0) {
   3172         /* Clearing the error queue is necessary on some OpenSSL versions,
   3173            otherwise the error will be reported again when another SSL call
   3174            is done. */
   3175         ERR_clear_error();
   3176         PyErr_SetString(PySSLErrorObject,
   3177                         "No cipher can be selected.");
   3178         return NULL;
   3179     }
   3180     Py_RETURN_NONE;
   3181 }
   3182 
   3183 #if OPENSSL_VERSION_NUMBER >= 0x10002000UL
   3184 /*[clinic input]
   3185 _ssl._SSLContext.get_ciphers
   3186 [clinic start generated code]*/
   3187 
   3188 static PyObject *
   3189 _ssl__SSLContext_get_ciphers_impl(PySSLContext *self)
   3190 /*[clinic end generated code: output=a56e4d68a406dfc4 input=a2aadc9af89b79c5]*/
   3191 {
   3192     SSL *ssl = NULL;
   3193     STACK_OF(SSL_CIPHER) *sk = NULL;
   3194     const SSL_CIPHER *cipher;
   3195     int i=0;
   3196     PyObject *result = NULL, *dct;
   3197 
   3198     ssl = SSL_new(self->ctx);
   3199     if (ssl == NULL) {
   3200         _setSSLError(NULL, 0, __FILE__, __LINE__);
   3201         goto exit;
   3202     }
   3203     sk = SSL_get_ciphers(ssl);
   3204 
   3205     result = PyList_New(sk_SSL_CIPHER_num(sk));
   3206     if (result == NULL) {
   3207         goto exit;
   3208     }
   3209 
   3210     for (i = 0; i < sk_SSL_CIPHER_num(sk); i++) {
   3211         cipher = sk_SSL_CIPHER_value(sk, i);
   3212         dct = cipher_to_dict(cipher);
   3213         if (dct == NULL) {
   3214             Py_CLEAR(result);
   3215             goto exit;
   3216         }
   3217         PyList_SET_ITEM(result, i, dct);
   3218     }
   3219 
   3220   exit:
   3221     if (ssl != NULL)
   3222         SSL_free(ssl);
   3223     return result;
   3224 
   3225 }
   3226 #endif
   3227 
   3228 
   3229 #if HAVE_NPN || HAVE_ALPN
   3230 static int
   3231 do_protocol_selection(int alpn, unsigned char **out, unsigned char *outlen,
   3232                       const unsigned char *server_protocols, unsigned int server_protocols_len,
   3233                       const unsigned char *client_protocols, unsigned int client_protocols_len)
   3234 {
   3235     int ret;
   3236     if (client_protocols == NULL) {
   3237         client_protocols = (unsigned char *)"";
   3238         client_protocols_len = 0;
   3239     }
   3240     if (server_protocols == NULL) {
   3241         server_protocols = (unsigned char *)"";
   3242         server_protocols_len = 0;
   3243     }
   3244 
   3245     ret = SSL_select_next_proto(out, outlen,
   3246                                 server_protocols, server_protocols_len,
   3247                                 client_protocols, client_protocols_len);
   3248     if (alpn && ret != OPENSSL_NPN_NEGOTIATED)
   3249         return SSL_TLSEXT_ERR_NOACK;
   3250 
   3251     return SSL_TLSEXT_ERR_OK;
   3252 }
   3253 #endif
   3254 
   3255 #if HAVE_NPN
   3256 /* this callback gets passed to SSL_CTX_set_next_protos_advertise_cb */
   3257 static int
   3258 _advertiseNPN_cb(SSL *s,
   3259                  const unsigned char **data, unsigned int *len,
   3260                  void *args)
   3261 {
   3262     PySSLContext *ssl_ctx = (PySSLContext *) args;
   3263 
   3264     if (ssl_ctx->npn_protocols == NULL) {
   3265         *data = (unsigned char *)"";
   3266         *len = 0;
   3267     } else {
   3268         *data = ssl_ctx->npn_protocols;
   3269         *len = ssl_ctx->npn_protocols_len;
   3270     }
   3271 
   3272     return SSL_TLSEXT_ERR_OK;
   3273 }
   3274 /* this callback gets passed to SSL_CTX_set_next_proto_select_cb */
   3275 static int
   3276 _selectNPN_cb(SSL *s,
   3277               unsigned char **out, unsigned char *outlen,
   3278               const unsigned char *server, unsigned int server_len,
   3279               void *args)
   3280 {
   3281     PySSLContext *ctx = (PySSLContext *)args;
   3282     return do_protocol_selection(0, out, outlen, server, server_len,
   3283                                  ctx->npn_protocols, ctx->npn_protocols_len);
   3284 }
   3285 #endif
   3286 
   3287 /*[clinic input]
   3288 _ssl._SSLContext._set_npn_protocols
   3289     protos: Py_buffer
   3290     /
   3291 [clinic start generated code]*/
   3292 
   3293 static PyObject *
   3294 _ssl__SSLContext__set_npn_protocols_impl(PySSLContext *self,
   3295                                          Py_buffer *protos)
   3296 /*[clinic end generated code: output=72b002c3324390c6 input=319fcb66abf95bd7]*/
   3297 {
   3298 #if HAVE_NPN
   3299     PyMem_Free(self->npn_protocols);
   3300     self->npn_protocols = PyMem_Malloc(protos->len);
   3301     if (self->npn_protocols == NULL)
   3302         return PyErr_NoMemory();
   3303     memcpy(self->npn_protocols, protos->buf, protos->len);
   3304     self->npn_protocols_len = (int) protos->len;
   3305 
   3306     /* set both server and client callbacks, because the context can
   3307      * be used to create both types of sockets */
   3308     SSL_CTX_set_next_protos_advertised_cb(self->ctx,
   3309                                           _advertiseNPN_cb,
   3310                                           self);
   3311     SSL_CTX_set_next_proto_select_cb(self->ctx,
   3312                                      _selectNPN_cb,
   3313                                      self);
   3314 
   3315     Py_RETURN_NONE;
   3316 #else
   3317     PyErr_SetString(PyExc_NotImplementedError,
   3318                     "The NPN extension requires OpenSSL 1.0.1 or later.");
   3319     return NULL;
   3320 #endif
   3321 }
   3322 
   3323 #if HAVE_ALPN
   3324 static int
   3325 _selectALPN_cb(SSL *s,
   3326               const unsigned char **out, unsigned char *outlen,
   3327               const unsigned char *client_protocols, unsigned int client_protocols_len,
   3328               void *args)
   3329 {
   3330     PySSLContext *ctx = (PySSLContext *)args;
   3331     return do_protocol_selection(1, (unsigned char **)out, outlen,
   3332                                  ctx->alpn_protocols, ctx->alpn_protocols_len,
   3333                                  client_protocols, client_protocols_len);
   3334 }
   3335 #endif
   3336 
   3337 /*[clinic input]
   3338 _ssl._SSLContext._set_alpn_protocols
   3339     protos: Py_buffer
   3340     /
   3341 [clinic start generated code]*/
   3342 
   3343 static PyObject *
   3344 _ssl__SSLContext__set_alpn_protocols_impl(PySSLContext *self,
   3345                                           Py_buffer *protos)
   3346 /*[clinic end generated code: output=87599a7f76651a9b input=9bba964595d519be]*/
   3347 {
   3348 #if HAVE_ALPN
   3349     if ((size_t)protos->len > UINT_MAX) {
   3350         PyErr_Format(PyExc_OverflowError,
   3351             "protocols longer than %d bytes", UINT_MAX);
   3352         return NULL;
   3353     }
   3354 
   3355     PyMem_FREE(self->alpn_protocols);
   3356     self->alpn_protocols = PyMem_Malloc(protos->len);
   3357     if (!self->alpn_protocols)
   3358         return PyErr_NoMemory();
   3359     memcpy(self->alpn_protocols, protos->buf, protos->len);
   3360     self->alpn_protocols_len = (unsigned int)protos->len;
   3361 
   3362     if (SSL_CTX_set_alpn_protos(self->ctx, self->alpn_protocols, self->alpn_protocols_len))
   3363         return PyErr_NoMemory();
   3364     SSL_CTX_set_alpn_select_cb(self->ctx, _selectALPN_cb, self);
   3365 
   3366     Py_RETURN_NONE;
   3367 #else
   3368     PyErr_SetString(PyExc_NotImplementedError,
   3369                     "The ALPN extension requires OpenSSL 1.0.2 or later.");
   3370     return NULL;
   3371 #endif
   3372 }
   3373 
   3374 static PyObject *
   3375 get_verify_mode(PySSLContext *self, void *c)
   3376 {
   3377     /* ignore SSL_VERIFY_CLIENT_ONCE and SSL_VERIFY_POST_HANDSHAKE */
   3378     int mask = (SSL_VERIFY_NONE | SSL_VERIFY_PEER |
   3379                 SSL_VERIFY_FAIL_IF_NO_PEER_CERT);
   3380     switch (SSL_CTX_get_verify_mode(self->ctx) & mask) {
   3381     case SSL_VERIFY_NONE:
   3382         return PyLong_FromLong(PY_SSL_CERT_NONE);
   3383     case SSL_VERIFY_PEER:
   3384         return PyLong_FromLong(PY_SSL_CERT_OPTIONAL);
   3385     case SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT:
   3386         return PyLong_FromLong(PY_SSL_CERT_REQUIRED);
   3387     }
   3388     PyErr_SetString(PySSLErrorObject,
   3389                     "invalid return value from SSL_CTX_get_verify_mode");
   3390     return NULL;
   3391 }
   3392 
   3393 static int
   3394 set_verify_mode(PySSLContext *self, PyObject *arg, void *c)
   3395 {
   3396     int n;
   3397     if (!PyArg_Parse(arg, "i", &n))
   3398         return -1;
   3399     if (n == PY_SSL_CERT_NONE && self->check_hostname) {
   3400         PyErr_SetString(PyExc_ValueError,
   3401                         "Cannot set verify_mode to CERT_NONE when "
   3402                         "check_hostname is enabled.");
   3403         return -1;
   3404     }
   3405     return _set_verify_mode(self, n);
   3406 }
   3407 
   3408 static PyObject *
   3409 get_verify_flags(PySSLContext *self, void *c)
   3410 {
   3411     X509_VERIFY_PARAM *param;
   3412     unsigned long flags;
   3413 
   3414     param = SSL_CTX_get0_param(self->ctx);
   3415     flags = X509_VERIFY_PARAM_get_flags(param);
   3416     return PyLong_FromUnsignedLong(flags);
   3417 }
   3418 
   3419 static int
   3420 set_verify_flags(PySSLContext *self, PyObject *arg, void *c)
   3421 {
   3422     X509_VERIFY_PARAM *param;
   3423     unsigned long new_flags, flags, set, clear;
   3424 
   3425     if (!PyArg_Parse(arg, "k", &new_flags))
   3426         return -1;
   3427     param = SSL_CTX_get0_param(self->ctx);
   3428     flags = X509_VERIFY_PARAM_get_flags(param);
   3429     clear = flags & ~new_flags;
   3430     set = ~flags & new_flags;
   3431     if (clear) {
   3432         if (!X509_VERIFY_PARAM_clear_flags(param, clear)) {
   3433             _setSSLError(NULL, 0, __FILE__, __LINE__);
   3434             return -1;
   3435         }
   3436     }
   3437     if (set) {
   3438         if (!X509_VERIFY_PARAM_set_flags(param, set)) {
   3439             _setSSLError(NULL, 0, __FILE__, __LINE__);
   3440             return -1;
   3441         }
   3442     }
   3443     return 0;
   3444 }
   3445 
   3446 /* Getter and setter for protocol version */
   3447 #if defined(SSL_CTRL_GET_MAX_PROTO_VERSION)
   3448 
   3449 
   3450 static int
   3451 set_min_max_proto_version(PySSLContext *self, PyObject *arg, int what)
   3452 {
   3453     long v;
   3454     int result;
   3455 
   3456     if (!PyArg_Parse(arg, "l", &v))
   3457         return -1;
   3458     if (v > INT_MAX) {
   3459         PyErr_SetString(PyExc_OverflowError, "Option is too long");
   3460         return -1;
   3461     }
   3462 
   3463     switch(self->protocol) {
   3464     case PY_SSL_VERSION_TLS_CLIENT:  /* fall through */
   3465     case PY_SSL_VERSION_TLS_SERVER:  /* fall through */
   3466     case PY_SSL_VERSION_TLS:
   3467         break;
   3468     default:
   3469         PyErr_SetString(
   3470             PyExc_ValueError,
   3471             "The context's protocol doesn't support modification of "
   3472             "highest and lowest version."
   3473         );
   3474         return -1;
   3475     }
   3476 
   3477     if (what == 0) {
   3478         switch(v) {
   3479         case PY_PROTO_MINIMUM_SUPPORTED:
   3480             v = 0;
   3481             break;
   3482         case PY_PROTO_MAXIMUM_SUPPORTED:
   3483             /* Emulate max for set_min_proto_version */
   3484             v = PY_PROTO_MAXIMUM_AVAILABLE;
   3485             break;
   3486         default:
   3487             break;
   3488         }
   3489         result = SSL_CTX_set_min_proto_version(self->ctx, v);
   3490     }
   3491     else {
   3492         switch(v) {
   3493         case PY_PROTO_MAXIMUM_SUPPORTED:
   3494             v = 0;
   3495             break;
   3496         case PY_PROTO_MINIMUM_SUPPORTED:
   3497             /* Emulate max for set_min_proto_version */
   3498             v = PY_PROTO_MINIMUM_AVAILABLE;
   3499             break;
   3500         default:
   3501             break;
   3502         }
   3503         result = SSL_CTX_set_max_proto_version(self->ctx, v);
   3504     }
   3505     if (result == 0) {
   3506         PyErr_Format(PyExc_ValueError,
   3507                      "Unsupported protocol version 0x%x", v);
   3508         return -1;
   3509     }
   3510     return 0;
   3511 }
   3512 
   3513 static PyObject *
   3514 get_minimum_version(PySSLContext *self, void *c)
   3515 {
   3516     int v = SSL_CTX_ctrl(self->ctx, SSL_CTRL_GET_MIN_PROTO_VERSION, 0, NULL);
   3517     if (v == 0) {
   3518         v = PY_PROTO_MINIMUM_SUPPORTED;
   3519     }
   3520     return PyLong_FromLong(v);
   3521 }
   3522 
   3523 static int
   3524 set_minimum_version(PySSLContext *self, PyObject *arg, void *c)
   3525 {
   3526     return set_min_max_proto_version(self, arg, 0);
   3527 }
   3528 
   3529 static PyObject *
   3530 get_maximum_version(PySSLContext *self, void *c)
   3531 {
   3532     int v = SSL_CTX_ctrl(self->ctx, SSL_CTRL_GET_MAX_PROTO_VERSION, 0, NULL);
   3533     if (v == 0) {
   3534         v = PY_PROTO_MAXIMUM_SUPPORTED;
   3535     }
   3536     return PyLong_FromLong(v);
   3537 }
   3538 
   3539 static int
   3540 set_maximum_version(PySSLContext *self, PyObject *arg, void *c)
   3541 {
   3542     return set_min_max_proto_version(self, arg, 1);
   3543 }
   3544 #endif /* SSL_CTRL_GET_MAX_PROTO_VERSION */
   3545 
   3546 static PyObject *
   3547 get_options(PySSLContext *self, void *c)
   3548 {
   3549     return PyLong_FromLong(SSL_CTX_get_options(self->ctx));
   3550 }
   3551 
   3552 static int
   3553 set_options(PySSLContext *self, PyObject *arg, void *c)
   3554 {
   3555     long new_opts, opts, set, clear;
   3556     if (!PyArg_Parse(arg, "l", &new_opts))
   3557         return -1;
   3558     opts = SSL_CTX_get_options(self->ctx);
   3559     clear = opts & ~new_opts;
   3560     set = ~opts & new_opts;
   3561     if (clear) {
   3562 #ifdef HAVE_SSL_CTX_CLEAR_OPTIONS
   3563         SSL_CTX_clear_options(self->ctx, clear);
   3564 #else
   3565         PyErr_SetString(PyExc_ValueError,
   3566                         "can't clear options before OpenSSL 0.9.8m");
   3567         return -1;
   3568 #endif
   3569     }
   3570     if (set)
   3571         SSL_CTX_set_options(self->ctx, set);
   3572     return 0;
   3573 }
   3574 
   3575 static PyObject *
   3576 get_host_flags(PySSLContext *self, void *c)
   3577 {
   3578     return PyLong_FromUnsignedLong(self->hostflags);
   3579 }
   3580 
   3581 static int
   3582 set_host_flags(PySSLContext *self, PyObject *arg, void *c)
   3583 {
   3584     X509_VERIFY_PARAM *param;
   3585     unsigned int new_flags = 0;
   3586 
   3587     if (!PyArg_Parse(arg, "I", &new_flags))
   3588         return -1;
   3589 
   3590     param = SSL_CTX_get0_param(self->ctx);
   3591     self->hostflags = new_flags;
   3592     X509_VERIFY_PARAM_set_hostflags(param, new_flags);
   3593     return 0;
   3594 }
   3595 
   3596 static PyObject *
   3597 get_check_hostname(PySSLContext *self, void *c)
   3598 {
   3599     return PyBool_FromLong(self->check_hostname);
   3600 }
   3601 
   3602 static int
   3603 set_check_hostname(PySSLContext *self, PyObject *arg, void *c)
   3604 {
   3605     int check_hostname;
   3606     if (!PyArg_Parse(arg, "p", &check_hostname))
   3607         return -1;
   3608     if (check_hostname &&
   3609             SSL_CTX_get_verify_mode(self->ctx) == SSL_VERIFY_NONE) {
   3610         /* check_hostname = True sets verify_mode = CERT_REQUIRED */
   3611         if (_set_verify_mode(self, PY_SSL_CERT_REQUIRED) == -1) {
   3612             return -1;
   3613         }
   3614     }
   3615     self->check_hostname = check_hostname;
   3616     return 0;
   3617 }
   3618 
   3619 static PyObject *
   3620 get_post_handshake_auth(PySSLContext *self, void *c) {
   3621 #if TLS1_3_VERSION
   3622     return PyBool_FromLong(self->post_handshake_auth);
   3623 #else
   3624     Py_RETURN_NONE;
   3625 #endif
   3626 }
   3627 
   3628 #if TLS1_3_VERSION
   3629 static int
   3630 set_post_handshake_auth(PySSLContext *self, PyObject *arg, void *c) {
   3631     int (*verify_cb)(int, X509_STORE_CTX *) = NULL;
   3632     int mode = SSL_CTX_get_verify_mode(self->ctx);
   3633     if (arg == NULL) {
   3634         PyErr_SetString(PyExc_AttributeError, "cannot delete attribute");
   3635         return -1;
   3636     }
   3637     int pha = PyObject_IsTrue(arg);
   3638 
   3639     if (pha == -1) {
   3640         return -1;
   3641     }
   3642     self->post_handshake_auth = pha;
   3643 
   3644     /* client-side socket setting, ignored by server-side */
   3645     SSL_CTX_set_post_handshake_auth(self->ctx, pha);
   3646 
   3647     /* server-side socket setting, ignored by client-side */
   3648     verify_cb = SSL_CTX_get_verify_callback(self->ctx);
   3649     if (pha) {
   3650         mode |= SSL_VERIFY_POST_HANDSHAKE;
   3651     } else {
   3652         mode ^= SSL_VERIFY_POST_HANDSHAKE;
   3653     }
   3654     SSL_CTX_set_verify(self->ctx, mode, verify_cb);
   3655 
   3656     return 0;
   3657 }
   3658 #endif
   3659 
   3660 static PyObject *
   3661 get_protocol(PySSLContext *self, void *c) {
   3662     return PyLong_FromLong(self->protocol);
   3663 }
   3664 
   3665 typedef struct {
   3666     PyThreadState *thread_state;
   3667     PyObject *callable;
   3668     char *password;
   3669     int size;
   3670     int error;
   3671 } _PySSLPasswordInfo;
   3672 
   3673 static int
   3674 _pwinfo_set(_PySSLPasswordInfo *pw_info, PyObject* password,
   3675             const char *bad_type_error)
   3676 {
   3677     /* Set the password and size fields of a _PySSLPasswordInfo struct
   3678        from a unicode, bytes, or byte array object.
   3679        The password field will be dynamically allocated and must be freed
   3680        by the caller */
   3681     PyObject *password_bytes = NULL;
   3682     const char *data = NULL;
   3683     Py_ssize_t size;
   3684 
   3685     if (PyUnicode_Check(password)) {
   3686         password_bytes = PyUnicode_AsEncodedString(password, NULL, NULL);
   3687         if (!password_bytes) {
   3688             goto error;
   3689         }
   3690         data = PyBytes_AS_STRING(password_bytes);
   3691         size = PyBytes_GET_SIZE(password_bytes);
   3692     } else if (PyBytes_Check(password)) {
   3693         data = PyBytes_AS_STRING(password);
   3694         size = PyBytes_GET_SIZE(password);
   3695     } else if (PyByteArray_Check(password)) {
   3696         data = PyByteArray_AS_STRING(password);
   3697         size = PyByteArray_GET_SIZE(password);
   3698     } else {
   3699         PyErr_SetString(PyExc_TypeError, bad_type_error);
   3700         goto error;
   3701     }
   3702 
   3703     if (size > (Py_ssize_t)INT_MAX) {
   3704         PyErr_Format(PyExc_ValueError,
   3705                      "password cannot be longer than %d bytes", INT_MAX);
   3706         goto error;
   3707     }
   3708 
   3709     PyMem_Free(pw_info->password);
   3710     pw_info->password = PyMem_Malloc(size);
   3711     if (!pw_info->password) {
   3712         PyErr_SetString(PyExc_MemoryError,
   3713                         "unable to allocate password buffer");
   3714         goto error;
   3715     }
   3716     memcpy(pw_info->password, data, size);
   3717     pw_info->size = (int)size;
   3718 
   3719     Py_XDECREF(password_bytes);
   3720     return 1;
   3721 
   3722 error:
   3723     Py_XDECREF(password_bytes);
   3724     return 0;
   3725 }
   3726 
   3727 static int
   3728 _password_callback(char *buf, int size, int rwflag, void *userdata)
   3729 {
   3730     _PySSLPasswordInfo *pw_info = (_PySSLPasswordInfo*) userdata;
   3731     PyObject *fn_ret = NULL;
   3732 
   3733     PySSL_END_ALLOW_THREADS_S(pw_info->thread_state);
   3734 
   3735     if (pw_info->callable) {
   3736         fn_ret = _PyObject_CallNoArg(pw_info->callable);
   3737         if (!fn_ret) {
   3738             /* TODO: It would be nice to move _ctypes_add_traceback() into the
   3739                core python API, so we could use it to add a frame here */
   3740             goto error;
   3741         }
   3742 
   3743         if (!_pwinfo_set(pw_info, fn_ret,
   3744                          "password callback must return a string")) {
   3745             goto error;
   3746         }
   3747         Py_CLEAR(fn_ret);
   3748     }
   3749 
   3750     if (pw_info->size > size) {
   3751         PyErr_Format(PyExc_ValueError,
   3752                      "password cannot be longer than %d bytes", size);
   3753         goto error;
   3754     }
   3755 
   3756     PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
   3757     memcpy(buf, pw_info->password, pw_info->size);
   3758     return pw_info->size;
   3759 
   3760 error:
   3761     Py_XDECREF(fn_ret);
   3762     PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
   3763     pw_info->error = 1;
   3764     return -1;
   3765 }
   3766 
   3767 /*[clinic input]
   3768 _ssl._SSLContext.load_cert_chain
   3769     certfile: object
   3770     keyfile: object = NULL
   3771     password: object = NULL
   3772 
   3773 [clinic start generated code]*/
   3774 
   3775 static PyObject *
   3776 _ssl__SSLContext_load_cert_chain_impl(PySSLContext *self, PyObject *certfile,
   3777                                       PyObject *keyfile, PyObject *password)
   3778 /*[clinic end generated code: output=9480bc1c380e2095 input=7cf9ac673cbee6fc]*/
   3779 {
   3780     PyObject *certfile_bytes = NULL, *keyfile_bytes = NULL;
   3781     pem_password_cb *orig_passwd_cb = SSL_CTX_get_default_passwd_cb(self->ctx);
   3782     void *orig_passwd_userdata = SSL_CTX_get_default_passwd_cb_userdata(self->ctx);
   3783     _PySSLPasswordInfo pw_info = { NULL, NULL, NULL, 0, 0 };
   3784     int r;
   3785 
   3786     errno = 0;
   3787     ERR_clear_error();
   3788     if (keyfile == Py_None)
   3789         keyfile = NULL;
   3790     if (!PyUnicode_FSConverter(certfile, &certfile_bytes)) {
   3791         PyErr_SetString(PyExc_TypeError,
   3792                         "certfile should be a valid filesystem path");
   3793         return NULL;
   3794     }
   3795     if (keyfile && !PyUnicode_FSConverter(keyfile, &keyfile_bytes)) {
   3796         PyErr_SetString(PyExc_TypeError,
   3797                         "keyfile should be a valid filesystem path");
   3798         goto error;
   3799     }
   3800     if (password && password != Py_None) {
   3801         if (PyCallable_Check(password)) {
   3802             pw_info.callable = password;
   3803         } else if (!_pwinfo_set(&pw_info, password,
   3804                                 "password should be a string or callable")) {
   3805             goto error;
   3806         }
   3807         SSL_CTX_set_default_passwd_cb(self->ctx, _password_callback);
   3808         SSL_CTX_set_default_passwd_cb_userdata(self->ctx, &pw_info);
   3809     }
   3810     PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
   3811     r = SSL_CTX_use_certificate_chain_file(self->ctx,
   3812         PyBytes_AS_STRING(certfile_bytes));
   3813     PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
   3814     if (r != 1) {
   3815         if (pw_info.error) {
   3816             ERR_clear_error();
   3817             /* the password callback has already set the error information */
   3818         }
   3819         else if (errno != 0) {
   3820             ERR_clear_error();
   3821             PyErr_SetFromErrno(PyExc_OSError);
   3822         }
   3823         else {
   3824             _setSSLError(NULL, 0, __FILE__, __LINE__);
   3825         }
   3826         goto error;
   3827     }
   3828     PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
   3829     r = SSL_CTX_use_PrivateKey_file(self->ctx,
   3830         PyBytes_AS_STRING(keyfile ? keyfile_bytes : certfile_bytes),
   3831         SSL_FILETYPE_PEM);
   3832     PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
   3833     Py_CLEAR(keyfile_bytes);
   3834     Py_CLEAR(certfile_bytes);
   3835     if (r != 1) {
   3836         if (pw_info.error) {
   3837             ERR_clear_error();
   3838             /* the password callback has already set the error information */
   3839         }
   3840         else if (errno != 0) {
   3841             ERR_clear_error();
   3842             PyErr_SetFromErrno(PyExc_OSError);
   3843         }
   3844         else {
   3845             _setSSLError(NULL, 0, __FILE__, __LINE__);
   3846         }
   3847         goto error;
   3848     }
   3849     PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
   3850     r = SSL_CTX_check_private_key(self->ctx);
   3851     PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
   3852     if (r != 1) {
   3853         _setSSLError(NULL, 0, __FILE__, __LINE__);
   3854         goto error;
   3855     }
   3856     SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
   3857     SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
   3858     PyMem_Free(pw_info.password);
   3859     Py_RETURN_NONE;
   3860 
   3861 error:
   3862     SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
   3863     SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
   3864     PyMem_Free(pw_info.password);
   3865     Py_XDECREF(keyfile_bytes);
   3866     Py_XDECREF(certfile_bytes);
   3867     return NULL;
   3868 }
   3869 
   3870 /* internal helper function, returns -1 on error
   3871  */
   3872 static int
   3873 _add_ca_certs(PySSLContext *self, void *data, Py_ssize_t len,
   3874               int filetype)
   3875 {
   3876     BIO *biobuf = NULL;
   3877     X509_STORE *store;
   3878     int retval = 0, err, loaded = 0;
   3879 
   3880     assert(filetype == SSL_FILETYPE_ASN1 || filetype == SSL_FILETYPE_PEM);
   3881 
   3882     if (len <= 0) {
   3883         PyErr_SetString(PyExc_ValueError,
   3884                         "Empty certificate data");
   3885         return -1;
   3886     } else if (len > INT_MAX) {
   3887         PyErr_SetString(PyExc_OverflowError,
   3888                         "Certificate data is too long.");
   3889         return -1;
   3890     }
   3891 
   3892     biobuf = BIO_new_mem_buf(data, (int)len);
   3893     if (biobuf == NULL) {
   3894         _setSSLError("Can't allocate buffer", 0, __FILE__, __LINE__);
   3895         return -1;
   3896     }
   3897 
   3898     store = SSL_CTX_get_cert_store(self->ctx);
   3899     assert(store != NULL);
   3900 
   3901     while (1) {
   3902         X509 *cert = NULL;
   3903         int r;
   3904 
   3905         if (filetype == SSL_FILETYPE_ASN1) {
   3906             cert = d2i_X509_bio(biobuf, NULL);
   3907         } else {
   3908             cert = PEM_read_bio_X509(biobuf, NULL,
   3909                                      SSL_CTX_get_default_passwd_cb(self->ctx),
   3910                                      SSL_CTX_get_default_passwd_cb_userdata(self->ctx)
   3911                                     );
   3912         }
   3913         if (cert == NULL) {
   3914             break;
   3915         }
   3916         r = X509_STORE_add_cert(store, cert);
   3917         X509_free(cert);
   3918         if (!r) {
   3919             err = ERR_peek_last_error();
   3920             if ((ERR_GET_LIB(err) == ERR_LIB_X509) &&
   3921                 (ERR_GET_REASON(err) == X509_R_CERT_ALREADY_IN_HASH_TABLE)) {
   3922                 /* cert already in hash table, not an error */
   3923                 ERR_clear_error();
   3924             } else {
   3925                 break;
   3926             }
   3927         }
   3928         loaded++;
   3929     }
   3930 
   3931     err = ERR_peek_last_error();
   3932     if ((filetype == SSL_FILETYPE_ASN1) &&
   3933             (loaded > 0) &&
   3934             (ERR_GET_LIB(err) == ERR_LIB_ASN1) &&
   3935             (ERR_GET_REASON(err) == ASN1_R_HEADER_TOO_LONG)) {
   3936         /* EOF ASN1 file, not an error */
   3937         ERR_clear_error();
   3938         retval = 0;
   3939     } else if ((filetype == SSL_FILETYPE_PEM) &&
   3940                    (loaded > 0) &&
   3941                    (ERR_GET_LIB(err) == ERR_LIB_PEM) &&
   3942                    (ERR_GET_REASON(err) == PEM_R_NO_START_LINE)) {
   3943         /* EOF PEM file, not an error */
   3944         ERR_clear_error();
   3945         retval = 0;
   3946     } else {
   3947         _setSSLError(NULL, 0, __FILE__, __LINE__);
   3948         retval = -1;
   3949     }
   3950 
   3951     BIO_free(biobuf);
   3952     return retval;
   3953 }
   3954 
   3955 
   3956 /*[clinic input]
   3957 _ssl._SSLContext.load_verify_locations
   3958     cafile: object = NULL
   3959     capath: object = NULL
   3960     cadata: object = NULL
   3961 
   3962 [clinic start generated code]*/
   3963 
   3964 static PyObject *
   3965 _ssl__SSLContext_load_verify_locations_impl(PySSLContext *self,
   3966                                             PyObject *cafile,
   3967                                             PyObject *capath,
   3968                                             PyObject *cadata)
   3969 /*[clinic end generated code: output=454c7e41230ca551 input=997f1fb3a784ef88]*/
   3970 {
   3971     PyObject *cafile_bytes = NULL, *capath_bytes = NULL;
   3972     const char *cafile_buf = NULL, *capath_buf = NULL;
   3973     int r = 0, ok = 1;
   3974 
   3975     errno = 0;
   3976     if (cafile == Py_None)
   3977         cafile = NULL;
   3978     if (capath == Py_None)
   3979         capath = NULL;
   3980     if (cadata == Py_None)
   3981         cadata = NULL;
   3982 
   3983     if (cafile == NULL && capath == NULL && cadata == NULL) {
   3984         PyErr_SetString(PyExc_TypeError,
   3985                         "cafile, capath and cadata cannot be all omitted");
   3986         goto error;
   3987     }
   3988     if (cafile && !PyUnicode_FSConverter(cafile, &cafile_bytes)) {
   3989         PyErr_SetString(PyExc_TypeError,
   3990                         "cafile should be a valid filesystem path");
   3991         goto error;
   3992     }
   3993     if (capath && !PyUnicode_FSConverter(capath, &capath_bytes)) {
   3994         PyErr_SetString(PyExc_TypeError,
   3995                         "capath should be a valid filesystem path");
   3996         goto error;
   3997     }
   3998 
   3999     /* validata cadata type and load cadata */
   4000     if (cadata) {
   4001         Py_buffer buf;
   4002         PyObject *cadata_ascii = NULL;
   4003 
   4004         if (PyObject_GetBuffer(cadata, &buf, PyBUF_SIMPLE) == 0) {
   4005             if (!PyBuffer_IsContiguous(&buf, 'C') || buf.ndim > 1) {
   4006                 PyBuffer_Release(&buf);
   4007                 PyErr_SetString(PyExc_TypeError,
   4008                                 "cadata should be a contiguous buffer with "
   4009                                 "a single dimension");
   4010                 goto error;
   4011             }
   4012             r = _add_ca_certs(self, buf.buf, buf.len, SSL_FILETYPE_ASN1);
   4013             PyBuffer_Release(&buf);
   4014             if (r == -1) {
   4015                 goto error;
   4016             }
   4017         } else {
   4018             PyErr_Clear();
   4019             cadata_ascii = PyUnicode_AsASCIIString(cadata);
   4020             if (cadata_ascii == NULL) {
   4021                 PyErr_SetString(PyExc_TypeError,
   4022                                 "cadata should be an ASCII string or a "
   4023                                 "bytes-like object");
   4024                 goto error;
   4025             }
   4026             r = _add_ca_certs(self,
   4027                               PyBytes_AS_STRING(cadata_ascii),
   4028                               PyBytes_GET_SIZE(cadata_ascii),
   4029                               SSL_FILETYPE_PEM);
   4030             Py_DECREF(cadata_ascii);
   4031             if (r == -1) {
   4032                 goto error;
   4033             }
   4034         }
   4035     }
   4036 
   4037     /* load cafile or capath */
   4038     if (cafile || capath) {
   4039         if (cafile)
   4040             cafile_buf = PyBytes_AS_STRING(cafile_bytes);
   4041         if (capath)
   4042             capath_buf = PyBytes_AS_STRING(capath_bytes);
   4043         PySSL_BEGIN_ALLOW_THREADS
   4044         r = SSL_CTX_load_verify_locations(self->ctx, cafile_buf, capath_buf);
   4045         PySSL_END_ALLOW_THREADS
   4046         if (r != 1) {
   4047             ok = 0;
   4048             if (errno != 0) {
   4049                 ERR_clear_error();
   4050                 PyErr_SetFromErrno(PyExc_OSError);
   4051             }
   4052             else {
   4053                 _setSSLError(NULL, 0, __FILE__, __LINE__);
   4054             }
   4055             goto error;
   4056         }
   4057     }
   4058     goto end;
   4059 
   4060   error:
   4061     ok = 0;
   4062   end:
   4063     Py_XDECREF(cafile_bytes);
   4064     Py_XDECREF(capath_bytes);
   4065     if (ok) {
   4066         Py_RETURN_NONE;
   4067     } else {
   4068         return NULL;
   4069     }
   4070 }
   4071 
   4072 /*[clinic input]
   4073 _ssl._SSLContext.load_dh_params
   4074     path as filepath: object
   4075     /
   4076 
   4077 [clinic start generated code]*/
   4078 
   4079 static PyObject *
   4080 _ssl__SSLContext_load_dh_params(PySSLContext *self, PyObject *filepath)
   4081 /*[clinic end generated code: output=1c8e57a38e055af0 input=c8871f3c796ae1d6]*/
   4082 {
   4083     FILE *f;
   4084     DH *dh;
   4085 
   4086     f = _Py_fopen_obj(filepath, "rb");
   4087     if (f == NULL)
   4088         return NULL;
   4089 
   4090     errno = 0;
   4091     PySSL_BEGIN_ALLOW_THREADS
   4092     dh = PEM_read_DHparams(f, NULL, NULL, NULL);
   4093     fclose(f);
   4094     PySSL_END_ALLOW_THREADS
   4095     if (dh == NULL) {
   4096         if (errno != 0) {
   4097             ERR_clear_error();
   4098             PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
   4099         }
   4100         else {
   4101             _setSSLError(NULL, 0, __FILE__, __LINE__);
   4102         }
   4103         return NULL;
   4104     }
   4105     if (SSL_CTX_set_tmp_dh(self->ctx, dh) == 0)
   4106         _setSSLError(NULL, 0, __FILE__, __LINE__);
   4107     DH_free(dh);
   4108     Py_RETURN_NONE;
   4109 }
   4110 
   4111 /*[clinic input]
   4112 _ssl._SSLContext._wrap_socket
   4113     sock: object(subclass_of="PySocketModule.Sock_Type")
   4114     server_side: int
   4115     server_hostname as hostname_obj: object = None
   4116     *
   4117     owner: object = None
   4118     session: object = None
   4119 
   4120 [clinic start generated code]*/
   4121 
   4122 static PyObject *
   4123 _ssl__SSLContext__wrap_socket_impl(PySSLContext *self, PyObject *sock,
   4124                                    int server_side, PyObject *hostname_obj,
   4125                                    PyObject *owner, PyObject *session)
   4126 /*[clinic end generated code: output=f103f238633940b4 input=957d5006183d1894]*/
   4127 {
   4128     char *hostname = NULL;
   4129     PyObject *res;
   4130 
   4131     /* server_hostname is either None (or absent), or to be encoded
   4132        as IDN A-label (ASCII str) without NULL bytes. */
   4133     if (hostname_obj != Py_None) {
   4134         if (!PyArg_Parse(hostname_obj, "es", "ascii", &hostname))
   4135             return NULL;
   4136     }
   4137 
   4138     res = (PyObject *) newPySSLSocket(self, (PySocketSockObject *)sock,
   4139                                       server_side, hostname,
   4140                                       owner, session,
   4141                                       NULL, NULL);
   4142     if (hostname != NULL)
   4143         PyMem_Free(hostname);
   4144     return res;
   4145 }
   4146 
   4147 /*[clinic input]
   4148 _ssl._SSLContext._wrap_bio
   4149     incoming: object(subclass_of="&PySSLMemoryBIO_Type", type="PySSLMemoryBIO *")
   4150     outgoing: object(subclass_of="&PySSLMemoryBIO_Type", type="PySSLMemoryBIO *")
   4151     server_side: int
   4152     server_hostname as hostname_obj: object = None
   4153     *
   4154     owner: object = None
   4155     session: object = None
   4156 
   4157 [clinic start generated code]*/
   4158 
   4159 static PyObject *
   4160 _ssl__SSLContext__wrap_bio_impl(PySSLContext *self, PySSLMemoryBIO *incoming,
   4161                                 PySSLMemoryBIO *outgoing, int server_side,
   4162                                 PyObject *hostname_obj, PyObject *owner,
   4163                                 PyObject *session)
   4164 /*[clinic end generated code: output=5c5d6d9b41f99332 input=8cf22f4d586ac56a]*/
   4165 {
   4166     char *hostname = NULL;
   4167     PyObject *res;
   4168 
   4169     /* server_hostname is either None (or absent), or to be encoded
   4170        as IDN A-label (ASCII str) without NULL bytes. */
   4171     if (hostname_obj != Py_None) {
   4172         if (!PyArg_Parse(hostname_obj, "es", "ascii", &hostname))
   4173             return NULL;
   4174     }
   4175 
   4176     res = (PyObject *) newPySSLSocket(self, NULL, server_side, hostname,
   4177                                       owner, session,
   4178                                       incoming, outgoing);
   4179 
   4180     PyMem_Free(hostname);
   4181     return res;
   4182 }
   4183 
   4184 /*[clinic input]
   4185 _ssl._SSLContext.session_stats
   4186 [clinic start generated code]*/
   4187 
   4188 static PyObject *
   4189 _ssl__SSLContext_session_stats_impl(PySSLContext *self)
   4190 /*[clinic end generated code: output=0d96411c42893bfb input=7e0a81fb11102c8b]*/
   4191 {
   4192     int r;
   4193     PyObject *value, *stats = PyDict_New();
   4194     if (!stats)
   4195         return NULL;
   4196 
   4197 #define ADD_STATS(SSL_NAME, KEY_NAME) \
   4198     value = PyLong_FromLong(SSL_CTX_sess_ ## SSL_NAME (self->ctx)); \
   4199     if (value == NULL) \
   4200         goto error; \
   4201     r = PyDict_SetItemString(stats, KEY_NAME, value); \
   4202     Py_DECREF(value); \
   4203     if (r < 0) \
   4204         goto error;
   4205 
   4206     ADD_STATS(number, "number");
   4207     ADD_STATS(connect, "connect");
   4208     ADD_STATS(connect_good, "connect_good");
   4209     ADD_STATS(connect_renegotiate, "connect_renegotiate");
   4210     ADD_STATS(accept, "accept");
   4211     ADD_STATS(accept_good, "accept_good");
   4212     ADD_STATS(accept_renegotiate, "accept_renegotiate");
   4213     ADD_STATS(accept, "accept");
   4214     ADD_STATS(hits, "hits");
   4215     ADD_STATS(misses, "misses");
   4216     ADD_STATS(timeouts, "timeouts");
   4217     ADD_STATS(cache_full, "cache_full");
   4218 
   4219 #undef ADD_STATS
   4220 
   4221     return stats;
   4222 
   4223 error:
   4224     Py_DECREF(stats);
   4225     return NULL;
   4226 }
   4227 
   4228 /*[clinic input]
   4229 _ssl._SSLContext.set_default_verify_paths
   4230 [clinic start generated code]*/
   4231 
   4232 static PyObject *
   4233 _ssl__SSLContext_set_default_verify_paths_impl(PySSLContext *self)
   4234 /*[clinic end generated code: output=0bee74e6e09deaaa input=35f3408021463d74]*/
   4235 {
   4236     if (!SSL_CTX_set_default_verify_paths(self->ctx)) {
   4237         _setSSLError(NULL, 0, __FILE__, __LINE__);
   4238         return NULL;
   4239     }
   4240     Py_RETURN_NONE;
   4241 }
   4242 
   4243 #ifndef OPENSSL_NO_ECDH
   4244 /*[clinic input]
   4245 _ssl._SSLContext.set_ecdh_curve
   4246     name: object
   4247     /
   4248 
   4249 [clinic start generated code]*/
   4250 
   4251 static PyObject *
   4252 _ssl__SSLContext_set_ecdh_curve(PySSLContext *self, PyObject *name)
   4253 /*[clinic end generated code: output=23022c196e40d7d2 input=c2bafb6f6e34726b]*/
   4254 {
   4255     PyObject *name_bytes;
   4256     int nid;
   4257     EC_KEY *key;
   4258 
   4259     if (!PyUnicode_FSConverter(name, &name_bytes))
   4260         return NULL;
   4261     assert(PyBytes_Check(name_bytes));
   4262     nid = OBJ_sn2nid(PyBytes_AS_STRING(name_bytes));
   4263     Py_DECREF(name_bytes);
   4264     if (nid == 0) {
   4265         PyErr_Format(PyExc_ValueError,
   4266                      "unknown elliptic curve name %R", name);
   4267         return NULL;
   4268     }
   4269     key = EC_KEY_new_by_curve_name(nid);
   4270     if (key == NULL) {
   4271         _setSSLError(NULL, 0, __FILE__, __LINE__);
   4272         return NULL;
   4273     }
   4274     SSL_CTX_set_tmp_ecdh(self->ctx, key);
   4275     EC_KEY_free(key);
   4276     Py_RETURN_NONE;
   4277 }
   4278 #endif
   4279 
   4280 #if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
   4281 static int
   4282 _servername_callback(SSL *s, int *al, void *args)
   4283 {
   4284     int ret;
   4285     PySSLContext *ssl_ctx = (PySSLContext *) args;
   4286     PySSLSocket *ssl;
   4287     PyObject *result;
   4288     /* The high-level ssl.SSLSocket object */
   4289     PyObject *ssl_socket;
   4290     const char *servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
   4291     PyGILState_STATE gstate = PyGILState_Ensure();
   4292 
   4293     if (ssl_ctx->set_sni_cb == NULL) {
   4294         /* remove race condition in this the call back while if removing the
   4295          * callback is in progress */
   4296         PyGILState_Release(gstate);
   4297         return SSL_TLSEXT_ERR_OK;
   4298     }
   4299 
   4300     ssl = SSL_get_app_data(s);
   4301     assert(PySSLSocket_Check(ssl));
   4302 
   4303     /* The servername callback expects an argument that represents the current
   4304      * SSL connection and that has a .context attribute that can be changed to
   4305      * identify the requested hostname. Since the official API is the Python
   4306      * level API we want to pass the callback a Python level object rather than
   4307      * a _ssl.SSLSocket instance. If there's an "owner" (typically an
   4308      * SSLObject) that will be passed. Otherwise if there's a socket then that
   4309      * will be passed. If both do not exist only then the C-level object is
   4310      * passed. */
   4311     if (ssl->owner)
   4312         ssl_socket = PyWeakref_GetObject(ssl->owner);
   4313     else if (ssl->Socket)
   4314         ssl_socket = PyWeakref_GetObject(ssl->Socket);
   4315     else
   4316         ssl_socket = (PyObject *) ssl;
   4317 
   4318     Py_INCREF(ssl_socket);
   4319     if (ssl_socket == Py_None)
   4320         goto error;
   4321 
   4322     if (servername == NULL) {
   4323         result = PyObject_CallFunctionObjArgs(ssl_ctx->set_sni_cb, ssl_socket,
   4324                                               Py_None, ssl_ctx, NULL);
   4325     }
   4326     else {
   4327         PyObject *servername_bytes;
   4328         PyObject *servername_str;
   4329 
   4330         servername_bytes = PyBytes_FromString(servername);
   4331         if (servername_bytes == NULL) {
   4332             PyErr_WriteUnraisable((PyObject *) ssl_ctx);
   4333             goto error;
   4334         }
   4335         /* server_hostname was encoded to an A-label by our caller; put it
   4336          * back into a str object, but still as an A-label (bpo-28414)
   4337          */
   4338         servername_str = PyUnicode_FromEncodedObject(servername_bytes, "ascii", NULL);
   4339         Py_DECREF(servername_bytes);
   4340         if (servername_str == NULL) {
   4341             PyErr_WriteUnraisable(servername_bytes);
   4342             goto error;
   4343         }
   4344         result = PyObject_CallFunctionObjArgs(
   4345             ssl_ctx->set_sni_cb, ssl_socket, servername_str,
   4346             ssl_ctx, NULL);
   4347         Py_DECREF(servername_str);
   4348     }
   4349     Py_DECREF(ssl_socket);
   4350 
   4351     if (result == NULL) {
   4352         PyErr_WriteUnraisable(ssl_ctx->set_sni_cb);
   4353         *al = SSL_AD_HANDSHAKE_FAILURE;
   4354         ret = SSL_TLSEXT_ERR_ALERT_FATAL;
   4355     }
   4356     else {
   4357         /* Result may be None, a SSLContext or an integer
   4358          * None and SSLContext are OK, integer or other values are an error.
   4359          */
   4360         if (result == Py_None) {
   4361             ret = SSL_TLSEXT_ERR_OK;
   4362         } else {
   4363             *al = (int) PyLong_AsLong(result);
   4364             if (PyErr_Occurred()) {
   4365                 PyErr_WriteUnraisable(result);
   4366                 *al = SSL_AD_INTERNAL_ERROR;
   4367             }
   4368             ret = SSL_TLSEXT_ERR_ALERT_FATAL;
   4369         }
   4370         Py_DECREF(result);
   4371     }
   4372 
   4373     PyGILState_Release(gstate);
   4374     return ret;
   4375 
   4376 error:
   4377     Py_DECREF(ssl_socket);
   4378     *al = SSL_AD_INTERNAL_ERROR;
   4379     ret = SSL_TLSEXT_ERR_ALERT_FATAL;
   4380     PyGILState_Release(gstate);
   4381     return ret;
   4382 }
   4383 #endif
   4384 
   4385 static PyObject *
   4386 get_sni_callback(PySSLContext *self, void *c)
   4387 {
   4388     PyObject *cb = self->set_sni_cb;
   4389     if (cb == NULL) {
   4390         Py_RETURN_NONE;
   4391     }
   4392     Py_INCREF(cb);
   4393     return cb;
   4394 }
   4395 
   4396 static int
   4397 set_sni_callback(PySSLContext *self, PyObject *arg, void *c)
   4398 {
   4399     if (self->protocol == PY_SSL_VERSION_TLS_CLIENT) {
   4400         PyErr_SetString(PyExc_ValueError,
   4401                         "sni_callback cannot be set on TLS_CLIENT context");
   4402         return -1;
   4403     }
   4404 #if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
   4405     Py_CLEAR(self->set_sni_cb);
   4406     if (arg == Py_None) {
   4407         SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
   4408     }
   4409     else {
   4410         if (!PyCallable_Check(arg)) {
   4411             SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
   4412             PyErr_SetString(PyExc_TypeError,
   4413                             "not a callable object");
   4414             return -1;
   4415         }
   4416         Py_INCREF(arg);
   4417         self->set_sni_cb = arg;
   4418         SSL_CTX_set_tlsext_servername_callback(self->ctx, _servername_callback);
   4419         SSL_CTX_set_tlsext_servername_arg(self->ctx, self);
   4420     }
   4421     return 0;
   4422 #else
   4423     PyErr_SetString(PyExc_NotImplementedError,
   4424                     "The TLS extension servername callback, "
   4425                     "SSL_CTX_set_tlsext_servername_callback, "
   4426                     "is not in the current OpenSSL library.");
   4427     return -1;
   4428 #endif
   4429 }
   4430 
   4431 PyDoc_STRVAR(PySSLContext_sni_callback_doc,
   4432 "Set a callback that will be called when a server name is provided by the SSL/TLS client in the SNI extension.\n\
   4433 \n\
   4434 If the argument is None then the callback is disabled. The method is called\n\
   4435 with the SSLSocket, the server name as a string, and the SSLContext object.\n\
   4436 See RFC 6066 for details of the SNI extension.");
   4437 
   4438 /*[clinic input]
   4439 _ssl._SSLContext.cert_store_stats
   4440 
   4441 Returns quantities of loaded X.509 certificates.
   4442 
   4443 X.509 certificates with a CA extension and certificate revocation lists
   4444 inside the context's cert store.
   4445 
   4446 NOTE: Certificates in a capath directory aren't loaded unless they have
   4447 been used at least once.
   4448 [clinic start generated code]*/
   4449 
   4450 static PyObject *
   4451 _ssl__SSLContext_cert_store_stats_impl(PySSLContext *self)
   4452 /*[clinic end generated code: output=5f356f4d9cca874d input=eb40dd0f6d0e40cf]*/
   4453 {
   4454     X509_STORE *store;
   4455     STACK_OF(X509_OBJECT) *objs;
   4456     X509_OBJECT *obj;
   4457     int x509 = 0, crl = 0, ca = 0, i;
   4458 
   4459     store = SSL_CTX_get_cert_store(self->ctx);
   4460     objs = X509_STORE_get0_objects(store);
   4461     for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
   4462         obj = sk_X509_OBJECT_value(objs, i);
   4463         switch (X509_OBJECT_get_type(obj)) {
   4464             case X509_LU_X509:
   4465                 x509++;
   4466                 if (X509_check_ca(X509_OBJECT_get0_X509(obj))) {
   4467                     ca++;
   4468                 }
   4469                 break;
   4470             case X509_LU_CRL:
   4471                 crl++;
   4472                 break;
   4473             default:
   4474                 /* Ignore X509_LU_FAIL, X509_LU_RETRY, X509_LU_PKEY.
   4475                  * As far as I can tell they are internal states and never
   4476                  * stored in a cert store */
   4477                 break;
   4478         }
   4479     }
   4480     return Py_BuildValue("{sisisi}", "x509", x509, "crl", crl,
   4481         "x509_ca", ca);
   4482 }
   4483 
   4484 /*[clinic input]
   4485 _ssl._SSLContext.get_ca_certs
   4486     binary_form: bool = False
   4487 
   4488 Returns a list of dicts with information of loaded CA certs.
   4489 
   4490 If the optional argument is True, returns a DER-encoded copy of the CA
   4491 certificate.
   4492 
   4493 NOTE: Certificates in a capath directory aren't loaded unless they have
   4494 been used at least once.
   4495 [clinic start generated code]*/
   4496 
   4497 static PyObject *
   4498 _ssl__SSLContext_get_ca_certs_impl(PySSLContext *self, int binary_form)
   4499 /*[clinic end generated code: output=0d58f148f37e2938 input=6887b5a09b7f9076]*/
   4500 {
   4501     X509_STORE *store;
   4502     STACK_OF(X509_OBJECT) *objs;
   4503     PyObject *ci = NULL, *rlist = NULL;
   4504     int i;
   4505 
   4506     if ((rlist = PyList_New(0)) == NULL) {
   4507         return NULL;
   4508     }
   4509 
   4510     store = SSL_CTX_get_cert_store(self->ctx);
   4511     objs = X509_STORE_get0_objects(store);
   4512     for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
   4513         X509_OBJECT *obj;
   4514         X509 *cert;
   4515 
   4516         obj = sk_X509_OBJECT_value(objs, i);
   4517         if (X509_OBJECT_get_type(obj) != X509_LU_X509) {
   4518             /* not a x509 cert */
   4519             continue;
   4520         }
   4521         /* CA for any purpose */
   4522         cert = X509_OBJECT_get0_X509(obj);
   4523         if (!X509_check_ca(cert)) {
   4524             continue;
   4525         }
   4526         if (binary_form) {
   4527             ci = _certificate_to_der(cert);
   4528         } else {
   4529             ci = _decode_certificate(cert);
   4530         }
   4531         if (ci == NULL) {
   4532             goto error;
   4533         }
   4534         if (PyList_Append(rlist, ci) == -1) {
   4535             goto error;
   4536         }
   4537         Py_CLEAR(ci);
   4538     }
   4539     return rlist;
   4540 
   4541   error:
   4542     Py_XDECREF(ci);
   4543     Py_XDECREF(rlist);
   4544     return NULL;
   4545 }
   4546 
   4547 
   4548 static PyGetSetDef context_getsetlist[] = {
   4549     {"check_hostname", (getter) get_check_hostname,
   4550                        (setter) set_check_hostname, NULL},
   4551     {"_host_flags", (getter) get_host_flags,
   4552                     (setter) set_host_flags, NULL},
   4553 #if SSL_CTRL_GET_MAX_PROTO_VERSION
   4554     {"minimum_version", (getter) get_minimum_version,
   4555                         (setter) set_minimum_version, NULL},
   4556     {"maximum_version", (getter) get_maximum_version,
   4557                         (setter) set_maximum_version, NULL},
   4558 #endif
   4559     {"sni_callback", (getter) get_sni_callback,
   4560                      (setter) set_sni_callback, PySSLContext_sni_callback_doc},
   4561     {"options", (getter) get_options,
   4562                 (setter) set_options, NULL},
   4563     {"post_handshake_auth", (getter) get_post_handshake_auth,
   4564 #ifdef TLS1_3_VERSION
   4565                             (setter) set_post_handshake_auth,
   4566 #else
   4567                             NULL,
   4568 #endif
   4569                             NULL},
   4570     {"protocol", (getter) get_protocol,
   4571                  NULL, NULL},
   4572     {"verify_flags", (getter) get_verify_flags,
   4573                      (setter) set_verify_flags, NULL},
   4574     {"verify_mode", (getter) get_verify_mode,
   4575                     (setter) set_verify_mode, NULL},
   4576     {NULL},            /* sentinel */
   4577 };
   4578 
   4579 static struct PyMethodDef context_methods[] = {
   4580     _SSL__SSLCONTEXT__WRAP_SOCKET_METHODDEF
   4581     _SSL__SSLCONTEXT__WRAP_BIO_METHODDEF
   4582     _SSL__SSLCONTEXT_SET_CIPHERS_METHODDEF
   4583     _SSL__SSLCONTEXT__SET_ALPN_PROTOCOLS_METHODDEF
   4584     _SSL__SSLCONTEXT__SET_NPN_PROTOCOLS_METHODDEF
   4585     _SSL__SSLCONTEXT_LOAD_CERT_CHAIN_METHODDEF
   4586     _SSL__SSLCONTEXT_LOAD_DH_PARAMS_METHODDEF
   4587     _SSL__SSLCONTEXT_LOAD_VERIFY_LOCATIONS_METHODDEF
   4588     _SSL__SSLCONTEXT_SESSION_STATS_METHODDEF
   4589     _SSL__SSLCONTEXT_SET_DEFAULT_VERIFY_PATHS_METHODDEF
   4590     _SSL__SSLCONTEXT_SET_ECDH_CURVE_METHODDEF
   4591     _SSL__SSLCONTEXT_CERT_STORE_STATS_METHODDEF
   4592     _SSL__SSLCONTEXT_GET_CA_CERTS_METHODDEF
   4593     _SSL__SSLCONTEXT_GET_CIPHERS_METHODDEF
   4594     {NULL, NULL}        /* sentinel */
   4595 };
   4596 
   4597 static PyTypeObject PySSLContext_Type = {
   4598     PyVarObject_HEAD_INIT(NULL, 0)
   4599     "_ssl._SSLContext",                        /*tp_name*/
   4600     sizeof(PySSLContext),                      /*tp_basicsize*/
   4601     0,                                         /*tp_itemsize*/
   4602     (destructor)context_dealloc,               /*tp_dealloc*/
   4603     0,                                         /*tp_print*/
   4604     0,                                         /*tp_getattr*/
   4605     0,                                         /*tp_setattr*/
   4606     0,                                         /*tp_reserved*/
   4607     0,                                         /*tp_repr*/
   4608     0,                                         /*tp_as_number*/
   4609     0,                                         /*tp_as_sequence*/
   4610     0,                                         /*tp_as_mapping*/
   4611     0,                                         /*tp_hash*/
   4612     0,                                         /*tp_call*/
   4613     0,                                         /*tp_str*/
   4614     0,                                         /*tp_getattro*/
   4615     0,                                         /*tp_setattro*/
   4616     0,                                         /*tp_as_buffer*/
   4617     Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
   4618     0,                                         /*tp_doc*/
   4619     (traverseproc) context_traverse,           /*tp_traverse*/
   4620     (inquiry) context_clear,                   /*tp_clear*/
   4621     0,                                         /*tp_richcompare*/
   4622     0,                                         /*tp_weaklistoffset*/
   4623     0,                                         /*tp_iter*/
   4624     0,                                         /*tp_iternext*/
   4625     context_methods,                           /*tp_methods*/
   4626     0,                                         /*tp_members*/
   4627     context_getsetlist,                        /*tp_getset*/
   4628     0,                                         /*tp_base*/
   4629     0,                                         /*tp_dict*/
   4630     0,                                         /*tp_descr_get*/
   4631     0,                                         /*tp_descr_set*/
   4632     0,                                         /*tp_dictoffset*/
   4633     0,                                         /*tp_init*/
   4634     0,                                         /*tp_alloc*/
   4635     _ssl__SSLContext,                          /*tp_new*/
   4636 };
   4637 
   4638 
   4639 /*
   4640  * MemoryBIO objects
   4641  */
   4642 
   4643 /*[clinic input]
   4644 @classmethod
   4645 _ssl.MemoryBIO.__new__
   4646 
   4647 [clinic start generated code]*/
   4648 
   4649 static PyObject *
   4650 _ssl_MemoryBIO_impl(PyTypeObject *type)
   4651 /*[clinic end generated code: output=8820a58db78330ac input=26d22e4909ecb1b5]*/
   4652 {
   4653     BIO *bio;
   4654     PySSLMemoryBIO *self;
   4655 
   4656     bio = BIO_new(BIO_s_mem());
   4657     if (bio == NULL) {
   4658         PyErr_SetString(PySSLErrorObject,
   4659                         "failed to allocate BIO");
   4660         return NULL;
   4661     }
   4662     /* Since our BIO is non-blocking an empty read() does not indicate EOF,
   4663      * just that no data is currently available. The SSL routines should retry
   4664      * the read, which we can achieve by calling BIO_set_retry_read(). */
   4665     BIO_set_retry_read(bio);
   4666     BIO_set_mem_eof_return(bio, -1);
   4667 
   4668     assert(type != NULL && type->tp_alloc != NULL);
   4669     self = (PySSLMemoryBIO *) type->tp_alloc(type, 0);
   4670     if (self == NULL) {
   4671         BIO_free(bio);
   4672         return NULL;
   4673     }
   4674     self->bio = bio;
   4675     self->eof_written = 0;
   4676 
   4677     return (PyObject *) self;
   4678 }
   4679 
   4680 static void
   4681 memory_bio_dealloc(PySSLMemoryBIO *self)
   4682 {
   4683     BIO_free(self->bio);
   4684     Py_TYPE(self)->tp_free(self);
   4685 }
   4686 
   4687 static PyObject *
   4688 memory_bio_get_pending(PySSLMemoryBIO *self, void *c)
   4689 {
   4690     return PyLong_FromSize_t(BIO_ctrl_pending(self->bio));
   4691 }
   4692 
   4693 PyDoc_STRVAR(PySSL_memory_bio_pending_doc,
   4694 "The number of bytes pending in the memory BIO.");
   4695 
   4696 static PyObject *
   4697 memory_bio_get_eof(PySSLMemoryBIO *self, void *c)
   4698 {
   4699     return PyBool_FromLong((BIO_ctrl_pending(self->bio) == 0)
   4700                            && self->eof_written);
   4701 }
   4702 
   4703 PyDoc_STRVAR(PySSL_memory_bio_eof_doc,
   4704 "Whether the memory BIO is at EOF.");
   4705 
   4706 /*[clinic input]
   4707 _ssl.MemoryBIO.read
   4708     size as len: int = -1
   4709     /
   4710 
   4711 Read up to size bytes from the memory BIO.
   4712 
   4713 If size is not specified, read the entire buffer.
   4714 If the return value is an empty bytes instance, this means either
   4715 EOF or that no data is available. Use the "eof" property to
   4716 distinguish between the two.
   4717 [clinic start generated code]*/
   4718 
   4719 static PyObject *
   4720 _ssl_MemoryBIO_read_impl(PySSLMemoryBIO *self, int len)
   4721 /*[clinic end generated code: output=a657aa1e79cd01b3 input=574d7be06a902366]*/
   4722 {
   4723     int avail, nbytes;
   4724     PyObject *result;
   4725 
   4726     avail = (int)Py_MIN(BIO_ctrl_pending(self->bio), INT_MAX);
   4727     if ((len < 0) || (len > avail))
   4728         len = avail;
   4729 
   4730     result = PyBytes_FromStringAndSize(NULL, len);
   4731     if ((result == NULL) || (len == 0))
   4732         return result;
   4733 
   4734     nbytes = BIO_read(self->bio, PyBytes_AS_STRING(result), len);
   4735     if (nbytes < 0) {
   4736         Py_DECREF(result);
   4737         _setSSLError(NULL, 0, __FILE__, __LINE__);
   4738         return NULL;
   4739     }
   4740 
   4741     /* There should never be any short reads but check anyway. */
   4742     if (nbytes < len) {
   4743         _PyBytes_Resize(&result, nbytes);
   4744     }
   4745 
   4746     return result;
   4747 }
   4748 
   4749 /*[clinic input]
   4750 _ssl.MemoryBIO.write
   4751     b: Py_buffer
   4752     /
   4753 
   4754 Writes the bytes b into the memory BIO.
   4755 
   4756 Returns the number of bytes written.
   4757 [clinic start generated code]*/
   4758 
   4759 static PyObject *
   4760 _ssl_MemoryBIO_write_impl(PySSLMemoryBIO *self, Py_buffer *b)
   4761 /*[clinic end generated code: output=156ec59110d75935 input=e45757b3e17c4808]*/
   4762 {
   4763     int nbytes;
   4764 
   4765     if (b->len > INT_MAX) {
   4766         PyErr_Format(PyExc_OverflowError,
   4767                      "string longer than %d bytes", INT_MAX);
   4768         return NULL;
   4769     }
   4770 
   4771     if (self->eof_written) {
   4772         PyErr_SetString(PySSLErrorObject,
   4773                         "cannot write() after write_eof()");
   4774         return NULL;
   4775     }
   4776 
   4777     nbytes = BIO_write(self->bio, b->buf, (int)b->len);
   4778     if (nbytes < 0) {
   4779         _setSSLError(NULL, 0, __FILE__, __LINE__);
   4780         return NULL;
   4781     }
   4782 
   4783     return PyLong_FromLong(nbytes);
   4784 }
   4785 
   4786 /*[clinic input]
   4787 _ssl.MemoryBIO.write_eof
   4788 
   4789 Write an EOF marker to the memory BIO.
   4790 
   4791 When all data has been read, the "eof" property will be True.
   4792 [clinic start generated code]*/
   4793 
   4794 static PyObject *
   4795 _ssl_MemoryBIO_write_eof_impl(PySSLMemoryBIO *self)
   4796 /*[clinic end generated code: output=d4106276ccd1ed34 input=56a945f1d29e8bd6]*/
   4797 {
   4798     self->eof_written = 1;
   4799     /* After an EOF is written, a zero return from read() should be a real EOF
   4800      * i.e. it should not be retried. Clear the SHOULD_RETRY flag. */
   4801     BIO_clear_retry_flags(self->bio);
   4802     BIO_set_mem_eof_return(self->bio, 0);
   4803 
   4804     Py_RETURN_NONE;
   4805 }
   4806 
   4807 static PyGetSetDef memory_bio_getsetlist[] = {
   4808     {"pending", (getter) memory_bio_get_pending, NULL,
   4809                 PySSL_memory_bio_pending_doc},
   4810     {"eof", (getter) memory_bio_get_eof, NULL,
   4811             PySSL_memory_bio_eof_doc},
   4812     {NULL},            /* sentinel */
   4813 };
   4814 
   4815 static struct PyMethodDef memory_bio_methods[] = {
   4816     _SSL_MEMORYBIO_READ_METHODDEF
   4817     _SSL_MEMORYBIO_WRITE_METHODDEF
   4818     _SSL_MEMORYBIO_WRITE_EOF_METHODDEF
   4819     {NULL, NULL}        /* sentinel */
   4820 };
   4821 
   4822 static PyTypeObject PySSLMemoryBIO_Type = {
   4823     PyVarObject_HEAD_INIT(NULL, 0)
   4824     "_ssl.MemoryBIO",                         /*tp_name*/
   4825     sizeof(PySSLMemoryBIO),                    /*tp_basicsize*/
   4826     0,                                         /*tp_itemsize*/
   4827     (destructor)memory_bio_dealloc,            /*tp_dealloc*/
   4828     0,                                         /*tp_print*/
   4829     0,                                         /*tp_getattr*/
   4830     0,                                         /*tp_setattr*/
   4831     0,                                         /*tp_reserved*/
   4832     0,                                         /*tp_repr*/
   4833     0,                                         /*tp_as_number*/
   4834     0,                                         /*tp_as_sequence*/
   4835     0,                                         /*tp_as_mapping*/
   4836     0,                                         /*tp_hash*/
   4837     0,                                         /*tp_call*/
   4838     0,                                         /*tp_str*/
   4839     0,                                         /*tp_getattro*/
   4840     0,                                         /*tp_setattro*/
   4841     0,                                         /*tp_as_buffer*/
   4842     Py_TPFLAGS_DEFAULT,                        /*tp_flags*/
   4843     0,                                         /*tp_doc*/
   4844     0,                                         /*tp_traverse*/
   4845     0,                                         /*tp_clear*/
   4846     0,                                         /*tp_richcompare*/
   4847     0,                                         /*tp_weaklistoffset*/
   4848     0,                                         /*tp_iter*/
   4849     0,                                         /*tp_iternext*/
   4850     memory_bio_methods,                        /*tp_methods*/
   4851     0,                                         /*tp_members*/
   4852     memory_bio_getsetlist,                     /*tp_getset*/
   4853     0,                                         /*tp_base*/
   4854     0,                                         /*tp_dict*/
   4855     0,                                         /*tp_descr_get*/
   4856     0,                                         /*tp_descr_set*/
   4857     0,                                         /*tp_dictoffset*/
   4858     0,                                         /*tp_init*/
   4859     0,                                         /*tp_alloc*/
   4860     _ssl_MemoryBIO,                            /*tp_new*/
   4861 };
   4862 
   4863 
   4864 /*
   4865  * SSL Session object
   4866  */
   4867 
   4868 static void
   4869 PySSLSession_dealloc(PySSLSession *self)
   4870 {
   4871     /* bpo-31095: UnTrack is needed before calling any callbacks */
   4872     PyObject_GC_UnTrack(self);
   4873     Py_XDECREF(self->ctx);
   4874     if (self->session != NULL) {
   4875         SSL_SESSION_free(self->session);
   4876     }
   4877     PyObject_GC_Del(self);
   4878 }
   4879 
   4880 static PyObject *
   4881 PySSLSession_richcompare(PyObject *left, PyObject *right, int op)
   4882 {
   4883     int result;
   4884 
   4885     if (left == NULL || right == NULL) {
   4886         PyErr_BadInternalCall();
   4887         return NULL;
   4888     }
   4889 
   4890     if (!PySSLSession_Check(left) || !PySSLSession_Check(right)) {
   4891         Py_RETURN_NOTIMPLEMENTED;
   4892     }
   4893 
   4894     if (left == right) {
   4895         result = 0;
   4896     } else {
   4897         const unsigned char *left_id, *right_id;
   4898         unsigned int left_len, right_len;
   4899         left_id = SSL_SESSION_get_id(((PySSLSession *)left)->session,
   4900                                      &left_len);
   4901         right_id = SSL_SESSION_get_id(((PySSLSession *)right)->session,
   4902                                       &right_len);
   4903         if (left_len == right_len) {
   4904             result = memcmp(left_id, right_id, left_len);
   4905         } else {
   4906             result = 1;
   4907         }
   4908     }
   4909 
   4910     switch (op) {
   4911       case Py_EQ:
   4912         if (result == 0) {
   4913             Py_RETURN_TRUE;
   4914         } else {
   4915             Py_RETURN_FALSE;
   4916         }
   4917         break;
   4918       case Py_NE:
   4919         if (result != 0) {
   4920             Py_RETURN_TRUE;
   4921         } else {
   4922             Py_RETURN_FALSE;
   4923         }
   4924         break;
   4925       case Py_LT:
   4926       case Py_LE:
   4927       case Py_GT:
   4928       case Py_GE:
   4929         Py_RETURN_NOTIMPLEMENTED;
   4930         break;
   4931       default:
   4932         PyErr_BadArgument();
   4933         return NULL;
   4934     }
   4935 }
   4936 
   4937 static int
   4938 PySSLSession_traverse(PySSLSession *self, visitproc visit, void *arg)
   4939 {
   4940     Py_VISIT(self->ctx);
   4941     return 0;
   4942 }
   4943 
   4944 static int
   4945 PySSLSession_clear(PySSLSession *self)
   4946 {
   4947     Py_CLEAR(self->ctx);
   4948     return 0;
   4949 }
   4950 
   4951 
   4952 static PyObject *
   4953 PySSLSession_get_time(PySSLSession *self, void *closure) {
   4954     return PyLong_FromLong(SSL_SESSION_get_time(self->session));
   4955 }
   4956 
   4957 PyDoc_STRVAR(PySSLSession_get_time_doc,
   4958 "Session creation time (seconds since epoch).");
   4959 
   4960 
   4961 static PyObject *
   4962 PySSLSession_get_timeout(PySSLSession *self, void *closure) {
   4963     return PyLong_FromLong(SSL_SESSION_get_timeout(self->session));
   4964 }
   4965 
   4966 PyDoc_STRVAR(PySSLSession_get_timeout_doc,
   4967 "Session timeout (delta in seconds).");
   4968 
   4969 
   4970 static PyObject *
   4971 PySSLSession_get_ticket_lifetime_hint(PySSLSession *self, void *closure) {
   4972     unsigned long hint = SSL_SESSION_get_ticket_lifetime_hint(self->session);
   4973     return PyLong_FromUnsignedLong(hint);
   4974 }
   4975 
   4976 PyDoc_STRVAR(PySSLSession_get_ticket_lifetime_hint_doc,
   4977 "Ticket life time hint.");
   4978 
   4979 
   4980 static PyObject *
   4981 PySSLSession_get_session_id(PySSLSession *self, void *closure) {
   4982     const unsigned char *id;
   4983     unsigned int len;
   4984     id = SSL_SESSION_get_id(self->session, &len);
   4985     return PyBytes_FromStringAndSize((const char *)id, len);
   4986 }
   4987 
   4988 PyDoc_STRVAR(PySSLSession_get_session_id_doc,
   4989 "Session id");
   4990 
   4991 
   4992 static PyObject *
   4993 PySSLSession_get_has_ticket(PySSLSession *self, void *closure) {
   4994     if (SSL_SESSION_has_ticket(self->session)) {
   4995         Py_RETURN_TRUE;
   4996     } else {
   4997         Py_RETURN_FALSE;
   4998     }
   4999 }
   5000 
   5001 PyDoc_STRVAR(PySSLSession_get_has_ticket_doc,
   5002 "Does the session contain a ticket?");
   5003 
   5004 
   5005 static PyGetSetDef PySSLSession_getsetlist[] = {
   5006     {"has_ticket", (getter) PySSLSession_get_has_ticket, NULL,
   5007               PySSLSession_get_has_ticket_doc},
   5008     {"id",   (getter) PySSLSession_get_session_id, NULL,
   5009               PySSLSession_get_session_id_doc},
   5010     {"ticket_lifetime_hint", (getter) PySSLSession_get_ticket_lifetime_hint,
   5011               NULL, PySSLSession_get_ticket_lifetime_hint_doc},
   5012     {"time", (getter) PySSLSession_get_time, NULL,
   5013               PySSLSession_get_time_doc},
   5014     {"timeout", (getter) PySSLSession_get_timeout, NULL,
   5015               PySSLSession_get_timeout_doc},
   5016     {NULL},            /* sentinel */
   5017 };
   5018 
   5019 static PyTypeObject PySSLSession_Type = {
   5020     PyVarObject_HEAD_INIT(NULL, 0)
   5021     "_ssl.Session",                            /*tp_name*/
   5022     sizeof(PySSLSession),                      /*tp_basicsize*/
   5023     0,                                         /*tp_itemsize*/
   5024     (destructor)PySSLSession_dealloc,          /*tp_dealloc*/
   5025     0,                                         /*tp_print*/
   5026     0,                                         /*tp_getattr*/
   5027     0,                                         /*tp_setattr*/
   5028     0,                                         /*tp_reserved*/
   5029     0,                                         /*tp_repr*/
   5030     0,                                         /*tp_as_number*/
   5031     0,                                         /*tp_as_sequence*/
   5032     0,                                         /*tp_as_mapping*/
   5033     0,                                         /*tp_hash*/
   5034     0,                                         /*tp_call*/
   5035     0,                                         /*tp_str*/
   5036     0,                                         /*tp_getattro*/
   5037     0,                                         /*tp_setattro*/
   5038     0,                                         /*tp_as_buffer*/
   5039     Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,   /*tp_flags*/
   5040     0,                                         /*tp_doc*/
   5041     (traverseproc)PySSLSession_traverse,       /*tp_traverse*/
   5042     (inquiry)PySSLSession_clear,               /*tp_clear*/
   5043     PySSLSession_richcompare,                  /*tp_richcompare*/
   5044     0,                                         /*tp_weaklistoffset*/
   5045     0,                                         /*tp_iter*/
   5046     0,                                         /*tp_iternext*/
   5047     0,                                         /*tp_methods*/
   5048     0,                                         /*tp_members*/
   5049     PySSLSession_getsetlist,                   /*tp_getset*/
   5050 };
   5051 
   5052 
   5053 /* helper routines for seeding the SSL PRNG */
   5054 /*[clinic input]
   5055 _ssl.RAND_add
   5056     string as view: Py_buffer(accept={str, buffer})
   5057     entropy: double
   5058     /
   5059 
   5060 Mix string into the OpenSSL PRNG state.
   5061 
   5062 entropy (a float) is a lower bound on the entropy contained in
   5063 string.  See RFC 4086.
   5064 [clinic start generated code]*/
   5065 
   5066 static PyObject *
   5067 _ssl_RAND_add_impl(PyObject *module, Py_buffer *view, double entropy)
   5068 /*[clinic end generated code: output=e6dd48df9c9024e9 input=5c33017422828f5c]*/
   5069 {
   5070     const char *buf;
   5071     Py_ssize_t len, written;
   5072 
   5073     buf = (const char *)view->buf;
   5074     len = view->len;
   5075     do {
   5076         written = Py_MIN(len, INT_MAX);
   5077         RAND_add(buf, (int)written, entropy);
   5078         buf += written;
   5079         len -= written;
   5080     } while (len);
   5081     Py_RETURN_NONE;
   5082 }
   5083 
   5084 static PyObject *
   5085 PySSL_RAND(int len, int pseudo)
   5086 {
   5087     int ok;
   5088     PyObject *bytes;
   5089     unsigned long err;
   5090     const char *errstr;
   5091     PyObject *v;
   5092 
   5093     if (len < 0) {
   5094         PyErr_SetString(PyExc_ValueError, "num must be positive");
   5095         return NULL;
   5096     }
   5097 
   5098     bytes = PyBytes_FromStringAndSize(NULL, len);
   5099     if (bytes == NULL)
   5100         return NULL;
   5101     if (pseudo) {
   5102         ok = RAND_pseudo_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
   5103         if (ok == 0 || ok == 1)
   5104             return Py_BuildValue("NO", bytes, ok == 1 ? Py_True : Py_False);
   5105     }
   5106     else {
   5107         ok = RAND_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
   5108         if (ok == 1)
   5109             return bytes;
   5110     }
   5111     Py_DECREF(bytes);
   5112 
   5113     err = ERR_get_error();
   5114     errstr = ERR_reason_error_string(err);
   5115     v = Py_BuildValue("(ks)", err, errstr);
   5116     if (v != NULL) {
   5117         PyErr_SetObject(PySSLErrorObject, v);
   5118         Py_DECREF(v);
   5119     }
   5120     return NULL;
   5121 }
   5122 
   5123 /*[clinic input]
   5124 _ssl.RAND_bytes
   5125     n: int
   5126     /
   5127 
   5128 Generate n cryptographically strong pseudo-random bytes.
   5129 [clinic start generated code]*/
   5130 
   5131 static PyObject *
   5132 _ssl_RAND_bytes_impl(PyObject *module, int n)
   5133 /*[clinic end generated code: output=977da635e4838bc7 input=678ddf2872dfebfc]*/
   5134 {
   5135     return PySSL_RAND(n, 0);
   5136 }
   5137 
   5138 /*[clinic input]
   5139 _ssl.RAND_pseudo_bytes
   5140     n: int
   5141     /
   5142 
   5143 Generate n pseudo-random bytes.
   5144 
   5145 Return a pair (bytes, is_cryptographic).  is_cryptographic is True
   5146 if the bytes generated are cryptographically strong.
   5147 [clinic start generated code]*/
   5148 
   5149 static PyObject *
   5150 _ssl_RAND_pseudo_bytes_impl(PyObject *module, int n)
   5151 /*[clinic end generated code: output=b1509e937000e52d input=58312bd53f9bbdd0]*/
   5152 {
   5153     return PySSL_RAND(n, 1);
   5154 }
   5155 
   5156 /*[clinic input]
   5157 _ssl.RAND_status
   5158 
   5159 Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.
   5160 
   5161 It is necessary to seed the PRNG with RAND_add() on some platforms before
   5162 using the ssl() function.
   5163 [clinic start generated code]*/
   5164 
   5165 static PyObject *
   5166 _ssl_RAND_status_impl(PyObject *module)
   5167 /*[clinic end generated code: output=7e0aaa2d39fdc1ad input=8a774b02d1dc81f3]*/
   5168 {
   5169     return PyLong_FromLong(RAND_status());
   5170 }
   5171 
   5172 #ifndef OPENSSL_NO_EGD
   5173 /* LCOV_EXCL_START */
   5174 /*[clinic input]
   5175 _ssl.RAND_egd
   5176     path: object(converter="PyUnicode_FSConverter")
   5177     /
   5178 
   5179 Queries the entropy gather daemon (EGD) on the socket named by 'path'.
   5180 
   5181 Returns number of bytes read.  Raises SSLError if connection to EGD
   5182 fails or if it does not provide enough data to seed PRNG.
   5183 [clinic start generated code]*/
   5184 
   5185 static PyObject *
   5186 _ssl_RAND_egd_impl(PyObject *module, PyObject *path)
   5187 /*[clinic end generated code: output=02a67c7c367f52fa input=1aeb7eb948312195]*/
   5188 {
   5189     int bytes = RAND_egd(PyBytes_AsString(path));
   5190     Py_DECREF(path);
   5191     if (bytes == -1) {
   5192         PyErr_SetString(PySSLErrorObject,
   5193                         "EGD connection failed or EGD did not return "
   5194                         "enough data to seed the PRNG");
   5195         return NULL;
   5196     }
   5197     return PyLong_FromLong(bytes);
   5198 }
   5199 /* LCOV_EXCL_STOP */
   5200 #endif /* OPENSSL_NO_EGD */
   5201 
   5202 
   5203 
   5204 /*[clinic input]
   5205 _ssl.get_default_verify_paths
   5206 
   5207 Return search paths and environment vars that are used by SSLContext's set_default_verify_paths() to load default CAs.
   5208 
   5209 The values are 'cert_file_env', 'cert_file', 'cert_dir_env', 'cert_dir'.
   5210 [clinic start generated code]*/
   5211 
   5212 static PyObject *
   5213 _ssl_get_default_verify_paths_impl(PyObject *module)
   5214 /*[clinic end generated code: output=e5b62a466271928b input=5210c953d98c3eb5]*/
   5215 {
   5216     PyObject *ofile_env = NULL;
   5217     PyObject *ofile = NULL;
   5218     PyObject *odir_env = NULL;
   5219     PyObject *odir = NULL;
   5220 
   5221 #define CONVERT(info, target) { \
   5222         const char *tmp = (info); \
   5223         target = NULL; \
   5224         if (!tmp) { Py_INCREF(Py_None); target = Py_None; } \
   5225         else if ((target = PyUnicode_DecodeFSDefault(tmp)) == NULL) { \
   5226             target = PyBytes_FromString(tmp); } \
   5227         if (!target) goto error; \
   5228     }
   5229 
   5230     CONVERT(X509_get_default_cert_file_env(), ofile_env);
   5231     CONVERT(X509_get_default_cert_file(), ofile);
   5232     CONVERT(X509_get_default_cert_dir_env(), odir_env);
   5233     CONVERT(X509_get_default_cert_dir(), odir);
   5234 #undef CONVERT
   5235 
   5236     return Py_BuildValue("NNNN", ofile_env, ofile, odir_env, odir);
   5237 
   5238   error:
   5239     Py_XDECREF(ofile_env);
   5240     Py_XDECREF(ofile);
   5241     Py_XDECREF(odir_env);
   5242     Py_XDECREF(odir);
   5243     return NULL;
   5244 }
   5245 
   5246 static PyObject*
   5247 asn1obj2py(ASN1_OBJECT *obj)
   5248 {
   5249     int nid;
   5250     const char *ln, *sn;
   5251 
   5252     nid = OBJ_obj2nid(obj);
   5253     if (nid == NID_undef) {
   5254         PyErr_Format(PyExc_ValueError, "Unknown object");
   5255         return NULL;
   5256     }
   5257     sn = OBJ_nid2sn(nid);
   5258     ln = OBJ_nid2ln(nid);
   5259     return Py_BuildValue("issN", nid, sn, ln, _asn1obj2py(obj, 1));
   5260 }
   5261 
   5262 /*[clinic input]
   5263 _ssl.txt2obj
   5264     txt: str
   5265     name: bool = False
   5266 
   5267 Lookup NID, short name, long name and OID of an ASN1_OBJECT.
   5268 
   5269 By default objects are looked up by OID. With name=True short and
   5270 long name are also matched.
   5271 [clinic start generated code]*/
   5272 
   5273 static PyObject *
   5274 _ssl_txt2obj_impl(PyObject *module, const char *txt, int name)
   5275 /*[clinic end generated code: output=c38e3991347079c1 input=1c1e7d0aa7c48602]*/
   5276 {
   5277     PyObject *result = NULL;
   5278     ASN1_OBJECT *obj;
   5279 
   5280     obj = OBJ_txt2obj(txt, name ? 0 : 1);
   5281     if (obj == NULL) {
   5282         PyErr_Format(PyExc_ValueError, "unknown object '%.100s'", txt);
   5283         return NULL;
   5284     }
   5285     result = asn1obj2py(obj);
   5286     ASN1_OBJECT_free(obj);
   5287     return result;
   5288 }
   5289 
   5290 /*[clinic input]
   5291 _ssl.nid2obj
   5292     nid: int
   5293     /
   5294 
   5295 Lookup NID, short name, long name and OID of an ASN1_OBJECT by NID.
   5296 [clinic start generated code]*/
   5297 
   5298 static PyObject *
   5299 _ssl_nid2obj_impl(PyObject *module, int nid)
   5300 /*[clinic end generated code: output=4a98ab691cd4f84a input=51787a3bee7d8f98]*/
   5301 {
   5302     PyObject *result = NULL;
   5303     ASN1_OBJECT *obj;
   5304 
   5305     if (nid < NID_undef) {
   5306         PyErr_SetString(PyExc_ValueError, "NID must be positive.");
   5307         return NULL;
   5308     }
   5309     obj = OBJ_nid2obj(nid);
   5310     if (obj == NULL) {
   5311         PyErr_Format(PyExc_ValueError, "unknown NID %i", nid);
   5312         return NULL;
   5313     }
   5314     result = asn1obj2py(obj);
   5315     ASN1_OBJECT_free(obj);
   5316     return result;
   5317 }
   5318 
   5319 #ifdef _MSC_VER
   5320 
   5321 static PyObject*
   5322 certEncodingType(DWORD encodingType)
   5323 {
   5324     static PyObject *x509_asn = NULL;
   5325     static PyObject *pkcs_7_asn = NULL;
   5326 
   5327     if (x509_asn == NULL) {
   5328         x509_asn = PyUnicode_InternFromString("x509_asn");
   5329         if (x509_asn == NULL)
   5330             return NULL;
   5331     }
   5332     if (pkcs_7_asn == NULL) {
   5333         pkcs_7_asn = PyUnicode_InternFromString("pkcs_7_asn");
   5334         if (pkcs_7_asn == NULL)
   5335             return NULL;
   5336     }
   5337     switch(encodingType) {
   5338     case X509_ASN_ENCODING:
   5339         Py_INCREF(x509_asn);
   5340         return x509_asn;
   5341     case PKCS_7_ASN_ENCODING:
   5342         Py_INCREF(pkcs_7_asn);
   5343         return pkcs_7_asn;
   5344     default:
   5345         return PyLong_FromLong(encodingType);
   5346     }
   5347 }
   5348 
   5349 static PyObject*
   5350 parseKeyUsage(PCCERT_CONTEXT pCertCtx, DWORD flags)
   5351 {
   5352     CERT_ENHKEY_USAGE *usage;
   5353     DWORD size, error, i;
   5354     PyObject *retval;
   5355 
   5356     if (!CertGetEnhancedKeyUsage(pCertCtx, flags, NULL, &size)) {
   5357         error = GetLastError();
   5358         if (error == CRYPT_E_NOT_FOUND) {
   5359             Py_RETURN_TRUE;
   5360         }
   5361         return PyErr_SetFromWindowsErr(error);
   5362     }
   5363 
   5364     usage = (CERT_ENHKEY_USAGE*)PyMem_Malloc(size);
   5365     if (usage == NULL) {
   5366         return PyErr_NoMemory();
   5367     }
   5368 
   5369     /* Now get the actual enhanced usage property */
   5370     if (!CertGetEnhancedKeyUsage(pCertCtx, flags, usage, &size)) {
   5371         PyMem_Free(usage);
   5372         error = GetLastError();
   5373         if (error == CRYPT_E_NOT_FOUND) {
   5374             Py_RETURN_TRUE;
   5375         }
   5376         return PyErr_SetFromWindowsErr(error);
   5377     }
   5378     retval = PySet_New(NULL);
   5379     if (retval == NULL) {
   5380         goto error;
   5381     }
   5382     for (i = 0; i < usage->cUsageIdentifier; ++i) {
   5383         if (usage->rgpszUsageIdentifier[i]) {
   5384             PyObject *oid;
   5385             int err;
   5386             oid = PyUnicode_FromString(usage->rgpszUsageIdentifier[i]);
   5387             if (oid == NULL) {
   5388                 Py_CLEAR(retval);
   5389                 goto error;
   5390             }
   5391             err = PySet_Add(retval, oid);
   5392             Py_DECREF(oid);
   5393             if (err == -1) {
   5394                 Py_CLEAR(retval);
   5395                 goto error;
   5396             }
   5397         }
   5398     }
   5399   error:
   5400     PyMem_Free(usage);
   5401     return retval;
   5402 }
   5403 
   5404 /*[clinic input]
   5405 _ssl.enum_certificates
   5406     store_name: str
   5407 
   5408 Retrieve certificates from Windows' cert store.
   5409 
   5410 store_name may be one of 'CA', 'ROOT' or 'MY'.  The system may provide
   5411 more cert storages, too.  The function returns a list of (bytes,
   5412 encoding_type, trust) tuples.  The encoding_type flag can be interpreted
   5413 with X509_ASN_ENCODING or PKCS_7_ASN_ENCODING. The trust setting is either
   5414 a set of OIDs or the boolean True.
   5415 [clinic start generated code]*/
   5416 
   5417 static PyObject *
   5418 _ssl_enum_certificates_impl(PyObject *module, const char *store_name)
   5419 /*[clinic end generated code: output=5134dc8bb3a3c893 input=915f60d70461ea4e]*/
   5420 {
   5421     HCERTSTORE hStore = NULL;
   5422     PCCERT_CONTEXT pCertCtx = NULL;
   5423     PyObject *keyusage = NULL, *cert = NULL, *enc = NULL, *tup = NULL;
   5424     PyObject *result = NULL;
   5425 
   5426     result = PyList_New(0);
   5427     if (result == NULL) {
   5428         return NULL;
   5429     }
   5430     hStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0, (HCRYPTPROV)NULL,
   5431                             CERT_STORE_READONLY_FLAG | CERT_SYSTEM_STORE_LOCAL_MACHINE,
   5432                             store_name);
   5433     if (hStore == NULL) {
   5434         Py_DECREF(result);
   5435         return PyErr_SetFromWindowsErr(GetLastError());
   5436     }
   5437 
   5438     while (pCertCtx = CertEnumCertificatesInStore(hStore, pCertCtx)) {
   5439         cert = PyBytes_FromStringAndSize((const char*)pCertCtx->pbCertEncoded,
   5440                                             pCertCtx->cbCertEncoded);
   5441         if (!cert) {
   5442             Py_CLEAR(result);
   5443             break;
   5444         }
   5445         if ((enc = certEncodingType(pCertCtx->dwCertEncodingType)) == NULL) {
   5446             Py_CLEAR(result);
   5447             break;
   5448         }
   5449         keyusage = parseKeyUsage(pCertCtx, CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG);
   5450         if (keyusage == Py_True) {
   5451             Py_DECREF(keyusage);
   5452             keyusage = parseKeyUsage(pCertCtx, CERT_FIND_EXT_ONLY_ENHKEY_USAGE_FLAG);
   5453         }
   5454         if (keyusage == NULL) {
   5455             Py_CLEAR(result);
   5456             break;
   5457         }
   5458         if ((tup = PyTuple_New(3)) == NULL) {
   5459             Py_CLEAR(result);
   5460             break;
   5461         }
   5462         PyTuple_SET_ITEM(tup, 0, cert);
   5463         cert = NULL;
   5464         PyTuple_SET_ITEM(tup, 1, enc);
   5465         enc = NULL;
   5466         PyTuple_SET_ITEM(tup, 2, keyusage);
   5467         keyusage = NULL;
   5468         if (PyList_Append(result, tup) < 0) {
   5469             Py_CLEAR(result);
   5470             break;
   5471         }
   5472         Py_CLEAR(tup);
   5473     }
   5474     if (pCertCtx) {
   5475         /* loop ended with an error, need to clean up context manually */
   5476         CertFreeCertificateContext(pCertCtx);
   5477     }
   5478 
   5479     /* In error cases cert, enc and tup may not be NULL */
   5480     Py_XDECREF(cert);
   5481     Py_XDECREF(enc);
   5482     Py_XDECREF(keyusage);
   5483     Py_XDECREF(tup);
   5484 
   5485     if (!CertCloseStore(hStore, 0)) {
   5486         /* This error case might shadow another exception.*/
   5487         Py_XDECREF(result);
   5488         return PyErr_SetFromWindowsErr(GetLastError());
   5489     }
   5490     return result;
   5491 }
   5492 
   5493 /*[clinic input]
   5494 _ssl.enum_crls
   5495     store_name: str
   5496 
   5497 Retrieve CRLs from Windows' cert store.
   5498 
   5499 store_name may be one of 'CA', 'ROOT' or 'MY'.  The system may provide
   5500 more cert storages, too.  The function returns a list of (bytes,
   5501 encoding_type) tuples.  The encoding_type flag can be interpreted with
   5502 X509_ASN_ENCODING or PKCS_7_ASN_ENCODING.
   5503 [clinic start generated code]*/
   5504 
   5505 static PyObject *
   5506 _ssl_enum_crls_impl(PyObject *module, const char *store_name)
   5507 /*[clinic end generated code: output=bce467f60ccd03b6 input=a1f1d7629f1c5d3d]*/
   5508 {
   5509     HCERTSTORE hStore = NULL;
   5510     PCCRL_CONTEXT pCrlCtx = NULL;
   5511     PyObject *crl = NULL, *enc = NULL, *tup = NULL;
   5512     PyObject *result = NULL;
   5513 
   5514     result = PyList_New(0);
   5515     if (result == NULL) {
   5516         return NULL;
   5517     }
   5518     hStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0, (HCRYPTPROV)NULL,
   5519                             CERT_STORE_READONLY_FLAG | CERT_SYSTEM_STORE_LOCAL_MACHINE,
   5520                             store_name);
   5521     if (hStore == NULL) {
   5522         Py_DECREF(result);
   5523         return PyErr_SetFromWindowsErr(GetLastError());
   5524     }
   5525 
   5526     while (pCrlCtx = CertEnumCRLsInStore(hStore, pCrlCtx)) {
   5527         crl = PyBytes_FromStringAndSize((const char*)pCrlCtx->pbCrlEncoded,
   5528                                             pCrlCtx->cbCrlEncoded);
   5529         if (!crl) {
   5530             Py_CLEAR(result);
   5531             break;
   5532         }
   5533         if ((enc = certEncodingType(pCrlCtx->dwCertEncodingType)) == NULL) {
   5534             Py_CLEAR(result);
   5535             break;
   5536         }
   5537         if ((tup = PyTuple_New(2)) == NULL) {
   5538             Py_CLEAR(result);
   5539             break;
   5540         }
   5541         PyTuple_SET_ITEM(tup, 0, crl);
   5542         crl = NULL;
   5543         PyTuple_SET_ITEM(tup, 1, enc);
   5544         enc = NULL;
   5545 
   5546         if (PyList_Append(result, tup) < 0) {
   5547             Py_CLEAR(result);
   5548             break;
   5549         }
   5550         Py_CLEAR(tup);
   5551     }
   5552     if (pCrlCtx) {
   5553         /* loop ended with an error, need to clean up context manually */
   5554         CertFreeCRLContext(pCrlCtx);
   5555     }
   5556 
   5557     /* In error cases cert, enc and tup may not be NULL */
   5558     Py_XDECREF(crl);
   5559     Py_XDECREF(enc);
   5560     Py_XDECREF(tup);
   5561 
   5562     if (!CertCloseStore(hStore, 0)) {
   5563         /* This error case might shadow another exception.*/
   5564         Py_XDECREF(result);
   5565         return PyErr_SetFromWindowsErr(GetLastError());
   5566     }
   5567     return result;
   5568 }
   5569 
   5570 #endif /* _MSC_VER */
   5571 
   5572 /* List of functions exported by this module. */
   5573 static PyMethodDef PySSL_methods[] = {
   5574     _SSL__TEST_DECODE_CERT_METHODDEF
   5575     _SSL_RAND_ADD_METHODDEF
   5576     _SSL_RAND_BYTES_METHODDEF
   5577     _SSL_RAND_PSEUDO_BYTES_METHODDEF
   5578     _SSL_RAND_EGD_METHODDEF
   5579     _SSL_RAND_STATUS_METHODDEF
   5580     _SSL_GET_DEFAULT_VERIFY_PATHS_METHODDEF
   5581     _SSL_ENUM_CERTIFICATES_METHODDEF
   5582     _SSL_ENUM_CRLS_METHODDEF
   5583     _SSL_TXT2OBJ_METHODDEF
   5584     _SSL_NID2OBJ_METHODDEF
   5585     {NULL,                  NULL}            /* Sentinel */
   5586 };
   5587 
   5588 
   5589 #ifdef HAVE_OPENSSL_CRYPTO_LOCK
   5590 
   5591 /* an implementation of OpenSSL threading operations in terms
   5592  * of the Python C thread library
   5593  * Only used up to 1.0.2. OpenSSL 1.1.0+ has its own locking code.
   5594  */
   5595 
   5596 static PyThread_type_lock *_ssl_locks = NULL;
   5597 
   5598 #if OPENSSL_VERSION_NUMBER >= 0x10000000
   5599 /* use new CRYPTO_THREADID API. */
   5600 static void
   5601 _ssl_threadid_callback(CRYPTO_THREADID *id)
   5602 {
   5603     CRYPTO_THREADID_set_numeric(id, PyThread_get_thread_ident());
   5604 }
   5605 #else
   5606 /* deprecated CRYPTO_set_id_callback() API. */
   5607 static unsigned long
   5608 _ssl_thread_id_function (void) {
   5609     return PyThread_get_thread_ident();
   5610 }
   5611 #endif
   5612 
   5613 static void _ssl_thread_locking_function
   5614     (int mode, int n, const char *file, int line) {
   5615     /* this function is needed to perform locking on shared data
   5616        structures. (Note that OpenSSL uses a number of global data
   5617        structures that will be implicitly shared whenever multiple
   5618        threads use OpenSSL.) Multi-threaded applications will
   5619        crash at random if it is not set.
   5620 
   5621        locking_function() must be able to handle up to
   5622        CRYPTO_num_locks() different mutex locks. It sets the n-th
   5623        lock if mode & CRYPTO_LOCK, and releases it otherwise.
   5624 
   5625        file and line are the file number of the function setting the
   5626        lock. They can be useful for debugging.
   5627     */
   5628 
   5629     if ((_ssl_locks == NULL) ||
   5630         (n < 0) || ((unsigned)n >= _ssl_locks_count))
   5631         return;
   5632 
   5633     if (mode & CRYPTO_LOCK) {
   5634         PyThread_acquire_lock(_ssl_locks[n], 1);
   5635     } else {
   5636         PyThread_release_lock(_ssl_locks[n]);
   5637     }
   5638 }
   5639 
   5640 static int _setup_ssl_threads(void) {
   5641 
   5642     unsigned int i;
   5643 
   5644     if (_ssl_locks == NULL) {
   5645         _ssl_locks_count = CRYPTO_num_locks();
   5646         _ssl_locks = PyMem_Calloc(_ssl_locks_count,
   5647                                   sizeof(PyThread_type_lock));
   5648         if (_ssl_locks == NULL) {
   5649             PyErr_NoMemory();
   5650             return 0;
   5651         }
   5652         for (i = 0;  i < _ssl_locks_count;  i++) {
   5653             _ssl_locks[i] = PyThread_allocate_lock();
   5654             if (_ssl_locks[i] == NULL) {
   5655                 unsigned int j;
   5656                 for (j = 0;  j < i;  j++) {
   5657                     PyThread_free_lock(_ssl_locks[j]);
   5658                 }
   5659                 PyMem_Free(_ssl_locks);
   5660                 return 0;
   5661             }
   5662         }
   5663         CRYPTO_set_locking_callback(_ssl_thread_locking_function);
   5664 #if OPENSSL_VERSION_NUMBER >= 0x10000000
   5665         CRYPTO_THREADID_set_callback(_ssl_threadid_callback);
   5666 #else
   5667         CRYPTO_set_id_callback(_ssl_thread_id_function);
   5668 #endif
   5669     }
   5670     return 1;
   5671 }
   5672 
   5673 #endif  /* HAVE_OPENSSL_CRYPTO_LOCK for OpenSSL < 1.1.0 */
   5674 
   5675 PyDoc_STRVAR(module_doc,
   5676 "Implementation module for SSL socket operations.  See the socket module\n\
   5677 for documentation.");
   5678 
   5679 
   5680 static struct PyModuleDef _sslmodule = {
   5681     PyModuleDef_HEAD_INIT,
   5682     "_ssl",
   5683     module_doc,
   5684     -1,
   5685     PySSL_methods,
   5686     NULL,
   5687     NULL,
   5688     NULL,
   5689     NULL
   5690 };
   5691 
   5692 
   5693 static void
   5694 parse_openssl_version(unsigned long libver,
   5695                       unsigned int *major, unsigned int *minor,
   5696                       unsigned int *fix, unsigned int *patch,
   5697                       unsigned int *status)
   5698 {
   5699     *status = libver & 0xF;
   5700     libver >>= 4;
   5701     *patch = libver & 0xFF;
   5702     libver >>= 8;
   5703     *fix = libver & 0xFF;
   5704     libver >>= 8;
   5705     *minor = libver & 0xFF;
   5706     libver >>= 8;
   5707     *major = libver & 0xFF;
   5708 }
   5709 
   5710 PyMODINIT_FUNC
   5711 PyInit__ssl(void)
   5712 {
   5713     PyObject *m, *d, *r, *bases;
   5714     unsigned long libver;
   5715     unsigned int major, minor, fix, patch, status;
   5716     PySocketModule_APIObject *socket_api;
   5717     struct py_ssl_error_code *errcode;
   5718     struct py_ssl_library_code *libcode;
   5719 
   5720     if (PyType_Ready(&PySSLContext_Type) < 0)
   5721         return NULL;
   5722     if (PyType_Ready(&PySSLSocket_Type) < 0)
   5723         return NULL;
   5724     if (PyType_Ready(&PySSLMemoryBIO_Type) < 0)
   5725         return NULL;
   5726     if (PyType_Ready(&PySSLSession_Type) < 0)
   5727         return NULL;
   5728 
   5729 
   5730     m = PyModule_Create(&_sslmodule);
   5731     if (m == NULL)
   5732         return NULL;
   5733     d = PyModule_GetDict(m);
   5734 
   5735     /* Load _socket module and its C API */
   5736     socket_api = PySocketModule_ImportModuleAndAPI();
   5737     if (!socket_api)
   5738         return NULL;
   5739     PySocketModule = *socket_api;
   5740 
   5741 #ifndef OPENSSL_VERSION_1_1
   5742     /* Load all algorithms and initialize cpuid */
   5743     OPENSSL_add_all_algorithms_noconf();
   5744     /* Init OpenSSL */
   5745     SSL_load_error_strings();
   5746     SSL_library_init();
   5747 #endif
   5748 
   5749 #ifdef HAVE_OPENSSL_CRYPTO_LOCK
   5750     /* note that this will start threading if not already started */
   5751     if (!_setup_ssl_threads()) {
   5752         return NULL;
   5753     }
   5754 #elif OPENSSL_VERSION_1_1 && defined(OPENSSL_THREADS)
   5755     /* OpenSSL 1.1.0 builtin thread support is enabled */
   5756     _ssl_locks_count++;
   5757 #endif
   5758 
   5759     /* Add symbols to module dict */
   5760     sslerror_type_slots[0].pfunc = PyExc_OSError;
   5761     PySSLErrorObject = PyType_FromSpec(&sslerror_type_spec);
   5762     if (PySSLErrorObject == NULL)
   5763         return NULL;
   5764 
   5765     /* ssl.CertificateError used to be a subclass of ValueError */
   5766     bases = Py_BuildValue("OO", PySSLErrorObject, PyExc_ValueError);
   5767     if (bases == NULL)
   5768         return NULL;
   5769     PySSLCertVerificationErrorObject = PyErr_NewExceptionWithDoc(
   5770         "ssl.SSLCertVerificationError", SSLCertVerificationError_doc,
   5771         bases, NULL);
   5772     Py_DECREF(bases);
   5773     PySSLZeroReturnErrorObject = PyErr_NewExceptionWithDoc(
   5774         "ssl.SSLZeroReturnError", SSLZeroReturnError_doc,
   5775         PySSLErrorObject, NULL);
   5776     PySSLWantReadErrorObject = PyErr_NewExceptionWithDoc(
   5777         "ssl.SSLWantReadError", SSLWantReadError_doc,
   5778         PySSLErrorObject, NULL);
   5779     PySSLWantWriteErrorObject = PyErr_NewExceptionWithDoc(
   5780         "ssl.SSLWantWriteError", SSLWantWriteError_doc,
   5781         PySSLErrorObject, NULL);
   5782     PySSLSyscallErrorObject = PyErr_NewExceptionWithDoc(
   5783         "ssl.SSLSyscallError", SSLSyscallError_doc,
   5784         PySSLErrorObject, NULL);
   5785     PySSLEOFErrorObject = PyErr_NewExceptionWithDoc(
   5786         "ssl.SSLEOFError", SSLEOFError_doc,
   5787         PySSLErrorObject, NULL);
   5788     if (PySSLCertVerificationErrorObject == NULL
   5789         || PySSLZeroReturnErrorObject == NULL
   5790         || PySSLWantReadErrorObject == NULL
   5791         || PySSLWantWriteErrorObject == NULL
   5792         || PySSLSyscallErrorObject == NULL
   5793         || PySSLEOFErrorObject == NULL)
   5794         return NULL;
   5795     if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0
   5796         || PyDict_SetItemString(d, "SSLCertVerificationError",
   5797                                 PySSLCertVerificationErrorObject) != 0
   5798         || PyDict_SetItemString(d, "SSLZeroReturnError", PySSLZeroReturnErrorObject) != 0
   5799         || PyDict_SetItemString(d, "SSLWantReadError", PySSLWantReadErrorObject) != 0
   5800         || PyDict_SetItemString(d, "SSLWantWriteError", PySSLWantWriteErrorObject) != 0
   5801         || PyDict_SetItemString(d, "SSLSyscallError", PySSLSyscallErrorObject) != 0
   5802         || PyDict_SetItemString(d, "SSLEOFError", PySSLEOFErrorObject) != 0)
   5803         return NULL;
   5804     if (PyDict_SetItemString(d, "_SSLContext",
   5805                              (PyObject *)&PySSLContext_Type) != 0)
   5806         return NULL;
   5807     if (PyDict_SetItemString(d, "_SSLSocket",
   5808                              (PyObject *)&PySSLSocket_Type) != 0)
   5809         return NULL;
   5810     if (PyDict_SetItemString(d, "MemoryBIO",
   5811                              (PyObject *)&PySSLMemoryBIO_Type) != 0)
   5812         return NULL;
   5813     if (PyDict_SetItemString(d, "SSLSession",
   5814                              (PyObject *)&PySSLSession_Type) != 0)
   5815         return NULL;
   5816 
   5817     PyModule_AddStringConstant(m, "_DEFAULT_CIPHERS",
   5818                                PY_SSL_DEFAULT_CIPHER_STRING);
   5819 
   5820     PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
   5821                             PY_SSL_ERROR_ZERO_RETURN);
   5822     PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
   5823                             PY_SSL_ERROR_WANT_READ);
   5824     PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
   5825                             PY_SSL_ERROR_WANT_WRITE);
   5826     PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
   5827                             PY_SSL_ERROR_WANT_X509_LOOKUP);
   5828     PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
   5829                             PY_SSL_ERROR_SYSCALL);
   5830     PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
   5831                             PY_SSL_ERROR_SSL);
   5832     PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
   5833                             PY_SSL_ERROR_WANT_CONNECT);
   5834     /* non ssl.h errorcodes */
   5835     PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
   5836                             PY_SSL_ERROR_EOF);
   5837     PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
   5838                             PY_SSL_ERROR_INVALID_ERROR_CODE);
   5839     /* cert requirements */
   5840     PyModule_AddIntConstant(m, "CERT_NONE",
   5841                             PY_SSL_CERT_NONE);
   5842     PyModule_AddIntConstant(m, "CERT_OPTIONAL",
   5843                             PY_SSL_CERT_OPTIONAL);
   5844     PyModule_AddIntConstant(m, "CERT_REQUIRED",
   5845                             PY_SSL_CERT_REQUIRED);
   5846     /* CRL verification for verification_flags */
   5847     PyModule_AddIntConstant(m, "VERIFY_DEFAULT",
   5848                             0);
   5849     PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_LEAF",
   5850                             X509_V_FLAG_CRL_CHECK);
   5851     PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_CHAIN",
   5852                             X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
   5853     PyModule_AddIntConstant(m, "VERIFY_X509_STRICT",
   5854                             X509_V_FLAG_X509_STRICT);
   5855 #ifdef X509_V_FLAG_TRUSTED_FIRST
   5856     PyModule_AddIntConstant(m, "VERIFY_X509_TRUSTED_FIRST",
   5857                             X509_V_FLAG_TRUSTED_FIRST);
   5858 #endif
   5859 
   5860     /* Alert Descriptions from ssl.h */
   5861     /* note RESERVED constants no longer intended for use have been removed */
   5862     /* http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-6 */
   5863 
   5864 #define ADD_AD_CONSTANT(s) \
   5865     PyModule_AddIntConstant(m, "ALERT_DESCRIPTION_"#s, \
   5866                             SSL_AD_##s)
   5867 
   5868     ADD_AD_CONSTANT(CLOSE_NOTIFY);
   5869     ADD_AD_CONSTANT(UNEXPECTED_MESSAGE);
   5870     ADD_AD_CONSTANT(BAD_RECORD_MAC);
   5871     ADD_AD_CONSTANT(RECORD_OVERFLOW);
   5872     ADD_AD_CONSTANT(DECOMPRESSION_FAILURE);
   5873     ADD_AD_CONSTANT(HANDSHAKE_FAILURE);
   5874     ADD_AD_CONSTANT(BAD_CERTIFICATE);
   5875     ADD_AD_CONSTANT(UNSUPPORTED_CERTIFICATE);
   5876     ADD_AD_CONSTANT(CERTIFICATE_REVOKED);
   5877     ADD_AD_CONSTANT(CERTIFICATE_EXPIRED);
   5878     ADD_AD_CONSTANT(CERTIFICATE_UNKNOWN);
   5879     ADD_AD_CONSTANT(ILLEGAL_PARAMETER);
   5880     ADD_AD_CONSTANT(UNKNOWN_CA);
   5881     ADD_AD_CONSTANT(ACCESS_DENIED);
   5882     ADD_AD_CONSTANT(DECODE_ERROR);
   5883     ADD_AD_CONSTANT(DECRYPT_ERROR);
   5884     ADD_AD_CONSTANT(PROTOCOL_VERSION);
   5885     ADD_AD_CONSTANT(INSUFFICIENT_SECURITY);
   5886     ADD_AD_CONSTANT(INTERNAL_ERROR);
   5887     ADD_AD_CONSTANT(USER_CANCELLED);
   5888     ADD_AD_CONSTANT(NO_RENEGOTIATION);
   5889     /* Not all constants are in old OpenSSL versions */
   5890 #ifdef SSL_AD_UNSUPPORTED_EXTENSION
   5891     ADD_AD_CONSTANT(UNSUPPORTED_EXTENSION);
   5892 #endif
   5893 #ifdef SSL_AD_CERTIFICATE_UNOBTAINABLE
   5894     ADD_AD_CONSTANT(CERTIFICATE_UNOBTAINABLE);
   5895 #endif
   5896 #ifdef SSL_AD_UNRECOGNIZED_NAME
   5897     ADD_AD_CONSTANT(UNRECOGNIZED_NAME);
   5898 #endif
   5899 #ifdef SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE
   5900     ADD_AD_CONSTANT(BAD_CERTIFICATE_STATUS_RESPONSE);
   5901 #endif
   5902 #ifdef SSL_AD_BAD_CERTIFICATE_HASH_VALUE
   5903     ADD_AD_CONSTANT(BAD_CERTIFICATE_HASH_VALUE);
   5904 #endif
   5905 #ifdef SSL_AD_UNKNOWN_PSK_IDENTITY
   5906     ADD_AD_CONSTANT(UNKNOWN_PSK_IDENTITY);
   5907 #endif
   5908 
   5909 #undef ADD_AD_CONSTANT
   5910 
   5911     /* protocol versions */
   5912 #ifndef OPENSSL_NO_SSL2
   5913     PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
   5914                             PY_SSL_VERSION_SSL2);
   5915 #endif
   5916 #ifndef OPENSSL_NO_SSL3
   5917     PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
   5918                             PY_SSL_VERSION_SSL3);
   5919 #endif
   5920     PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
   5921                             PY_SSL_VERSION_TLS);
   5922     PyModule_AddIntConstant(m, "PROTOCOL_TLS",
   5923                             PY_SSL_VERSION_TLS);
   5924     PyModule_AddIntConstant(m, "PROTOCOL_TLS_CLIENT",
   5925                             PY_SSL_VERSION_TLS_CLIENT);
   5926     PyModule_AddIntConstant(m, "PROTOCOL_TLS_SERVER",
   5927                             PY_SSL_VERSION_TLS_SERVER);
   5928     PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
   5929                             PY_SSL_VERSION_TLS1);
   5930 #if HAVE_TLSv1_2
   5931     PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_1",
   5932                             PY_SSL_VERSION_TLS1_1);
   5933     PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_2",
   5934                             PY_SSL_VERSION_TLS1_2);
   5935 #endif
   5936 
   5937     /* protocol options */
   5938     PyModule_AddIntConstant(m, "OP_ALL",
   5939                             SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
   5940     PyModule_AddIntConstant(m, "OP_NO_SSLv2", SSL_OP_NO_SSLv2);
   5941     PyModule_AddIntConstant(m, "OP_NO_SSLv3", SSL_OP_NO_SSLv3);
   5942     PyModule_AddIntConstant(m, "OP_NO_TLSv1", SSL_OP_NO_TLSv1);
   5943 #if HAVE_TLSv1_2
   5944     PyModule_AddIntConstant(m, "OP_NO_TLSv1_1", SSL_OP_NO_TLSv1_1);
   5945     PyModule_AddIntConstant(m, "OP_NO_TLSv1_2", SSL_OP_NO_TLSv1_2);
   5946 #endif
   5947 #ifdef SSL_OP_NO_TLSv1_3
   5948     PyModule_AddIntConstant(m, "OP_NO_TLSv1_3", SSL_OP_NO_TLSv1_3);
   5949 #else
   5950     PyModule_AddIntConstant(m, "OP_NO_TLSv1_3", 0);
   5951 #endif
   5952     PyModule_AddIntConstant(m, "OP_CIPHER_SERVER_PREFERENCE",
   5953                             SSL_OP_CIPHER_SERVER_PREFERENCE);
   5954     PyModule_AddIntConstant(m, "OP_SINGLE_DH_USE", SSL_OP_SINGLE_DH_USE);
   5955     PyModule_AddIntConstant(m, "OP_NO_TICKET", SSL_OP_NO_TICKET);
   5956 #ifdef SSL_OP_SINGLE_ECDH_USE
   5957     PyModule_AddIntConstant(m, "OP_SINGLE_ECDH_USE", SSL_OP_SINGLE_ECDH_USE);
   5958 #endif
   5959 #ifdef SSL_OP_NO_COMPRESSION
   5960     PyModule_AddIntConstant(m, "OP_NO_COMPRESSION",
   5961                             SSL_OP_NO_COMPRESSION);
   5962 #endif
   5963 #ifdef SSL_OP_ENABLE_MIDDLEBOX_COMPAT
   5964     PyModule_AddIntConstant(m, "OP_ENABLE_MIDDLEBOX_COMPAT",
   5965                             SSL_OP_ENABLE_MIDDLEBOX_COMPAT);
   5966 #endif
   5967 #ifdef SSL_OP_NO_RENEGOTIATION
   5968     PyModule_AddIntConstant(m, "OP_NO_RENEGOTIATION",
   5969                             SSL_OP_NO_RENEGOTIATION);
   5970 #endif
   5971 
   5972 #ifdef X509_CHECK_FLAG_ALWAYS_CHECK_SUBJECT
   5973     PyModule_AddIntConstant(m, "HOSTFLAG_ALWAYS_CHECK_SUBJECT",
   5974                             X509_CHECK_FLAG_ALWAYS_CHECK_SUBJECT);
   5975 #endif
   5976 #ifdef X509_CHECK_FLAG_NEVER_CHECK_SUBJECT
   5977     PyModule_AddIntConstant(m, "HOSTFLAG_NEVER_CHECK_SUBJECT",
   5978                             X509_CHECK_FLAG_NEVER_CHECK_SUBJECT);
   5979 #endif
   5980 #ifdef X509_CHECK_FLAG_NO_WILDCARDS
   5981     PyModule_AddIntConstant(m, "HOSTFLAG_NO_WILDCARDS",
   5982                             X509_CHECK_FLAG_NO_WILDCARDS);
   5983 #endif
   5984 #ifdef X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS
   5985     PyModule_AddIntConstant(m, "HOSTFLAG_NO_PARTIAL_WILDCARDS",
   5986                             X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS);
   5987 #endif
   5988 #ifdef X509_CHECK_FLAG_MULTI_LABEL_WILDCARDS
   5989     PyModule_AddIntConstant(m, "HOSTFLAG_MULTI_LABEL_WILDCARDS",
   5990                             X509_CHECK_FLAG_MULTI_LABEL_WILDCARDS);
   5991 #endif
   5992 #ifdef X509_CHECK_FLAG_SINGLE_LABEL_SUBDOMAINS
   5993     PyModule_AddIntConstant(m, "HOSTFLAG_SINGLE_LABEL_SUBDOMAINS",
   5994                             X509_CHECK_FLAG_SINGLE_LABEL_SUBDOMAINS);
   5995 #endif
   5996 
   5997     /* protocol versions */
   5998     PyModule_AddIntConstant(m, "PROTO_MINIMUM_SUPPORTED",
   5999                             PY_PROTO_MINIMUM_SUPPORTED);
   6000     PyModule_AddIntConstant(m, "PROTO_MAXIMUM_SUPPORTED",
   6001                             PY_PROTO_MAXIMUM_SUPPORTED);
   6002     PyModule_AddIntConstant(m, "PROTO_SSLv3", PY_PROTO_SSLv3);
   6003     PyModule_AddIntConstant(m, "PROTO_TLSv1", PY_PROTO_TLSv1);
   6004     PyModule_AddIntConstant(m, "PROTO_TLSv1_1", PY_PROTO_TLSv1_1);
   6005     PyModule_AddIntConstant(m, "PROTO_TLSv1_2", PY_PROTO_TLSv1_2);
   6006     PyModule_AddIntConstant(m, "PROTO_TLSv1_3", PY_PROTO_TLSv1_3);
   6007 
   6008 #define addbool(m, v, b) \
   6009     Py_INCREF((b) ? Py_True : Py_False); \
   6010     PyModule_AddObject((m), (v), (b) ? Py_True : Py_False);
   6011 
   6012 #if HAVE_SNI
   6013     addbool(m, "HAS_SNI", 1);
   6014 #else
   6015     addbool(m, "HAS_SNI", 0);
   6016 #endif
   6017 
   6018     addbool(m, "HAS_TLS_UNIQUE", 1);
   6019 
   6020 #ifndef OPENSSL_NO_ECDH
   6021     addbool(m, "HAS_ECDH", 1);
   6022 #else
   6023     addbool(m, "HAS_ECDH", 0);
   6024 #endif
   6025 
   6026 #if HAVE_NPN
   6027     addbool(m, "HAS_NPN", 1);
   6028 #else
   6029     addbool(m, "HAS_NPN", 0);
   6030 #endif
   6031 
   6032 #if HAVE_ALPN
   6033     addbool(m, "HAS_ALPN", 1);
   6034 #else
   6035     addbool(m, "HAS_ALPN", 0);
   6036 #endif
   6037 
   6038 #if defined(SSL2_VERSION) && !defined(OPENSSL_NO_SSL2)
   6039     addbool(m, "HAS_SSLv2", 1);
   6040 #else
   6041     addbool(m, "HAS_SSLv2", 0);
   6042 #endif
   6043 
   6044 #if defined(SSL3_VERSION) && !defined(OPENSSL_NO_SSL3)
   6045     addbool(m, "HAS_SSLv3", 1);
   6046 #else
   6047     addbool(m, "HAS_SSLv3", 0);
   6048 #endif
   6049 
   6050 #if defined(TLS1_VERSION) && !defined(OPENSSL_NO_TLS1)
   6051     addbool(m, "HAS_TLSv1", 1);
   6052 #else
   6053     addbool(m, "HAS_TLSv1", 0);
   6054 #endif
   6055 
   6056 #if defined(TLS1_1_VERSION) && !defined(OPENSSL_NO_TLS1_1)
   6057     addbool(m, "HAS_TLSv1_1", 1);
   6058 #else
   6059     addbool(m, "HAS_TLSv1_1", 0);
   6060 #endif
   6061 
   6062 #if defined(TLS1_2_VERSION) && !defined(OPENSSL_NO_TLS1_2)
   6063     addbool(m, "HAS_TLSv1_2", 1);
   6064 #else
   6065     addbool(m, "HAS_TLSv1_2", 0);
   6066 #endif
   6067 
   6068 #if defined(TLS1_3_VERSION) && !defined(OPENSSL_NO_TLS1_3)
   6069     addbool(m, "HAS_TLSv1_3", 1);
   6070 #else
   6071     addbool(m, "HAS_TLSv1_3", 0);
   6072 #endif
   6073 
   6074     /* Mappings for error codes */
   6075     err_codes_to_names = PyDict_New();
   6076     err_names_to_codes = PyDict_New();
   6077     if (err_codes_to_names == NULL || err_names_to_codes == NULL)
   6078         return NULL;
   6079     errcode = error_codes;
   6080     while (errcode->mnemonic != NULL) {
   6081         PyObject *mnemo, *key;
   6082         mnemo = PyUnicode_FromString(errcode->mnemonic);
   6083         key = Py_BuildValue("ii", errcode->library, errcode->reason);
   6084         if (mnemo == NULL || key == NULL)
   6085             return NULL;
   6086         if (PyDict_SetItem(err_codes_to_names, key, mnemo))
   6087             return NULL;
   6088         if (PyDict_SetItem(err_names_to_codes, mnemo, key))
   6089             return NULL;
   6090         Py_DECREF(key);
   6091         Py_DECREF(mnemo);
   6092         errcode++;
   6093     }
   6094     if (PyModule_AddObject(m, "err_codes_to_names", err_codes_to_names))
   6095         return NULL;
   6096     if (PyModule_AddObject(m, "err_names_to_codes", err_names_to_codes))
   6097         return NULL;
   6098 
   6099     lib_codes_to_names = PyDict_New();
   6100     if (lib_codes_to_names == NULL)
   6101         return NULL;
   6102     libcode = library_codes;
   6103     while (libcode->library != NULL) {
   6104         PyObject *mnemo, *key;
   6105         key = PyLong_FromLong(libcode->code);
   6106         mnemo = PyUnicode_FromString(libcode->library);
   6107         if (key == NULL || mnemo == NULL)
   6108             return NULL;
   6109         if (PyDict_SetItem(lib_codes_to_names, key, mnemo))
   6110             return NULL;
   6111         Py_DECREF(key);
   6112         Py_DECREF(mnemo);
   6113         libcode++;
   6114     }
   6115     if (PyModule_AddObject(m, "lib_codes_to_names", lib_codes_to_names))
   6116         return NULL;
   6117 
   6118     /* OpenSSL version */
   6119     /* SSLeay() gives us the version of the library linked against,
   6120        which could be different from the headers version.
   6121     */
   6122     libver = SSLeay();
   6123     r = PyLong_FromUnsignedLong(libver);
   6124     if (r == NULL)
   6125         return NULL;
   6126     if (PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r))
   6127         return NULL;
   6128     parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
   6129     r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
   6130     if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r))
   6131         return NULL;
   6132     r = PyUnicode_FromString(SSLeay_version(SSLEAY_VERSION));
   6133     if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r))
   6134         return NULL;
   6135 
   6136     libver = OPENSSL_VERSION_NUMBER;
   6137     parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
   6138     r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
   6139     if (r == NULL || PyModule_AddObject(m, "_OPENSSL_API_VERSION", r))
   6140         return NULL;
   6141 
   6142     return m;
   6143 }
   6144