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