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