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