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