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