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