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