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