blob: 73544bb12d1d8b6d9ee28fe518954591100ea5b0 [file] [log] [blame]
Thomas Woutersed03b412007-08-28 21:37:11 +00001/* SSL socket module
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002
3 SSL support based on patches by Brian E Gallew and Laszlo Kovacs.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004 Re-worked a bit by Bill Janssen to add server-side support and
Bill Janssen6e027db2007-11-15 22:23:56 +00005 certificate decoding. Chris Stawarz contributed some non-blocking
6 patches.
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00007
Thomas Wouters1b7f8912007-09-19 03:06:30 +00008 This module is imported by ssl.py. It should *not* be used
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00009 directly.
10
Thomas Wouters1b7f8912007-09-19 03:06:30 +000011 XXX should partial writes be enabled, SSL_MODE_ENABLE_PARTIAL_WRITE?
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +000012
13 XXX integrate several "shutdown modes" as suggested in
14 http://bugs.python.org/issue8108#msg102867 ?
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000015*/
16
Christian Heimesa4833882021-04-13 08:17:26 +020017/* 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
Victor Stinner2e57b4e2014-07-01 16:37:17 +020024#define PY_SSIZE_T_CLEAN
25
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000026#include "Python.h"
Thomas Woutersed03b412007-08-28 21:37:11 +000027
Christian Heimes7f1305e2021-04-17 20:06:38 +020028/* Include symbols from _socket module */
29#include "socketmodule.h"
30
31#include "_ssl.h"
32
Steve Dower68d663c2017-07-17 11:15:48 +020033/* Redefined below for Windows debug builds after important #includes */
34#define _PySSL_FIX_ERRNO
Christian Heimesf77b4b22013-08-21 13:26:05 +020035
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +020036#define PySSL_BEGIN_ALLOW_THREADS_S(save) \
Christian Heimes39258d32021-04-17 11:36:35 +020037 do { (save) = PyEval_SaveThread(); } while(0)
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +020038#define PySSL_END_ALLOW_THREADS_S(save) \
Christian Heimes39258d32021-04-17 11:36:35 +020039 do { PyEval_RestoreThread(save); _PySSL_FIX_ERRNO; } while(0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +000040#define PySSL_BEGIN_ALLOW_THREADS { \
Antoine Pitroucbb82eb2010-05-05 15:57:33 +000041 PyThreadState *_save = NULL; \
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +020042 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); }
Thomas Wouters1b7f8912007-09-19 03:06:30 +000046
Antoine Pitrou2463e5f2013-03-28 22:24:43 +010047
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"
Antoine Pitroub1fdf472014-10-05 20:41:53 +020063#include "openssl/bio.h"
Alexandru Ardeleanb3a271f2018-09-17 14:53:31 +030064#include "openssl/dh.h"
Antoine Pitrou2463e5f2013-03-28 22:24:43 +010065
Christian Heimesc087a262020-05-15 20:55:25 +020066#ifndef OPENSSL_THREADS
67# error "OPENSSL_THREADS is not defined, Python requires thread-safe OpenSSL"
68#endif
69
Antoine Pitrou2463e5f2013-03-28 22:24:43 +010070
Antoine Pitrou2463e5f2013-03-28 22:24:43 +010071
72struct py_ssl_error_code {
73 const char *mnemonic;
74 int library, reason;
75};
Christian Heimes7f1305e2021-04-17 20:06:38 +020076
Antoine Pitrou2463e5f2013-03-28 22:24:43 +010077struct py_ssl_library_code {
78 const char *library;
79 int code;
80};
81
Steve Dower68d663c2017-07-17 11:15:48 +020082#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
93static 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
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100116/* Include generated data (error codes) */
Christian Heimes150af752021-04-09 17:02:00 +0200117#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
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100122#include "_ssl_data.h"
Christian Heimes150af752021-04-09 17:02:00 +0200123#endif
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100124
Christian Heimes39258d32021-04-17 11:36:35 +0200125/* OpenSSL API 1.1.0+ does not include version methods */
Christian Heimes33091132021-04-20 18:10:10 +0200126#ifndef OPENSSL_NO_SSL3_METHOD
127extern const SSL_METHOD *SSLv3_method(void);
128#endif
Christian Heimesa871f692020-06-01 08:58:14 +0200129#ifndef OPENSSL_NO_TLS1_METHOD
Christian Heimesa4833882021-04-13 08:17:26 +0200130extern const SSL_METHOD *TLSv1_method(void);
Christian Heimesa871f692020-06-01 08:58:14 +0200131#endif
132#ifndef OPENSSL_NO_TLS1_1_METHOD
Christian Heimesa4833882021-04-13 08:17:26 +0200133extern const SSL_METHOD *TLSv1_1_method(void);
Christian Heimesa871f692020-06-01 08:58:14 +0200134#endif
135#ifndef OPENSSL_NO_TLS1_2_METHOD
Christian Heimesa4833882021-04-13 08:17:26 +0200136extern const SSL_METHOD *TLSv1_2_method(void);
Christian Heimesa871f692020-06-01 08:58:14 +0200137#endif
138
Victor Stinner524714e2016-07-22 17:43:59 +0200139#ifndef INVALID_SOCKET /* MS defines this */
140#define INVALID_SOCKET (-1)
141#endif
142
Christian Heimes39258d32021-04-17 11:36:35 +0200143/* OpenSSL 1.1 does not have SSL 2.0 */
Christian Heimes598894f2016-09-05 23:19:05 +0200144#define OPENSSL_NO_SSL2
Christian Heimes598894f2016-09-05 23:19:05 +0200145
Christian Heimes892d66e2018-01-29 14:10:18 +0100146/* 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
Christian Heimese9832522021-05-01 20:53:10 +0200155 #ifndef PY_SSL_MIN_PROTOCOL
156 #define PY_SSL_MIN_PROTOCOL TLS1_2_VERSION
157 #endif
Christian Heimes892d66e2018-01-29 14:10:18 +0100158#elif PY_SSL_DEFAULT_CIPHERS == 1
Stéphane Wirtel07fbbfd2018-10-05 16:17:18 +0200159/* Python custom selection of sensible cipher suites
Christian Heimese9832522021-05-01 20:53:10 +0200160 * @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
Christian Heimes892d66e2018-01-29 14:10:18 +0100164 * !aNULL:!eNULL: really no NULL ciphers
Christian Heimes892d66e2018-01-29 14:10:18 +0100165 * !aDSS: no authentication with discrete logarithm DSA algorithm
Christian Heimese9832522021-05-01 20:53:10 +0200166 * !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/
Christian Heimes892d66e2018-01-29 14:10:18 +0100171 */
Christian Heimese9832522021-05-01 20:53:10 +0200172 #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
Christian Heimes892d66e2018-01-29 14:10:18 +0100176#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
Christian Heimes598894f2016-09-05 23:19:05 +0200183
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000184enum py_ssl_error {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000185 /* 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
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000198};
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000199
Thomas Woutersed03b412007-08-28 21:37:11 +0000200enum py_ssl_server_or_client {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000201 PY_SSL_CLIENT,
202 PY_SSL_SERVER
Thomas Woutersed03b412007-08-28 21:37:11 +0000203};
204
205enum py_ssl_cert_requirements {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000206 PY_SSL_CERT_NONE,
207 PY_SSL_CERT_OPTIONAL,
208 PY_SSL_CERT_REQUIRED
Thomas Woutersed03b412007-08-28 21:37:11 +0000209};
210
211enum py_ssl_version {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000212 PY_SSL_VERSION_SSL2,
Victor Stinner3de49192011-05-09 00:42:58 +0200213 PY_SSL_VERSION_SSL3=1,
Christian Heimes5fe668c2016-09-12 00:01:11 +0200214 PY_SSL_VERSION_TLS, /* SSLv23 */
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100215 PY_SSL_VERSION_TLS1,
216 PY_SSL_VERSION_TLS1_1,
Christian Heimes5fe668c2016-09-12 00:01:11 +0200217 PY_SSL_VERSION_TLS1_2,
Christian Heimes5fe668c2016-09-12 00:01:11 +0200218 PY_SSL_VERSION_TLS_CLIENT=0x10,
219 PY_SSL_VERSION_TLS_SERVER,
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100220};
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200221
Christian Heimes698dde12018-02-27 11:54:43 +0100222enum 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
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000268/* SSL socket object */
269
270#define X509_NAME_MAXLEN 256
271
Antoine Pitroub5218772010-05-21 09:56:06 +0000272
Antoine Pitroud6494802011-07-21 01:11:30 +0200273/* 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
Antoine Pitroua9bf2ac2012-02-17 18:47:54 +0100277
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000278typedef struct {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000279 PyObject_HEAD
Antoine Pitrou152efa22010-05-16 18:19:27 +0000280 SSL_CTX *ctx;
Benjamin Petersoncca27322015-01-23 16:35:37 -0500281 unsigned char *alpn_protocols;
Segev Finer5cff6372017-07-27 01:19:17 +0300282 unsigned int alpn_protocols_len;
Christian Heimes11a14932018-02-24 02:35:08 +0100283 PyObject *set_sni_cb;
Christian Heimes1aa9a752013-12-02 02:41:19 +0100284 int check_hostname;
Christian Heimes61d478c2018-01-27 15:51:38 +0100285 /* 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;
Christian Heimes11a14932018-02-24 02:35:08 +0100289 int protocol;
Christian Heimes9fb051f2018-09-23 08:32:31 +0200290#ifdef TLS1_3_VERSION
291 int post_handshake_auth;
292#endif
Christian Heimesc7f70692019-05-31 11:44:05 +0200293 PyObject *msg_cb;
Christian Heimesc7f70692019-05-31 11:44:05 +0200294 PyObject *keylog_filename;
295 BIO *keylog_bio;
Christian Heimes7f1305e2021-04-17 20:06:38 +0200296 /* Cached module state, also used in SSLSocket and SSLSession code. */
297 _sslmodulestate *state;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000298} PySSLContext;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000299
Antoine Pitrou152efa22010-05-16 18:19:27 +0000300typedef struct {
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700301 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
308typedef struct {
Antoine Pitrou152efa22010-05-16 18:19:27 +0000309 PyObject_HEAD
310 PyObject *Socket; /* weakref to socket on which we're layered */
311 SSL *ssl;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100312 PySSLContext *ctx; /* weakref to SSL context */
Antoine Pitrou20b85552013-09-29 19:50:53 +0200313 char shutdown_seen_zero;
Antoine Pitroud6494802011-07-21 01:11:30 +0200314 enum py_ssl_server_or_client socket_type;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200315 PyObject *owner; /* Python level "owner" passed to servername callback */
316 PyObject *server_hostname;
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700317 _PySSLError err; /* last seen error from various sources */
Christian Heimesc7f70692019-05-31 11:44:05 +0200318 /* 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;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000325} PySSLSocket;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000326
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200327typedef struct {
328 PyObject_HEAD
329 BIO *bio;
330 int eof_written;
331} PySSLMemoryBIO;
332
Christian Heimes99a65702016-09-10 23:44:53 +0200333typedef struct {
334 PyObject_HEAD
335 SSL_SESSION *session;
336 PySSLContext *ctx;
337} PySSLSession;
338
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700339static inline _PySSLError _PySSL_errno(int failed, const SSL *ssl, int retcode)
340{
341 _PySSLError err = { 0 };
342 if (failed) {
Steve Dowere6eb48c2017-09-08 15:16:15 -0700343#ifdef MS_WINDOWS
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700344 err.ws = WSAGetLastError();
345 _PySSL_FIX_ERRNO;
Steve Dowere6eb48c2017-09-08 15:16:15 -0700346#endif
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700347 err.c = errno;
348 err.ssl = SSL_get_error(ssl, retcode);
349 }
350 return err;
351}
Steve Dowere6eb48c2017-09-08 15:16:15 -0700352
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +0300353/*[clinic input]
354module _ssl
Christian Heimes7f1305e2021-04-17 20:06:38 +0200355class _ssl._SSLContext "PySSLContext *" "get_state_type(type)->PySSLContext_Type"
356class _ssl._SSLSocket "PySSLSocket *" "get_state_type(type)->PySSLSocket_Type"
357class _ssl.MemoryBIO "PySSLMemoryBIO *" "get_state_type(type)->PySSLMemoryBIO_Type"
358class _ssl.SSLSession "PySSLSession *" "get_state_type(type)->PySSLSession_Type"
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +0300359[clinic start generated code]*/
Christian Heimes7f1305e2021-04-17 20:06:38 +0200360/*[clinic end generated code: output=da39a3ee5e6b4b0d input=d293bed8bae240fd]*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +0300361
362#include "clinic/_ssl.c.h"
363
Victor Stinner14690702015-04-06 22:46:13 +0200364static int PySSL_select(PySocketSockObject *s, int writing, _PyTime_t timeout);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000365
Christian Heimes141c5e82018-02-24 21:10:57 +0100366static int PySSL_set_owner(PySSLSocket *, PyObject *, void *);
367static int PySSL_set_session(PySSLSocket *, PyObject *, void *);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000368
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000369typedef enum {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000370 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
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000376} timeout_state;
377
Thomas Woutersed03b412007-08-28 21:37:11 +0000378/* Wrap error strings with filename and line # */
Thomas Woutersed03b412007-08-28 21:37:11 +0000379#define ERRSTR1(x,y,z) (x ":" y ": " z)
Victor Stinner45e8e2f2014-05-14 17:24:35 +0200380#define ERRSTR(x) ERRSTR1("_ssl.c", Py_STRINGIFY(__LINE__), x)
Thomas Woutersed03b412007-08-28 21:37:11 +0000381
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200382/* Get the socket from a PySSLSocket, if it has one */
383#define GET_SOCKET(obj) ((obj)->Socket ? \
384 (PySocketSockObject *) PyWeakref_GetObject((obj)->Socket) : NULL)
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200385
Victor Stinner14690702015-04-06 22:46:13 +0200386/* If sock is NULL, use a timeout of 0 second */
387#define GET_SOCKET_TIMEOUT(sock) \
388 ((sock != NULL) ? (sock)->sock_timeout : 0)
389
Christian Heimesc7f70692019-05-31 11:44:05 +0200390#include "_ssl/debughelpers.c"
391
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200392/*
393 * SSL errors.
394 */
395
396PyDoc_STRVAR(SSLError_doc,
397"An error occurred in the SSL implementation.");
398
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700399PyDoc_STRVAR(SSLCertVerificationError_doc,
400"A certificate could not be verified.");
401
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200402PyDoc_STRVAR(SSLZeroReturnError_doc,
403"SSL/TLS session closed cleanly.");
404
405PyDoc_STRVAR(SSLWantReadError_doc,
406"Non-blocking SSL socket needs to read more data\n"
407"before the requested operation can be completed.");
408
409PyDoc_STRVAR(SSLWantWriteError_doc,
410"Non-blocking SSL socket needs to write more data\n"
411"before the requested operation can be completed.");
412
413PyDoc_STRVAR(SSLSyscallError_doc,
414"System error when attempting SSL operation.");
415
416PyDoc_STRVAR(SSLEOFError_doc,
417"SSL/TLS connection terminated abruptly.");
418
419static PyObject *
420SSLError_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
430static PyType_Slot sslerror_type_slots[] = {
Inada Naoki926b0cb2019-04-17 08:39:46 +0900431 {Py_tp_doc, (void*)SSLError_doc},
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200432 {Py_tp_str, SSLError_str},
433 {0, 0},
434};
435
436static PyType_Spec sslerror_type_spec = {
Miss Islington (bot)ea47a8a2021-05-27 09:25:22 -0700437 .name = "ssl.SSLError",
438 .basicsize = sizeof(PyOSErrorObject),
Miss Islington (bot)a7aa1052021-05-28 16:47:36 -0700439 .flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_IMMUTABLETYPE),
Miss Islington (bot)ea47a8a2021-05-27 09:25:22 -0700440 .slots = sslerror_type_slots
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200441};
442
443static void
Christian Heimes7f1305e2021-04-17 20:06:38 +0200444fill_and_set_sslerror(_sslmodulestate *state,
445 PySSLSocket *sslsock, PyObject *type, int ssl_errno,
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700446 const char *errstr, int lineno, unsigned long errcode)
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200447{
448 PyObject *err_value = NULL, *reason_obj = NULL, *lib_obj = NULL;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700449 PyObject *verify_obj = NULL, *verify_code_obj = NULL;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200450 PyObject *init_value, *msg, *key;
451 _Py_IDENTIFIER(reason);
452 _Py_IDENTIFIER(library);
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700453 _Py_IDENTIFIER(verify_message);
454 _Py_IDENTIFIER(verify_code);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200455
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;
Christian Heimes7f1305e2021-04-17 20:06:38 +0200464 reason_obj = PyDict_GetItemWithError(state->err_codes_to_names, key);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200465 Py_DECREF(key);
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +0300466 if (reason_obj == NULL && PyErr_Occurred()) {
467 goto fail;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200468 }
469 key = PyLong_FromLong(lib);
470 if (key == NULL)
471 goto fail;
Christian Heimes7f1305e2021-04-17 20:06:38 +0200472 lib_obj = PyDict_GetItemWithError(state->lib_codes_to_names, key);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200473 Py_DECREF(key);
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +0300474 if (lib_obj == NULL && PyErr_Occurred()) {
475 goto fail;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200476 }
477 if (errstr == NULL)
478 errstr = ERR_reason_error_string(errcode);
479 }
480 if (errstr == NULL)
481 errstr = "unknown error";
482
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700483 /* verify code for cert validation error */
Christian Heimes7f1305e2021-04-17 20:06:38 +0200484 if ((sslsock != NULL) && (type == state->PySSLCertVerificationErrorObject)) {
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700485 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)
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200527 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);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200534 if (msg == NULL)
535 goto fail;
Victor Stinnerba9be472013-10-31 15:00:24 +0100536
Paul Monsonfb7e7502019-05-15 15:38:55 -0700537 init_value = Py_BuildValue("iN", ERR_GET_REASON(ssl_errno), msg);
Victor Stinnerba9be472013-10-31 15:00:24 +0100538 if (init_value == NULL)
539 goto fail;
540
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200541 err_value = PyObject_CallObject(type, init_value);
542 Py_DECREF(init_value);
543 if (err_value == NULL)
544 goto fail;
Victor Stinnerba9be472013-10-31 15:00:24 +0100545
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200546 if (reason_obj == NULL)
547 reason_obj = Py_None;
548 if (_PyObject_SetAttrId(err_value, &PyId_reason, reason_obj))
549 goto fail;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700550
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200551 if (lib_obj == NULL)
552 lib_obj = Py_None;
553 if (_PyObject_SetAttrId(err_value, &PyId_library, lib_obj))
554 goto fail;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700555
Christian Heimes7f1305e2021-04-17 20:06:38 +0200556 if ((sslsock != NULL) && (type == state->PySSLCertVerificationErrorObject)) {
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700557 /* 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
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200565 PyErr_SetObject(type, err_value);
566fail:
567 Py_XDECREF(err_value);
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700568 Py_XDECREF(verify_code_obj);
569 Py_XDECREF(verify_obj);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200570}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000571
Christian Heimesc7f70692019-05-31 11:44:05 +0200572static int
573PySSL_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
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000584static PyObject *
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700585PySSL_SetError(PySSLSocket *sslsock, int ret, const char *filename, int lineno)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000586{
Christian Heimes7f1305e2021-04-17 20:06:38 +0200587 PyObject *type;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200588 char *errstr = NULL;
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700589 _PySSLError err;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000590 enum py_ssl_error p = PY_SSL_ERROR_NONE;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200591 unsigned long e = 0;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000592
Christian Heimes7f1305e2021-04-17 20:06:38 +0200593 assert(sslsock != NULL);
594
595 _sslmodulestate *state = get_state_sock(sslsock);
596 type = state->PySSLErrorObject;
597
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000598 assert(ret <= 0);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200599 e = ERR_peek_last_error();
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000600
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700601 if (sslsock->ssl != NULL) {
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700602 err = sslsock->err;
Thomas Woutersed03b412007-08-28 21:37:11 +0000603
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700604 switch (err.ssl) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000605 case SSL_ERROR_ZERO_RETURN:
Antoine Pitrou41032a62011-10-27 23:56:55 +0200606 errstr = "TLS/SSL connection has been closed (EOF)";
Christian Heimes7f1305e2021-04-17 20:06:38 +0200607 type = state->PySSLZeroReturnErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000608 p = PY_SSL_ERROR_ZERO_RETURN;
609 break;
610 case SSL_ERROR_WANT_READ:
611 errstr = "The operation did not complete (read)";
Christian Heimes7f1305e2021-04-17 20:06:38 +0200612 type = state->PySSLWantReadErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000613 p = PY_SSL_ERROR_WANT_READ;
614 break;
615 case SSL_ERROR_WANT_WRITE:
616 p = PY_SSL_ERROR_WANT_WRITE;
Christian Heimes7f1305e2021-04-17 20:06:38 +0200617 type = state->PySSLWantWriteErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000618 errstr = "The operation did not complete (write)";
619 break;
620 case SSL_ERROR_WANT_X509_LOOKUP:
621 p = PY_SSL_ERROR_WANT_X509_LOOKUP;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000622 errstr = "The operation did not complete (X509 lookup)";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000623 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 {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000630 if (e == 0) {
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700631 PySocketSockObject *s = GET_SOCKET(sslsock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000632 if (ret == 0 || (((PyObject *)s) == Py_None)) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000633 p = PY_SSL_ERROR_EOF;
Christian Heimes7f1305e2021-04-17 20:06:38 +0200634 type = state->PySSLEOFErrorObject;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000635 errstr = "EOF occurred in violation of protocol";
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200636 } else if (s && ret == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000637 /* underlying BIO reported an I/O error */
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000638 ERR_clear_error();
Steve Dowere6eb48c2017-09-08 15:16:15 -0700639#ifdef MS_WINDOWS
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700640 if (err.ws) {
641 return PyErr_SetFromWindowsErr(err.ws);
642 }
Steve Dowere6eb48c2017-09-08 15:16:15 -0700643#endif
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700644 if (err.c) {
645 errno = err.c;
Steve Dowere6eb48c2017-09-08 15:16:15 -0700646 return PyErr_SetFromErrno(PyExc_OSError);
647 }
Dima Tisnek495bd032020-08-16 02:01:19 +0900648 else {
649 p = PY_SSL_ERROR_EOF;
Christian Heimes7f1305e2021-04-17 20:06:38 +0200650 type = state->PySSLEOFErrorObject;
Dima Tisnek495bd032020-08-16 02:01:19 +0900651 errstr = "EOF occurred in violation of protocol";
652 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000653 } else { /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000654 p = PY_SSL_ERROR_SYSCALL;
Christian Heimes7f1305e2021-04-17 20:06:38 +0200655 type = state->PySSLSyscallErrorObject;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000656 errstr = "Some I/O error occurred";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000657 }
658 } else {
659 p = PY_SSL_ERROR_SYSCALL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000660 }
661 break;
662 }
663 case SSL_ERROR_SSL:
664 {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000665 p = PY_SSL_ERROR_SSL;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700666 if (e == 0) {
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200667 /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000668 errstr = "A failure in the SSL library occurred";
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700669 }
670 if (ERR_GET_LIB(e) == ERR_LIB_SSL &&
671 ERR_GET_REASON(e) == SSL_R_CERTIFICATE_VERIFY_FAILED) {
Christian Heimes7f1305e2021-04-17 20:06:38 +0200672 type = state->PySSLCertVerificationErrorObject;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700673 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000674 break;
675 }
676 default:
677 p = PY_SSL_ERROR_INVALID_ERROR_CODE;
678 errstr = "Invalid error code";
679 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000680 }
Christian Heimes7f1305e2021-04-17 20:06:38 +0200681 fill_and_set_sslerror(state, sslsock, type, p, errstr, lineno, e);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000682 ERR_clear_error();
Christian Heimesc7f70692019-05-31 11:44:05 +0200683 PySSL_ChainExceptions(sslsock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000684 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000685}
686
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000687static PyObject *
Christian Heimes7f1305e2021-04-17 20:06:38 +0200688_setSSLError (_sslmodulestate *state, const char *errstr, int errcode, const char *filename, int lineno)
689{
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200690 if (errstr == NULL)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000691 errcode = ERR_peek_last_error();
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200692 else
693 errcode = 0;
Christian Heimes7f1305e2021-04-17 20:06:38 +0200694 fill_and_set_sslerror(state, NULL, state->PySSLErrorObject, errcode, errstr, lineno, errcode);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000695 ERR_clear_error();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000696 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000697}
698
Christian Heimes2875c602021-04-19 07:27:10 +0200699static int
700_ssl_deprecated(const char* name, int stacklevel) {
701 return PyErr_WarnFormat(
702 PyExc_DeprecationWarning, stacklevel,
703 "ssl module: %s is deprecated", name
704 );
705}
706
707#define PY_SSL_DEPRECATED(name, stacklevel, ret) \
708 if (_ssl_deprecated((name), (stacklevel)) == -1) return (ret)
709
Christian Heimes61d478c2018-01-27 15:51:38 +0100710/*
711 * SSL objects
712 */
713
714static int
715_ssl_configure_hostname(PySSLSocket *self, const char* server_hostname)
716{
717 int retval = -1;
718 ASN1_OCTET_STRING *ip;
719 PyObject *hostname;
720 size_t len;
721
722 assert(server_hostname);
723
724 /* Disable OpenSSL's special mode with leading dot in hostname:
725 * When name starts with a dot (e.g ".example.com"), it will be
726 * matched by a certificate valid for any sub-domain of name.
727 */
728 len = strlen(server_hostname);
729 if (len == 0 || *server_hostname == '.') {
730 PyErr_SetString(
731 PyExc_ValueError,
732 "server_hostname cannot be an empty string or start with a "
733 "leading dot.");
734 return retval;
735 }
736
737 /* inet_pton is not available on all platforms. */
738 ip = a2i_IPADDRESS(server_hostname);
739 if (ip == NULL) {
740 ERR_clear_error();
741 }
742
Christian Heimes11a14932018-02-24 02:35:08 +0100743 hostname = PyUnicode_Decode(server_hostname, len, "ascii", "strict");
Christian Heimes61d478c2018-01-27 15:51:38 +0100744 if (hostname == NULL) {
745 goto error;
746 }
747 self->server_hostname = hostname;
748
749 /* Only send SNI extension for non-IP hostnames */
750 if (ip == NULL) {
751 if (!SSL_set_tlsext_host_name(self->ssl, server_hostname)) {
Christian Heimes7f1305e2021-04-17 20:06:38 +0200752 _setSSLError(get_state_sock(self), NULL, 0, __FILE__, __LINE__);
Zackery Spytzc32f2972020-10-25 12:02:30 -0600753 goto error;
Christian Heimes61d478c2018-01-27 15:51:38 +0100754 }
755 }
756 if (self->ctx->check_hostname) {
757 X509_VERIFY_PARAM *param = SSL_get0_param(self->ssl);
758 if (ip == NULL) {
Christian Heimesd02ac252018-03-25 12:36:13 +0200759 if (!X509_VERIFY_PARAM_set1_host(param, server_hostname,
760 strlen(server_hostname))) {
Christian Heimes7f1305e2021-04-17 20:06:38 +0200761 _setSSLError(get_state_sock(self), NULL, 0, __FILE__, __LINE__);
Christian Heimes61d478c2018-01-27 15:51:38 +0100762 goto error;
763 }
764 } else {
Christian Heimesa871f692020-06-01 08:58:14 +0200765 if (!X509_VERIFY_PARAM_set1_ip(param, ASN1_STRING_get0_data(ip),
Christian Heimes61d478c2018-01-27 15:51:38 +0100766 ASN1_STRING_length(ip))) {
Christian Heimes7f1305e2021-04-17 20:06:38 +0200767 _setSSLError(get_state_sock(self), NULL, 0, __FILE__, __LINE__);
Christian Heimes61d478c2018-01-27 15:51:38 +0100768 goto error;
769 }
770 }
771 }
772 retval = 0;
773 error:
774 if (ip != NULL) {
775 ASN1_OCTET_STRING_free(ip);
776 }
777 return retval;
778}
779
Antoine Pitrou152efa22010-05-16 18:19:27 +0000780static PySSLSocket *
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100781newPySSLSocket(PySSLContext *sslctx, PySocketSockObject *sock,
Antoine Pitroud5323212010-10-22 18:19:07 +0000782 enum py_ssl_server_or_client socket_type,
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200783 char *server_hostname,
Christian Heimes141c5e82018-02-24 21:10:57 +0100784 PyObject *owner, PyObject *session,
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200785 PySSLMemoryBIO *inbio, PySSLMemoryBIO *outbio)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000786{
Antoine Pitrou152efa22010-05-16 18:19:27 +0000787 PySSLSocket *self;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100788 SSL_CTX *ctx = sslctx->ctx;
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700789 _PySSLError err = { 0 };
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000790
Miss Islington (bot)ea47a8a2021-05-27 09:25:22 -0700791 self = PyObject_GC_New(PySSLSocket,
792 get_state_ctx(sslctx)->PySSLSocket_Type);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000793 if (self == NULL)
794 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000795
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000796 self->ssl = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000797 self->Socket = NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100798 self->ctx = sslctx;
Nathaniel J. Smith65ece7c2017-06-07 23:30:43 -0700799 Py_INCREF(sslctx);
Antoine Pitrou860aee72013-09-29 19:52:45 +0200800 self->shutdown_seen_zero = 0;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200801 self->owner = NULL;
Benjamin Peterson81b9ecd2016-08-15 21:55:37 -0700802 self->server_hostname = NULL;
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700803 self->err = err;
Christian Heimesc7f70692019-05-31 11:44:05 +0200804 self->exc_type = NULL;
805 self->exc_value = NULL;
806 self->exc_tb = NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200807
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000808 /* Make sure the SSL error state is initialized */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000809 ERR_clear_error();
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000810
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000811 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitrou152efa22010-05-16 18:19:27 +0000812 self->ssl = SSL_new(ctx);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000813 PySSL_END_ALLOW_THREADS
Zackery Spytz4c49da02018-12-07 03:11:30 -0700814 if (self->ssl == NULL) {
815 Py_DECREF(self);
Christian Heimes7f1305e2021-04-17 20:06:38 +0200816 _setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
Zackery Spytz4c49da02018-12-07 03:11:30 -0700817 return NULL;
818 }
Christian Heimesb467d9a2021-04-17 10:07:19 +0200819 /* bpo43522 and OpenSSL < 1.1.1l: copy hostflags manually */
820#if !defined(LIBRESSL_VERSION_NUMBER) && OPENSSL_VERSION < 0x101010cf
821 X509_VERIFY_PARAM *ssl_params = SSL_get0_param(self->ssl);
822 X509_VERIFY_PARAM_set_hostflags(ssl_params, sslctx->hostflags);
823#endif
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200824 SSL_set_app_data(self->ssl, self);
825 if (sock) {
826 SSL_set_fd(self->ssl, Py_SAFE_DOWNCAST(sock->sock_fd, SOCKET_T, int));
827 } else {
828 /* BIOs are reference counted and SSL_set_bio borrows our reference.
829 * To prevent a double free in memory_bio_dealloc() we need to take an
830 * extra reference here. */
Christian Heimes598894f2016-09-05 23:19:05 +0200831 BIO_up_ref(inbio->bio);
832 BIO_up_ref(outbio->bio);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200833 SSL_set_bio(self->ssl, inbio->bio, outbio->bio);
834 }
Alex Gaynorf0422422018-05-14 11:51:45 -0400835 SSL_set_mode(self->ssl,
836 SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER | SSL_MODE_AUTO_RETRY);
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000837
Christian Heimesf0f59302019-07-01 08:29:17 +0200838#ifdef TLS1_3_VERSION
839 if (sslctx->post_handshake_auth == 1) {
840 if (socket_type == PY_SSL_SERVER) {
841 /* bpo-37428: OpenSSL does not ignore SSL_VERIFY_POST_HANDSHAKE.
842 * Set SSL_VERIFY_POST_HANDSHAKE flag only for server sockets and
843 * only in combination with SSL_VERIFY_PEER flag. */
844 int mode = SSL_get_verify_mode(self->ssl);
845 if (mode & SSL_VERIFY_PEER) {
846 int (*verify_cb)(int, X509_STORE_CTX *) = NULL;
847 verify_cb = SSL_get_verify_callback(self->ssl);
848 mode |= SSL_VERIFY_POST_HANDSHAKE;
849 SSL_set_verify(self->ssl, mode, verify_cb);
850 }
851 } else {
852 /* client socket */
853 SSL_set_post_handshake_auth(self->ssl, 1);
854 }
855 }
856#endif
857
Christian Heimes61d478c2018-01-27 15:51:38 +0100858 if (server_hostname != NULL) {
859 if (_ssl_configure_hostname(self, server_hostname) < 0) {
860 Py_DECREF(self);
861 return NULL;
862 }
863 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000864 /* If the socket is in non-blocking mode or timeout mode, set the BIO
865 * to non-blocking mode (blocking is the default)
866 */
Victor Stinnere2452312015-03-28 03:00:46 +0100867 if (sock && sock->sock_timeout >= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000868 BIO_set_nbio(SSL_get_rbio(self->ssl), 1);
869 BIO_set_nbio(SSL_get_wbio(self->ssl), 1);
870 }
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000871
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000872 PySSL_BEGIN_ALLOW_THREADS
873 if (socket_type == PY_SSL_CLIENT)
874 SSL_set_connect_state(self->ssl);
875 else
876 SSL_set_accept_state(self->ssl);
877 PySSL_END_ALLOW_THREADS
Martin v. Löwis09c35f72002-07-28 09:57:45 +0000878
Antoine Pitroud6494802011-07-21 01:11:30 +0200879 self->socket_type = socket_type;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200880 if (sock != NULL) {
881 self->Socket = PyWeakref_NewRef((PyObject *) sock, NULL);
882 if (self->Socket == NULL) {
883 Py_DECREF(self);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200884 return NULL;
885 }
Victor Stinnera9eb38f2013-10-31 16:35:38 +0100886 }
Christian Heimes141c5e82018-02-24 21:10:57 +0100887 if (owner && owner != Py_None) {
888 if (PySSL_set_owner(self, owner, NULL) == -1) {
889 Py_DECREF(self);
890 return NULL;
891 }
892 }
893 if (session && session != Py_None) {
894 if (PySSL_set_session(self, session, NULL) == -1) {
895 Py_DECREF(self);
896 return NULL;
897 }
898 }
Miss Islington (bot)ea47a8a2021-05-27 09:25:22 -0700899
900 PyObject_GC_Track(self);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000901 return self;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000902}
903
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000904/* SSL object methods */
905
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +0300906/*[clinic input]
907_ssl._SSLSocket.do_handshake
908[clinic start generated code]*/
909
910static PyObject *
911_ssl__SSLSocket_do_handshake_impl(PySSLSocket *self)
912/*[clinic end generated code: output=6c0898a8936548f6 input=d2d737de3df018c8]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000913{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000914 int ret;
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700915 _PySSLError err;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000916 int sockstate, nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200917 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +0200918 _PyTime_t timeout, deadline = 0;
919 int has_timeout;
Antoine Pitroud3f8ab82010-04-24 21:26:44 +0000920
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200921 if (sock) {
922 if (((PyObject*)sock) == Py_None) {
Christian Heimes7f1305e2021-04-17 20:06:38 +0200923 _setSSLError(get_state_sock(self),
924 "Underlying socket connection gone",
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200925 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
926 return NULL;
927 }
928 Py_INCREF(sock);
929
930 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +0100931 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200932 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
933 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000934 }
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000935
Victor Stinner14690702015-04-06 22:46:13 +0200936 timeout = GET_SOCKET_TIMEOUT(sock);
937 has_timeout = (timeout > 0);
938 if (has_timeout)
939 deadline = _PyTime_GetMonotonicClock() + timeout;
940
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000941 /* Actually negotiate SSL connection */
942 /* XXX If SSL_do_handshake() returns 0, it's also a failure. */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000943 do {
Bill Janssen6e027db2007-11-15 22:23:56 +0000944 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000945 ret = SSL_do_handshake(self->ssl);
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700946 err = _PySSL_errno(ret < 1, self->ssl, ret);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000947 PySSL_END_ALLOW_THREADS
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700948 self->err = err;
Victor Stinner4e3cfa42015-04-02 21:28:28 +0200949
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000950 if (PyErr_CheckSignals())
951 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +0200952
Victor Stinner14690702015-04-06 22:46:13 +0200953 if (has_timeout)
954 timeout = deadline - _PyTime_GetMonotonicClock();
955
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700956 if (err.ssl == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +0200957 sockstate = PySSL_select(sock, 0, timeout);
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700958 } else if (err.ssl == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +0200959 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000960 } else {
961 sockstate = SOCKET_OPERATION_OK;
962 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +0200963
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000964 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Christian Heimes03c8ddd2020-11-20 09:26:07 +0100965 PyErr_SetString(PyExc_TimeoutError,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000966 ERRSTR("The handshake operation timed out"));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000967 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000968 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
Christian Heimes7f1305e2021-04-17 20:06:38 +0200969 PyErr_SetString(get_state_sock(self)->PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000970 ERRSTR("Underlying socket has been closed."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000971 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000972 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
Christian Heimes7f1305e2021-04-17 20:06:38 +0200973 PyErr_SetString(get_state_sock(self)->PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000974 ERRSTR("Underlying socket too large for select()."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000975 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000976 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
977 break;
978 }
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700979 } while (err.ssl == SSL_ERROR_WANT_READ ||
980 err.ssl == SSL_ERROR_WANT_WRITE);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200981 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000982 if (ret < 1)
983 return PySSL_SetError(self, ret, __FILE__, __LINE__);
Christian Heimesc7f70692019-05-31 11:44:05 +0200984 if (PySSL_ChainExceptions(self) < 0)
985 return NULL;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200986 Py_RETURN_NONE;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000987error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200988 Py_XDECREF(sock);
Christian Heimesc7f70692019-05-31 11:44:05 +0200989 PySSL_ChainExceptions(self);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000990 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000991}
992
Thomas Woutersed03b412007-08-28 21:37:11 +0000993static PyObject *
Christian Heimes7f1305e2021-04-17 20:06:38 +0200994_asn1obj2py(_sslmodulestate *state, const ASN1_OBJECT *name, int no_name)
Serhiy Storchakae503ca52017-09-05 01:28:53 +0300995{
996 char buf[X509_NAME_MAXLEN];
997 char *namebuf = buf;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000998 int buflen;
Serhiy Storchakae503ca52017-09-05 01:28:53 +0300999 PyObject *name_obj = NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001000
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001001 buflen = OBJ_obj2txt(namebuf, X509_NAME_MAXLEN, name, no_name);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001002 if (buflen < 0) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02001003 _setSSLError(state, NULL, 0, __FILE__, __LINE__);
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001004 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001005 }
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001006 /* initial buffer is too small for oid + terminating null byte */
1007 if (buflen > X509_NAME_MAXLEN - 1) {
1008 /* make OBJ_obj2txt() calculate the required buflen */
1009 buflen = OBJ_obj2txt(NULL, 0, name, no_name);
1010 /* allocate len + 1 for terminating NULL byte */
1011 namebuf = PyMem_Malloc(buflen + 1);
1012 if (namebuf == NULL) {
1013 PyErr_NoMemory();
1014 return NULL;
1015 }
1016 buflen = OBJ_obj2txt(namebuf, buflen + 1, name, no_name);
1017 if (buflen < 0) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02001018 _setSSLError(state, NULL, 0, __FILE__, __LINE__);
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001019 goto done;
1020 }
1021 }
1022 if (!buflen && no_name) {
1023 Py_INCREF(Py_None);
1024 name_obj = Py_None;
1025 }
1026 else {
1027 name_obj = PyUnicode_FromStringAndSize(namebuf, buflen);
1028 }
1029
1030 done:
1031 if (buf != namebuf) {
1032 PyMem_Free(namebuf);
1033 }
1034 return name_obj;
1035}
1036
1037static PyObject *
Christian Heimes7f1305e2021-04-17 20:06:38 +02001038_create_tuple_for_attribute(_sslmodulestate *state,
1039 ASN1_OBJECT *name, ASN1_STRING *value)
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001040{
1041 Py_ssize_t buflen;
1042 unsigned char *valuebuf = NULL;
1043 PyObject *attr;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001044
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001045 buflen = ASN1_STRING_to_UTF8(&valuebuf, value);
1046 if (buflen < 0) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02001047 _setSSLError(state, NULL, 0, __FILE__, __LINE__);
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001048 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001049 }
Christian Heimes7f1305e2021-04-17 20:06:38 +02001050 attr = Py_BuildValue("Ns#", _asn1obj2py(state, name, 0), valuebuf, buflen);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001051 OPENSSL_free(valuebuf);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001052 return attr;
Thomas Woutersed03b412007-08-28 21:37:11 +00001053}
1054
1055static PyObject *
Christian Heimes7f1305e2021-04-17 20:06:38 +02001056_create_tuple_for_X509_NAME (_sslmodulestate *state, X509_NAME *xname)
Thomas Woutersed03b412007-08-28 21:37:11 +00001057{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001058 PyObject *dn = NULL; /* tuple which represents the "distinguished name" */
1059 PyObject *rdn = NULL; /* tuple to hold a "relative distinguished name" */
1060 PyObject *rdnt;
1061 PyObject *attr = NULL; /* tuple to hold an attribute */
1062 int entry_count = X509_NAME_entry_count(xname);
1063 X509_NAME_ENTRY *entry;
1064 ASN1_OBJECT *name;
1065 ASN1_STRING *value;
1066 int index_counter;
1067 int rdn_level = -1;
1068 int retcode;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001069
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001070 dn = PyList_New(0);
1071 if (dn == NULL)
1072 return NULL;
1073 /* now create another tuple to hold the top-level RDN */
1074 rdn = PyList_New(0);
1075 if (rdn == NULL)
1076 goto fail0;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001077
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001078 for (index_counter = 0;
1079 index_counter < entry_count;
1080 index_counter++)
1081 {
1082 entry = X509_NAME_get_entry(xname, index_counter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001083
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001084 /* check to see if we've gotten to a new RDN */
1085 if (rdn_level >= 0) {
Christian Heimes598894f2016-09-05 23:19:05 +02001086 if (rdn_level != X509_NAME_ENTRY_set(entry)) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001087 /* yes, new RDN */
1088 /* add old RDN to DN */
1089 rdnt = PyList_AsTuple(rdn);
1090 Py_DECREF(rdn);
1091 if (rdnt == NULL)
1092 goto fail0;
1093 retcode = PyList_Append(dn, rdnt);
1094 Py_DECREF(rdnt);
1095 if (retcode < 0)
1096 goto fail0;
1097 /* create new RDN */
1098 rdn = PyList_New(0);
1099 if (rdn == NULL)
1100 goto fail0;
1101 }
1102 }
Christian Heimes598894f2016-09-05 23:19:05 +02001103 rdn_level = X509_NAME_ENTRY_set(entry);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001104
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001105 /* now add this attribute to the current RDN */
1106 name = X509_NAME_ENTRY_get_object(entry);
1107 value = X509_NAME_ENTRY_get_data(entry);
Christian Heimes7f1305e2021-04-17 20:06:38 +02001108 attr = _create_tuple_for_attribute(state, name, value);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001109 /*
1110 fprintf(stderr, "RDN level %d, attribute %s: %s\n",
1111 entry->set,
1112 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 0)),
1113 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 1)));
1114 */
1115 if (attr == NULL)
1116 goto fail1;
1117 retcode = PyList_Append(rdn, attr);
1118 Py_DECREF(attr);
1119 if (retcode < 0)
1120 goto fail1;
1121 }
1122 /* now, there's typically a dangling RDN */
Antoine Pitrou2f5a1632012-02-15 22:25:27 +01001123 if (rdn != NULL) {
1124 if (PyList_GET_SIZE(rdn) > 0) {
1125 rdnt = PyList_AsTuple(rdn);
1126 Py_DECREF(rdn);
1127 if (rdnt == NULL)
1128 goto fail0;
1129 retcode = PyList_Append(dn, rdnt);
1130 Py_DECREF(rdnt);
1131 if (retcode < 0)
1132 goto fail0;
1133 }
1134 else {
1135 Py_DECREF(rdn);
1136 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001137 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001138
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001139 /* convert list to tuple */
1140 rdnt = PyList_AsTuple(dn);
1141 Py_DECREF(dn);
1142 if (rdnt == NULL)
1143 return NULL;
1144 return rdnt;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001145
1146 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001147 Py_XDECREF(rdn);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001148
1149 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001150 Py_XDECREF(dn);
1151 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001152}
1153
1154static PyObject *
Christian Heimes7f1305e2021-04-17 20:06:38 +02001155_get_peer_alt_names (_sslmodulestate *state, X509 *certificate) {
Guido van Rossumf06628b2007-11-21 20:01:53 +00001156
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001157 /* this code follows the procedure outlined in
1158 OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print()
1159 function to extract the STACK_OF(GENERAL_NAME),
1160 then iterates through the stack to add the
1161 names. */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001162
Alex Gaynorb87c0df2017-06-06 07:53:11 -04001163 int j;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001164 PyObject *peer_alt_names = Py_None;
Christian Heimes60bf2fc2013-09-05 16:04:35 +02001165 PyObject *v = NULL, *t;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001166 GENERAL_NAMES *names = NULL;
1167 GENERAL_NAME *name;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001168 BIO *biobuf = NULL;
1169 char buf[2048];
1170 char *vptr;
1171 int len;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001172
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001173 if (certificate == NULL)
1174 return peer_alt_names;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001175
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001176 /* get a memory buffer */
1177 biobuf = BIO_new(BIO_s_mem());
Zackery Spytz4c49da02018-12-07 03:11:30 -07001178 if (biobuf == NULL) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02001179 PyErr_SetString(state->PySSLErrorObject, "failed to allocate BIO");
Zackery Spytz4c49da02018-12-07 03:11:30 -07001180 return NULL;
1181 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001182
Alex Gaynorb87c0df2017-06-06 07:53:11 -04001183 names = (GENERAL_NAMES *)X509_get_ext_d2i(
1184 certificate, NID_subject_alt_name, NULL, NULL);
1185 if (names != NULL) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001186 if (peer_alt_names == Py_None) {
1187 peer_alt_names = PyList_New(0);
1188 if (peer_alt_names == NULL)
1189 goto fail;
1190 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001191
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001192 for(j = 0; j < sk_GENERAL_NAME_num(names); j++) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001193 /* get a rendering of each name in the set of names */
Christian Heimes824f7f32013-08-17 00:54:47 +02001194 int gntype;
1195 ASN1_STRING *as = NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001196
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001197 name = sk_GENERAL_NAME_value(names, j);
Christian Heimes474afdd2013-08-17 17:18:56 +02001198 gntype = name->type;
Christian Heimes824f7f32013-08-17 00:54:47 +02001199 switch (gntype) {
1200 case GEN_DIRNAME:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001201 /* we special-case DirName as a tuple of
1202 tuples of attributes */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001203
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001204 t = PyTuple_New(2);
1205 if (t == NULL) {
1206 goto fail;
1207 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001208
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001209 v = PyUnicode_FromString("DirName");
1210 if (v == NULL) {
1211 Py_DECREF(t);
1212 goto fail;
1213 }
1214 PyTuple_SET_ITEM(t, 0, v);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001215
Christian Heimes7f1305e2021-04-17 20:06:38 +02001216 v = _create_tuple_for_X509_NAME(state, name->d.dirn);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001217 if (v == NULL) {
1218 Py_DECREF(t);
1219 goto fail;
1220 }
1221 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +02001222 break;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001223
Christian Heimes824f7f32013-08-17 00:54:47 +02001224 case GEN_EMAIL:
1225 case GEN_DNS:
1226 case GEN_URI:
1227 /* GENERAL_NAME_print() doesn't handle NULL bytes in ASN1_string
1228 correctly, CVE-2013-4238 */
1229 t = PyTuple_New(2);
1230 if (t == NULL)
1231 goto fail;
1232 switch (gntype) {
1233 case GEN_EMAIL:
1234 v = PyUnicode_FromString("email");
1235 as = name->d.rfc822Name;
1236 break;
1237 case GEN_DNS:
1238 v = PyUnicode_FromString("DNS");
1239 as = name->d.dNSName;
1240 break;
1241 case GEN_URI:
1242 v = PyUnicode_FromString("URI");
1243 as = name->d.uniformResourceIdentifier;
1244 break;
1245 }
1246 if (v == NULL) {
1247 Py_DECREF(t);
1248 goto fail;
1249 }
1250 PyTuple_SET_ITEM(t, 0, v);
Christian Heimesa871f692020-06-01 08:58:14 +02001251 v = PyUnicode_FromStringAndSize((char *)ASN1_STRING_get0_data(as),
Christian Heimes824f7f32013-08-17 00:54:47 +02001252 ASN1_STRING_length(as));
1253 if (v == NULL) {
1254 Py_DECREF(t);
1255 goto fail;
1256 }
1257 PyTuple_SET_ITEM(t, 1, v);
1258 break;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001259
Christian Heimes1c03abd2016-09-06 23:25:35 +02001260 case GEN_RID:
1261 t = PyTuple_New(2);
1262 if (t == NULL)
1263 goto fail;
1264
1265 v = PyUnicode_FromString("Registered ID");
1266 if (v == NULL) {
1267 Py_DECREF(t);
1268 goto fail;
1269 }
1270 PyTuple_SET_ITEM(t, 0, v);
1271
1272 len = i2t_ASN1_OBJECT(buf, sizeof(buf)-1, name->d.rid);
1273 if (len < 0) {
1274 Py_DECREF(t);
Christian Heimes7f1305e2021-04-17 20:06:38 +02001275 _setSSLError(state, NULL, 0, __FILE__, __LINE__);
Christian Heimes1c03abd2016-09-06 23:25:35 +02001276 goto fail;
1277 } else if (len >= (int)sizeof(buf)) {
1278 v = PyUnicode_FromString("<INVALID>");
1279 } else {
1280 v = PyUnicode_FromStringAndSize(buf, len);
1281 }
1282 if (v == NULL) {
1283 Py_DECREF(t);
1284 goto fail;
1285 }
1286 PyTuple_SET_ITEM(t, 1, v);
1287 break;
1288
Christian Heimes2b7de662019-12-07 17:59:36 +01001289 case GEN_IPADD:
1290 /* OpenSSL < 3.0.0 adds a trailing \n to IPv6. 3.0.0 removed
1291 * the trailing newline. Remove it in all versions
1292 */
1293 t = PyTuple_New(2);
1294 if (t == NULL)
1295 goto fail;
1296
1297 v = PyUnicode_FromString("IP Address");
1298 if (v == NULL) {
1299 Py_DECREF(t);
1300 goto fail;
1301 }
1302 PyTuple_SET_ITEM(t, 0, v);
1303
1304 if (name->d.ip->length == 4) {
1305 unsigned char *p = name->d.ip->data;
1306 v = PyUnicode_FromFormat(
1307 "%d.%d.%d.%d",
1308 p[0], p[1], p[2], p[3]
1309 );
1310 } else if (name->d.ip->length == 16) {
1311 /* PyUnicode_FromFormat() does not support %X */
1312 unsigned char *p = name->d.ip->data;
1313 len = sprintf(
1314 buf,
1315 "%X:%X:%X:%X:%X:%X:%X:%X",
1316 p[0] << 8 | p[1],
1317 p[2] << 8 | p[3],
1318 p[4] << 8 | p[5],
1319 p[6] << 8 | p[7],
1320 p[8] << 8 | p[9],
1321 p[10] << 8 | p[11],
1322 p[12] << 8 | p[13],
1323 p[14] << 8 | p[15]
1324 );
1325 v = PyUnicode_FromStringAndSize(buf, len);
1326 } else {
1327 v = PyUnicode_FromString("<invalid>");
1328 }
1329
1330 if (v == NULL) {
1331 Py_DECREF(t);
1332 goto fail;
1333 }
1334 PyTuple_SET_ITEM(t, 1, v);
1335 break;
1336
Christian Heimes824f7f32013-08-17 00:54:47 +02001337 default:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001338 /* for everything else, we use the OpenSSL print form */
Christian Heimes824f7f32013-08-17 00:54:47 +02001339 switch (gntype) {
1340 /* check for new general name type */
1341 case GEN_OTHERNAME:
1342 case GEN_X400:
1343 case GEN_EDIPARTY:
Christian Heimes824f7f32013-08-17 00:54:47 +02001344 case GEN_RID:
1345 break;
1346 default:
1347 if (PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
1348 "Unknown general name type %d",
1349 gntype) == -1) {
1350 goto fail;
1351 }
1352 break;
1353 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001354 (void) BIO_reset(biobuf);
1355 GENERAL_NAME_print(biobuf, name);
1356 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1357 if (len < 0) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02001358 _setSSLError(state, NULL, 0, __FILE__, __LINE__);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001359 goto fail;
1360 }
1361 vptr = strchr(buf, ':');
Christian Heimes1c03abd2016-09-06 23:25:35 +02001362 if (vptr == NULL) {
1363 PyErr_Format(PyExc_ValueError,
1364 "Invalid value %.200s",
1365 buf);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001366 goto fail;
Christian Heimes1c03abd2016-09-06 23:25:35 +02001367 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001368 t = PyTuple_New(2);
1369 if (t == NULL)
1370 goto fail;
1371 v = PyUnicode_FromStringAndSize(buf, (vptr - buf));
1372 if (v == NULL) {
1373 Py_DECREF(t);
1374 goto fail;
1375 }
1376 PyTuple_SET_ITEM(t, 0, v);
1377 v = PyUnicode_FromStringAndSize((vptr + 1),
1378 (len - (vptr - buf + 1)));
1379 if (v == NULL) {
1380 Py_DECREF(t);
1381 goto fail;
1382 }
1383 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +02001384 break;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001385 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001386
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001387 /* and add that rendering to the list */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001388
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001389 if (PyList_Append(peer_alt_names, t) < 0) {
1390 Py_DECREF(t);
1391 goto fail;
1392 }
1393 Py_DECREF(t);
1394 }
Antoine Pitrou116d6b92011-11-23 01:39:19 +01001395 sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001396 }
1397 BIO_free(biobuf);
1398 if (peer_alt_names != Py_None) {
1399 v = PyList_AsTuple(peer_alt_names);
1400 Py_DECREF(peer_alt_names);
1401 return v;
1402 } else {
1403 return peer_alt_names;
1404 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001405
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001406
1407 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001408 if (biobuf != NULL)
1409 BIO_free(biobuf);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001410
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001411 if (peer_alt_names != Py_None) {
1412 Py_XDECREF(peer_alt_names);
1413 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001414
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001415 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001416}
1417
1418static PyObject *
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001419_get_aia_uri(X509 *certificate, int nid) {
1420 PyObject *lst = NULL, *ostr = NULL;
1421 int i, result;
1422 AUTHORITY_INFO_ACCESS *info;
1423
1424 info = X509_get_ext_d2i(certificate, NID_info_access, NULL, NULL);
Benjamin Petersonf0c90382015-11-14 15:12:18 -08001425 if (info == NULL)
1426 return Py_None;
1427 if (sk_ACCESS_DESCRIPTION_num(info) == 0) {
1428 AUTHORITY_INFO_ACCESS_free(info);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001429 return Py_None;
1430 }
1431
1432 if ((lst = PyList_New(0)) == NULL) {
1433 goto fail;
1434 }
1435
1436 for (i = 0; i < sk_ACCESS_DESCRIPTION_num(info); i++) {
1437 ACCESS_DESCRIPTION *ad = sk_ACCESS_DESCRIPTION_value(info, i);
1438 ASN1_IA5STRING *uri;
1439
1440 if ((OBJ_obj2nid(ad->method) != nid) ||
1441 (ad->location->type != GEN_URI)) {
1442 continue;
1443 }
1444 uri = ad->location->d.uniformResourceIdentifier;
1445 ostr = PyUnicode_FromStringAndSize((char *)uri->data,
1446 uri->length);
1447 if (ostr == NULL) {
1448 goto fail;
1449 }
1450 result = PyList_Append(lst, ostr);
1451 Py_DECREF(ostr);
1452 if (result < 0) {
1453 goto fail;
1454 }
1455 }
1456 AUTHORITY_INFO_ACCESS_free(info);
1457
1458 /* convert to tuple or None */
1459 if (PyList_Size(lst) == 0) {
1460 Py_DECREF(lst);
1461 return Py_None;
1462 } else {
1463 PyObject *tup;
1464 tup = PyList_AsTuple(lst);
1465 Py_DECREF(lst);
1466 return tup;
1467 }
1468
1469 fail:
1470 AUTHORITY_INFO_ACCESS_free(info);
Christian Heimes18fc7be2013-11-21 23:57:49 +01001471 Py_XDECREF(lst);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001472 return NULL;
1473}
1474
1475static PyObject *
1476_get_crl_dp(X509 *certificate) {
1477 STACK_OF(DIST_POINT) *dps;
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001478 int i, j;
1479 PyObject *lst, *res = NULL;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001480
Christian Heimes598894f2016-09-05 23:19:05 +02001481 dps = X509_get_ext_d2i(certificate, NID_crl_distribution_points, NULL, NULL);
Christian Heimes949ec142013-11-21 16:26:51 +01001482
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001483 if (dps == NULL)
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001484 return Py_None;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001485
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001486 lst = PyList_New(0);
1487 if (lst == NULL)
1488 goto done;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001489
1490 for (i=0; i < sk_DIST_POINT_num(dps); i++) {
1491 DIST_POINT *dp;
1492 STACK_OF(GENERAL_NAME) *gns;
1493
1494 dp = sk_DIST_POINT_value(dps, i);
Christian Heimesa37f5242019-01-15 23:47:42 +01001495 if (dp->distpoint == NULL) {
1496 /* Ignore empty DP value, CVE-2019-5010 */
1497 continue;
1498 }
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001499 gns = dp->distpoint->name.fullname;
1500
1501 for (j=0; j < sk_GENERAL_NAME_num(gns); j++) {
1502 GENERAL_NAME *gn;
1503 ASN1_IA5STRING *uri;
1504 PyObject *ouri;
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001505 int err;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001506
1507 gn = sk_GENERAL_NAME_value(gns, j);
1508 if (gn->type != GEN_URI) {
1509 continue;
1510 }
1511 uri = gn->d.uniformResourceIdentifier;
1512 ouri = PyUnicode_FromStringAndSize((char *)uri->data,
1513 uri->length);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001514 if (ouri == NULL)
1515 goto done;
1516
1517 err = PyList_Append(lst, ouri);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001518 Py_DECREF(ouri);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001519 if (err < 0)
1520 goto done;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001521 }
1522 }
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001523
1524 /* Convert to tuple. */
1525 res = (PyList_GET_SIZE(lst) > 0) ? PyList_AsTuple(lst) : Py_None;
1526
1527 done:
1528 Py_XDECREF(lst);
Olivier Vielpeau2849cc32017-04-14 21:06:07 -04001529 CRL_DIST_POINTS_free(dps);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001530 return res;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001531}
1532
1533static PyObject *
Christian Heimes7f1305e2021-04-17 20:06:38 +02001534_decode_certificate(_sslmodulestate *state, X509 *certificate) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001535
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001536 PyObject *retval = NULL;
1537 BIO *biobuf = NULL;
1538 PyObject *peer;
1539 PyObject *peer_alt_names = NULL;
1540 PyObject *issuer;
1541 PyObject *version;
1542 PyObject *sn_obj;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001543 PyObject *obj;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001544 ASN1_INTEGER *serialNumber;
1545 char buf[2048];
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001546 int len, result;
Christian Heimesa871f692020-06-01 08:58:14 +02001547 const ASN1_TIME *notBefore, *notAfter;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001548 PyObject *pnotBefore, *pnotAfter;
Thomas Woutersed03b412007-08-28 21:37:11 +00001549
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001550 retval = PyDict_New();
1551 if (retval == NULL)
1552 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001553
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001554 peer = _create_tuple_for_X509_NAME(
Christian Heimes7f1305e2021-04-17 20:06:38 +02001555 state,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001556 X509_get_subject_name(certificate));
1557 if (peer == NULL)
1558 goto fail0;
1559 if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) {
1560 Py_DECREF(peer);
1561 goto fail0;
1562 }
1563 Py_DECREF(peer);
Thomas Woutersed03b412007-08-28 21:37:11 +00001564
Antoine Pitroufb046912010-11-09 20:21:19 +00001565 issuer = _create_tuple_for_X509_NAME(
Christian Heimes7f1305e2021-04-17 20:06:38 +02001566 state,
Antoine Pitroufb046912010-11-09 20:21:19 +00001567 X509_get_issuer_name(certificate));
1568 if (issuer == NULL)
1569 goto fail0;
1570 if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001571 Py_DECREF(issuer);
Antoine Pitroufb046912010-11-09 20:21:19 +00001572 goto fail0;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001573 }
Antoine Pitroufb046912010-11-09 20:21:19 +00001574 Py_DECREF(issuer);
1575
1576 version = PyLong_FromLong(X509_get_version(certificate) + 1);
Christian Heimes5962bef2013-07-26 15:51:18 +02001577 if (version == NULL)
1578 goto fail0;
Antoine Pitroufb046912010-11-09 20:21:19 +00001579 if (PyDict_SetItemString(retval, "version", version) < 0) {
1580 Py_DECREF(version);
1581 goto fail0;
1582 }
1583 Py_DECREF(version);
Guido van Rossumf06628b2007-11-21 20:01:53 +00001584
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001585 /* get a memory buffer */
1586 biobuf = BIO_new(BIO_s_mem());
Zackery Spytz4c49da02018-12-07 03:11:30 -07001587 if (biobuf == NULL) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02001588 PyErr_SetString(state->PySSLErrorObject, "failed to allocate BIO");
Zackery Spytz4c49da02018-12-07 03:11:30 -07001589 goto fail0;
1590 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001591
Antoine Pitroufb046912010-11-09 20:21:19 +00001592 (void) BIO_reset(biobuf);
1593 serialNumber = X509_get_serialNumber(certificate);
1594 /* should not exceed 20 octets, 160 bits, so buf is big enough */
1595 i2a_ASN1_INTEGER(biobuf, serialNumber);
1596 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1597 if (len < 0) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02001598 _setSSLError(state, NULL, 0, __FILE__, __LINE__);
Antoine Pitroufb046912010-11-09 20:21:19 +00001599 goto fail1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001600 }
Antoine Pitroufb046912010-11-09 20:21:19 +00001601 sn_obj = PyUnicode_FromStringAndSize(buf, len);
1602 if (sn_obj == NULL)
1603 goto fail1;
1604 if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) {
1605 Py_DECREF(sn_obj);
1606 goto fail1;
1607 }
1608 Py_DECREF(sn_obj);
1609
1610 (void) BIO_reset(biobuf);
Christian Heimesa871f692020-06-01 08:58:14 +02001611 notBefore = X509_get0_notBefore(certificate);
Antoine Pitroufb046912010-11-09 20:21:19 +00001612 ASN1_TIME_print(biobuf, notBefore);
1613 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1614 if (len < 0) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02001615 _setSSLError(state, NULL, 0, __FILE__, __LINE__);
Antoine Pitroufb046912010-11-09 20:21:19 +00001616 goto fail1;
1617 }
1618 pnotBefore = PyUnicode_FromStringAndSize(buf, len);
1619 if (pnotBefore == NULL)
1620 goto fail1;
1621 if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) {
1622 Py_DECREF(pnotBefore);
1623 goto fail1;
1624 }
1625 Py_DECREF(pnotBefore);
Thomas Woutersed03b412007-08-28 21:37:11 +00001626
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001627 (void) BIO_reset(biobuf);
Christian Heimesa871f692020-06-01 08:58:14 +02001628 notAfter = X509_get0_notAfter(certificate);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001629 ASN1_TIME_print(biobuf, notAfter);
1630 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1631 if (len < 0) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02001632 _setSSLError(state, NULL, 0, __FILE__, __LINE__);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001633 goto fail1;
1634 }
1635 pnotAfter = PyUnicode_FromStringAndSize(buf, len);
1636 if (pnotAfter == NULL)
1637 goto fail1;
1638 if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) {
1639 Py_DECREF(pnotAfter);
1640 goto fail1;
1641 }
1642 Py_DECREF(pnotAfter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001643
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001644 /* Now look for subjectAltName */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001645
Christian Heimes7f1305e2021-04-17 20:06:38 +02001646 peer_alt_names = _get_peer_alt_names(state, certificate);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001647 if (peer_alt_names == NULL)
1648 goto fail1;
1649 else if (peer_alt_names != Py_None) {
1650 if (PyDict_SetItemString(retval, "subjectAltName",
1651 peer_alt_names) < 0) {
1652 Py_DECREF(peer_alt_names);
1653 goto fail1;
1654 }
1655 Py_DECREF(peer_alt_names);
1656 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001657
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001658 /* Authority Information Access: OCSP URIs */
1659 obj = _get_aia_uri(certificate, NID_ad_OCSP);
1660 if (obj == NULL) {
1661 goto fail1;
1662 } else if (obj != Py_None) {
1663 result = PyDict_SetItemString(retval, "OCSP", obj);
1664 Py_DECREF(obj);
1665 if (result < 0) {
1666 goto fail1;
1667 }
1668 }
1669
1670 obj = _get_aia_uri(certificate, NID_ad_ca_issuers);
1671 if (obj == NULL) {
1672 goto fail1;
1673 } else if (obj != Py_None) {
1674 result = PyDict_SetItemString(retval, "caIssuers", obj);
1675 Py_DECREF(obj);
1676 if (result < 0) {
1677 goto fail1;
1678 }
1679 }
1680
1681 /* CDP (CRL distribution points) */
1682 obj = _get_crl_dp(certificate);
1683 if (obj == NULL) {
1684 goto fail1;
1685 } else if (obj != Py_None) {
1686 result = PyDict_SetItemString(retval, "crlDistributionPoints", obj);
1687 Py_DECREF(obj);
1688 if (result < 0) {
1689 goto fail1;
1690 }
1691 }
1692
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001693 BIO_free(biobuf);
1694 return retval;
Thomas Woutersed03b412007-08-28 21:37:11 +00001695
1696 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001697 if (biobuf != NULL)
1698 BIO_free(biobuf);
Thomas Woutersed03b412007-08-28 21:37:11 +00001699 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001700 Py_XDECREF(retval);
1701 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001702}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001703
Christian Heimes9a5395a2013-06-17 15:44:12 +02001704static PyObject *
Christian Heimes7f1305e2021-04-17 20:06:38 +02001705_certificate_to_der(_sslmodulestate *state, X509 *certificate)
Christian Heimes9a5395a2013-06-17 15:44:12 +02001706{
1707 unsigned char *bytes_buf = NULL;
1708 int len;
1709 PyObject *retval;
1710
1711 bytes_buf = NULL;
1712 len = i2d_X509(certificate, &bytes_buf);
1713 if (len < 0) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02001714 _setSSLError(state, NULL, 0, __FILE__, __LINE__);
Christian Heimes9a5395a2013-06-17 15:44:12 +02001715 return NULL;
1716 }
1717 /* this is actually an immutable bytes sequence */
1718 retval = PyBytes_FromStringAndSize((const char *) bytes_buf, len);
1719 OPENSSL_free(bytes_buf);
1720 return retval;
1721}
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001722
Christian Heimes666991f2021-04-26 15:01:40 +02001723#include "_ssl/misc.c"
1724#include "_ssl/cert.c"
1725
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001726/*[clinic input]
1727_ssl._test_decode_cert
1728 path: object(converter="PyUnicode_FSConverter")
1729 /
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001730
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001731[clinic start generated code]*/
1732
1733static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001734_ssl__test_decode_cert_impl(PyObject *module, PyObject *path)
1735/*[clinic end generated code: output=96becb9abb23c091 input=cdeaaf02d4346628]*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001736{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001737 PyObject *retval = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001738 X509 *x=NULL;
1739 BIO *cert;
Christian Heimes7f1305e2021-04-17 20:06:38 +02001740 _sslmodulestate *state = get_ssl_state(module);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001741
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001742 if ((cert=BIO_new(BIO_s_file())) == NULL) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02001743 PyErr_SetString(state->PySSLErrorObject,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001744 "Can't malloc memory to read file");
1745 goto fail0;
1746 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001747
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001748 if (BIO_read_filename(cert, PyBytes_AsString(path)) <= 0) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02001749 PyErr_SetString(state->PySSLErrorObject,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001750 "Can't open file");
1751 goto fail0;
1752 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001753
Alex Gaynor40dad952019-08-15 08:31:28 -04001754 x = PEM_read_bio_X509(cert, NULL, NULL, NULL);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001755 if (x == NULL) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02001756 PyErr_SetString(state->PySSLErrorObject,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001757 "Error decoding PEM-encoded file");
1758 goto fail0;
1759 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001760
Christian Heimes7f1305e2021-04-17 20:06:38 +02001761 retval = _decode_certificate(state, x);
Mark Dickinsonee55df52010-08-03 18:31:54 +00001762 X509_free(x);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001763
1764 fail0:
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001765 Py_DECREF(path);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001766 if (cert != NULL) BIO_free(cert);
1767 return retval;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001768}
1769
1770
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001771/*[clinic input]
Christian Heimes141c5e82018-02-24 21:10:57 +01001772_ssl._SSLSocket.getpeercert
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001773 der as binary_mode: bool = False
1774 /
1775
1776Returns the certificate for the peer.
1777
1778If no certificate was provided, returns None. If a certificate was
1779provided, but not validated, returns an empty dictionary. Otherwise
1780returns a dict containing information about the peer certificate.
1781
1782If the optional argument is True, returns a DER-encoded copy of the
1783peer certificate, or None if no certificate was provided. This will
1784return the certificate even if it wasn't validated.
1785[clinic start generated code]*/
1786
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001787static PyObject *
Christian Heimes141c5e82018-02-24 21:10:57 +01001788_ssl__SSLSocket_getpeercert_impl(PySSLSocket *self, int binary_mode)
1789/*[clinic end generated code: output=1f0ab66dfb693c88 input=c0fbe802e57629b7]*/
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001790{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001791 int verification;
Christian Heimes66dc33b2017-05-23 16:02:02 -07001792 X509 *peer_cert;
1793 PyObject *result;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001794
Christian Heimes66dc33b2017-05-23 16:02:02 -07001795 if (!SSL_is_init_finished(self->ssl)) {
Antoine Pitrou20b85552013-09-29 19:50:53 +02001796 PyErr_SetString(PyExc_ValueError,
1797 "handshake not done yet");
1798 return NULL;
1799 }
Christian Heimes66dc33b2017-05-23 16:02:02 -07001800 peer_cert = SSL_get_peer_certificate(self->ssl);
1801 if (peer_cert == NULL)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001802 Py_RETURN_NONE;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001803
Antoine Pitrou721738f2012-08-15 23:20:39 +02001804 if (binary_mode) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001805 /* return cert in DER-encoded format */
Christian Heimes7f1305e2021-04-17 20:06:38 +02001806 result = _certificate_to_der(get_state_sock(self), peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001807 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00001808 verification = SSL_CTX_get_verify_mode(SSL_get_SSL_CTX(self->ssl));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001809 if ((verification & SSL_VERIFY_PEER) == 0)
Christian Heimes66dc33b2017-05-23 16:02:02 -07001810 result = PyDict_New();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001811 else
Christian Heimes7f1305e2021-04-17 20:06:38 +02001812 result = _decode_certificate(get_state_sock(self), peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001813 }
Christian Heimes66dc33b2017-05-23 16:02:02 -07001814 X509_free(peer_cert);
1815 return result;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001816}
1817
Christian Heimes666991f2021-04-26 15:01:40 +02001818/*[clinic input]
1819_ssl._SSLSocket.get_verified_chain
1820
1821[clinic start generated code]*/
1822
1823static PyObject *
1824_ssl__SSLSocket_get_verified_chain_impl(PySSLSocket *self)
1825/*[clinic end generated code: output=802421163cdc3110 input=5fb0714f77e2bd51]*/
1826{
1827 /* borrowed reference */
1828 STACK_OF(X509) *chain = SSL_get0_verified_chain(self->ssl);
1829 if (chain == NULL) {
1830 Py_RETURN_NONE;
1831 }
1832 return _PySSL_CertificateFromX509Stack(self->ctx->state, chain, 1);
1833}
1834
1835/*[clinic input]
1836_ssl._SSLSocket.get_unverified_chain
1837
1838[clinic start generated code]*/
1839
1840static PyObject *
1841_ssl__SSLSocket_get_unverified_chain_impl(PySSLSocket *self)
1842/*[clinic end generated code: output=5acdae414e13f913 input=78c33c360c635cb5]*/
1843{
1844 PyObject *retval;
1845 /* borrowed reference */
1846 /* TODO: include SSL_get_peer_certificate() for server-side sockets */
1847 STACK_OF(X509) *chain = SSL_get_peer_cert_chain(self->ssl);
1848 if (chain == NULL) {
1849 Py_RETURN_NONE;
1850 }
1851 retval = _PySSL_CertificateFromX509Stack(self->ctx->state, chain, 1);
1852 if (retval == NULL) {
1853 return NULL;
1854 }
1855 /* OpenSSL does not include peer cert for server side connections */
1856 if (self->socket_type == PY_SSL_SERVER) {
1857 PyObject *peerobj = NULL;
1858 X509 *peer = SSL_get_peer_certificate(self->ssl);
1859
1860 if (peer == NULL) {
1861 peerobj = Py_None;
1862 Py_INCREF(peerobj);
1863 } else {
1864 /* consume X509 reference on success */
1865 peerobj = _PySSL_CertificateFromX509(self->ctx->state, peer, 0);
1866 if (peerobj == NULL) {
1867 X509_free(peer);
1868 Py_DECREF(retval);
1869 return NULL;
1870 }
1871 }
1872 int res = PyList_Insert(retval, 0, peerobj);
1873 Py_DECREF(peerobj);
1874 if (res < 0) {
1875 Py_DECREF(retval);
1876 return NULL;
1877 }
1878 }
1879 return retval;
1880}
1881
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001882static PyObject *
1883cipher_to_tuple(const SSL_CIPHER *cipher)
1884{
1885 const char *cipher_name, *cipher_protocol;
1886 PyObject *v, *retval = PyTuple_New(3);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001887 if (retval == NULL)
1888 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001889
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001890 cipher_name = SSL_CIPHER_get_name(cipher);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001891 if (cipher_name == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001892 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001893 PyTuple_SET_ITEM(retval, 0, Py_None);
1894 } else {
1895 v = PyUnicode_FromString(cipher_name);
1896 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001897 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001898 PyTuple_SET_ITEM(retval, 0, v);
1899 }
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001900
1901 cipher_protocol = SSL_CIPHER_get_version(cipher);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001902 if (cipher_protocol == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001903 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001904 PyTuple_SET_ITEM(retval, 1, Py_None);
1905 } else {
1906 v = PyUnicode_FromString(cipher_protocol);
1907 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001908 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001909 PyTuple_SET_ITEM(retval, 1, v);
1910 }
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001911
1912 v = PyLong_FromLong(SSL_CIPHER_get_bits(cipher, NULL));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001913 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001914 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001915 PyTuple_SET_ITEM(retval, 2, v);
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001916
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001917 return retval;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001918
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001919 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001920 Py_DECREF(retval);
1921 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001922}
1923
Christian Heimes25bfcd52016-09-06 00:04:45 +02001924static PyObject *
1925cipher_to_dict(const SSL_CIPHER *cipher)
1926{
1927 const char *cipher_name, *cipher_protocol;
1928
1929 unsigned long cipher_id;
1930 int alg_bits, strength_bits, len;
1931 char buf[512] = {0};
Christian Heimes25bfcd52016-09-06 00:04:45 +02001932 int aead, nid;
1933 const char *skcipher = NULL, *digest = NULL, *kx = NULL, *auth = NULL;
Christian Heimes25bfcd52016-09-06 00:04:45 +02001934
1935 /* can be NULL */
1936 cipher_name = SSL_CIPHER_get_name(cipher);
1937 cipher_protocol = SSL_CIPHER_get_version(cipher);
1938 cipher_id = SSL_CIPHER_get_id(cipher);
1939 SSL_CIPHER_description(cipher, buf, sizeof(buf) - 1);
Segev Finer5cff6372017-07-27 01:19:17 +03001940 /* Downcast to avoid a warning. Safe since buf is always 512 bytes */
1941 len = (int)strlen(buf);
Christian Heimes25bfcd52016-09-06 00:04:45 +02001942 if (len > 1 && buf[len-1] == '\n')
1943 buf[len-1] = '\0';
1944 strength_bits = SSL_CIPHER_get_bits(cipher, &alg_bits);
1945
Christian Heimes25bfcd52016-09-06 00:04:45 +02001946 aead = SSL_CIPHER_is_aead(cipher);
1947 nid = SSL_CIPHER_get_cipher_nid(cipher);
1948 skcipher = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1949 nid = SSL_CIPHER_get_digest_nid(cipher);
1950 digest = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1951 nid = SSL_CIPHER_get_kx_nid(cipher);
1952 kx = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1953 nid = SSL_CIPHER_get_auth_nid(cipher);
1954 auth = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
Christian Heimes25bfcd52016-09-06 00:04:45 +02001955
Victor Stinner410b9882016-09-12 12:00:23 +02001956 return Py_BuildValue(
Christian Heimes25bfcd52016-09-06 00:04:45 +02001957 "{sksssssssisi"
Christian Heimes25bfcd52016-09-06 00:04:45 +02001958 "sOssssssss"
Christian Heimes25bfcd52016-09-06 00:04:45 +02001959 "}",
1960 "id", cipher_id,
1961 "name", cipher_name,
1962 "protocol", cipher_protocol,
1963 "description", buf,
1964 "strength_bits", strength_bits,
1965 "alg_bits", alg_bits
Christian Heimes25bfcd52016-09-06 00:04:45 +02001966 ,"aead", aead ? Py_True : Py_False,
1967 "symmetric", skcipher,
1968 "digest", digest,
1969 "kea", kx,
1970 "auth", auth
Christian Heimes25bfcd52016-09-06 00:04:45 +02001971 );
Christian Heimes25bfcd52016-09-06 00:04:45 +02001972}
Christian Heimes25bfcd52016-09-06 00:04:45 +02001973
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001974/*[clinic input]
1975_ssl._SSLSocket.shared_ciphers
1976[clinic start generated code]*/
1977
1978static PyObject *
1979_ssl__SSLSocket_shared_ciphers_impl(PySSLSocket *self)
1980/*[clinic end generated code: output=3d174ead2e42c4fd input=0bfe149da8fe6306]*/
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001981{
1982 STACK_OF(SSL_CIPHER) *ciphers;
1983 int i;
1984 PyObject *res;
1985
Christian Heimes598894f2016-09-05 23:19:05 +02001986 ciphers = SSL_get_ciphers(self->ssl);
1987 if (!ciphers)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001988 Py_RETURN_NONE;
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001989 res = PyList_New(sk_SSL_CIPHER_num(ciphers));
1990 if (!res)
1991 return NULL;
1992 for (i = 0; i < sk_SSL_CIPHER_num(ciphers); i++) {
1993 PyObject *tup = cipher_to_tuple(sk_SSL_CIPHER_value(ciphers, i));
1994 if (!tup) {
1995 Py_DECREF(res);
1996 return NULL;
1997 }
1998 PyList_SET_ITEM(res, i, tup);
1999 }
2000 return res;
2001}
2002
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002003/*[clinic input]
2004_ssl._SSLSocket.cipher
2005[clinic start generated code]*/
2006
2007static PyObject *
2008_ssl__SSLSocket_cipher_impl(PySSLSocket *self)
2009/*[clinic end generated code: output=376417c16d0e5815 input=548fb0e27243796d]*/
Benjamin Peterson4cb17812015-01-07 11:14:26 -06002010{
2011 const SSL_CIPHER *current;
2012
2013 if (self->ssl == NULL)
2014 Py_RETURN_NONE;
2015 current = SSL_get_current_cipher(self->ssl);
2016 if (current == NULL)
2017 Py_RETURN_NONE;
2018 return cipher_to_tuple(current);
2019}
2020
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002021/*[clinic input]
2022_ssl._SSLSocket.version
2023[clinic start generated code]*/
2024
2025static PyObject *
2026_ssl__SSLSocket_version_impl(PySSLSocket *self)
2027/*[clinic end generated code: output=178aed33193b2cdb input=900186a503436fd6]*/
Antoine Pitrou47e40422014-09-04 21:00:10 +02002028{
2029 const char *version;
2030
2031 if (self->ssl == NULL)
2032 Py_RETURN_NONE;
Christian Heimes68771112017-09-05 21:55:40 -07002033 if (!SSL_is_init_finished(self->ssl)) {
2034 /* handshake not finished */
2035 Py_RETURN_NONE;
2036 }
Antoine Pitrou47e40422014-09-04 21:00:10 +02002037 version = SSL_get_version(self->ssl);
2038 if (!strcmp(version, "unknown"))
2039 Py_RETURN_NONE;
2040 return PyUnicode_FromString(version);
2041}
2042
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002043/*[clinic input]
2044_ssl._SSLSocket.selected_alpn_protocol
2045[clinic start generated code]*/
2046
2047static PyObject *
2048_ssl__SSLSocket_selected_alpn_protocol_impl(PySSLSocket *self)
2049/*[clinic end generated code: output=ec33688b303d250f input=442de30e35bc2913]*/
2050{
Benjamin Petersoncca27322015-01-23 16:35:37 -05002051 const unsigned char *out;
2052 unsigned int outlen;
2053
2054 SSL_get0_alpn_selected(self->ssl, &out, &outlen);
2055
2056 if (out == NULL)
2057 Py_RETURN_NONE;
2058 return PyUnicode_FromStringAndSize((char *)out, outlen);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002059}
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002060
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002061/*[clinic input]
2062_ssl._SSLSocket.compression
2063[clinic start generated code]*/
2064
2065static PyObject *
2066_ssl__SSLSocket_compression_impl(PySSLSocket *self)
2067/*[clinic end generated code: output=bd16cb1bb4646ae7 input=5d059d0a2bbc32c8]*/
2068{
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01002069#ifdef OPENSSL_NO_COMP
2070 Py_RETURN_NONE;
2071#else
2072 const COMP_METHOD *comp_method;
2073 const char *short_name;
2074
2075 if (self->ssl == NULL)
2076 Py_RETURN_NONE;
2077 comp_method = SSL_get_current_compression(self->ssl);
Christian Heimes598894f2016-09-05 23:19:05 +02002078 if (comp_method == NULL || COMP_get_type(comp_method) == NID_undef)
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01002079 Py_RETURN_NONE;
Christian Heimes281e5f82016-09-06 01:10:39 +02002080 short_name = OBJ_nid2sn(COMP_get_type(comp_method));
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01002081 if (short_name == NULL)
2082 Py_RETURN_NONE;
2083 return PyUnicode_DecodeFSDefault(short_name);
2084#endif
2085}
2086
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002087static PySSLContext *PySSL_get_context(PySSLSocket *self, void *closure) {
2088 Py_INCREF(self->ctx);
2089 return self->ctx;
2090}
2091
2092static int PySSL_set_context(PySSLSocket *self, PyObject *value,
2093 void *closure) {
2094
Christian Heimes7f1305e2021-04-17 20:06:38 +02002095 if (PyObject_TypeCheck(value, self->ctx->state->PySSLContext_Type)) {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002096 Py_INCREF(value);
Serhiy Storchaka57a01d32016-04-10 18:05:40 +03002097 Py_SETREF(self->ctx, (PySSLContext *)value);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002098 SSL_set_SSL_CTX(self->ssl, self->ctx->ctx);
Christian Heimes77cde502021-03-21 16:13:09 +01002099 /* Set SSL* internal msg_callback to state of new context's state */
2100 SSL_set_msg_callback(
2101 self->ssl,
2102 self->ctx->msg_cb ? _PySSL_msg_callback : NULL
2103 );
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002104 } else {
Ned Deily4531ec72018-06-11 20:26:28 -04002105 PyErr_SetString(PyExc_TypeError, "The value must be a SSLContext");
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002106 return -1;
2107 }
2108
2109 return 0;
2110}
2111
2112PyDoc_STRVAR(PySSL_set_context_doc,
2113"_setter_context(ctx)\n\
2114\
2115This changes the context associated with the SSLSocket. This is typically\n\
Christian Heimes11a14932018-02-24 02:35:08 +01002116used from within a callback function set by the sni_callback\n\
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002117on the SSLContext to change the certificate information associated with the\n\
2118SSLSocket before the cryptographic exchange handshake messages\n");
2119
2120
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002121static PyObject *
2122PySSL_get_server_side(PySSLSocket *self, void *c)
2123{
2124 return PyBool_FromLong(self->socket_type == PY_SSL_SERVER);
2125}
2126
2127PyDoc_STRVAR(PySSL_get_server_side_doc,
2128"Whether this is a server-side socket.");
2129
2130static PyObject *
2131PySSL_get_server_hostname(PySSLSocket *self, void *c)
2132{
2133 if (self->server_hostname == NULL)
2134 Py_RETURN_NONE;
2135 Py_INCREF(self->server_hostname);
2136 return self->server_hostname;
2137}
2138
2139PyDoc_STRVAR(PySSL_get_server_hostname_doc,
2140"The currently set server hostname (for SNI).");
2141
2142static PyObject *
2143PySSL_get_owner(PySSLSocket *self, void *c)
2144{
2145 PyObject *owner;
2146
2147 if (self->owner == NULL)
2148 Py_RETURN_NONE;
2149
2150 owner = PyWeakref_GetObject(self->owner);
2151 Py_INCREF(owner);
2152 return owner;
2153}
2154
2155static int
2156PySSL_set_owner(PySSLSocket *self, PyObject *value, void *c)
2157{
Serhiy Storchaka48842712016-04-06 09:45:48 +03002158 Py_XSETREF(self->owner, PyWeakref_NewRef(value, NULL));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002159 if (self->owner == NULL)
2160 return -1;
2161 return 0;
2162}
2163
2164PyDoc_STRVAR(PySSL_get_owner_doc,
2165"The Python-level owner of this object.\
2166Passed as \"self\" in servername callback.");
2167
Christian Heimesc7f70692019-05-31 11:44:05 +02002168static int
2169PySSL_traverse(PySSLSocket *self, visitproc visit, void *arg)
2170{
2171 Py_VISIT(self->exc_type);
2172 Py_VISIT(self->exc_value);
2173 Py_VISIT(self->exc_tb);
Miss Islington (bot)ea47a8a2021-05-27 09:25:22 -07002174 Py_VISIT(Py_TYPE(self));
Christian Heimesc7f70692019-05-31 11:44:05 +02002175 return 0;
2176}
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002177
Christian Heimesc7f70692019-05-31 11:44:05 +02002178static int
2179PySSL_clear(PySSLSocket *self)
2180{
2181 Py_CLEAR(self->exc_type);
2182 Py_CLEAR(self->exc_value);
2183 Py_CLEAR(self->exc_tb);
2184 return 0;
2185}
2186
2187static void
2188PySSL_dealloc(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002189{
Christian Heimes5c36da72020-11-20 09:40:12 +01002190 PyTypeObject *tp = Py_TYPE(self);
Miss Islington (bot)ea47a8a2021-05-27 09:25:22 -07002191 PyObject_GC_UnTrack(self);
2192 if (self->ssl) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002193 SSL_free(self->ssl);
Miss Islington (bot)ea47a8a2021-05-27 09:25:22 -07002194 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002195 Py_XDECREF(self->Socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002196 Py_XDECREF(self->ctx);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002197 Py_XDECREF(self->server_hostname);
2198 Py_XDECREF(self->owner);
Miss Islington (bot)ea47a8a2021-05-27 09:25:22 -07002199 PyObject_GC_Del(self);
Christian Heimes5c36da72020-11-20 09:40:12 +01002200 Py_DECREF(tp);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002201}
2202
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002203/* If the socket has a timeout, do a select()/poll() on the socket.
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002204 The argument writing indicates the direction.
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00002205 Returns one of the possibilities in the timeout_state enum (above).
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002206 */
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00002207
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002208static int
Victor Stinner14690702015-04-06 22:46:13 +02002209PySSL_select(PySocketSockObject *s, int writing, _PyTime_t timeout)
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002210{
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002211 int rc;
2212#ifdef HAVE_POLL
2213 struct pollfd pollfd;
2214 _PyTime_t ms;
2215#else
2216 int nfds;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002217 fd_set fds;
2218 struct timeval tv;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002219#endif
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002220
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002221 /* Nothing to do unless we're in timeout mode (not non-blocking) */
Victor Stinner14690702015-04-06 22:46:13 +02002222 if ((s == NULL) || (timeout == 0))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002223 return SOCKET_IS_NONBLOCKING;
Victor Stinner14690702015-04-06 22:46:13 +02002224 else if (timeout < 0) {
2225 if (s->sock_timeout > 0)
2226 return SOCKET_HAS_TIMED_OUT;
2227 else
2228 return SOCKET_IS_BLOCKING;
2229 }
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002230
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002231 /* Guard against closed socket */
Victor Stinner524714e2016-07-22 17:43:59 +02002232 if (s->sock_fd == INVALID_SOCKET)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002233 return SOCKET_HAS_BEEN_CLOSED;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002234
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002235 /* Prefer poll, if available, since you can poll() any fd
2236 * which can't be done with select(). */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002237#ifdef HAVE_POLL
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002238 pollfd.fd = s->sock_fd;
2239 pollfd.events = writing ? POLLOUT : POLLIN;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002240
Victor Stinner14690702015-04-06 22:46:13 +02002241 /* timeout is in seconds, poll() uses milliseconds */
2242 ms = (int)_PyTime_AsMilliseconds(timeout, _PyTime_ROUND_CEILING);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002243 assert(ms <= INT_MAX);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002244
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002245 PySSL_BEGIN_ALLOW_THREADS
2246 rc = poll(&pollfd, 1, (int)ms);
2247 PySSL_END_ALLOW_THREADS
2248#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002249 /* Guard against socket too large for select*/
Charles-François Nataliaa26b272011-08-28 17:51:43 +02002250 if (!_PyIsSelectable_fd(s->sock_fd))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002251 return SOCKET_TOO_LARGE_FOR_SELECT;
Neal Norwitz082b2df2006-02-07 07:04:46 +00002252
Victor Stinner14690702015-04-06 22:46:13 +02002253 _PyTime_AsTimeval_noraise(timeout, &tv, _PyTime_ROUND_CEILING);
Victor Stinnere2452312015-03-28 03:00:46 +01002254
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002255 FD_ZERO(&fds);
2256 FD_SET(s->sock_fd, &fds);
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002257
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002258 /* Wait until the socket becomes ready */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002259 PySSL_BEGIN_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002260 nfds = Py_SAFE_DOWNCAST(s->sock_fd+1, SOCKET_T, int);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002261 if (writing)
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002262 rc = select(nfds, NULL, &fds, NULL, &tv);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002263 else
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002264 rc = select(nfds, &fds, NULL, NULL, &tv);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002265 PySSL_END_ALLOW_THREADS
Bill Janssen6e027db2007-11-15 22:23:56 +00002266#endif
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002267
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002268 /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
2269 (when we are able to write or when there's something to read) */
2270 return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002271}
2272
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002273/*[clinic input]
2274_ssl._SSLSocket.write
2275 b: Py_buffer
2276 /
2277
2278Writes the bytes-like object b into the SSL object.
2279
2280Returns the number of bytes written.
2281[clinic start generated code]*/
2282
2283static PyObject *
2284_ssl__SSLSocket_write_impl(PySSLSocket *self, Py_buffer *b)
2285/*[clinic end generated code: output=aa7a6be5527358d8 input=77262d994fe5100a]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002286{
Christian Heimes89d15502021-04-19 06:55:30 +02002287 size_t count = 0;
2288 int retval;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002289 int sockstate;
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002290 _PySSLError err;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002291 int nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002292 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002293 _PyTime_t timeout, deadline = 0;
2294 int has_timeout;
Bill Janssen54cc54c2007-12-14 22:08:56 +00002295
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002296 if (sock != NULL) {
2297 if (((PyObject*)sock) == Py_None) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02002298 _setSSLError(get_state_sock(self),
2299 "Underlying socket connection gone",
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002300 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2301 return NULL;
2302 }
2303 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002304 }
2305
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002306 if (sock != NULL) {
2307 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002308 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002309 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2310 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
2311 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002312
Victor Stinner14690702015-04-06 22:46:13 +02002313 timeout = GET_SOCKET_TIMEOUT(sock);
2314 has_timeout = (timeout > 0);
2315 if (has_timeout)
2316 deadline = _PyTime_GetMonotonicClock() + timeout;
2317
2318 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002319 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Christian Heimes03c8ddd2020-11-20 09:26:07 +01002320 PyErr_SetString(PyExc_TimeoutError,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002321 "The write operation timed out");
2322 goto error;
2323 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02002324 PyErr_SetString(get_state_sock(self)->PySSLErrorObject,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002325 "Underlying socket has been closed.");
2326 goto error;
2327 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02002328 PyErr_SetString(get_state_sock(self)->PySSLErrorObject,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002329 "Underlying socket too large for select().");
2330 goto error;
2331 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002332
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002333 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002334 PySSL_BEGIN_ALLOW_THREADS
Christian Heimes89d15502021-04-19 06:55:30 +02002335 retval = SSL_write_ex(self->ssl, b->buf, (int)b->len, &count);
2336 err = _PySSL_errno(retval == 0, self->ssl, retval);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002337 PySSL_END_ALLOW_THREADS
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002338 self->err = err;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002339
2340 if (PyErr_CheckSignals())
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002341 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002342
Victor Stinner14690702015-04-06 22:46:13 +02002343 if (has_timeout)
2344 timeout = deadline - _PyTime_GetMonotonicClock();
2345
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002346 if (err.ssl == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +02002347 sockstate = PySSL_select(sock, 0, timeout);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002348 } else if (err.ssl == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +02002349 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002350 } else {
2351 sockstate = SOCKET_OPERATION_OK;
2352 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002353
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002354 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Christian Heimes03c8ddd2020-11-20 09:26:07 +01002355 PyErr_SetString(PyExc_TimeoutError,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002356 "The write operation timed out");
2357 goto error;
2358 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02002359 PyErr_SetString(get_state_sock(self)->PySSLErrorObject,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002360 "Underlying socket has been closed.");
2361 goto error;
2362 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
2363 break;
2364 }
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002365 } while (err.ssl == SSL_ERROR_WANT_READ ||
2366 err.ssl == SSL_ERROR_WANT_WRITE);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002367
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002368 Py_XDECREF(sock);
Christian Heimes89d15502021-04-19 06:55:30 +02002369 if (retval == 0)
2370 return PySSL_SetError(self, retval, __FILE__, __LINE__);
Christian Heimesc7f70692019-05-31 11:44:05 +02002371 if (PySSL_ChainExceptions(self) < 0)
2372 return NULL;
Christian Heimes89d15502021-04-19 06:55:30 +02002373 return PyLong_FromSize_t(count);
Antoine Pitrou7d7aede2009-11-25 18:55:32 +00002374error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002375 Py_XDECREF(sock);
Christian Heimesc7f70692019-05-31 11:44:05 +02002376 PySSL_ChainExceptions(self);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002377 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002378}
2379
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002380/*[clinic input]
2381_ssl._SSLSocket.pending
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002382
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002383Returns the number of already decrypted bytes available for read, pending on the connection.
2384[clinic start generated code]*/
2385
2386static PyObject *
2387_ssl__SSLSocket_pending_impl(PySSLSocket *self)
2388/*[clinic end generated code: output=983d9fecdc308a83 input=2b77487d6dfd597f]*/
Bill Janssen6e027db2007-11-15 22:23:56 +00002389{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002390 int count = 0;
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002391 _PySSLError err;
Bill Janssen6e027db2007-11-15 22:23:56 +00002392
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002393 PySSL_BEGIN_ALLOW_THREADS
2394 count = SSL_pending(self->ssl);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002395 err = _PySSL_errno(count < 0, self->ssl, count);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002396 PySSL_END_ALLOW_THREADS
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002397 self->err = err;
2398
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002399 if (count < 0)
2400 return PySSL_SetError(self, count, __FILE__, __LINE__);
2401 else
2402 return PyLong_FromLong(count);
Bill Janssen6e027db2007-11-15 22:23:56 +00002403}
2404
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002405/*[clinic input]
2406_ssl._SSLSocket.read
2407 size as len: int
2408 [
Larry Hastingsdbfdc382015-05-04 06:59:46 -07002409 buffer: Py_buffer(accept={rwbuffer})
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002410 ]
2411 /
Bill Janssen6e027db2007-11-15 22:23:56 +00002412
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002413Read up to size bytes from the SSL socket.
2414[clinic start generated code]*/
2415
2416static PyObject *
2417_ssl__SSLSocket_read_impl(PySSLSocket *self, int len, int group_right_1,
2418 Py_buffer *buffer)
Larry Hastingsdbfdc382015-05-04 06:59:46 -07002419/*[clinic end generated code: output=00097776cec2a0af input=ff157eb918d0905b]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002420{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002421 PyObject *dest = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002422 char *mem;
Christian Heimes89d15502021-04-19 06:55:30 +02002423 size_t count = 0;
2424 int retval;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002425 int sockstate;
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002426 _PySSLError err;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002427 int nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002428 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002429 _PyTime_t timeout, deadline = 0;
2430 int has_timeout;
Bill Janssen54cc54c2007-12-14 22:08:56 +00002431
Martin Panter5503d472016-03-27 05:35:19 +00002432 if (!group_right_1 && len < 0) {
2433 PyErr_SetString(PyExc_ValueError, "size should not be negative");
2434 return NULL;
2435 }
2436
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002437 if (sock != NULL) {
2438 if (((PyObject*)sock) == Py_None) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02002439 _setSSLError(get_state_sock(self),
2440 "Underlying socket connection gone",
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002441 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2442 return NULL;
2443 }
2444 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002445 }
2446
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002447 if (!group_right_1) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002448 dest = PyBytes_FromStringAndSize(NULL, len);
2449 if (dest == NULL)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002450 goto error;
Martin Panterbed7f1a2016-07-11 00:17:13 +00002451 if (len == 0) {
2452 Py_XDECREF(sock);
2453 return dest;
2454 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002455 mem = PyBytes_AS_STRING(dest);
2456 }
2457 else {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002458 mem = buffer->buf;
2459 if (len <= 0 || len > buffer->len) {
2460 len = (int) buffer->len;
2461 if (buffer->len != len) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002462 PyErr_SetString(PyExc_OverflowError,
2463 "maximum length can't fit in a C 'int'");
2464 goto error;
2465 }
Martin Panterbed7f1a2016-07-11 00:17:13 +00002466 if (len == 0) {
2467 count = 0;
2468 goto done;
2469 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002470 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002471 }
2472
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002473 if (sock != NULL) {
2474 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002475 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002476 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2477 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
2478 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002479
Victor Stinner14690702015-04-06 22:46:13 +02002480 timeout = GET_SOCKET_TIMEOUT(sock);
2481 has_timeout = (timeout > 0);
2482 if (has_timeout)
2483 deadline = _PyTime_GetMonotonicClock() + timeout;
2484
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002485 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002486 PySSL_BEGIN_ALLOW_THREADS
Christian Heimes89d15502021-04-19 06:55:30 +02002487 retval = SSL_read_ex(self->ssl, mem, len, &count);
2488 err = _PySSL_errno(retval == 0, self->ssl, retval);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002489 PySSL_END_ALLOW_THREADS
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002490 self->err = err;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002491
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002492 if (PyErr_CheckSignals())
2493 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002494
Victor Stinner14690702015-04-06 22:46:13 +02002495 if (has_timeout)
2496 timeout = deadline - _PyTime_GetMonotonicClock();
2497
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002498 if (err.ssl == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +02002499 sockstate = PySSL_select(sock, 0, timeout);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002500 } else if (err.ssl == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +02002501 sockstate = PySSL_select(sock, 1, timeout);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002502 } else if (err.ssl == SSL_ERROR_ZERO_RETURN &&
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002503 SSL_get_shutdown(self->ssl) == SSL_RECEIVED_SHUTDOWN)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002504 {
2505 count = 0;
2506 goto done;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002507 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002508 else
2509 sockstate = SOCKET_OPERATION_OK;
2510
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002511 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Christian Heimes03c8ddd2020-11-20 09:26:07 +01002512 PyErr_SetString(PyExc_TimeoutError,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002513 "The read operation timed out");
2514 goto error;
2515 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
2516 break;
2517 }
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002518 } while (err.ssl == SSL_ERROR_WANT_READ ||
2519 err.ssl == SSL_ERROR_WANT_WRITE);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002520
Christian Heimes89d15502021-04-19 06:55:30 +02002521 if (retval == 0) {
2522 PySSL_SetError(self, retval, __FILE__, __LINE__);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002523 goto error;
2524 }
Christian Heimesc7f70692019-05-31 11:44:05 +02002525 if (self->exc_type != NULL)
2526 goto error;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002527
2528done:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002529 Py_XDECREF(sock);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002530 if (!group_right_1) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002531 _PyBytes_Resize(&dest, count);
2532 return dest;
2533 }
2534 else {
Christian Heimes89d15502021-04-19 06:55:30 +02002535 return PyLong_FromSize_t(count);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002536 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002537
2538error:
Christian Heimesc7f70692019-05-31 11:44:05 +02002539 PySSL_ChainExceptions(self);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002540 Py_XDECREF(sock);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002541 if (!group_right_1)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002542 Py_XDECREF(dest);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002543 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002544}
2545
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002546/*[clinic input]
2547_ssl._SSLSocket.shutdown
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002548
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002549Does the SSL shutdown handshake with the remote end.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002550[clinic start generated code]*/
2551
2552static PyObject *
2553_ssl__SSLSocket_shutdown_impl(PySSLSocket *self)
Christian Heimes141c5e82018-02-24 21:10:57 +01002554/*[clinic end generated code: output=ca1aa7ed9d25ca42 input=11d39e69b0a2bf4a]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00002555{
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002556 _PySSLError err;
2557 int sockstate, nonblocking, ret;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002558 int zeros = 0;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002559 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002560 _PyTime_t timeout, deadline = 0;
2561 int has_timeout;
Bill Janssen40a0f662008-08-12 16:56:25 +00002562
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002563 if (sock != NULL) {
2564 /* Guard against closed socket */
Victor Stinner524714e2016-07-22 17:43:59 +02002565 if ((((PyObject*)sock) == Py_None) || (sock->sock_fd == INVALID_SOCKET)) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02002566 _setSSLError(get_state_sock(self),
2567 "Underlying socket connection gone",
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002568 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2569 return NULL;
2570 }
2571 Py_INCREF(sock);
2572
2573 /* Just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002574 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002575 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2576 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002577 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002578
Victor Stinner14690702015-04-06 22:46:13 +02002579 timeout = GET_SOCKET_TIMEOUT(sock);
2580 has_timeout = (timeout > 0);
2581 if (has_timeout)
2582 deadline = _PyTime_GetMonotonicClock() + timeout;
2583
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002584 while (1) {
2585 PySSL_BEGIN_ALLOW_THREADS
2586 /* Disable read-ahead so that unwrap can work correctly.
2587 * Otherwise OpenSSL might read in too much data,
2588 * eating clear text data that happens to be
2589 * transmitted after the SSL shutdown.
Ezio Melotti85a86292013-08-17 16:57:41 +03002590 * Should be safe to call repeatedly every time this
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002591 * function is used and the shutdown_seen_zero != 0
2592 * condition is met.
2593 */
2594 if (self->shutdown_seen_zero)
2595 SSL_set_read_ahead(self->ssl, 0);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002596 ret = SSL_shutdown(self->ssl);
2597 err = _PySSL_errno(ret < 0, self->ssl, ret);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002598 PySSL_END_ALLOW_THREADS
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002599 self->err = err;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002600
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002601 /* If err == 1, a secure shutdown with SSL_shutdown() is complete */
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002602 if (ret > 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002603 break;
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002604 if (ret == 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002605 /* Don't loop endlessly; instead preserve legacy
2606 behaviour of trying SSL_shutdown() only twice.
2607 This looks necessary for OpenSSL < 0.9.8m */
2608 if (++zeros > 1)
2609 break;
2610 /* Shutdown was sent, now try receiving */
2611 self->shutdown_seen_zero = 1;
2612 continue;
Bill Janssen40a0f662008-08-12 16:56:25 +00002613 }
2614
Victor Stinner14690702015-04-06 22:46:13 +02002615 if (has_timeout)
2616 timeout = deadline - _PyTime_GetMonotonicClock();
2617
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002618 /* Possibly retry shutdown until timeout or failure */
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002619 if (err.ssl == SSL_ERROR_WANT_READ)
Victor Stinner14690702015-04-06 22:46:13 +02002620 sockstate = PySSL_select(sock, 0, timeout);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002621 else if (err.ssl == SSL_ERROR_WANT_WRITE)
Victor Stinner14690702015-04-06 22:46:13 +02002622 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002623 else
2624 break;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002625
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002626 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002627 if (err.ssl == SSL_ERROR_WANT_READ)
Christian Heimes03c8ddd2020-11-20 09:26:07 +01002628 PyErr_SetString(PyExc_TimeoutError,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002629 "The read operation timed out");
2630 else
Christian Heimes03c8ddd2020-11-20 09:26:07 +01002631 PyErr_SetString(PyExc_TimeoutError,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002632 "The write operation timed out");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002633 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002634 }
2635 else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02002636 PyErr_SetString(get_state_sock(self)->PySSLErrorObject,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002637 "Underlying socket too large for select().");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002638 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002639 }
2640 else if (sockstate != SOCKET_OPERATION_OK)
2641 /* Retain the SSL error code */
2642 break;
2643 }
Nathaniel J. Smithc0da5822018-09-21 21:44:12 -07002644 if (ret < 0) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002645 Py_XDECREF(sock);
Christian Heimesc7f70692019-05-31 11:44:05 +02002646 PySSL_SetError(self, ret, __FILE__, __LINE__);
2647 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002648 }
Christian Heimesc7f70692019-05-31 11:44:05 +02002649 if (self->exc_type != NULL)
2650 goto error;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002651 if (sock)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002652 /* It's already INCREF'ed */
2653 return (PyObject *) sock;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002654 else
2655 Py_RETURN_NONE;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002656
2657error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002658 Py_XDECREF(sock);
Christian Heimesc7f70692019-05-31 11:44:05 +02002659 PySSL_ChainExceptions(self);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002660 return NULL;
Bill Janssen40a0f662008-08-12 16:56:25 +00002661}
2662
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002663/*[clinic input]
Christian Heimes141c5e82018-02-24 21:10:57 +01002664_ssl._SSLSocket.get_channel_binding
2665 cb_type: str = "tls-unique"
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002666
Christian Heimes141c5e82018-02-24 21:10:57 +01002667Get channel binding data for current connection.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002668
Christian Heimes141c5e82018-02-24 21:10:57 +01002669Raise ValueError if the requested `cb_type` is not supported. Return bytes
2670of the data or None if the data is not available (e.g. before the handshake).
2671Only 'tls-unique' channel binding data from RFC 5929 is supported.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002672[clinic start generated code]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00002673
Antoine Pitroud6494802011-07-21 01:11:30 +02002674static PyObject *
Christian Heimes141c5e82018-02-24 21:10:57 +01002675_ssl__SSLSocket_get_channel_binding_impl(PySSLSocket *self,
2676 const char *cb_type)
2677/*[clinic end generated code: output=34bac9acb6a61d31 input=08b7e43b99c17d41]*/
Antoine Pitroud6494802011-07-21 01:11:30 +02002678{
Antoine Pitroud6494802011-07-21 01:11:30 +02002679 char buf[PySSL_CB_MAXLEN];
Victor Stinner9ee02032013-06-23 15:08:23 +02002680 size_t len;
Antoine Pitroud6494802011-07-21 01:11:30 +02002681
Christian Heimes141c5e82018-02-24 21:10:57 +01002682 if (strcmp(cb_type, "tls-unique") == 0) {
2683 if (SSL_session_reused(self->ssl) ^ !self->socket_type) {
2684 /* if session is resumed XOR we are the client */
2685 len = SSL_get_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2686 }
2687 else {
2688 /* if a new session XOR we are the server */
2689 len = SSL_get_peer_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2690 }
Antoine Pitroud6494802011-07-21 01:11:30 +02002691 }
2692 else {
Christian Heimes141c5e82018-02-24 21:10:57 +01002693 PyErr_Format(
2694 PyExc_ValueError,
2695 "'%s' channel binding type not implemented",
2696 cb_type
2697 );
2698 return NULL;
Antoine Pitroud6494802011-07-21 01:11:30 +02002699 }
2700
2701 /* It cannot be negative in current OpenSSL version as of July 2011 */
Antoine Pitroud6494802011-07-21 01:11:30 +02002702 if (len == 0)
2703 Py_RETURN_NONE;
2704
Christian Heimes141c5e82018-02-24 21:10:57 +01002705 return PyBytes_FromStringAndSize(buf, len);
Antoine Pitroud6494802011-07-21 01:11:30 +02002706}
2707
Christian Heimes9fb051f2018-09-23 08:32:31 +02002708/*[clinic input]
2709_ssl._SSLSocket.verify_client_post_handshake
2710
2711Initiate TLS 1.3 post-handshake authentication
2712[clinic start generated code]*/
2713
2714static PyObject *
2715_ssl__SSLSocket_verify_client_post_handshake_impl(PySSLSocket *self)
2716/*[clinic end generated code: output=532147f3b1341425 input=6bfa874810a3d889]*/
2717{
2718#ifdef TLS1_3_VERSION
2719 int err = SSL_verify_client_post_handshake(self->ssl);
2720 if (err == 0)
Christian Heimes7f1305e2021-04-17 20:06:38 +02002721 return _setSSLError(get_state_sock(self), NULL, 0, __FILE__, __LINE__);
Christian Heimes9fb051f2018-09-23 08:32:31 +02002722 else
2723 Py_RETURN_NONE;
2724#else
2725 PyErr_SetString(PyExc_NotImplementedError,
2726 "Post-handshake auth is not supported by your "
2727 "OpenSSL version.");
2728 return NULL;
2729#endif
2730}
2731
Christian Heimes99a65702016-09-10 23:44:53 +02002732static SSL_SESSION*
2733_ssl_session_dup(SSL_SESSION *session) {
2734 SSL_SESSION *newsession = NULL;
2735 int slen;
2736 unsigned char *senc = NULL, *p;
2737 const unsigned char *const_p;
2738
2739 if (session == NULL) {
2740 PyErr_SetString(PyExc_ValueError, "Invalid session");
2741 goto error;
2742 }
2743
2744 /* get length */
2745 slen = i2d_SSL_SESSION(session, NULL);
2746 if (slen == 0 || slen > 0xFF00) {
2747 PyErr_SetString(PyExc_ValueError, "i2d() failed.");
2748 goto error;
2749 }
2750 if ((senc = PyMem_Malloc(slen)) == NULL) {
2751 PyErr_NoMemory();
2752 goto error;
2753 }
2754 p = senc;
2755 if (!i2d_SSL_SESSION(session, &p)) {
2756 PyErr_SetString(PyExc_ValueError, "i2d() failed.");
2757 goto error;
2758 }
2759 const_p = senc;
2760 newsession = d2i_SSL_SESSION(NULL, &const_p, slen);
2761 if (session == NULL) {
2762 goto error;
2763 }
2764 PyMem_Free(senc);
2765 return newsession;
2766 error:
2767 if (senc != NULL) {
2768 PyMem_Free(senc);
2769 }
2770 return NULL;
2771}
Christian Heimes99a65702016-09-10 23:44:53 +02002772
2773static PyObject *
2774PySSL_get_session(PySSLSocket *self, void *closure) {
2775 /* get_session can return sessions from a server-side connection,
2776 * it does not check for handshake done or client socket. */
2777 PySSLSession *pysess;
2778 SSL_SESSION *session;
2779
Christian Heimes99a65702016-09-10 23:44:53 +02002780 /* duplicate session as workaround for session bug in OpenSSL 1.1.0,
2781 * https://github.com/openssl/openssl/issues/1550 */
2782 session = SSL_get0_session(self->ssl); /* borrowed reference */
2783 if (session == NULL) {
2784 Py_RETURN_NONE;
2785 }
2786 if ((session = _ssl_session_dup(session)) == NULL) {
2787 return NULL;
2788 }
Christian Heimes99a65702016-09-10 23:44:53 +02002789 session = SSL_get1_session(self->ssl);
2790 if (session == NULL) {
2791 Py_RETURN_NONE;
2792 }
Christian Heimes7f1305e2021-04-17 20:06:38 +02002793 pysess = PyObject_GC_New(PySSLSession, self->ctx->state->PySSLSession_Type);
Christian Heimes99a65702016-09-10 23:44:53 +02002794 if (pysess == NULL) {
2795 SSL_SESSION_free(session);
2796 return NULL;
2797 }
2798
2799 assert(self->ctx);
2800 pysess->ctx = self->ctx;
2801 Py_INCREF(pysess->ctx);
2802 pysess->session = session;
Christian Heimesa5d07652016-09-24 10:48:05 +02002803 PyObject_GC_Track(pysess);
Christian Heimes99a65702016-09-10 23:44:53 +02002804 return (PyObject *)pysess;
2805}
2806
2807static int PySSL_set_session(PySSLSocket *self, PyObject *value,
2808 void *closure)
2809 {
2810 PySSLSession *pysess;
Christian Heimes99a65702016-09-10 23:44:53 +02002811 SSL_SESSION *session;
Christian Heimes99a65702016-09-10 23:44:53 +02002812 int result;
2813
Christian Heimes7f1305e2021-04-17 20:06:38 +02002814 if (!Py_IS_TYPE(value, get_state_sock(self)->PySSLSession_Type)) {
Ned Deily4531ec72018-06-11 20:26:28 -04002815 PyErr_SetString(PyExc_TypeError, "Value is not a SSLSession.");
Christian Heimes99a65702016-09-10 23:44:53 +02002816 return -1;
2817 }
2818 pysess = (PySSLSession *)value;
2819
2820 if (self->ctx->ctx != pysess->ctx->ctx) {
2821 PyErr_SetString(PyExc_ValueError,
2822 "Session refers to a different SSLContext.");
2823 return -1;
2824 }
2825 if (self->socket_type != PY_SSL_CLIENT) {
2826 PyErr_SetString(PyExc_ValueError,
2827 "Cannot set session for server-side SSLSocket.");
2828 return -1;
2829 }
Christian Heimes66dc33b2017-05-23 16:02:02 -07002830 if (SSL_is_init_finished(self->ssl)) {
Christian Heimes99a65702016-09-10 23:44:53 +02002831 PyErr_SetString(PyExc_ValueError,
2832 "Cannot set session after handshake.");
2833 return -1;
2834 }
Christian Heimes99a65702016-09-10 23:44:53 +02002835 /* duplicate session */
2836 if ((session = _ssl_session_dup(pysess->session)) == NULL) {
2837 return -1;
2838 }
2839 result = SSL_set_session(self->ssl, session);
2840 /* free duplicate, SSL_set_session() bumps ref count */
2841 SSL_SESSION_free(session);
Christian Heimes99a65702016-09-10 23:44:53 +02002842 if (result == 0) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02002843 _setSSLError(get_state_sock(self), NULL, 0, __FILE__, __LINE__);
Christian Heimes99a65702016-09-10 23:44:53 +02002844 return -1;
2845 }
2846 return 0;
2847}
2848
2849PyDoc_STRVAR(PySSL_set_session_doc,
2850"_setter_session(session)\n\
2851\
2852Get / set SSLSession.");
2853
2854static PyObject *
2855PySSL_get_session_reused(PySSLSocket *self, void *closure) {
2856 if (SSL_session_reused(self->ssl)) {
2857 Py_RETURN_TRUE;
2858 } else {
2859 Py_RETURN_FALSE;
2860 }
2861}
2862
2863PyDoc_STRVAR(PySSL_get_session_reused_doc,
2864"Was the client session reused during handshake?");
2865
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002866static PyGetSetDef ssl_getsetlist[] = {
2867 {"context", (getter) PySSL_get_context,
2868 (setter) PySSL_set_context, PySSL_set_context_doc},
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002869 {"server_side", (getter) PySSL_get_server_side, NULL,
2870 PySSL_get_server_side_doc},
2871 {"server_hostname", (getter) PySSL_get_server_hostname, NULL,
2872 PySSL_get_server_hostname_doc},
2873 {"owner", (getter) PySSL_get_owner, (setter) PySSL_set_owner,
2874 PySSL_get_owner_doc},
Christian Heimes99a65702016-09-10 23:44:53 +02002875 {"session", (getter) PySSL_get_session,
2876 (setter) PySSL_set_session, PySSL_set_session_doc},
2877 {"session_reused", (getter) PySSL_get_session_reused, NULL,
2878 PySSL_get_session_reused_doc},
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002879 {NULL}, /* sentinel */
2880};
2881
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002882static PyMethodDef PySSLMethods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002883 _SSL__SSLSOCKET_DO_HANDSHAKE_METHODDEF
2884 _SSL__SSLSOCKET_WRITE_METHODDEF
2885 _SSL__SSLSOCKET_READ_METHODDEF
2886 _SSL__SSLSOCKET_PENDING_METHODDEF
Christian Heimes141c5e82018-02-24 21:10:57 +01002887 _SSL__SSLSOCKET_GETPEERCERT_METHODDEF
2888 _SSL__SSLSOCKET_GET_CHANNEL_BINDING_METHODDEF
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002889 _SSL__SSLSOCKET_CIPHER_METHODDEF
2890 _SSL__SSLSOCKET_SHARED_CIPHERS_METHODDEF
2891 _SSL__SSLSOCKET_VERSION_METHODDEF
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002892 _SSL__SSLSOCKET_SELECTED_ALPN_PROTOCOL_METHODDEF
2893 _SSL__SSLSOCKET_COMPRESSION_METHODDEF
2894 _SSL__SSLSOCKET_SHUTDOWN_METHODDEF
Christian Heimes9fb051f2018-09-23 08:32:31 +02002895 _SSL__SSLSOCKET_VERIFY_CLIENT_POST_HANDSHAKE_METHODDEF
Christian Heimes666991f2021-04-26 15:01:40 +02002896 _SSL__SSLSOCKET_GET_UNVERIFIED_CHAIN_METHODDEF
2897 _SSL__SSLSOCKET_GET_VERIFIED_CHAIN_METHODDEF
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002898 {NULL, NULL}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002899};
2900
Christian Heimes5c36da72020-11-20 09:40:12 +01002901static PyType_Slot PySSLSocket_slots[] = {
2902 {Py_tp_methods, PySSLMethods},
2903 {Py_tp_getset, ssl_getsetlist},
2904 {Py_tp_dealloc, PySSL_dealloc},
2905 {Py_tp_traverse, PySSL_traverse},
2906 {Py_tp_clear, PySSL_clear},
2907 {0, 0},
2908};
2909
2910static PyType_Spec PySSLSocket_spec = {
Miss Islington (bot)ea47a8a2021-05-27 09:25:22 -07002911 .name = "_ssl._SSLSocket",
2912 .basicsize = sizeof(PySSLSocket),
2913 .flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_IMMUTABLETYPE |
2914 Py_TPFLAGS_HAVE_GC),
2915 .slots = PySSLSocket_slots,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002916};
2917
Antoine Pitrou152efa22010-05-16 18:19:27 +00002918/*
2919 * _SSLContext objects
2920 */
2921
Christian Heimes5fe668c2016-09-12 00:01:11 +02002922static int
Christian Heimes9fb051f2018-09-23 08:32:31 +02002923_set_verify_mode(PySSLContext *self, enum py_ssl_cert_requirements n)
Christian Heimes5fe668c2016-09-12 00:01:11 +02002924{
2925 int mode;
2926 int (*verify_cb)(int, X509_STORE_CTX *) = NULL;
2927
2928 switch(n) {
2929 case PY_SSL_CERT_NONE:
2930 mode = SSL_VERIFY_NONE;
2931 break;
2932 case PY_SSL_CERT_OPTIONAL:
2933 mode = SSL_VERIFY_PEER;
2934 break;
2935 case PY_SSL_CERT_REQUIRED:
2936 mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
2937 break;
2938 default:
2939 PyErr_SetString(PyExc_ValueError,
2940 "invalid value for verify_mode");
2941 return -1;
2942 }
Christian Heimesf0f59302019-07-01 08:29:17 +02002943
2944 /* bpo-37428: newPySSLSocket() sets SSL_VERIFY_POST_HANDSHAKE flag for
2945 * server sockets and SSL_set_post_handshake_auth() for client. */
2946
Christian Heimes5fe668c2016-09-12 00:01:11 +02002947 /* keep current verify cb */
Christian Heimes9fb051f2018-09-23 08:32:31 +02002948 verify_cb = SSL_CTX_get_verify_callback(self->ctx);
2949 SSL_CTX_set_verify(self->ctx, mode, verify_cb);
Christian Heimes5fe668c2016-09-12 00:01:11 +02002950 return 0;
2951}
2952
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002953/*[clinic input]
2954@classmethod
2955_ssl._SSLContext.__new__
2956 protocol as proto_version: int
2957 /
2958[clinic start generated code]*/
2959
Antoine Pitrou152efa22010-05-16 18:19:27 +00002960static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002961_ssl__SSLContext_impl(PyTypeObject *type, int proto_version)
2962/*[clinic end generated code: output=2cf0d7a0741b6bd1 input=8d58a805b95fc534]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00002963{
Antoine Pitrou152efa22010-05-16 18:19:27 +00002964 PySSLContext *self;
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01002965 long options;
Christian Heimes2875c602021-04-19 07:27:10 +02002966 const SSL_METHOD *method = NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002967 SSL_CTX *ctx = NULL;
Christian Heimes61d478c2018-01-27 15:51:38 +01002968 X509_VERIFY_PARAM *params;
Christian Heimes358cfd42016-09-10 22:43:48 +02002969 int result;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002970
Christian Heimes7f1305e2021-04-17 20:06:38 +02002971 /* slower approach, walk MRO and get borrowed reference to module.
2972 * _PyType_GetModuleByDef is required for SSLContext subclasses */
2973 PyObject *module = _PyType_GetModuleByDef(type, &_sslmodule_def);
2974 if (module == NULL) {
2975 PyErr_SetString(PyExc_RuntimeError,
2976 "Cannot find internal module state");
2977 return NULL;
2978 }
2979
Christian Heimes6e8cda92020-05-16 03:33:05 +02002980 switch(proto_version) {
2981#if defined(SSL3_VERSION) && !defined(OPENSSL_NO_SSL3)
2982 case PY_SSL_VERSION_SSL3:
Christian Heimes2875c602021-04-19 07:27:10 +02002983 PY_SSL_DEPRECATED("PROTOCOL_SSLv3", 2, NULL);
2984 method = SSLv3_method();
Christian Heimes6e8cda92020-05-16 03:33:05 +02002985 break;
Benjamin Petersone32467c2014-12-05 21:59:35 -05002986#endif
Christian Heimesa871f692020-06-01 08:58:14 +02002987#if (defined(TLS1_VERSION) && \
2988 !defined(OPENSSL_NO_TLS1) && \
2989 !defined(OPENSSL_NO_TLS1_METHOD))
Christian Heimes6e8cda92020-05-16 03:33:05 +02002990 case PY_SSL_VERSION_TLS1:
Christian Heimes2875c602021-04-19 07:27:10 +02002991 PY_SSL_DEPRECATED("PROTOCOL_TLSv1", 2, NULL);
2992 method = TLSv1_method();
Christian Heimes6e8cda92020-05-16 03:33:05 +02002993 break;
Victor Stinner3de49192011-05-09 00:42:58 +02002994#endif
Christian Heimesa871f692020-06-01 08:58:14 +02002995#if (defined(TLS1_1_VERSION) && \
2996 !defined(OPENSSL_NO_TLS1_1) && \
2997 !defined(OPENSSL_NO_TLS1_1_METHOD))
Christian Heimes6e8cda92020-05-16 03:33:05 +02002998 case PY_SSL_VERSION_TLS1_1:
Christian Heimes2875c602021-04-19 07:27:10 +02002999 PY_SSL_DEPRECATED("PROTOCOL_TLSv1_1", 2, NULL);
3000 method = TLSv1_1_method();
Christian Heimes6e8cda92020-05-16 03:33:05 +02003001 break;
3002#endif
Christian Heimesa871f692020-06-01 08:58:14 +02003003#if (defined(TLS1_2_VERSION) && \
3004 !defined(OPENSSL_NO_TLS1_2) && \
3005 !defined(OPENSSL_NO_TLS1_2_METHOD))
Christian Heimes6e8cda92020-05-16 03:33:05 +02003006 case PY_SSL_VERSION_TLS1_2:
Christian Heimes2875c602021-04-19 07:27:10 +02003007 PY_SSL_DEPRECATED("PROTOCOL_TLSv1_2", 2, NULL);
3008 method = TLSv1_2_method();
Christian Heimes6e8cda92020-05-16 03:33:05 +02003009 break;
3010#endif
3011 case PY_SSL_VERSION_TLS:
Christian Heimes2875c602021-04-19 07:27:10 +02003012 PY_SSL_DEPRECATED("PROTOCOL_TLS", 2, NULL);
3013 method = TLS_method();
Christian Heimes6e8cda92020-05-16 03:33:05 +02003014 break;
3015 case PY_SSL_VERSION_TLS_CLIENT:
Christian Heimes2875c602021-04-19 07:27:10 +02003016 method = TLS_client_method();
Christian Heimes6e8cda92020-05-16 03:33:05 +02003017 break;
3018 case PY_SSL_VERSION_TLS_SERVER:
Christian Heimes2875c602021-04-19 07:27:10 +02003019 method = TLS_server_method();
Christian Heimes6e8cda92020-05-16 03:33:05 +02003020 break;
3021 default:
Christian Heimes2875c602021-04-19 07:27:10 +02003022 method = NULL;
Christian Heimes6e8cda92020-05-16 03:33:05 +02003023 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003024
Christian Heimes2875c602021-04-19 07:27:10 +02003025 if (method == NULL) {
3026 PyErr_Format(PyExc_ValueError,
3027 "invalid or unsupported protocol version %i",
3028 proto_version);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003029 return NULL;
3030 }
Christian Heimes2875c602021-04-19 07:27:10 +02003031
3032 PySSL_BEGIN_ALLOW_THREADS
3033 ctx = SSL_CTX_new(method);
3034 PySSL_END_ALLOW_THREADS
3035
Antoine Pitrou152efa22010-05-16 18:19:27 +00003036 if (ctx == NULL) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02003037 _setSSLError(get_ssl_state(module), NULL, 0, __FILE__, __LINE__);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003038 return NULL;
3039 }
3040
3041 assert(type != NULL && type->tp_alloc != NULL);
3042 self = (PySSLContext *) type->tp_alloc(type, 0);
3043 if (self == NULL) {
3044 SSL_CTX_free(ctx);
3045 return NULL;
3046 }
3047 self->ctx = ctx;
Christian Heimes61d478c2018-01-27 15:51:38 +01003048 self->hostflags = X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS;
Christian Heimes11a14932018-02-24 02:35:08 +01003049 self->protocol = proto_version;
Christian Heimesc7f70692019-05-31 11:44:05 +02003050 self->msg_cb = NULL;
Christian Heimesc7f70692019-05-31 11:44:05 +02003051 self->keylog_filename = NULL;
3052 self->keylog_bio = NULL;
Benjamin Petersoncca27322015-01-23 16:35:37 -05003053 self->alpn_protocols = NULL;
Christian Heimes11a14932018-02-24 02:35:08 +01003054 self->set_sni_cb = NULL;
Christian Heimes7f1305e2021-04-17 20:06:38 +02003055 self->state = get_ssl_state(module);
3056
Christian Heimes1aa9a752013-12-02 02:41:19 +01003057 /* Don't check host name by default */
Christian Heimes5fe668c2016-09-12 00:01:11 +02003058 if (proto_version == PY_SSL_VERSION_TLS_CLIENT) {
3059 self->check_hostname = 1;
Christian Heimes9fb051f2018-09-23 08:32:31 +02003060 if (_set_verify_mode(self, PY_SSL_CERT_REQUIRED) == -1) {
Christian Heimes5fe668c2016-09-12 00:01:11 +02003061 Py_DECREF(self);
3062 return NULL;
3063 }
3064 } else {
3065 self->check_hostname = 0;
Christian Heimes9fb051f2018-09-23 08:32:31 +02003066 if (_set_verify_mode(self, PY_SSL_CERT_NONE) == -1) {
Christian Heimes5fe668c2016-09-12 00:01:11 +02003067 Py_DECREF(self);
3068 return NULL;
3069 }
3070 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003071 /* Defaults */
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01003072 options = SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
3073 if (proto_version != PY_SSL_VERSION_SSL2)
3074 options |= SSL_OP_NO_SSLv2;
Benjamin Petersona9dcdab2015-11-11 22:38:41 -08003075 if (proto_version != PY_SSL_VERSION_SSL3)
3076 options |= SSL_OP_NO_SSLv3;
Christian Heimes358cfd42016-09-10 22:43:48 +02003077 /* Minimal security flags for server and client side context.
3078 * Client sockets ignore server-side parameters. */
3079#ifdef SSL_OP_NO_COMPRESSION
3080 options |= SSL_OP_NO_COMPRESSION;
3081#endif
3082#ifdef SSL_OP_CIPHER_SERVER_PREFERENCE
3083 options |= SSL_OP_CIPHER_SERVER_PREFERENCE;
3084#endif
3085#ifdef SSL_OP_SINGLE_DH_USE
3086 options |= SSL_OP_SINGLE_DH_USE;
3087#endif
3088#ifdef SSL_OP_SINGLE_ECDH_USE
3089 options |= SSL_OP_SINGLE_ECDH_USE;
3090#endif
Christian Heimes6f37ebc2021-04-09 17:59:21 +02003091#ifdef SSL_OP_IGNORE_UNEXPECTED_EOF
3092 /* Make OpenSSL 3.0.0 behave like 1.1.1 */
3093 options |= SSL_OP_IGNORE_UNEXPECTED_EOF;
3094#endif
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01003095 SSL_CTX_set_options(self->ctx, options);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003096
Semen Zhydenko1295e112017-10-15 21:28:31 +02003097 /* A bare minimum cipher list without completely broken cipher suites.
Christian Heimes358cfd42016-09-10 22:43:48 +02003098 * It's far from perfect but gives users a better head start. */
3099 if (proto_version != PY_SSL_VERSION_SSL2) {
Christian Heimes892d66e2018-01-29 14:10:18 +01003100#if PY_SSL_DEFAULT_CIPHERS == 2
3101 /* stick to OpenSSL's default settings */
3102 result = 1;
3103#else
3104 result = SSL_CTX_set_cipher_list(ctx, PY_SSL_DEFAULT_CIPHER_STRING);
3105#endif
Christian Heimes358cfd42016-09-10 22:43:48 +02003106 } else {
3107 /* SSLv2 needs MD5 */
3108 result = SSL_CTX_set_cipher_list(ctx, "HIGH:!aNULL:!eNULL");
3109 }
3110 if (result == 0) {
3111 Py_DECREF(self);
3112 ERR_clear_error();
Christian Heimes7f1305e2021-04-17 20:06:38 +02003113 PyErr_SetString(get_state_ctx(self)->PySSLErrorObject,
Christian Heimes358cfd42016-09-10 22:43:48 +02003114 "No cipher can be selected.");
Christian Heimese9832522021-05-01 20:53:10 +02003115 goto error;
Christian Heimes358cfd42016-09-10 22:43:48 +02003116 }
Christian Heimese9832522021-05-01 20:53:10 +02003117#ifdef PY_SSL_MIN_PROTOCOL
3118 switch(proto_version) {
3119 case PY_SSL_VERSION_TLS:
3120 case PY_SSL_VERSION_TLS_CLIENT:
3121 case PY_SSL_VERSION_TLS_SERVER:
3122 result = SSL_CTX_set_min_proto_version(ctx, PY_SSL_MIN_PROTOCOL);
3123 if (result == 0) {
3124 PyErr_Format(PyExc_ValueError,
3125 "Failed to set minimum protocol 0x%x",
3126 PY_SSL_MIN_PROTOCOL);
3127 goto error;
3128 }
3129 break;
3130 default:
3131 break;
3132 }
3133#endif
Christian Heimes358cfd42016-09-10 22:43:48 +02003134
Benjamin Peterson3b1a8b32016-01-07 21:37:37 -08003135 /* Set SSL_MODE_RELEASE_BUFFERS. This potentially greatly reduces memory
Christian Heimes39258d32021-04-17 11:36:35 +02003136 usage for no cost at all. */
3137 SSL_CTX_set_mode(self->ctx, SSL_MODE_RELEASE_BUFFERS);
Antoine Pitrou0bebbc32014-03-22 18:13:50 +01003138
Antoine Pitroufc113ee2010-10-13 12:46:13 +00003139#define SID_CTX "Python"
3140 SSL_CTX_set_session_id_context(self->ctx, (const unsigned char *) SID_CTX,
3141 sizeof(SID_CTX));
3142#undef SID_CTX
3143
Christian Heimes61d478c2018-01-27 15:51:38 +01003144 params = SSL_CTX_get0_param(self->ctx);
Christian Heimes61d478c2018-01-27 15:51:38 +01003145 /* Improve trust chain building when cross-signed intermediate
3146 certificates are present. See https://bugs.python.org/issue23476. */
3147 X509_VERIFY_PARAM_set_flags(params, X509_V_FLAG_TRUSTED_FIRST);
Christian Heimes61d478c2018-01-27 15:51:38 +01003148 X509_VERIFY_PARAM_set_hostflags(params, self->hostflags);
Benjamin Petersonfdb19712015-03-04 22:11:12 -05003149
Christian Heimes9fb051f2018-09-23 08:32:31 +02003150#ifdef TLS1_3_VERSION
3151 self->post_handshake_auth = 0;
3152 SSL_CTX_set_post_handshake_auth(self->ctx, self->post_handshake_auth);
3153#endif
3154
Antoine Pitrou152efa22010-05-16 18:19:27 +00003155 return (PyObject *)self;
Christian Heimese9832522021-05-01 20:53:10 +02003156 error:
3157 Py_XDECREF(self);
3158 ERR_clear_error();
3159 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003160}
3161
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003162static int
3163context_traverse(PySSLContext *self, visitproc visit, void *arg)
3164{
Christian Heimes11a14932018-02-24 02:35:08 +01003165 Py_VISIT(self->set_sni_cb);
Christian Heimesc7f70692019-05-31 11:44:05 +02003166 Py_VISIT(self->msg_cb);
Miss Islington (bot)ea47a8a2021-05-27 09:25:22 -07003167 Py_VISIT(Py_TYPE(self));
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003168 return 0;
3169}
3170
3171static int
3172context_clear(PySSLContext *self)
3173{
Christian Heimes11a14932018-02-24 02:35:08 +01003174 Py_CLEAR(self->set_sni_cb);
Christian Heimesc7f70692019-05-31 11:44:05 +02003175 Py_CLEAR(self->msg_cb);
Christian Heimesc7f70692019-05-31 11:44:05 +02003176 Py_CLEAR(self->keylog_filename);
3177 if (self->keylog_bio != NULL) {
3178 PySSL_BEGIN_ALLOW_THREADS
3179 BIO_free_all(self->keylog_bio);
3180 PySSL_END_ALLOW_THREADS
3181 self->keylog_bio = NULL;
3182 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003183 return 0;
3184}
3185
Antoine Pitrou152efa22010-05-16 18:19:27 +00003186static void
3187context_dealloc(PySSLContext *self)
3188{
Christian Heimes5c36da72020-11-20 09:40:12 +01003189 PyTypeObject *tp = Py_TYPE(self);
INADA Naokia6296d32017-08-24 14:55:17 +09003190 /* bpo-31095: UnTrack is needed before calling any callbacks */
3191 PyObject_GC_UnTrack(self);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003192 context_clear(self);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003193 SSL_CTX_free(self->ctx);
Christian Heimes39258d32021-04-17 11:36:35 +02003194 PyMem_FREE(self->alpn_protocols);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003195 Py_TYPE(self)->tp_free(self);
Christian Heimes5c36da72020-11-20 09:40:12 +01003196 Py_DECREF(tp);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003197}
3198
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003199/*[clinic input]
3200_ssl._SSLContext.set_ciphers
3201 cipherlist: str
3202 /
3203[clinic start generated code]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003204
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003205static PyObject *
3206_ssl__SSLContext_set_ciphers_impl(PySSLContext *self, const char *cipherlist)
3207/*[clinic end generated code: output=3a3162f3557c0f3f input=a7ac931b9f3ca7fc]*/
3208{
3209 int ret = SSL_CTX_set_cipher_list(self->ctx, cipherlist);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003210 if (ret == 0) {
Antoine Pitrou65ec8ae2010-05-16 19:56:32 +00003211 /* Clearing the error queue is necessary on some OpenSSL versions,
3212 otherwise the error will be reported again when another SSL call
3213 is done. */
3214 ERR_clear_error();
Christian Heimes7f1305e2021-04-17 20:06:38 +02003215 PyErr_SetString(get_state_ctx(self)->PySSLErrorObject,
Antoine Pitrou152efa22010-05-16 18:19:27 +00003216 "No cipher can be selected.");
3217 return NULL;
3218 }
3219 Py_RETURN_NONE;
3220}
3221
Christian Heimes25bfcd52016-09-06 00:04:45 +02003222/*[clinic input]
3223_ssl._SSLContext.get_ciphers
3224[clinic start generated code]*/
3225
3226static PyObject *
3227_ssl__SSLContext_get_ciphers_impl(PySSLContext *self)
3228/*[clinic end generated code: output=a56e4d68a406dfc4 input=a2aadc9af89b79c5]*/
3229{
3230 SSL *ssl = NULL;
3231 STACK_OF(SSL_CIPHER) *sk = NULL;
Christian Heimes99a65702016-09-10 23:44:53 +02003232 const SSL_CIPHER *cipher;
Christian Heimes25bfcd52016-09-06 00:04:45 +02003233 int i=0;
3234 PyObject *result = NULL, *dct;
3235
3236 ssl = SSL_new(self->ctx);
3237 if (ssl == NULL) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02003238 _setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
Christian Heimes25bfcd52016-09-06 00:04:45 +02003239 goto exit;
3240 }
3241 sk = SSL_get_ciphers(ssl);
3242
3243 result = PyList_New(sk_SSL_CIPHER_num(sk));
3244 if (result == NULL) {
3245 goto exit;
3246 }
3247
3248 for (i = 0; i < sk_SSL_CIPHER_num(sk); i++) {
3249 cipher = sk_SSL_CIPHER_value(sk, i);
3250 dct = cipher_to_dict(cipher);
3251 if (dct == NULL) {
3252 Py_CLEAR(result);
3253 goto exit;
3254 }
3255 PyList_SET_ITEM(result, i, dct);
3256 }
3257
3258 exit:
3259 if (ssl != NULL)
3260 SSL_free(ssl);
3261 return result;
3262
3263}
Christian Heimes25bfcd52016-09-06 00:04:45 +02003264
3265
Benjamin Petersoncca27322015-01-23 16:35:37 -05003266static int
Benjamin Peterson88615022015-01-23 17:30:26 -05003267do_protocol_selection(int alpn, unsigned char **out, unsigned char *outlen,
3268 const unsigned char *server_protocols, unsigned int server_protocols_len,
3269 const unsigned char *client_protocols, unsigned int client_protocols_len)
Benjamin Petersoncca27322015-01-23 16:35:37 -05003270{
Benjamin Peterson88615022015-01-23 17:30:26 -05003271 int ret;
3272 if (client_protocols == NULL) {
3273 client_protocols = (unsigned char *)"";
3274 client_protocols_len = 0;
3275 }
3276 if (server_protocols == NULL) {
3277 server_protocols = (unsigned char *)"";
3278 server_protocols_len = 0;
Benjamin Petersoncca27322015-01-23 16:35:37 -05003279 }
3280
Benjamin Peterson88615022015-01-23 17:30:26 -05003281 ret = SSL_select_next_proto(out, outlen,
3282 server_protocols, server_protocols_len,
3283 client_protocols, client_protocols_len);
3284 if (alpn && ret != OPENSSL_NPN_NEGOTIATED)
3285 return SSL_TLSEXT_ERR_NOACK;
Benjamin Petersoncca27322015-01-23 16:35:37 -05003286
3287 return SSL_TLSEXT_ERR_OK;
3288}
3289
Benjamin Petersoncca27322015-01-23 16:35:37 -05003290static int
3291_selectALPN_cb(SSL *s,
3292 const unsigned char **out, unsigned char *outlen,
3293 const unsigned char *client_protocols, unsigned int client_protocols_len,
3294 void *args)
3295{
3296 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Peterson88615022015-01-23 17:30:26 -05003297 return do_protocol_selection(1, (unsigned char **)out, outlen,
3298 ctx->alpn_protocols, ctx->alpn_protocols_len,
3299 client_protocols, client_protocols_len);
Benjamin Petersoncca27322015-01-23 16:35:37 -05003300}
Benjamin Petersoncca27322015-01-23 16:35:37 -05003301
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003302/*[clinic input]
3303_ssl._SSLContext._set_alpn_protocols
3304 protos: Py_buffer
3305 /
3306[clinic start generated code]*/
3307
Benjamin Petersoncca27322015-01-23 16:35:37 -05003308static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003309_ssl__SSLContext__set_alpn_protocols_impl(PySSLContext *self,
3310 Py_buffer *protos)
3311/*[clinic end generated code: output=87599a7f76651a9b input=9bba964595d519be]*/
Benjamin Petersoncca27322015-01-23 16:35:37 -05003312{
Victor Stinner5a615592017-09-14 01:10:30 -07003313 if ((size_t)protos->len > UINT_MAX) {
Segev Finer5cff6372017-07-27 01:19:17 +03003314 PyErr_Format(PyExc_OverflowError,
Serhiy Storchakad53fe5f2019-03-13 22:59:55 +02003315 "protocols longer than %u bytes", UINT_MAX);
Segev Finer5cff6372017-07-27 01:19:17 +03003316 return NULL;
3317 }
3318
Victor Stinner00d7abd2020-12-01 09:56:42 +01003319 PyMem_Free(self->alpn_protocols);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003320 self->alpn_protocols = PyMem_Malloc(protos->len);
Benjamin Petersoncca27322015-01-23 16:35:37 -05003321 if (!self->alpn_protocols)
3322 return PyErr_NoMemory();
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003323 memcpy(self->alpn_protocols, protos->buf, protos->len);
Segev Finer5cff6372017-07-27 01:19:17 +03003324 self->alpn_protocols_len = (unsigned int)protos->len;
Benjamin Petersoncca27322015-01-23 16:35:37 -05003325
3326 if (SSL_CTX_set_alpn_protos(self->ctx, self->alpn_protocols, self->alpn_protocols_len))
3327 return PyErr_NoMemory();
3328 SSL_CTX_set_alpn_select_cb(self->ctx, _selectALPN_cb, self);
3329
Benjamin Petersoncca27322015-01-23 16:35:37 -05003330 Py_RETURN_NONE;
Benjamin Petersoncca27322015-01-23 16:35:37 -05003331}
3332
Antoine Pitrou152efa22010-05-16 18:19:27 +00003333static PyObject *
3334get_verify_mode(PySSLContext *self, void *c)
3335{
Christian Heimes9fb051f2018-09-23 08:32:31 +02003336 /* ignore SSL_VERIFY_CLIENT_ONCE and SSL_VERIFY_POST_HANDSHAKE */
3337 int mask = (SSL_VERIFY_NONE | SSL_VERIFY_PEER |
3338 SSL_VERIFY_FAIL_IF_NO_PEER_CERT);
3339 switch (SSL_CTX_get_verify_mode(self->ctx) & mask) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003340 case SSL_VERIFY_NONE:
3341 return PyLong_FromLong(PY_SSL_CERT_NONE);
3342 case SSL_VERIFY_PEER:
3343 return PyLong_FromLong(PY_SSL_CERT_OPTIONAL);
3344 case SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT:
3345 return PyLong_FromLong(PY_SSL_CERT_REQUIRED);
3346 }
Christian Heimes7f1305e2021-04-17 20:06:38 +02003347 PyErr_SetString(get_state_ctx(self)->PySSLErrorObject,
Antoine Pitrou152efa22010-05-16 18:19:27 +00003348 "invalid return value from SSL_CTX_get_verify_mode");
3349 return NULL;
3350}
3351
3352static int
3353set_verify_mode(PySSLContext *self, PyObject *arg, void *c)
3354{
Christian Heimes5fe668c2016-09-12 00:01:11 +02003355 int n;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003356 if (!PyArg_Parse(arg, "i", &n))
3357 return -1;
Christian Heimes5fe668c2016-09-12 00:01:11 +02003358 if (n == PY_SSL_CERT_NONE && self->check_hostname) {
Christian Heimes1aa9a752013-12-02 02:41:19 +01003359 PyErr_SetString(PyExc_ValueError,
3360 "Cannot set verify_mode to CERT_NONE when "
3361 "check_hostname is enabled.");
3362 return -1;
3363 }
Christian Heimes9fb051f2018-09-23 08:32:31 +02003364 return _set_verify_mode(self, n);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003365}
3366
3367static PyObject *
Christian Heimes22587792013-11-21 23:56:13 +01003368get_verify_flags(PySSLContext *self, void *c)
3369{
Christian Heimes598894f2016-09-05 23:19:05 +02003370 X509_VERIFY_PARAM *param;
Christian Heimes22587792013-11-21 23:56:13 +01003371 unsigned long flags;
3372
Christian Heimes61d478c2018-01-27 15:51:38 +01003373 param = SSL_CTX_get0_param(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02003374 flags = X509_VERIFY_PARAM_get_flags(param);
Christian Heimes22587792013-11-21 23:56:13 +01003375 return PyLong_FromUnsignedLong(flags);
3376}
3377
3378static int
3379set_verify_flags(PySSLContext *self, PyObject *arg, void *c)
3380{
Christian Heimes598894f2016-09-05 23:19:05 +02003381 X509_VERIFY_PARAM *param;
Christian Heimes22587792013-11-21 23:56:13 +01003382 unsigned long new_flags, flags, set, clear;
3383
3384 if (!PyArg_Parse(arg, "k", &new_flags))
3385 return -1;
Christian Heimes61d478c2018-01-27 15:51:38 +01003386 param = SSL_CTX_get0_param(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02003387 flags = X509_VERIFY_PARAM_get_flags(param);
Christian Heimes22587792013-11-21 23:56:13 +01003388 clear = flags & ~new_flags;
3389 set = ~flags & new_flags;
3390 if (clear) {
Christian Heimes598894f2016-09-05 23:19:05 +02003391 if (!X509_VERIFY_PARAM_clear_flags(param, clear)) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02003392 _setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
Christian Heimes22587792013-11-21 23:56:13 +01003393 return -1;
3394 }
3395 }
3396 if (set) {
Christian Heimes598894f2016-09-05 23:19:05 +02003397 if (!X509_VERIFY_PARAM_set_flags(param, set)) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02003398 _setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
Christian Heimes22587792013-11-21 23:56:13 +01003399 return -1;
3400 }
3401 }
3402 return 0;
3403}
3404
Christian Heimes698dde12018-02-27 11:54:43 +01003405/* Getter and setter for protocol version */
Christian Heimes698dde12018-02-27 11:54:43 +01003406static int
3407set_min_max_proto_version(PySSLContext *self, PyObject *arg, int what)
3408{
3409 long v;
3410 int result;
3411
3412 if (!PyArg_Parse(arg, "l", &v))
3413 return -1;
3414 if (v > INT_MAX) {
3415 PyErr_SetString(PyExc_OverflowError, "Option is too long");
3416 return -1;
3417 }
3418
3419 switch(self->protocol) {
3420 case PY_SSL_VERSION_TLS_CLIENT: /* fall through */
3421 case PY_SSL_VERSION_TLS_SERVER: /* fall through */
3422 case PY_SSL_VERSION_TLS:
3423 break;
3424 default:
3425 PyErr_SetString(
3426 PyExc_ValueError,
3427 "The context's protocol doesn't support modification of "
3428 "highest and lowest version."
3429 );
3430 return -1;
3431 }
3432
Christian Heimes2875c602021-04-19 07:27:10 +02003433 /* check for deprecations and supported values */
3434 switch(v) {
3435 case PY_PROTO_SSLv3:
3436 PY_SSL_DEPRECATED("TLSVersion.SSLv3", 2, -1);
3437 break;
3438 case PY_PROTO_TLSv1:
3439 PY_SSL_DEPRECATED("TLSVersion.TLSv1", 2, -1);
3440 break;
3441 case PY_PROTO_TLSv1_1:
3442 PY_SSL_DEPRECATED("TLSVersion.TLSv1_1", 2, -1);
3443 break;
3444 case PY_PROTO_MINIMUM_SUPPORTED:
3445 case PY_PROTO_MAXIMUM_SUPPORTED:
3446 case PY_PROTO_TLSv1_2:
3447 case PY_PROTO_TLSv1_3:
3448 /* ok */
3449 break;
3450 default:
3451 PyErr_Format(PyExc_ValueError,
3452 "Unsupported TLS/SSL version 0x%x", v);
3453 return -1;
3454 }
3455
Christian Heimes698dde12018-02-27 11:54:43 +01003456 if (what == 0) {
3457 switch(v) {
3458 case PY_PROTO_MINIMUM_SUPPORTED:
3459 v = 0;
3460 break;
3461 case PY_PROTO_MAXIMUM_SUPPORTED:
3462 /* Emulate max for set_min_proto_version */
3463 v = PY_PROTO_MAXIMUM_AVAILABLE;
3464 break;
3465 default:
3466 break;
3467 }
3468 result = SSL_CTX_set_min_proto_version(self->ctx, v);
3469 }
3470 else {
3471 switch(v) {
3472 case PY_PROTO_MAXIMUM_SUPPORTED:
3473 v = 0;
3474 break;
3475 case PY_PROTO_MINIMUM_SUPPORTED:
3476 /* Emulate max for set_min_proto_version */
3477 v = PY_PROTO_MINIMUM_AVAILABLE;
3478 break;
3479 default:
3480 break;
3481 }
3482 result = SSL_CTX_set_max_proto_version(self->ctx, v);
3483 }
3484 if (result == 0) {
3485 PyErr_Format(PyExc_ValueError,
3486 "Unsupported protocol version 0x%x", v);
3487 return -1;
3488 }
3489 return 0;
3490}
3491
3492static PyObject *
3493get_minimum_version(PySSLContext *self, void *c)
3494{
3495 int v = SSL_CTX_ctrl(self->ctx, SSL_CTRL_GET_MIN_PROTO_VERSION, 0, NULL);
3496 if (v == 0) {
3497 v = PY_PROTO_MINIMUM_SUPPORTED;
3498 }
3499 return PyLong_FromLong(v);
3500}
3501
3502static int
3503set_minimum_version(PySSLContext *self, PyObject *arg, void *c)
3504{
3505 return set_min_max_proto_version(self, arg, 0);
3506}
3507
3508static PyObject *
3509get_maximum_version(PySSLContext *self, void *c)
3510{
3511 int v = SSL_CTX_ctrl(self->ctx, SSL_CTRL_GET_MAX_PROTO_VERSION, 0, NULL);
3512 if (v == 0) {
3513 v = PY_PROTO_MAXIMUM_SUPPORTED;
3514 }
3515 return PyLong_FromLong(v);
3516}
3517
3518static int
3519set_maximum_version(PySSLContext *self, PyObject *arg, void *c)
3520{
3521 return set_min_max_proto_version(self, arg, 1);
3522}
Christian Heimes698dde12018-02-27 11:54:43 +01003523
Christian Heimes39258d32021-04-17 11:36:35 +02003524#ifdef TLS1_3_VERSION
Christian Heimes78c7d522019-06-03 21:00:10 +02003525static PyObject *
3526get_num_tickets(PySSLContext *self, void *c)
3527{
Victor Stinner76611c72019-07-09 13:30:52 +02003528 return PyLong_FromSize_t(SSL_CTX_get_num_tickets(self->ctx));
Christian Heimes78c7d522019-06-03 21:00:10 +02003529}
3530
3531static int
3532set_num_tickets(PySSLContext *self, PyObject *arg, void *c)
3533{
3534 long num;
3535 if (!PyArg_Parse(arg, "l", &num))
3536 return -1;
3537 if (num < 0) {
3538 PyErr_SetString(PyExc_ValueError, "value must be non-negative");
3539 return -1;
3540 }
3541 if (self->protocol != PY_SSL_VERSION_TLS_SERVER) {
3542 PyErr_SetString(PyExc_ValueError,
3543 "SSLContext is not a server context.");
3544 return -1;
3545 }
3546 if (SSL_CTX_set_num_tickets(self->ctx, num) != 1) {
3547 PyErr_SetString(PyExc_ValueError, "failed to set num tickets.");
3548 return -1;
3549 }
3550 return 0;
3551}
3552
3553PyDoc_STRVAR(PySSLContext_num_tickets_doc,
3554"Control the number of TLSv1.3 session tickets");
Christian Heimes39258d32021-04-17 11:36:35 +02003555#endif /* TLS1_3_VERSION */
Christian Heimes78c7d522019-06-03 21:00:10 +02003556
matthewhughes9348e836bb2020-07-17 09:59:15 +01003557static PyObject *
3558get_security_level(PySSLContext *self, void *c)
3559{
3560 return PyLong_FromLong(SSL_CTX_get_security_level(self->ctx));
3561}
3562PyDoc_STRVAR(PySSLContext_security_level_doc, "The current security level");
matthewhughes9348e836bb2020-07-17 09:59:15 +01003563
Christian Heimes22587792013-11-21 23:56:13 +01003564static PyObject *
Antoine Pitroub5218772010-05-21 09:56:06 +00003565get_options(PySSLContext *self, void *c)
3566{
3567 return PyLong_FromLong(SSL_CTX_get_options(self->ctx));
3568}
3569
3570static int
3571set_options(PySSLContext *self, PyObject *arg, void *c)
3572{
3573 long new_opts, opts, set, clear;
Christian Heimes2875c602021-04-19 07:27:10 +02003574 long opt_no = (
3575 SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1 |
3576 SSL_OP_NO_TLSv1_1 | SSL_OP_NO_TLSv1_2 | SSL_OP_NO_TLSv1_2
3577 );
3578
Antoine Pitroub5218772010-05-21 09:56:06 +00003579 if (!PyArg_Parse(arg, "l", &new_opts))
3580 return -1;
3581 opts = SSL_CTX_get_options(self->ctx);
3582 clear = opts & ~new_opts;
3583 set = ~opts & new_opts;
Christian Heimes2875c602021-04-19 07:27:10 +02003584
3585 if ((set & opt_no) != 0) {
3586 if (_ssl_deprecated("Setting OP_NO_SSL* or SSL_NO_TLS* options is "
3587 "deprecated", 2) < 0) {
3588 return -1;
3589 }
3590 }
Antoine Pitroub5218772010-05-21 09:56:06 +00003591 if (clear) {
Antoine Pitroub5218772010-05-21 09:56:06 +00003592 SSL_CTX_clear_options(self->ctx, clear);
Antoine Pitroub5218772010-05-21 09:56:06 +00003593 }
3594 if (set)
3595 SSL_CTX_set_options(self->ctx, set);
3596 return 0;
3597}
3598
Christian Heimes1aa9a752013-12-02 02:41:19 +01003599static PyObject *
Christian Heimes61d478c2018-01-27 15:51:38 +01003600get_host_flags(PySSLContext *self, void *c)
3601{
3602 return PyLong_FromUnsignedLong(self->hostflags);
3603}
3604
3605static int
3606set_host_flags(PySSLContext *self, PyObject *arg, void *c)
3607{
3608 X509_VERIFY_PARAM *param;
3609 unsigned int new_flags = 0;
3610
3611 if (!PyArg_Parse(arg, "I", &new_flags))
3612 return -1;
3613
3614 param = SSL_CTX_get0_param(self->ctx);
3615 self->hostflags = new_flags;
3616 X509_VERIFY_PARAM_set_hostflags(param, new_flags);
3617 return 0;
3618}
3619
3620static PyObject *
Christian Heimes1aa9a752013-12-02 02:41:19 +01003621get_check_hostname(PySSLContext *self, void *c)
3622{
3623 return PyBool_FromLong(self->check_hostname);
3624}
3625
3626static int
3627set_check_hostname(PySSLContext *self, PyObject *arg, void *c)
3628{
3629 int check_hostname;
3630 if (!PyArg_Parse(arg, "p", &check_hostname))
3631 return -1;
3632 if (check_hostname &&
3633 SSL_CTX_get_verify_mode(self->ctx) == SSL_VERIFY_NONE) {
Christian Heimese82c0342017-09-15 20:29:57 +02003634 /* check_hostname = True sets verify_mode = CERT_REQUIRED */
Christian Heimes9fb051f2018-09-23 08:32:31 +02003635 if (_set_verify_mode(self, PY_SSL_CERT_REQUIRED) == -1) {
Christian Heimese82c0342017-09-15 20:29:57 +02003636 return -1;
3637 }
Christian Heimes1aa9a752013-12-02 02:41:19 +01003638 }
3639 self->check_hostname = check_hostname;
3640 return 0;
3641}
3642
Christian Heimes11a14932018-02-24 02:35:08 +01003643static PyObject *
Christian Heimes9fb051f2018-09-23 08:32:31 +02003644get_post_handshake_auth(PySSLContext *self, void *c) {
3645#if TLS1_3_VERSION
3646 return PyBool_FromLong(self->post_handshake_auth);
3647#else
3648 Py_RETURN_NONE;
3649#endif
3650}
3651
3652#if TLS1_3_VERSION
3653static int
3654set_post_handshake_auth(PySSLContext *self, PyObject *arg, void *c) {
Zackery Spytz842acaa2018-12-17 07:52:45 -07003655 if (arg == NULL) {
3656 PyErr_SetString(PyExc_AttributeError, "cannot delete attribute");
3657 return -1;
3658 }
Christian Heimes9fb051f2018-09-23 08:32:31 +02003659 int pha = PyObject_IsTrue(arg);
3660
3661 if (pha == -1) {
3662 return -1;
3663 }
3664 self->post_handshake_auth = pha;
3665
Christian Heimesf0f59302019-07-01 08:29:17 +02003666 /* bpo-37428: newPySSLSocket() sets SSL_VERIFY_POST_HANDSHAKE flag for
3667 * server sockets and SSL_set_post_handshake_auth() for client. */
Christian Heimes9fb051f2018-09-23 08:32:31 +02003668
3669 return 0;
3670}
3671#endif
3672
3673static PyObject *
Christian Heimes11a14932018-02-24 02:35:08 +01003674get_protocol(PySSLContext *self, void *c) {
3675 return PyLong_FromLong(self->protocol);
3676}
Christian Heimes1aa9a752013-12-02 02:41:19 +01003677
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003678typedef struct {
3679 PyThreadState *thread_state;
3680 PyObject *callable;
3681 char *password;
Victor Stinner9ee02032013-06-23 15:08:23 +02003682 int size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003683 int error;
3684} _PySSLPasswordInfo;
3685
3686static int
3687_pwinfo_set(_PySSLPasswordInfo *pw_info, PyObject* password,
3688 const char *bad_type_error)
3689{
3690 /* Set the password and size fields of a _PySSLPasswordInfo struct
3691 from a unicode, bytes, or byte array object.
3692 The password field will be dynamically allocated and must be freed
3693 by the caller */
3694 PyObject *password_bytes = NULL;
3695 const char *data = NULL;
3696 Py_ssize_t size;
3697
3698 if (PyUnicode_Check(password)) {
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03003699 password_bytes = PyUnicode_AsUTF8String(password);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003700 if (!password_bytes) {
3701 goto error;
3702 }
3703 data = PyBytes_AS_STRING(password_bytes);
3704 size = PyBytes_GET_SIZE(password_bytes);
3705 } else if (PyBytes_Check(password)) {
3706 data = PyBytes_AS_STRING(password);
3707 size = PyBytes_GET_SIZE(password);
3708 } else if (PyByteArray_Check(password)) {
3709 data = PyByteArray_AS_STRING(password);
3710 size = PyByteArray_GET_SIZE(password);
3711 } else {
3712 PyErr_SetString(PyExc_TypeError, bad_type_error);
3713 goto error;
3714 }
3715
Victor Stinner9ee02032013-06-23 15:08:23 +02003716 if (size > (Py_ssize_t)INT_MAX) {
3717 PyErr_Format(PyExc_ValueError,
3718 "password cannot be longer than %d bytes", INT_MAX);
3719 goto error;
3720 }
3721
Victor Stinner11ebff22013-07-07 17:07:52 +02003722 PyMem_Free(pw_info->password);
3723 pw_info->password = PyMem_Malloc(size);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003724 if (!pw_info->password) {
3725 PyErr_SetString(PyExc_MemoryError,
3726 "unable to allocate password buffer");
3727 goto error;
3728 }
3729 memcpy(pw_info->password, data, size);
Victor Stinner9ee02032013-06-23 15:08:23 +02003730 pw_info->size = (int)size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003731
3732 Py_XDECREF(password_bytes);
3733 return 1;
3734
3735error:
3736 Py_XDECREF(password_bytes);
3737 return 0;
3738}
3739
3740static int
3741_password_callback(char *buf, int size, int rwflag, void *userdata)
3742{
3743 _PySSLPasswordInfo *pw_info = (_PySSLPasswordInfo*) userdata;
3744 PyObject *fn_ret = NULL;
3745
3746 PySSL_END_ALLOW_THREADS_S(pw_info->thread_state);
3747
Christian Heimesd3b73f32021-04-09 15:23:38 +02003748 if (pw_info->error) {
3749 /* already failed previously. OpenSSL 3.0.0-alpha14 invokes the
3750 * callback multiple times which can lead to fatal Python error in
3751 * exception check. */
3752 goto error;
3753 }
3754
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003755 if (pw_info->callable) {
Victor Stinnerf17c3de2016-12-06 18:46:19 +01003756 fn_ret = _PyObject_CallNoArg(pw_info->callable);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003757 if (!fn_ret) {
3758 /* TODO: It would be nice to move _ctypes_add_traceback() into the
3759 core python API, so we could use it to add a frame here */
3760 goto error;
3761 }
3762
3763 if (!_pwinfo_set(pw_info, fn_ret,
3764 "password callback must return a string")) {
3765 goto error;
3766 }
3767 Py_CLEAR(fn_ret);
3768 }
3769
3770 if (pw_info->size > size) {
3771 PyErr_Format(PyExc_ValueError,
3772 "password cannot be longer than %d bytes", size);
3773 goto error;
3774 }
3775
3776 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
3777 memcpy(buf, pw_info->password, pw_info->size);
3778 return pw_info->size;
3779
3780error:
3781 Py_XDECREF(fn_ret);
3782 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
3783 pw_info->error = 1;
3784 return -1;
3785}
3786
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003787/*[clinic input]
3788_ssl._SSLContext.load_cert_chain
3789 certfile: object
Serhiy Storchaka279f4462019-09-14 12:24:05 +03003790 keyfile: object = None
3791 password: object = None
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003792
3793[clinic start generated code]*/
3794
Antoine Pitroub5218772010-05-21 09:56:06 +00003795static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003796_ssl__SSLContext_load_cert_chain_impl(PySSLContext *self, PyObject *certfile,
3797 PyObject *keyfile, PyObject *password)
Serhiy Storchaka279f4462019-09-14 12:24:05 +03003798/*[clinic end generated code: output=9480bc1c380e2095 input=30bc7e967ea01a58]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003799{
Antoine Pitrou152efa22010-05-16 18:19:27 +00003800 PyObject *certfile_bytes = NULL, *keyfile_bytes = NULL;
Christian Heimes598894f2016-09-05 23:19:05 +02003801 pem_password_cb *orig_passwd_cb = SSL_CTX_get_default_passwd_cb(self->ctx);
3802 void *orig_passwd_userdata = SSL_CTX_get_default_passwd_cb_userdata(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003803 _PySSLPasswordInfo pw_info = { NULL, NULL, NULL, 0, 0 };
Antoine Pitrou152efa22010-05-16 18:19:27 +00003804 int r;
3805
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003806 errno = 0;
Antoine Pitrou67e8e562010-09-01 20:55:41 +00003807 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00003808 if (keyfile == Py_None)
3809 keyfile = NULL;
3810 if (!PyUnicode_FSConverter(certfile, &certfile_bytes)) {
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03003811 if (PyErr_ExceptionMatches(PyExc_TypeError)) {
3812 PyErr_SetString(PyExc_TypeError,
3813 "certfile should be a valid filesystem path");
3814 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003815 return NULL;
3816 }
3817 if (keyfile && !PyUnicode_FSConverter(keyfile, &keyfile_bytes)) {
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03003818 if (PyErr_ExceptionMatches(PyExc_TypeError)) {
3819 PyErr_SetString(PyExc_TypeError,
3820 "keyfile should be a valid filesystem path");
3821 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003822 goto error;
3823 }
Serhiy Storchaka279f4462019-09-14 12:24:05 +03003824 if (password != Py_None) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003825 if (PyCallable_Check(password)) {
3826 pw_info.callable = password;
3827 } else if (!_pwinfo_set(&pw_info, password,
3828 "password should be a string or callable")) {
3829 goto error;
3830 }
3831 SSL_CTX_set_default_passwd_cb(self->ctx, _password_callback);
3832 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, &pw_info);
3833 }
3834 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003835 r = SSL_CTX_use_certificate_chain_file(self->ctx,
3836 PyBytes_AS_STRING(certfile_bytes));
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003837 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003838 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003839 if (pw_info.error) {
3840 ERR_clear_error();
3841 /* the password callback has already set the error information */
3842 }
3843 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00003844 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03003845 PyErr_SetFromErrno(PyExc_OSError);
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003846 }
3847 else {
Christian Heimes7f1305e2021-04-17 20:06:38 +02003848 _setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003849 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003850 goto error;
3851 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003852 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou9c254862011-04-03 18:15:34 +02003853 r = SSL_CTX_use_PrivateKey_file(self->ctx,
Antoine Pitrou152efa22010-05-16 18:19:27 +00003854 PyBytes_AS_STRING(keyfile ? keyfile_bytes : certfile_bytes),
3855 SSL_FILETYPE_PEM);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003856 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
3857 Py_CLEAR(keyfile_bytes);
3858 Py_CLEAR(certfile_bytes);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003859 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003860 if (pw_info.error) {
3861 ERR_clear_error();
3862 /* the password callback has already set the error information */
3863 }
3864 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00003865 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03003866 PyErr_SetFromErrno(PyExc_OSError);
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003867 }
3868 else {
Christian Heimes7f1305e2021-04-17 20:06:38 +02003869 _setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003870 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003871 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003872 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003873 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003874 r = SSL_CTX_check_private_key(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003875 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003876 if (r != 1) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02003877 _setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003878 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003879 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003880 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
3881 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02003882 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003883 Py_RETURN_NONE;
3884
3885error:
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003886 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
3887 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02003888 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003889 Py_XDECREF(keyfile_bytes);
3890 Py_XDECREF(certfile_bytes);
3891 return NULL;
3892}
3893
Christian Heimesefff7062013-11-21 03:35:02 +01003894/* internal helper function, returns -1 on error
3895 */
3896static int
Serhiy Storchaka8f87eef2020-04-12 14:58:27 +03003897_add_ca_certs(PySSLContext *self, const void *data, Py_ssize_t len,
Christian Heimesefff7062013-11-21 03:35:02 +01003898 int filetype)
3899{
3900 BIO *biobuf = NULL;
3901 X509_STORE *store;
Christian Heimesb9ad88b2021-04-23 13:51:40 +02003902 int retval = -1, err, loaded = 0;
Christian Heimesefff7062013-11-21 03:35:02 +01003903
3904 assert(filetype == SSL_FILETYPE_ASN1 || filetype == SSL_FILETYPE_PEM);
3905
3906 if (len <= 0) {
3907 PyErr_SetString(PyExc_ValueError,
3908 "Empty certificate data");
3909 return -1;
3910 } else if (len > INT_MAX) {
3911 PyErr_SetString(PyExc_OverflowError,
3912 "Certificate data is too long.");
3913 return -1;
3914 }
3915
Christian Heimes1dbf61f2013-11-22 00:34:18 +01003916 biobuf = BIO_new_mem_buf(data, (int)len);
Christian Heimesefff7062013-11-21 03:35:02 +01003917 if (biobuf == NULL) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02003918 _setSSLError(get_state_ctx(self), "Can't allocate buffer", 0, __FILE__, __LINE__);
Christian Heimesefff7062013-11-21 03:35:02 +01003919 return -1;
3920 }
3921
3922 store = SSL_CTX_get_cert_store(self->ctx);
3923 assert(store != NULL);
3924
3925 while (1) {
3926 X509 *cert = NULL;
3927 int r;
3928
3929 if (filetype == SSL_FILETYPE_ASN1) {
3930 cert = d2i_X509_bio(biobuf, NULL);
3931 } else {
3932 cert = PEM_read_bio_X509(biobuf, NULL,
Christian Heimes598894f2016-09-05 23:19:05 +02003933 SSL_CTX_get_default_passwd_cb(self->ctx),
3934 SSL_CTX_get_default_passwd_cb_userdata(self->ctx)
3935 );
Christian Heimesefff7062013-11-21 03:35:02 +01003936 }
3937 if (cert == NULL) {
3938 break;
3939 }
3940 r = X509_STORE_add_cert(store, cert);
3941 X509_free(cert);
3942 if (!r) {
3943 err = ERR_peek_last_error();
3944 if ((ERR_GET_LIB(err) == ERR_LIB_X509) &&
3945 (ERR_GET_REASON(err) == X509_R_CERT_ALREADY_IN_HASH_TABLE)) {
3946 /* cert already in hash table, not an error */
3947 ERR_clear_error();
3948 } else {
3949 break;
3950 }
3951 }
3952 loaded++;
3953 }
3954
3955 err = ERR_peek_last_error();
Christian Heimesb9ad88b2021-04-23 13:51:40 +02003956 if (loaded == 0) {
3957 const char *msg = NULL;
3958 if (filetype == SSL_FILETYPE_PEM) {
3959 msg = "no start line: cadata does not contain a certificate";
3960 } else {
3961 msg = "not enough data: cadata does not contain a certificate";
3962 }
3963 _setSSLError(get_state_ctx(self), msg, 0, __FILE__, __LINE__);
3964 retval = -1;
3965 } else if ((filetype == SSL_FILETYPE_ASN1) &&
3966 (ERR_GET_LIB(err) == ERR_LIB_ASN1) &&
3967 (ERR_GET_REASON(err) == ASN1_R_HEADER_TOO_LONG)) {
Christian Heimesefff7062013-11-21 03:35:02 +01003968 /* EOF ASN1 file, not an error */
3969 ERR_clear_error();
3970 retval = 0;
3971 } else if ((filetype == SSL_FILETYPE_PEM) &&
Christian Heimesefff7062013-11-21 03:35:02 +01003972 (ERR_GET_LIB(err) == ERR_LIB_PEM) &&
3973 (ERR_GET_REASON(err) == PEM_R_NO_START_LINE)) {
3974 /* EOF PEM file, not an error */
3975 ERR_clear_error();
3976 retval = 0;
Christian Heimesb9ad88b2021-04-23 13:51:40 +02003977 } else if (err != 0) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02003978 _setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
Christian Heimesefff7062013-11-21 03:35:02 +01003979 retval = -1;
Christian Heimesb9ad88b2021-04-23 13:51:40 +02003980 } else {
3981 retval = 0;
Christian Heimesefff7062013-11-21 03:35:02 +01003982 }
3983
3984 BIO_free(biobuf);
3985 return retval;
3986}
3987
3988
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003989/*[clinic input]
3990_ssl._SSLContext.load_verify_locations
Serhiy Storchaka279f4462019-09-14 12:24:05 +03003991 cafile: object = None
3992 capath: object = None
3993 cadata: object = None
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003994
3995[clinic start generated code]*/
3996
Antoine Pitrou152efa22010-05-16 18:19:27 +00003997static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003998_ssl__SSLContext_load_verify_locations_impl(PySSLContext *self,
3999 PyObject *cafile,
4000 PyObject *capath,
4001 PyObject *cadata)
Serhiy Storchaka279f4462019-09-14 12:24:05 +03004002/*[clinic end generated code: output=454c7e41230ca551 input=42ecfe258233e194]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004003{
Antoine Pitrou152efa22010-05-16 18:19:27 +00004004 PyObject *cafile_bytes = NULL, *capath_bytes = NULL;
4005 const char *cafile_buf = NULL, *capath_buf = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01004006 int r = 0, ok = 1;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004007
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00004008 errno = 0;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004009 if (cafile == Py_None)
4010 cafile = NULL;
4011 if (capath == Py_None)
4012 capath = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01004013 if (cadata == Py_None)
4014 cadata = NULL;
4015
4016 if (cafile == NULL && capath == NULL && cadata == NULL) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00004017 PyErr_SetString(PyExc_TypeError,
Christian Heimesefff7062013-11-21 03:35:02 +01004018 "cafile, capath and cadata cannot be all omitted");
4019 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004020 }
4021 if (cafile && !PyUnicode_FSConverter(cafile, &cafile_bytes)) {
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03004022 if (PyErr_ExceptionMatches(PyExc_TypeError)) {
4023 PyErr_SetString(PyExc_TypeError,
4024 "cafile should be a valid filesystem path");
4025 }
Christian Heimesefff7062013-11-21 03:35:02 +01004026 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004027 }
4028 if (capath && !PyUnicode_FSConverter(capath, &capath_bytes)) {
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03004029 if (PyErr_ExceptionMatches(PyExc_TypeError)) {
4030 PyErr_SetString(PyExc_TypeError,
4031 "capath should be a valid filesystem path");
4032 }
Christian Heimesefff7062013-11-21 03:35:02 +01004033 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004034 }
Christian Heimesefff7062013-11-21 03:35:02 +01004035
4036 /* validata cadata type and load cadata */
4037 if (cadata) {
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03004038 if (PyUnicode_Check(cadata)) {
4039 PyObject *cadata_ascii = PyUnicode_AsASCIIString(cadata);
4040 if (cadata_ascii == NULL) {
4041 if (PyErr_ExceptionMatches(PyExc_UnicodeEncodeError)) {
4042 goto invalid_cadata;
4043 }
4044 goto error;
4045 }
4046 r = _add_ca_certs(self,
4047 PyBytes_AS_STRING(cadata_ascii),
4048 PyBytes_GET_SIZE(cadata_ascii),
4049 SSL_FILETYPE_PEM);
4050 Py_DECREF(cadata_ascii);
4051 if (r == -1) {
4052 goto error;
4053 }
4054 }
4055 else if (PyObject_CheckBuffer(cadata)) {
4056 Py_buffer buf;
4057 if (PyObject_GetBuffer(cadata, &buf, PyBUF_SIMPLE)) {
4058 goto error;
4059 }
Christian Heimesefff7062013-11-21 03:35:02 +01004060 if (!PyBuffer_IsContiguous(&buf, 'C') || buf.ndim > 1) {
4061 PyBuffer_Release(&buf);
4062 PyErr_SetString(PyExc_TypeError,
4063 "cadata should be a contiguous buffer with "
4064 "a single dimension");
4065 goto error;
4066 }
4067 r = _add_ca_certs(self, buf.buf, buf.len, SSL_FILETYPE_ASN1);
4068 PyBuffer_Release(&buf);
4069 if (r == -1) {
4070 goto error;
4071 }
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03004072 }
4073 else {
4074 invalid_cadata:
4075 PyErr_SetString(PyExc_TypeError,
4076 "cadata should be an ASCII string or a "
4077 "bytes-like object");
4078 goto error;
Christian Heimesefff7062013-11-21 03:35:02 +01004079 }
4080 }
4081
4082 /* load cafile or capath */
4083 if (cafile || capath) {
4084 if (cafile)
4085 cafile_buf = PyBytes_AS_STRING(cafile_bytes);
4086 if (capath)
4087 capath_buf = PyBytes_AS_STRING(capath_bytes);
4088 PySSL_BEGIN_ALLOW_THREADS
4089 r = SSL_CTX_load_verify_locations(self->ctx, cafile_buf, capath_buf);
4090 PySSL_END_ALLOW_THREADS
4091 if (r != 1) {
Christian Heimesefff7062013-11-21 03:35:02 +01004092 if (errno != 0) {
4093 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03004094 PyErr_SetFromErrno(PyExc_OSError);
Christian Heimesefff7062013-11-21 03:35:02 +01004095 }
4096 else {
Christian Heimes7f1305e2021-04-17 20:06:38 +02004097 _setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
Christian Heimesefff7062013-11-21 03:35:02 +01004098 }
4099 goto error;
4100 }
4101 }
4102 goto end;
4103
4104 error:
4105 ok = 0;
4106 end:
Antoine Pitrou152efa22010-05-16 18:19:27 +00004107 Py_XDECREF(cafile_bytes);
4108 Py_XDECREF(capath_bytes);
Christian Heimesefff7062013-11-21 03:35:02 +01004109 if (ok) {
4110 Py_RETURN_NONE;
4111 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00004112 return NULL;
4113 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00004114}
4115
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004116/*[clinic input]
4117_ssl._SSLContext.load_dh_params
4118 path as filepath: object
4119 /
4120
4121[clinic start generated code]*/
4122
Antoine Pitrou152efa22010-05-16 18:19:27 +00004123static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004124_ssl__SSLContext_load_dh_params(PySSLContext *self, PyObject *filepath)
4125/*[clinic end generated code: output=1c8e57a38e055af0 input=c8871f3c796ae1d6]*/
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004126{
4127 FILE *f;
4128 DH *dh;
4129
Victor Stinnerdaf45552013-08-28 00:53:59 +02004130 f = _Py_fopen_obj(filepath, "rb");
Victor Stinnere42ccd22015-03-18 01:39:23 +01004131 if (f == NULL)
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004132 return NULL;
Victor Stinnere42ccd22015-03-18 01:39:23 +01004133
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004134 errno = 0;
4135 PySSL_BEGIN_ALLOW_THREADS
4136 dh = PEM_read_DHparams(f, NULL, NULL, NULL);
Antoine Pitrou457a2292013-01-12 21:43:45 +01004137 fclose(f);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004138 PySSL_END_ALLOW_THREADS
4139 if (dh == NULL) {
4140 if (errno != 0) {
4141 ERR_clear_error();
4142 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
4143 }
4144 else {
Christian Heimes7f1305e2021-04-17 20:06:38 +02004145 _setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004146 }
4147 return NULL;
4148 }
Zackery Spytzaebc0492020-07-07 22:21:58 -06004149 if (!SSL_CTX_set_tmp_dh(self->ctx, dh)) {
4150 DH_free(dh);
Christian Heimes7f1305e2021-04-17 20:06:38 +02004151 return _setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
Zackery Spytzaebc0492020-07-07 22:21:58 -06004152 }
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004153 DH_free(dh);
4154 Py_RETURN_NONE;
4155}
4156
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004157/*[clinic input]
4158_ssl._SSLContext._wrap_socket
Christian Heimes7f1305e2021-04-17 20:06:38 +02004159 sock: object(subclass_of="get_state_ctx(self)->Sock_Type")
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004160 server_side: int
4161 server_hostname as hostname_obj: object = None
Christian Heimes141c5e82018-02-24 21:10:57 +01004162 *
4163 owner: object = None
4164 session: object = None
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004165
4166[clinic start generated code]*/
4167
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004168static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004169_ssl__SSLContext__wrap_socket_impl(PySSLContext *self, PyObject *sock,
Christian Heimes141c5e82018-02-24 21:10:57 +01004170 int server_side, PyObject *hostname_obj,
4171 PyObject *owner, PyObject *session)
Christian Heimes7f1305e2021-04-17 20:06:38 +02004172/*[clinic end generated code: output=f103f238633940b4 input=f5916eadbc6eae81]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004173{
Antoine Pitroud5323212010-10-22 18:19:07 +00004174 char *hostname = NULL;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004175 PyObject *res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004176
Antoine Pitroud5323212010-10-22 18:19:07 +00004177 /* server_hostname is either None (or absent), or to be encoded
Christian Heimesd02ac252018-03-25 12:36:13 +02004178 as IDN A-label (ASCII str) without NULL bytes. */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004179 if (hostname_obj != Py_None) {
Christian Heimes11a14932018-02-24 02:35:08 +01004180 if (!PyArg_Parse(hostname_obj, "es", "ascii", &hostname))
Antoine Pitroud5323212010-10-22 18:19:07 +00004181 return NULL;
Antoine Pitroud5323212010-10-22 18:19:07 +00004182 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00004183
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004184 res = (PyObject *) newPySSLSocket(self, (PySocketSockObject *)sock,
4185 server_side, hostname,
Christian Heimes141c5e82018-02-24 21:10:57 +01004186 owner, session,
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004187 NULL, NULL);
Antoine Pitroud5323212010-10-22 18:19:07 +00004188 if (hostname != NULL)
4189 PyMem_Free(hostname);
4190 return res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004191}
4192
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004193/*[clinic input]
4194_ssl._SSLContext._wrap_bio
Christian Heimes7f1305e2021-04-17 20:06:38 +02004195 incoming: object(subclass_of="get_state_ctx(self)->PySSLMemoryBIO_Type", type="PySSLMemoryBIO *")
4196 outgoing: object(subclass_of="get_state_ctx(self)->PySSLMemoryBIO_Type", type="PySSLMemoryBIO *")
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004197 server_side: int
4198 server_hostname as hostname_obj: object = None
Christian Heimes141c5e82018-02-24 21:10:57 +01004199 *
4200 owner: object = None
4201 session: object = None
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004202
4203[clinic start generated code]*/
4204
Antoine Pitroub0182c82010-10-12 20:09:02 +00004205static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004206_ssl__SSLContext__wrap_bio_impl(PySSLContext *self, PySSLMemoryBIO *incoming,
4207 PySSLMemoryBIO *outgoing, int server_side,
Christian Heimes141c5e82018-02-24 21:10:57 +01004208 PyObject *hostname_obj, PyObject *owner,
4209 PyObject *session)
Christian Heimes7f1305e2021-04-17 20:06:38 +02004210/*[clinic end generated code: output=5c5d6d9b41f99332 input=331edeec9c738382]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004211{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004212 char *hostname = NULL;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004213 PyObject *res;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004214
4215 /* server_hostname is either None (or absent), or to be encoded
Christian Heimesd02ac252018-03-25 12:36:13 +02004216 as IDN A-label (ASCII str) without NULL bytes. */
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004217 if (hostname_obj != Py_None) {
Christian Heimes11a14932018-02-24 02:35:08 +01004218 if (!PyArg_Parse(hostname_obj, "es", "ascii", &hostname))
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004219 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004220 }
4221
4222 res = (PyObject *) newPySSLSocket(self, NULL, server_side, hostname,
Christian Heimes141c5e82018-02-24 21:10:57 +01004223 owner, session,
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004224 incoming, outgoing);
4225
4226 PyMem_Free(hostname);
4227 return res;
4228}
4229
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004230/*[clinic input]
4231_ssl._SSLContext.session_stats
4232[clinic start generated code]*/
4233
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004234static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004235_ssl__SSLContext_session_stats_impl(PySSLContext *self)
4236/*[clinic end generated code: output=0d96411c42893bfb input=7e0a81fb11102c8b]*/
Antoine Pitroub0182c82010-10-12 20:09:02 +00004237{
4238 int r;
4239 PyObject *value, *stats = PyDict_New();
4240 if (!stats)
4241 return NULL;
4242
4243#define ADD_STATS(SSL_NAME, KEY_NAME) \
4244 value = PyLong_FromLong(SSL_CTX_sess_ ## SSL_NAME (self->ctx)); \
4245 if (value == NULL) \
4246 goto error; \
4247 r = PyDict_SetItemString(stats, KEY_NAME, value); \
4248 Py_DECREF(value); \
4249 if (r < 0) \
4250 goto error;
4251
4252 ADD_STATS(number, "number");
4253 ADD_STATS(connect, "connect");
4254 ADD_STATS(connect_good, "connect_good");
4255 ADD_STATS(connect_renegotiate, "connect_renegotiate");
4256 ADD_STATS(accept, "accept");
4257 ADD_STATS(accept_good, "accept_good");
4258 ADD_STATS(accept_renegotiate, "accept_renegotiate");
4259 ADD_STATS(accept, "accept");
4260 ADD_STATS(hits, "hits");
4261 ADD_STATS(misses, "misses");
4262 ADD_STATS(timeouts, "timeouts");
4263 ADD_STATS(cache_full, "cache_full");
4264
4265#undef ADD_STATS
4266
4267 return stats;
4268
4269error:
4270 Py_DECREF(stats);
4271 return NULL;
4272}
4273
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004274/*[clinic input]
4275_ssl._SSLContext.set_default_verify_paths
4276[clinic start generated code]*/
4277
Antoine Pitrou664c2d12010-11-17 20:29:42 +00004278static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004279_ssl__SSLContext_set_default_verify_paths_impl(PySSLContext *self)
4280/*[clinic end generated code: output=0bee74e6e09deaaa input=35f3408021463d74]*/
Antoine Pitrou664c2d12010-11-17 20:29:42 +00004281{
4282 if (!SSL_CTX_set_default_verify_paths(self->ctx)) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02004283 _setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
Antoine Pitrou664c2d12010-11-17 20:29:42 +00004284 return NULL;
4285 }
4286 Py_RETURN_NONE;
4287}
4288
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004289/*[clinic input]
4290_ssl._SSLContext.set_ecdh_curve
4291 name: object
4292 /
4293
4294[clinic start generated code]*/
4295
Antoine Pitrou923df6f2011-12-19 17:16:51 +01004296static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004297_ssl__SSLContext_set_ecdh_curve(PySSLContext *self, PyObject *name)
4298/*[clinic end generated code: output=23022c196e40d7d2 input=c2bafb6f6e34726b]*/
Antoine Pitrou923df6f2011-12-19 17:16:51 +01004299{
4300 PyObject *name_bytes;
4301 int nid;
4302 EC_KEY *key;
4303
4304 if (!PyUnicode_FSConverter(name, &name_bytes))
4305 return NULL;
4306 assert(PyBytes_Check(name_bytes));
4307 nid = OBJ_sn2nid(PyBytes_AS_STRING(name_bytes));
4308 Py_DECREF(name_bytes);
4309 if (nid == 0) {
4310 PyErr_Format(PyExc_ValueError,
4311 "unknown elliptic curve name %R", name);
4312 return NULL;
4313 }
4314 key = EC_KEY_new_by_curve_name(nid);
4315 if (key == NULL) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02004316 _setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
Antoine Pitrou923df6f2011-12-19 17:16:51 +01004317 return NULL;
4318 }
4319 SSL_CTX_set_tmp_ecdh(self->ctx, key);
4320 EC_KEY_free(key);
4321 Py_RETURN_NONE;
4322}
4323
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004324static int
4325_servername_callback(SSL *s, int *al, void *args)
4326{
4327 int ret;
Christian Heimes7f1305e2021-04-17 20:06:38 +02004328 PySSLContext *sslctx = (PySSLContext *) args;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004329 PySSLSocket *ssl;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004330 PyObject *result;
4331 /* The high-level ssl.SSLSocket object */
4332 PyObject *ssl_socket;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004333 const char *servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
Stefan Krah20d60802013-01-17 17:07:17 +01004334 PyGILState_STATE gstate = PyGILState_Ensure();
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004335
Christian Heimes7f1305e2021-04-17 20:06:38 +02004336 if (sslctx->set_sni_cb == NULL) {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004337 /* remove race condition in this the call back while if removing the
4338 * callback is in progress */
4339 PyGILState_Release(gstate);
Antoine Pitrou5dd12a52013-01-06 15:25:36 +01004340 return SSL_TLSEXT_ERR_OK;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004341 }
4342
4343 ssl = SSL_get_app_data(s);
Christian Heimes7f1305e2021-04-17 20:06:38 +02004344 assert(Py_IS_TYPE(ssl, get_state_ctx(sslctx)->PySSLSocket_Type));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004345
Serhiy Storchakaf51d7152015-11-02 14:40:41 +02004346 /* The servername callback expects an argument that represents the current
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004347 * SSL connection and that has a .context attribute that can be changed to
4348 * identify the requested hostname. Since the official API is the Python
4349 * level API we want to pass the callback a Python level object rather than
4350 * a _ssl.SSLSocket instance. If there's an "owner" (typically an
4351 * SSLObject) that will be passed. Otherwise if there's a socket then that
4352 * will be passed. If both do not exist only then the C-level object is
4353 * passed. */
4354 if (ssl->owner)
4355 ssl_socket = PyWeakref_GetObject(ssl->owner);
4356 else if (ssl->Socket)
4357 ssl_socket = PyWeakref_GetObject(ssl->Socket);
4358 else
4359 ssl_socket = (PyObject *) ssl;
4360
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004361 Py_INCREF(ssl_socket);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004362 if (ssl_socket == Py_None)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004363 goto error;
Victor Stinner7e001512013-06-25 00:44:31 +02004364
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004365 if (servername == NULL) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02004366 result = PyObject_CallFunctionObjArgs(sslctx->set_sni_cb, ssl_socket,
4367 Py_None, sslctx, NULL);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004368 }
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004369 else {
Christian Heimes11a14932018-02-24 02:35:08 +01004370 PyObject *servername_bytes;
4371 PyObject *servername_str;
4372
4373 servername_bytes = PyBytes_FromString(servername);
4374 if (servername_bytes == NULL) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02004375 PyErr_WriteUnraisable((PyObject *) sslctx);
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004376 goto error;
4377 }
Christian Heimes11a14932018-02-24 02:35:08 +01004378 /* server_hostname was encoded to an A-label by our caller; put it
4379 * back into a str object, but still as an A-label (bpo-28414)
4380 */
4381 servername_str = PyUnicode_FromEncodedObject(servername_bytes, "ascii", NULL);
Christian Heimes11a14932018-02-24 02:35:08 +01004382 if (servername_str == NULL) {
4383 PyErr_WriteUnraisable(servername_bytes);
Zackery Spytzee96f322020-07-09 04:00:21 -06004384 Py_DECREF(servername_bytes);
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004385 goto error;
4386 }
Zackery Spytzee96f322020-07-09 04:00:21 -06004387 Py_DECREF(servername_bytes);
Christian Heimes11a14932018-02-24 02:35:08 +01004388 result = PyObject_CallFunctionObjArgs(
Christian Heimes7f1305e2021-04-17 20:06:38 +02004389 sslctx->set_sni_cb, ssl_socket, servername_str,
4390 sslctx, NULL);
Christian Heimes11a14932018-02-24 02:35:08 +01004391 Py_DECREF(servername_str);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004392 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004393 Py_DECREF(ssl_socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004394
4395 if (result == NULL) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02004396 PyErr_WriteUnraisable(sslctx->set_sni_cb);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004397 *al = SSL_AD_HANDSHAKE_FAILURE;
4398 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
4399 }
4400 else {
Christian Heimes11a14932018-02-24 02:35:08 +01004401 /* Result may be None, a SSLContext or an integer
4402 * None and SSLContext are OK, integer or other values are an error.
4403 */
4404 if (result == Py_None) {
4405 ret = SSL_TLSEXT_ERR_OK;
4406 } else {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004407 *al = (int) PyLong_AsLong(result);
4408 if (PyErr_Occurred()) {
4409 PyErr_WriteUnraisable(result);
4410 *al = SSL_AD_INTERNAL_ERROR;
4411 }
4412 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
4413 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004414 Py_DECREF(result);
4415 }
4416
4417 PyGILState_Release(gstate);
4418 return ret;
4419
4420error:
4421 Py_DECREF(ssl_socket);
4422 *al = SSL_AD_INTERNAL_ERROR;
4423 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
4424 PyGILState_Release(gstate);
4425 return ret;
4426}
4427
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004428static PyObject *
Christian Heimes11a14932018-02-24 02:35:08 +01004429get_sni_callback(PySSLContext *self, void *c)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004430{
Christian Heimes11a14932018-02-24 02:35:08 +01004431 PyObject *cb = self->set_sni_cb;
4432 if (cb == NULL) {
4433 Py_RETURN_NONE;
4434 }
4435 Py_INCREF(cb);
4436 return cb;
4437}
4438
4439static int
4440set_sni_callback(PySSLContext *self, PyObject *arg, void *c)
4441{
4442 if (self->protocol == PY_SSL_VERSION_TLS_CLIENT) {
4443 PyErr_SetString(PyExc_ValueError,
4444 "sni_callback cannot be set on TLS_CLIENT context");
4445 return -1;
4446 }
Christian Heimes11a14932018-02-24 02:35:08 +01004447 Py_CLEAR(self->set_sni_cb);
4448 if (arg == Py_None) {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004449 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
4450 }
4451 else {
Christian Heimes11a14932018-02-24 02:35:08 +01004452 if (!PyCallable_Check(arg)) {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004453 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
4454 PyErr_SetString(PyExc_TypeError,
4455 "not a callable object");
Christian Heimes11a14932018-02-24 02:35:08 +01004456 return -1;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004457 }
Christian Heimes11a14932018-02-24 02:35:08 +01004458 Py_INCREF(arg);
4459 self->set_sni_cb = arg;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004460 SSL_CTX_set_tlsext_servername_callback(self->ctx, _servername_callback);
4461 SSL_CTX_set_tlsext_servername_arg(self->ctx, self);
4462 }
Christian Heimes11a14932018-02-24 02:35:08 +01004463 return 0;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004464}
4465
Christian Heimes11a14932018-02-24 02:35:08 +01004466PyDoc_STRVAR(PySSLContext_sni_callback_doc,
4467"Set a callback that will be called when a server name is provided by the SSL/TLS client in the SNI extension.\n\
4468\n\
4469If the argument is None then the callback is disabled. The method is called\n\
4470with the SSLSocket, the server name as a string, and the SSLContext object.\n\
4471See RFC 6066 for details of the SNI extension.");
4472
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004473/*[clinic input]
4474_ssl._SSLContext.cert_store_stats
4475
4476Returns quantities of loaded X.509 certificates.
4477
4478X.509 certificates with a CA extension and certificate revocation lists
4479inside the context's cert store.
4480
4481NOTE: Certificates in a capath directory aren't loaded unless they have
4482been used at least once.
4483[clinic start generated code]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004484
4485static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004486_ssl__SSLContext_cert_store_stats_impl(PySSLContext *self)
4487/*[clinic end generated code: output=5f356f4d9cca874d input=eb40dd0f6d0e40cf]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004488{
4489 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02004490 STACK_OF(X509_OBJECT) *objs;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004491 X509_OBJECT *obj;
Christian Heimes598894f2016-09-05 23:19:05 +02004492 int x509 = 0, crl = 0, ca = 0, i;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004493
4494 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02004495 objs = X509_STORE_get0_objects(store);
4496 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
4497 obj = sk_X509_OBJECT_value(objs, i);
4498 switch (X509_OBJECT_get_type(obj)) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004499 case X509_LU_X509:
4500 x509++;
Christian Heimes598894f2016-09-05 23:19:05 +02004501 if (X509_check_ca(X509_OBJECT_get0_X509(obj))) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004502 ca++;
4503 }
4504 break;
4505 case X509_LU_CRL:
4506 crl++;
4507 break;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004508 default:
4509 /* Ignore X509_LU_FAIL, X509_LU_RETRY, X509_LU_PKEY.
4510 * As far as I can tell they are internal states and never
4511 * stored in a cert store */
4512 break;
4513 }
4514 }
4515 return Py_BuildValue("{sisisi}", "x509", x509, "crl", crl,
4516 "x509_ca", ca);
4517}
4518
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004519/*[clinic input]
4520_ssl._SSLContext.get_ca_certs
4521 binary_form: bool = False
4522
4523Returns a list of dicts with information of loaded CA certs.
4524
4525If the optional argument is True, returns a DER-encoded copy of the CA
4526certificate.
4527
4528NOTE: Certificates in a capath directory aren't loaded unless they have
4529been used at least once.
4530[clinic start generated code]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004531
4532static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004533_ssl__SSLContext_get_ca_certs_impl(PySSLContext *self, int binary_form)
4534/*[clinic end generated code: output=0d58f148f37e2938 input=6887b5a09b7f9076]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004535{
4536 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02004537 STACK_OF(X509_OBJECT) *objs;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004538 PyObject *ci = NULL, *rlist = NULL;
4539 int i;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004540
4541 if ((rlist = PyList_New(0)) == NULL) {
4542 return NULL;
4543 }
4544
4545 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02004546 objs = X509_STORE_get0_objects(store);
4547 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004548 X509_OBJECT *obj;
4549 X509 *cert;
4550
Christian Heimes598894f2016-09-05 23:19:05 +02004551 obj = sk_X509_OBJECT_value(objs, i);
4552 if (X509_OBJECT_get_type(obj) != X509_LU_X509) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004553 /* not a x509 cert */
4554 continue;
4555 }
4556 /* CA for any purpose */
Christian Heimes598894f2016-09-05 23:19:05 +02004557 cert = X509_OBJECT_get0_X509(obj);
Christian Heimes9a5395a2013-06-17 15:44:12 +02004558 if (!X509_check_ca(cert)) {
4559 continue;
4560 }
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004561 if (binary_form) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02004562 ci = _certificate_to_der(get_state_ctx(self), cert);
Christian Heimes9a5395a2013-06-17 15:44:12 +02004563 } else {
Christian Heimes7f1305e2021-04-17 20:06:38 +02004564 ci = _decode_certificate(get_state_ctx(self), cert);
Christian Heimes9a5395a2013-06-17 15:44:12 +02004565 }
4566 if (ci == NULL) {
4567 goto error;
4568 }
4569 if (PyList_Append(rlist, ci) == -1) {
4570 goto error;
4571 }
4572 Py_CLEAR(ci);
4573 }
4574 return rlist;
4575
4576 error:
4577 Py_XDECREF(ci);
4578 Py_XDECREF(rlist);
4579 return NULL;
4580}
4581
4582
Antoine Pitrou152efa22010-05-16 18:19:27 +00004583static PyGetSetDef context_getsetlist[] = {
Christian Heimes1aa9a752013-12-02 02:41:19 +01004584 {"check_hostname", (getter) get_check_hostname,
4585 (setter) set_check_hostname, NULL},
Christian Heimes61d478c2018-01-27 15:51:38 +01004586 {"_host_flags", (getter) get_host_flags,
4587 (setter) set_host_flags, NULL},
Christian Heimes698dde12018-02-27 11:54:43 +01004588 {"minimum_version", (getter) get_minimum_version,
4589 (setter) set_minimum_version, NULL},
4590 {"maximum_version", (getter) get_maximum_version,
4591 (setter) set_maximum_version, NULL},
Christian Heimesc7f70692019-05-31 11:44:05 +02004592 {"keylog_filename", (getter) _PySSLContext_get_keylog_filename,
4593 (setter) _PySSLContext_set_keylog_filename, NULL},
Christian Heimesc7f70692019-05-31 11:44:05 +02004594 {"_msg_callback", (getter) _PySSLContext_get_msg_callback,
4595 (setter) _PySSLContext_set_msg_callback, NULL},
Christian Heimes11a14932018-02-24 02:35:08 +01004596 {"sni_callback", (getter) get_sni_callback,
Christian Heimes698dde12018-02-27 11:54:43 +01004597 (setter) set_sni_callback, PySSLContext_sni_callback_doc},
Christian Heimes39258d32021-04-17 11:36:35 +02004598#ifdef TLS1_3_VERSION
Christian Heimes78c7d522019-06-03 21:00:10 +02004599 {"num_tickets", (getter) get_num_tickets,
4600 (setter) set_num_tickets, PySSLContext_num_tickets_doc},
4601#endif
Antoine Pitroub5218772010-05-21 09:56:06 +00004602 {"options", (getter) get_options,
4603 (setter) set_options, NULL},
Christian Heimes9fb051f2018-09-23 08:32:31 +02004604 {"post_handshake_auth", (getter) get_post_handshake_auth,
4605#ifdef TLS1_3_VERSION
4606 (setter) set_post_handshake_auth,
4607#else
4608 NULL,
4609#endif
4610 NULL},
Christian Heimes11a14932018-02-24 02:35:08 +01004611 {"protocol", (getter) get_protocol,
4612 NULL, NULL},
Christian Heimes22587792013-11-21 23:56:13 +01004613 {"verify_flags", (getter) get_verify_flags,
4614 (setter) set_verify_flags, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00004615 {"verify_mode", (getter) get_verify_mode,
4616 (setter) set_verify_mode, NULL},
matthewhughes9348e836bb2020-07-17 09:59:15 +01004617 {"security_level", (getter) get_security_level,
4618 NULL, PySSLContext_security_level_doc},
Antoine Pitrou152efa22010-05-16 18:19:27 +00004619 {NULL}, /* sentinel */
4620};
4621
4622static struct PyMethodDef context_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004623 _SSL__SSLCONTEXT__WRAP_SOCKET_METHODDEF
4624 _SSL__SSLCONTEXT__WRAP_BIO_METHODDEF
4625 _SSL__SSLCONTEXT_SET_CIPHERS_METHODDEF
4626 _SSL__SSLCONTEXT__SET_ALPN_PROTOCOLS_METHODDEF
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004627 _SSL__SSLCONTEXT_LOAD_CERT_CHAIN_METHODDEF
4628 _SSL__SSLCONTEXT_LOAD_DH_PARAMS_METHODDEF
4629 _SSL__SSLCONTEXT_LOAD_VERIFY_LOCATIONS_METHODDEF
4630 _SSL__SSLCONTEXT_SESSION_STATS_METHODDEF
4631 _SSL__SSLCONTEXT_SET_DEFAULT_VERIFY_PATHS_METHODDEF
4632 _SSL__SSLCONTEXT_SET_ECDH_CURVE_METHODDEF
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004633 _SSL__SSLCONTEXT_CERT_STORE_STATS_METHODDEF
4634 _SSL__SSLCONTEXT_GET_CA_CERTS_METHODDEF
Christian Heimes25bfcd52016-09-06 00:04:45 +02004635 _SSL__SSLCONTEXT_GET_CIPHERS_METHODDEF
Antoine Pitrou152efa22010-05-16 18:19:27 +00004636 {NULL, NULL} /* sentinel */
4637};
4638
Christian Heimes5c36da72020-11-20 09:40:12 +01004639static PyType_Slot PySSLContext_slots[] = {
4640 {Py_tp_methods, context_methods},
4641 {Py_tp_getset, context_getsetlist},
4642 {Py_tp_new, _ssl__SSLContext},
4643 {Py_tp_dealloc, context_dealloc},
4644 {Py_tp_traverse, context_traverse},
4645 {Py_tp_clear, context_clear},
4646 {0, 0},
4647};
4648
4649static PyType_Spec PySSLContext_spec = {
Miss Islington (bot)ea47a8a2021-05-27 09:25:22 -07004650 .name = "_ssl._SSLContext",
4651 .basicsize = sizeof(PySSLContext),
4652 .flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC |
4653 Py_TPFLAGS_IMMUTABLETYPE),
4654 .slots = PySSLContext_slots,
Antoine Pitrou152efa22010-05-16 18:19:27 +00004655};
4656
4657
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004658/*
4659 * MemoryBIO objects
4660 */
4661
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004662/*[clinic input]
4663@classmethod
4664_ssl.MemoryBIO.__new__
4665
4666[clinic start generated code]*/
4667
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004668static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004669_ssl_MemoryBIO_impl(PyTypeObject *type)
4670/*[clinic end generated code: output=8820a58db78330ac input=26d22e4909ecb1b5]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004671{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004672 BIO *bio;
4673 PySSLMemoryBIO *self;
4674
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004675 bio = BIO_new(BIO_s_mem());
4676 if (bio == NULL) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02004677 PyErr_SetString(PyExc_MemoryError, "failed to allocate BIO");
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004678 return NULL;
4679 }
4680 /* Since our BIO is non-blocking an empty read() does not indicate EOF,
4681 * just that no data is currently available. The SSL routines should retry
4682 * the read, which we can achieve by calling BIO_set_retry_read(). */
4683 BIO_set_retry_read(bio);
4684 BIO_set_mem_eof_return(bio, -1);
4685
4686 assert(type != NULL && type->tp_alloc != NULL);
4687 self = (PySSLMemoryBIO *) type->tp_alloc(type, 0);
4688 if (self == NULL) {
4689 BIO_free(bio);
4690 return NULL;
4691 }
4692 self->bio = bio;
4693 self->eof_written = 0;
4694
4695 return (PyObject *) self;
4696}
4697
Miss Islington (bot)ea47a8a2021-05-27 09:25:22 -07004698static int
4699memory_bio_traverse(PySSLMemoryBIO *self, visitproc visit, void *arg)
4700{
4701 Py_VISIT(Py_TYPE(self));
4702 return 0;
4703}
4704
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004705static void
4706memory_bio_dealloc(PySSLMemoryBIO *self)
4707{
Christian Heimes5c36da72020-11-20 09:40:12 +01004708 PyTypeObject *tp = Py_TYPE(self);
Miss Islington (bot)ea47a8a2021-05-27 09:25:22 -07004709 PyObject_GC_UnTrack(self);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004710 BIO_free(self->bio);
4711 Py_TYPE(self)->tp_free(self);
Christian Heimes5c36da72020-11-20 09:40:12 +01004712 Py_DECREF(tp);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004713}
4714
4715static PyObject *
4716memory_bio_get_pending(PySSLMemoryBIO *self, void *c)
4717{
Segev Finer5cff6372017-07-27 01:19:17 +03004718 return PyLong_FromSize_t(BIO_ctrl_pending(self->bio));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004719}
4720
4721PyDoc_STRVAR(PySSL_memory_bio_pending_doc,
4722"The number of bytes pending in the memory BIO.");
4723
4724static PyObject *
4725memory_bio_get_eof(PySSLMemoryBIO *self, void *c)
4726{
4727 return PyBool_FromLong((BIO_ctrl_pending(self->bio) == 0)
4728 && self->eof_written);
4729}
4730
4731PyDoc_STRVAR(PySSL_memory_bio_eof_doc,
4732"Whether the memory BIO is at EOF.");
4733
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004734/*[clinic input]
4735_ssl.MemoryBIO.read
4736 size as len: int = -1
4737 /
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004738
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004739Read up to size bytes from the memory BIO.
4740
4741If size is not specified, read the entire buffer.
4742If the return value is an empty bytes instance, this means either
4743EOF or that no data is available. Use the "eof" property to
4744distinguish between the two.
4745[clinic start generated code]*/
4746
4747static PyObject *
4748_ssl_MemoryBIO_read_impl(PySSLMemoryBIO *self, int len)
4749/*[clinic end generated code: output=a657aa1e79cd01b3 input=574d7be06a902366]*/
4750{
4751 int avail, nbytes;
4752 PyObject *result;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004753
Segev Finer5cff6372017-07-27 01:19:17 +03004754 avail = (int)Py_MIN(BIO_ctrl_pending(self->bio), INT_MAX);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004755 if ((len < 0) || (len > avail))
4756 len = avail;
4757
4758 result = PyBytes_FromStringAndSize(NULL, len);
4759 if ((result == NULL) || (len == 0))
4760 return result;
4761
4762 nbytes = BIO_read(self->bio, PyBytes_AS_STRING(result), len);
Zackery Spytz365ad2e2018-10-06 11:41:45 -06004763 if (nbytes < 0) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02004764 _sslmodulestate *state = get_state_mbio(self);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004765 Py_DECREF(result);
Christian Heimes7f1305e2021-04-17 20:06:38 +02004766 _setSSLError(state, NULL, 0, __FILE__, __LINE__);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004767 return NULL;
4768 }
4769
Zackery Spytz365ad2e2018-10-06 11:41:45 -06004770 /* There should never be any short reads but check anyway. */
4771 if (nbytes < len) {
4772 _PyBytes_Resize(&result, nbytes);
4773 }
4774
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004775 return result;
4776}
4777
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004778/*[clinic input]
4779_ssl.MemoryBIO.write
4780 b: Py_buffer
4781 /
4782
4783Writes the bytes b into the memory BIO.
4784
4785Returns the number of bytes written.
4786[clinic start generated code]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004787
4788static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004789_ssl_MemoryBIO_write_impl(PySSLMemoryBIO *self, Py_buffer *b)
4790/*[clinic end generated code: output=156ec59110d75935 input=e45757b3e17c4808]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004791{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004792 int nbytes;
4793
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004794 if (b->len > INT_MAX) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004795 PyErr_Format(PyExc_OverflowError,
4796 "string longer than %d bytes", INT_MAX);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004797 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004798 }
4799
4800 if (self->eof_written) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02004801 PyObject *module = PyType_GetModule(Py_TYPE(self));
4802 if (module == NULL)
4803 return NULL;
4804 PyErr_SetString(get_ssl_state(module)->PySSLErrorObject,
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004805 "cannot write() after write_eof()");
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004806 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004807 }
4808
Segev Finer5cff6372017-07-27 01:19:17 +03004809 nbytes = BIO_write(self->bio, b->buf, (int)b->len);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004810 if (nbytes < 0) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02004811 _sslmodulestate *state = get_state_mbio(self);
4812 _setSSLError(state, NULL, 0, __FILE__, __LINE__);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004813 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004814 }
4815
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004816 return PyLong_FromLong(nbytes);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004817}
4818
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004819/*[clinic input]
4820_ssl.MemoryBIO.write_eof
4821
4822Write an EOF marker to the memory BIO.
4823
4824When all data has been read, the "eof" property will be True.
4825[clinic start generated code]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004826
4827static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004828_ssl_MemoryBIO_write_eof_impl(PySSLMemoryBIO *self)
4829/*[clinic end generated code: output=d4106276ccd1ed34 input=56a945f1d29e8bd6]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004830{
4831 self->eof_written = 1;
4832 /* After an EOF is written, a zero return from read() should be a real EOF
4833 * i.e. it should not be retried. Clear the SHOULD_RETRY flag. */
4834 BIO_clear_retry_flags(self->bio);
4835 BIO_set_mem_eof_return(self->bio, 0);
4836
4837 Py_RETURN_NONE;
4838}
4839
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004840static PyGetSetDef memory_bio_getsetlist[] = {
4841 {"pending", (getter) memory_bio_get_pending, NULL,
4842 PySSL_memory_bio_pending_doc},
4843 {"eof", (getter) memory_bio_get_eof, NULL,
4844 PySSL_memory_bio_eof_doc},
4845 {NULL}, /* sentinel */
4846};
4847
4848static struct PyMethodDef memory_bio_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004849 _SSL_MEMORYBIO_READ_METHODDEF
4850 _SSL_MEMORYBIO_WRITE_METHODDEF
4851 _SSL_MEMORYBIO_WRITE_EOF_METHODDEF
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004852 {NULL, NULL} /* sentinel */
4853};
4854
Christian Heimes5c36da72020-11-20 09:40:12 +01004855static PyType_Slot PySSLMemoryBIO_slots[] = {
4856 {Py_tp_methods, memory_bio_methods},
4857 {Py_tp_getset, memory_bio_getsetlist},
4858 {Py_tp_new, _ssl_MemoryBIO},
4859 {Py_tp_dealloc, memory_bio_dealloc},
Miss Islington (bot)ea47a8a2021-05-27 09:25:22 -07004860 {Py_tp_traverse, memory_bio_traverse},
Christian Heimes5c36da72020-11-20 09:40:12 +01004861 {0, 0},
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004862};
4863
Christian Heimes5c36da72020-11-20 09:40:12 +01004864static PyType_Spec PySSLMemoryBIO_spec = {
Miss Islington (bot)ea47a8a2021-05-27 09:25:22 -07004865 .name = "_ssl.MemoryBIO",
4866 .basicsize = sizeof(PySSLMemoryBIO),
4867 .flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_IMMUTABLETYPE |
4868 Py_TPFLAGS_HAVE_GC),
4869 .slots = PySSLMemoryBIO_slots,
Christian Heimes5c36da72020-11-20 09:40:12 +01004870};
Antoine Pitrou152efa22010-05-16 18:19:27 +00004871
Christian Heimes99a65702016-09-10 23:44:53 +02004872/*
4873 * SSL Session object
4874 */
4875
4876static void
4877PySSLSession_dealloc(PySSLSession *self)
4878{
Christian Heimes5c36da72020-11-20 09:40:12 +01004879 PyTypeObject *tp = Py_TYPE(self);
INADA Naokia6296d32017-08-24 14:55:17 +09004880 /* bpo-31095: UnTrack is needed before calling any callbacks */
Christian Heimesa5d07652016-09-24 10:48:05 +02004881 PyObject_GC_UnTrack(self);
Christian Heimes99a65702016-09-10 23:44:53 +02004882 Py_XDECREF(self->ctx);
4883 if (self->session != NULL) {
4884 SSL_SESSION_free(self->session);
4885 }
Christian Heimesa5d07652016-09-24 10:48:05 +02004886 PyObject_GC_Del(self);
Christian Heimes5c36da72020-11-20 09:40:12 +01004887 Py_DECREF(tp);
Christian Heimes99a65702016-09-10 23:44:53 +02004888}
4889
4890static PyObject *
4891PySSLSession_richcompare(PyObject *left, PyObject *right, int op)
4892{
4893 int result;
Christian Heimes7f1305e2021-04-17 20:06:38 +02004894 PyTypeObject *sesstype = ((PySSLSession*)left)->ctx->state->PySSLSession_Type;
Christian Heimes99a65702016-09-10 23:44:53 +02004895
4896 if (left == NULL || right == NULL) {
4897 PyErr_BadInternalCall();
4898 return NULL;
4899 }
4900
Christian Heimes7f1305e2021-04-17 20:06:38 +02004901 if (!Py_IS_TYPE(left, sesstype) || !Py_IS_TYPE(right, sesstype)) {
Christian Heimes99a65702016-09-10 23:44:53 +02004902 Py_RETURN_NOTIMPLEMENTED;
4903 }
4904
4905 if (left == right) {
4906 result = 0;
4907 } else {
4908 const unsigned char *left_id, *right_id;
4909 unsigned int left_len, right_len;
4910 left_id = SSL_SESSION_get_id(((PySSLSession *)left)->session,
4911 &left_len);
4912 right_id = SSL_SESSION_get_id(((PySSLSession *)right)->session,
4913 &right_len);
4914 if (left_len == right_len) {
4915 result = memcmp(left_id, right_id, left_len);
4916 } else {
4917 result = 1;
4918 }
4919 }
4920
4921 switch (op) {
4922 case Py_EQ:
4923 if (result == 0) {
4924 Py_RETURN_TRUE;
4925 } else {
4926 Py_RETURN_FALSE;
4927 }
4928 break;
4929 case Py_NE:
4930 if (result != 0) {
4931 Py_RETURN_TRUE;
4932 } else {
4933 Py_RETURN_FALSE;
4934 }
4935 break;
4936 case Py_LT:
4937 case Py_LE:
4938 case Py_GT:
4939 case Py_GE:
4940 Py_RETURN_NOTIMPLEMENTED;
4941 break;
4942 default:
4943 PyErr_BadArgument();
4944 return NULL;
4945 }
4946}
4947
4948static int
4949PySSLSession_traverse(PySSLSession *self, visitproc visit, void *arg)
4950{
4951 Py_VISIT(self->ctx);
Miss Islington (bot)ea47a8a2021-05-27 09:25:22 -07004952 Py_VISIT(Py_TYPE(self));
Christian Heimes99a65702016-09-10 23:44:53 +02004953 return 0;
4954}
4955
4956static int
4957PySSLSession_clear(PySSLSession *self)
4958{
4959 Py_CLEAR(self->ctx);
4960 return 0;
4961}
4962
4963
4964static PyObject *
4965PySSLSession_get_time(PySSLSession *self, void *closure) {
4966 return PyLong_FromLong(SSL_SESSION_get_time(self->session));
4967}
4968
4969PyDoc_STRVAR(PySSLSession_get_time_doc,
4970"Session creation time (seconds since epoch).");
4971
4972
4973static PyObject *
4974PySSLSession_get_timeout(PySSLSession *self, void *closure) {
4975 return PyLong_FromLong(SSL_SESSION_get_timeout(self->session));
4976}
4977
4978PyDoc_STRVAR(PySSLSession_get_timeout_doc,
4979"Session timeout (delta in seconds).");
4980
4981
4982static PyObject *
4983PySSLSession_get_ticket_lifetime_hint(PySSLSession *self, void *closure) {
4984 unsigned long hint = SSL_SESSION_get_ticket_lifetime_hint(self->session);
4985 return PyLong_FromUnsignedLong(hint);
4986}
4987
4988PyDoc_STRVAR(PySSLSession_get_ticket_lifetime_hint_doc,
4989"Ticket life time hint.");
4990
4991
4992static PyObject *
4993PySSLSession_get_session_id(PySSLSession *self, void *closure) {
4994 const unsigned char *id;
4995 unsigned int len;
4996 id = SSL_SESSION_get_id(self->session, &len);
4997 return PyBytes_FromStringAndSize((const char *)id, len);
4998}
4999
5000PyDoc_STRVAR(PySSLSession_get_session_id_doc,
5001"Session id");
5002
5003
5004static PyObject *
5005PySSLSession_get_has_ticket(PySSLSession *self, void *closure) {
5006 if (SSL_SESSION_has_ticket(self->session)) {
5007 Py_RETURN_TRUE;
5008 } else {
5009 Py_RETURN_FALSE;
5010 }
5011}
5012
5013PyDoc_STRVAR(PySSLSession_get_has_ticket_doc,
5014"Does the session contain a ticket?");
5015
5016
5017static PyGetSetDef PySSLSession_getsetlist[] = {
5018 {"has_ticket", (getter) PySSLSession_get_has_ticket, NULL,
5019 PySSLSession_get_has_ticket_doc},
5020 {"id", (getter) PySSLSession_get_session_id, NULL,
5021 PySSLSession_get_session_id_doc},
5022 {"ticket_lifetime_hint", (getter) PySSLSession_get_ticket_lifetime_hint,
5023 NULL, PySSLSession_get_ticket_lifetime_hint_doc},
5024 {"time", (getter) PySSLSession_get_time, NULL,
5025 PySSLSession_get_time_doc},
5026 {"timeout", (getter) PySSLSession_get_timeout, NULL,
5027 PySSLSession_get_timeout_doc},
5028 {NULL}, /* sentinel */
5029};
5030
Christian Heimes5c36da72020-11-20 09:40:12 +01005031static PyType_Slot PySSLSession_slots[] = {
5032 {Py_tp_getset,PySSLSession_getsetlist},
5033 {Py_tp_richcompare, PySSLSession_richcompare},
5034 {Py_tp_dealloc, PySSLSession_dealloc},
5035 {Py_tp_traverse, PySSLSession_traverse},
5036 {Py_tp_clear, PySSLSession_clear},
5037 {0, 0},
5038};
5039
5040static PyType_Spec PySSLSession_spec = {
Miss Islington (bot)ea47a8a2021-05-27 09:25:22 -07005041 .name = "_ssl.SSLSession",
5042 .basicsize = sizeof(PySSLSession),
5043 .flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
5044 Py_TPFLAGS_IMMUTABLETYPE),
5045 .slots = PySSLSession_slots,
Christian Heimes99a65702016-09-10 23:44:53 +02005046};
5047
5048
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005049/* helper routines for seeding the SSL PRNG */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005050/*[clinic input]
5051_ssl.RAND_add
Larry Hastingsdbfdc382015-05-04 06:59:46 -07005052 string as view: Py_buffer(accept={str, buffer})
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005053 entropy: double
5054 /
5055
5056Mix string into the OpenSSL PRNG state.
5057
5058entropy (a float) is a lower bound on the entropy contained in
Chandan Kumar63c2c8a2017-06-09 15:13:58 +05305059string. See RFC 4086.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005060[clinic start generated code]*/
5061
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005062static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005063_ssl_RAND_add_impl(PyObject *module, Py_buffer *view, double entropy)
Serhiy Storchaka5f31d5c2017-06-10 13:13:51 +03005064/*[clinic end generated code: output=e6dd48df9c9024e9 input=5c33017422828f5c]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005065{
Serhiy Storchaka8490f5a2015-03-20 09:00:36 +02005066 const char *buf;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02005067 Py_ssize_t len, written;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005068
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005069 buf = (const char *)view->buf;
5070 len = view->len;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02005071 do {
5072 written = Py_MIN(len, INT_MAX);
5073 RAND_add(buf, (int)written, entropy);
5074 buf += written;
5075 len -= written;
5076 } while (len);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02005077 Py_RETURN_NONE;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005078}
5079
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005080static PyObject *
Christian Heimes7f1305e2021-04-17 20:06:38 +02005081PySSL_RAND(PyObject *module, int len, int pseudo)
Victor Stinner99c8b162011-05-24 12:05:19 +02005082{
5083 int ok;
5084 PyObject *bytes;
5085 unsigned long err;
5086 const char *errstr;
5087 PyObject *v;
5088
Victor Stinner1e81a392013-12-19 16:47:04 +01005089 if (len < 0) {
5090 PyErr_SetString(PyExc_ValueError, "num must be positive");
5091 return NULL;
5092 }
5093
Victor Stinner99c8b162011-05-24 12:05:19 +02005094 bytes = PyBytes_FromStringAndSize(NULL, len);
5095 if (bytes == NULL)
5096 return NULL;
5097 if (pseudo) {
Christian Heimesa871f692020-06-01 08:58:14 +02005098 ok = RAND_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
Victor Stinner99c8b162011-05-24 12:05:19 +02005099 if (ok == 0 || ok == 1)
5100 return Py_BuildValue("NO", bytes, ok == 1 ? Py_True : Py_False);
5101 }
5102 else {
5103 ok = RAND_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
5104 if (ok == 1)
5105 return bytes;
5106 }
5107 Py_DECREF(bytes);
5108
5109 err = ERR_get_error();
5110 errstr = ERR_reason_error_string(err);
5111 v = Py_BuildValue("(ks)", err, errstr);
5112 if (v != NULL) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02005113 PyErr_SetObject(get_ssl_state(module)->PySSLErrorObject, v);
Victor Stinner99c8b162011-05-24 12:05:19 +02005114 Py_DECREF(v);
5115 }
5116 return NULL;
5117}
5118
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005119/*[clinic input]
5120_ssl.RAND_bytes
5121 n: int
5122 /
5123
5124Generate n cryptographically strong pseudo-random bytes.
5125[clinic start generated code]*/
5126
Victor Stinner99c8b162011-05-24 12:05:19 +02005127static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005128_ssl_RAND_bytes_impl(PyObject *module, int n)
5129/*[clinic end generated code: output=977da635e4838bc7 input=678ddf2872dfebfc]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02005130{
Christian Heimes7f1305e2021-04-17 20:06:38 +02005131 return PySSL_RAND(module, n, 0);
Victor Stinner99c8b162011-05-24 12:05:19 +02005132}
5133
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005134/*[clinic input]
5135_ssl.RAND_pseudo_bytes
5136 n: int
5137 /
5138
5139Generate n pseudo-random bytes.
5140
5141Return a pair (bytes, is_cryptographic). is_cryptographic is True
5142if the bytes generated are cryptographically strong.
5143[clinic start generated code]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02005144
5145static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005146_ssl_RAND_pseudo_bytes_impl(PyObject *module, int n)
5147/*[clinic end generated code: output=b1509e937000e52d input=58312bd53f9bbdd0]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02005148{
Christian Heimes2875c602021-04-19 07:27:10 +02005149 PY_SSL_DEPRECATED("RAND_pseudo_bytes", 1, NULL);
Christian Heimes7f1305e2021-04-17 20:06:38 +02005150 return PySSL_RAND(module, n, 1);
Victor Stinner99c8b162011-05-24 12:05:19 +02005151}
5152
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005153/*[clinic input]
5154_ssl.RAND_status
5155
Zackery Spytz7d37b862021-04-23 10:07:37 -06005156Returns True if the OpenSSL PRNG has been seeded with enough data and False if not.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005157
5158It is necessary to seed the PRNG with RAND_add() on some platforms before
5159using the ssl() function.
5160[clinic start generated code]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02005161
5162static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005163_ssl_RAND_status_impl(PyObject *module)
Zackery Spytz7d37b862021-04-23 10:07:37 -06005164/*[clinic end generated code: output=7e0aaa2d39fdc1ad input=d5ae5aea52f36e01]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005165{
Zackery Spytz7d37b862021-04-23 10:07:37 -06005166 return PyBool_FromLong(RAND_status());
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005167}
5168
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005169/*[clinic input]
5170_ssl.get_default_verify_paths
5171
5172Return search paths and environment vars that are used by SSLContext's set_default_verify_paths() to load default CAs.
5173
5174The values are 'cert_file_env', 'cert_file', 'cert_dir_env', 'cert_dir'.
5175[clinic start generated code]*/
Christian Heimes6d7ad132013-06-09 18:02:55 +02005176
5177static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005178_ssl_get_default_verify_paths_impl(PyObject *module)
5179/*[clinic end generated code: output=e5b62a466271928b input=5210c953d98c3eb5]*/
Christian Heimes6d7ad132013-06-09 18:02:55 +02005180{
5181 PyObject *ofile_env = NULL;
5182 PyObject *ofile = NULL;
5183 PyObject *odir_env = NULL;
5184 PyObject *odir = NULL;
5185
Benjamin Petersond113c962015-07-18 10:59:13 -07005186#define CONVERT(info, target) { \
Christian Heimes6d7ad132013-06-09 18:02:55 +02005187 const char *tmp = (info); \
5188 target = NULL; \
5189 if (!tmp) { Py_INCREF(Py_None); target = Py_None; } \
5190 else if ((target = PyUnicode_DecodeFSDefault(tmp)) == NULL) { \
5191 target = PyBytes_FromString(tmp); } \
5192 if (!target) goto error; \
Benjamin Peterson025a1fd2015-11-14 15:12:38 -08005193 }
Christian Heimes6d7ad132013-06-09 18:02:55 +02005194
Benjamin Petersond113c962015-07-18 10:59:13 -07005195 CONVERT(X509_get_default_cert_file_env(), ofile_env);
5196 CONVERT(X509_get_default_cert_file(), ofile);
5197 CONVERT(X509_get_default_cert_dir_env(), odir_env);
5198 CONVERT(X509_get_default_cert_dir(), odir);
5199#undef CONVERT
Christian Heimes6d7ad132013-06-09 18:02:55 +02005200
Christian Heimes200bb1b2013-06-14 15:14:29 +02005201 return Py_BuildValue("NNNN", ofile_env, ofile, odir_env, odir);
Christian Heimes6d7ad132013-06-09 18:02:55 +02005202
5203 error:
5204 Py_XDECREF(ofile_env);
5205 Py_XDECREF(ofile);
5206 Py_XDECREF(odir_env);
5207 Py_XDECREF(odir);
5208 return NULL;
5209}
5210
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005211static PyObject*
Christian Heimes7f1305e2021-04-17 20:06:38 +02005212asn1obj2py(_sslmodulestate *state, ASN1_OBJECT *obj)
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005213{
5214 int nid;
5215 const char *ln, *sn;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005216
5217 nid = OBJ_obj2nid(obj);
5218 if (nid == NID_undef) {
5219 PyErr_Format(PyExc_ValueError, "Unknown object");
5220 return NULL;
5221 }
5222 sn = OBJ_nid2sn(nid);
5223 ln = OBJ_nid2ln(nid);
Christian Heimes7f1305e2021-04-17 20:06:38 +02005224 return Py_BuildValue("issN", nid, sn, ln, _asn1obj2py(state, obj, 1));
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005225}
5226
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005227/*[clinic input]
5228_ssl.txt2obj
5229 txt: str
5230 name: bool = False
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005231
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005232Lookup NID, short name, long name and OID of an ASN1_OBJECT.
5233
5234By default objects are looked up by OID. With name=True short and
5235long name are also matched.
5236[clinic start generated code]*/
5237
5238static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005239_ssl_txt2obj_impl(PyObject *module, const char *txt, int name)
5240/*[clinic end generated code: output=c38e3991347079c1 input=1c1e7d0aa7c48602]*/
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005241{
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005242 PyObject *result = NULL;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005243 ASN1_OBJECT *obj;
5244
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005245 obj = OBJ_txt2obj(txt, name ? 0 : 1);
5246 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01005247 PyErr_Format(PyExc_ValueError, "unknown object '%.100s'", txt);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005248 return NULL;
5249 }
Christian Heimes7f1305e2021-04-17 20:06:38 +02005250 result = asn1obj2py(get_ssl_state(module), obj);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005251 ASN1_OBJECT_free(obj);
5252 return result;
5253}
5254
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005255/*[clinic input]
5256_ssl.nid2obj
5257 nid: int
5258 /
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005259
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005260Lookup NID, short name, long name and OID of an ASN1_OBJECT by NID.
5261[clinic start generated code]*/
5262
5263static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005264_ssl_nid2obj_impl(PyObject *module, int nid)
5265/*[clinic end generated code: output=4a98ab691cd4f84a input=51787a3bee7d8f98]*/
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005266{
5267 PyObject *result = NULL;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005268 ASN1_OBJECT *obj;
5269
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005270 if (nid < NID_undef) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01005271 PyErr_SetString(PyExc_ValueError, "NID must be positive.");
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005272 return NULL;
5273 }
5274 obj = OBJ_nid2obj(nid);
5275 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01005276 PyErr_Format(PyExc_ValueError, "unknown NID %i", nid);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005277 return NULL;
5278 }
Christian Heimes7f1305e2021-04-17 20:06:38 +02005279 result = asn1obj2py(get_ssl_state(module), obj);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005280 ASN1_OBJECT_free(obj);
5281 return result;
5282}
5283
Christian Heimes46bebee2013-06-09 19:03:31 +02005284#ifdef _MSC_VER
Christian Heimes44109d72013-11-22 01:51:30 +01005285
5286static PyObject*
5287certEncodingType(DWORD encodingType)
5288{
5289 static PyObject *x509_asn = NULL;
5290 static PyObject *pkcs_7_asn = NULL;
5291
5292 if (x509_asn == NULL) {
5293 x509_asn = PyUnicode_InternFromString("x509_asn");
5294 if (x509_asn == NULL)
5295 return NULL;
5296 }
5297 if (pkcs_7_asn == NULL) {
5298 pkcs_7_asn = PyUnicode_InternFromString("pkcs_7_asn");
5299 if (pkcs_7_asn == NULL)
5300 return NULL;
5301 }
5302 switch(encodingType) {
5303 case X509_ASN_ENCODING:
5304 Py_INCREF(x509_asn);
5305 return x509_asn;
5306 case PKCS_7_ASN_ENCODING:
5307 Py_INCREF(pkcs_7_asn);
5308 return pkcs_7_asn;
5309 default:
5310 return PyLong_FromLong(encodingType);
5311 }
5312}
5313
5314static PyObject*
5315parseKeyUsage(PCCERT_CONTEXT pCertCtx, DWORD flags)
5316{
5317 CERT_ENHKEY_USAGE *usage;
5318 DWORD size, error, i;
5319 PyObject *retval;
5320
5321 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, NULL, &size)) {
5322 error = GetLastError();
5323 if (error == CRYPT_E_NOT_FOUND) {
5324 Py_RETURN_TRUE;
5325 }
5326 return PyErr_SetFromWindowsErr(error);
5327 }
5328
5329 usage = (CERT_ENHKEY_USAGE*)PyMem_Malloc(size);
5330 if (usage == NULL) {
5331 return PyErr_NoMemory();
5332 }
5333
5334 /* Now get the actual enhanced usage property */
5335 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, usage, &size)) {
5336 PyMem_Free(usage);
5337 error = GetLastError();
5338 if (error == CRYPT_E_NOT_FOUND) {
5339 Py_RETURN_TRUE;
5340 }
5341 return PyErr_SetFromWindowsErr(error);
5342 }
Christian Heimes915cd3f2019-09-09 18:06:55 +02005343 retval = PyFrozenSet_New(NULL);
Christian Heimes44109d72013-11-22 01:51:30 +01005344 if (retval == NULL) {
5345 goto error;
5346 }
5347 for (i = 0; i < usage->cUsageIdentifier; ++i) {
5348 if (usage->rgpszUsageIdentifier[i]) {
5349 PyObject *oid;
5350 int err;
5351 oid = PyUnicode_FromString(usage->rgpszUsageIdentifier[i]);
5352 if (oid == NULL) {
5353 Py_CLEAR(retval);
5354 goto error;
5355 }
5356 err = PySet_Add(retval, oid);
5357 Py_DECREF(oid);
5358 if (err == -1) {
5359 Py_CLEAR(retval);
5360 goto error;
5361 }
5362 }
5363 }
5364 error:
5365 PyMem_Free(usage);
5366 return retval;
5367}
5368
kctherookied93fbbf2019-03-29 00:59:06 +07005369static HCERTSTORE
5370ssl_collect_certificates(const char *store_name)
5371{
5372/* this function collects the system certificate stores listed in
5373 * system_stores into a collection certificate store for being
5374 * enumerated. The store must be readable to be added to the
5375 * store collection.
5376 */
5377
5378 HCERTSTORE hCollectionStore = NULL, hSystemStore = NULL;
5379 static DWORD system_stores[] = {
5380 CERT_SYSTEM_STORE_LOCAL_MACHINE,
5381 CERT_SYSTEM_STORE_LOCAL_MACHINE_ENTERPRISE,
5382 CERT_SYSTEM_STORE_LOCAL_MACHINE_GROUP_POLICY,
5383 CERT_SYSTEM_STORE_CURRENT_USER,
5384 CERT_SYSTEM_STORE_CURRENT_USER_GROUP_POLICY,
5385 CERT_SYSTEM_STORE_SERVICES,
5386 CERT_SYSTEM_STORE_USERS};
5387 size_t i, storesAdded;
5388 BOOL result;
5389
5390 hCollectionStore = CertOpenStore(CERT_STORE_PROV_COLLECTION, 0,
5391 (HCRYPTPROV)NULL, 0, NULL);
5392 if (!hCollectionStore) {
5393 return NULL;
5394 }
5395 storesAdded = 0;
5396 for (i = 0; i < sizeof(system_stores) / sizeof(DWORD); i++) {
5397 hSystemStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0,
5398 (HCRYPTPROV)NULL,
5399 CERT_STORE_READONLY_FLAG |
5400 system_stores[i], store_name);
5401 if (hSystemStore) {
5402 result = CertAddStoreToCollection(hCollectionStore, hSystemStore,
5403 CERT_PHYSICAL_STORE_ADD_ENABLE_FLAG, 0);
5404 if (result) {
5405 ++storesAdded;
5406 }
neoneneed701292019-09-09 21:33:43 +09005407 CertCloseStore(hSystemStore, 0); /* flag must be 0 */
kctherookied93fbbf2019-03-29 00:59:06 +07005408 }
5409 }
5410 if (storesAdded == 0) {
5411 CertCloseStore(hCollectionStore, CERT_CLOSE_STORE_FORCE_FLAG);
5412 return NULL;
5413 }
5414
5415 return hCollectionStore;
5416}
5417
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005418/*[clinic input]
5419_ssl.enum_certificates
5420 store_name: str
5421
5422Retrieve certificates from Windows' cert store.
5423
5424store_name may be one of 'CA', 'ROOT' or 'MY'. The system may provide
5425more cert storages, too. The function returns a list of (bytes,
5426encoding_type, trust) tuples. The encoding_type flag can be interpreted
5427with X509_ASN_ENCODING or PKCS_7_ASN_ENCODING. The trust setting is either
5428a set of OIDs or the boolean True.
5429[clinic start generated code]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00005430
Christian Heimes46bebee2013-06-09 19:03:31 +02005431static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005432_ssl_enum_certificates_impl(PyObject *module, const char *store_name)
5433/*[clinic end generated code: output=5134dc8bb3a3c893 input=915f60d70461ea4e]*/
Christian Heimes46bebee2013-06-09 19:03:31 +02005434{
kctherookied93fbbf2019-03-29 00:59:06 +07005435 HCERTSTORE hCollectionStore = NULL;
Christian Heimes44109d72013-11-22 01:51:30 +01005436 PCCERT_CONTEXT pCertCtx = NULL;
5437 PyObject *keyusage = NULL, *cert = NULL, *enc = NULL, *tup = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02005438 PyObject *result = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02005439
Christian Heimes915cd3f2019-09-09 18:06:55 +02005440 result = PySet_New(NULL);
Christian Heimes44109d72013-11-22 01:51:30 +01005441 if (result == NULL) {
5442 return NULL;
5443 }
kctherookied93fbbf2019-03-29 00:59:06 +07005444 hCollectionStore = ssl_collect_certificates(store_name);
5445 if (hCollectionStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02005446 Py_DECREF(result);
5447 return PyErr_SetFromWindowsErr(GetLastError());
5448 }
5449
kctherookied93fbbf2019-03-29 00:59:06 +07005450 while (pCertCtx = CertEnumCertificatesInStore(hCollectionStore, pCertCtx)) {
Christian Heimes44109d72013-11-22 01:51:30 +01005451 cert = PyBytes_FromStringAndSize((const char*)pCertCtx->pbCertEncoded,
5452 pCertCtx->cbCertEncoded);
5453 if (!cert) {
5454 Py_CLEAR(result);
5455 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02005456 }
Christian Heimes44109d72013-11-22 01:51:30 +01005457 if ((enc = certEncodingType(pCertCtx->dwCertEncodingType)) == NULL) {
5458 Py_CLEAR(result);
5459 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02005460 }
Christian Heimes44109d72013-11-22 01:51:30 +01005461 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG);
5462 if (keyusage == Py_True) {
5463 Py_DECREF(keyusage);
5464 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_EXT_ONLY_ENHKEY_USAGE_FLAG);
Christian Heimes46bebee2013-06-09 19:03:31 +02005465 }
Christian Heimes44109d72013-11-22 01:51:30 +01005466 if (keyusage == NULL) {
5467 Py_CLEAR(result);
5468 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02005469 }
Christian Heimes44109d72013-11-22 01:51:30 +01005470 if ((tup = PyTuple_New(3)) == NULL) {
5471 Py_CLEAR(result);
5472 break;
5473 }
5474 PyTuple_SET_ITEM(tup, 0, cert);
5475 cert = NULL;
5476 PyTuple_SET_ITEM(tup, 1, enc);
5477 enc = NULL;
5478 PyTuple_SET_ITEM(tup, 2, keyusage);
5479 keyusage = NULL;
Christian Heimes915cd3f2019-09-09 18:06:55 +02005480 if (PySet_Add(result, tup) == -1) {
5481 Py_CLEAR(result);
5482 Py_CLEAR(tup);
5483 break;
Christian Heimes44109d72013-11-22 01:51:30 +01005484 }
5485 Py_CLEAR(tup);
5486 }
5487 if (pCertCtx) {
5488 /* loop ended with an error, need to clean up context manually */
5489 CertFreeCertificateContext(pCertCtx);
Christian Heimes46bebee2013-06-09 19:03:31 +02005490 }
5491
5492 /* In error cases cert, enc and tup may not be NULL */
5493 Py_XDECREF(cert);
5494 Py_XDECREF(enc);
Christian Heimes44109d72013-11-22 01:51:30 +01005495 Py_XDECREF(keyusage);
Christian Heimes46bebee2013-06-09 19:03:31 +02005496 Py_XDECREF(tup);
5497
kctherookied93fbbf2019-03-29 00:59:06 +07005498 /* CERT_CLOSE_STORE_FORCE_FLAG forces freeing of memory for all contexts
5499 associated with the store, in this case our collection store and the
5500 associated system stores. */
5501 if (!CertCloseStore(hCollectionStore, CERT_CLOSE_STORE_FORCE_FLAG)) {
Christian Heimes46bebee2013-06-09 19:03:31 +02005502 /* This error case might shadow another exception.*/
Christian Heimes44109d72013-11-22 01:51:30 +01005503 Py_XDECREF(result);
5504 return PyErr_SetFromWindowsErr(GetLastError());
5505 }
kctherookied93fbbf2019-03-29 00:59:06 +07005506
Christian Heimes915cd3f2019-09-09 18:06:55 +02005507 /* convert set to list */
5508 if (result == NULL) {
5509 return NULL;
5510 } else {
5511 PyObject *lst = PySequence_List(result);
5512 Py_DECREF(result);
5513 return lst;
5514 }
Christian Heimes44109d72013-11-22 01:51:30 +01005515}
5516
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005517/*[clinic input]
5518_ssl.enum_crls
5519 store_name: str
5520
5521Retrieve CRLs from Windows' cert store.
5522
5523store_name may be one of 'CA', 'ROOT' or 'MY'. The system may provide
5524more cert storages, too. The function returns a list of (bytes,
5525encoding_type) tuples. The encoding_type flag can be interpreted with
5526X509_ASN_ENCODING or PKCS_7_ASN_ENCODING.
5527[clinic start generated code]*/
Christian Heimes44109d72013-11-22 01:51:30 +01005528
5529static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005530_ssl_enum_crls_impl(PyObject *module, const char *store_name)
5531/*[clinic end generated code: output=bce467f60ccd03b6 input=a1f1d7629f1c5d3d]*/
Christian Heimes44109d72013-11-22 01:51:30 +01005532{
kctherookied93fbbf2019-03-29 00:59:06 +07005533 HCERTSTORE hCollectionStore = NULL;
Christian Heimes44109d72013-11-22 01:51:30 +01005534 PCCRL_CONTEXT pCrlCtx = NULL;
5535 PyObject *crl = NULL, *enc = NULL, *tup = NULL;
5536 PyObject *result = NULL;
5537
Christian Heimes915cd3f2019-09-09 18:06:55 +02005538 result = PySet_New(NULL);
Christian Heimes44109d72013-11-22 01:51:30 +01005539 if (result == NULL) {
5540 return NULL;
5541 }
kctherookied93fbbf2019-03-29 00:59:06 +07005542 hCollectionStore = ssl_collect_certificates(store_name);
5543 if (hCollectionStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02005544 Py_DECREF(result);
5545 return PyErr_SetFromWindowsErr(GetLastError());
5546 }
Christian Heimes44109d72013-11-22 01:51:30 +01005547
kctherookied93fbbf2019-03-29 00:59:06 +07005548 while (pCrlCtx = CertEnumCRLsInStore(hCollectionStore, pCrlCtx)) {
Christian Heimes44109d72013-11-22 01:51:30 +01005549 crl = PyBytes_FromStringAndSize((const char*)pCrlCtx->pbCrlEncoded,
5550 pCrlCtx->cbCrlEncoded);
5551 if (!crl) {
5552 Py_CLEAR(result);
5553 break;
5554 }
5555 if ((enc = certEncodingType(pCrlCtx->dwCertEncodingType)) == NULL) {
5556 Py_CLEAR(result);
5557 break;
5558 }
5559 if ((tup = PyTuple_New(2)) == NULL) {
5560 Py_CLEAR(result);
5561 break;
5562 }
5563 PyTuple_SET_ITEM(tup, 0, crl);
5564 crl = NULL;
5565 PyTuple_SET_ITEM(tup, 1, enc);
5566 enc = NULL;
5567
Christian Heimes915cd3f2019-09-09 18:06:55 +02005568 if (PySet_Add(result, tup) == -1) {
5569 Py_CLEAR(result);
5570 Py_CLEAR(tup);
5571 break;
Christian Heimes44109d72013-11-22 01:51:30 +01005572 }
5573 Py_CLEAR(tup);
Christian Heimes46bebee2013-06-09 19:03:31 +02005574 }
Christian Heimes44109d72013-11-22 01:51:30 +01005575 if (pCrlCtx) {
5576 /* loop ended with an error, need to clean up context manually */
5577 CertFreeCRLContext(pCrlCtx);
5578 }
5579
5580 /* In error cases cert, enc and tup may not be NULL */
5581 Py_XDECREF(crl);
5582 Py_XDECREF(enc);
5583 Py_XDECREF(tup);
5584
kctherookied93fbbf2019-03-29 00:59:06 +07005585 /* CERT_CLOSE_STORE_FORCE_FLAG forces freeing of memory for all contexts
5586 associated with the store, in this case our collection store and the
5587 associated system stores. */
5588 if (!CertCloseStore(hCollectionStore, CERT_CLOSE_STORE_FORCE_FLAG)) {
Christian Heimes44109d72013-11-22 01:51:30 +01005589 /* This error case might shadow another exception.*/
5590 Py_XDECREF(result);
5591 return PyErr_SetFromWindowsErr(GetLastError());
5592 }
Christian Heimes915cd3f2019-09-09 18:06:55 +02005593 /* convert set to list */
5594 if (result == NULL) {
5595 return NULL;
5596 } else {
5597 PyObject *lst = PySequence_List(result);
5598 Py_DECREF(result);
5599 return lst;
5600 }
Christian Heimes46bebee2013-06-09 19:03:31 +02005601}
Christian Heimes44109d72013-11-22 01:51:30 +01005602
5603#endif /* _MSC_VER */
Bill Janssen40a0f662008-08-12 16:56:25 +00005604
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005605/* List of functions exported by this module. */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005606static PyMethodDef PySSL_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005607 _SSL__TEST_DECODE_CERT_METHODDEF
5608 _SSL_RAND_ADD_METHODDEF
5609 _SSL_RAND_BYTES_METHODDEF
5610 _SSL_RAND_PSEUDO_BYTES_METHODDEF
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005611 _SSL_RAND_STATUS_METHODDEF
5612 _SSL_GET_DEFAULT_VERIFY_PATHS_METHODDEF
5613 _SSL_ENUM_CERTIFICATES_METHODDEF
5614 _SSL_ENUM_CRLS_METHODDEF
5615 _SSL_TXT2OBJ_METHODDEF
5616 _SSL_NID2OBJ_METHODDEF
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005617 {NULL, NULL} /* Sentinel */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005618};
5619
5620
Christian Heimes7f1305e2021-04-17 20:06:38 +02005621PyDoc_STRVAR(module_doc,
5622"Implementation module for SSL socket operations. See the socket module\n\
5623for documentation.");
Christian Heimes5c36da72020-11-20 09:40:12 +01005624
5625static int
5626sslmodule_init_exceptions(PyObject *module)
5627{
Christian Heimes7f1305e2021-04-17 20:06:38 +02005628 _sslmodulestate *state = get_ssl_state(module);
Christian Heimes5c36da72020-11-20 09:40:12 +01005629 PyObject *bases = NULL;
5630
Christian Heimes7f1305e2021-04-17 20:06:38 +02005631#define add_exception(exc, name, doc, base) \
5632do { \
5633 (exc) = PyErr_NewExceptionWithDoc("ssl." name, (doc), (base), NULL); \
5634 if ((state) == NULL) goto error; \
5635 if (PyModule_AddObjectRef(module, name, exc) < 0) goto error; \
Christian Heimes5c36da72020-11-20 09:40:12 +01005636} while(0)
5637
Christian Heimes7f1305e2021-04-17 20:06:38 +02005638 state->PySSLErrorObject = PyType_FromSpecWithBases(
5639 &sslerror_type_spec, PyExc_OSError);
5640 if (state->PySSLErrorObject == NULL) {
Christian Heimes5c36da72020-11-20 09:40:12 +01005641 goto error;
5642 }
Christian Heimes7f1305e2021-04-17 20:06:38 +02005643 if (PyModule_AddObjectRef(module, "SSLError", state->PySSLErrorObject) < 0) {
Christian Heimes5c36da72020-11-20 09:40:12 +01005644 goto error;
5645 }
5646
5647 /* ssl.CertificateError used to be a subclass of ValueError */
Christian Heimes7f1305e2021-04-17 20:06:38 +02005648 bases = PyTuple_Pack(2, state->PySSLErrorObject, PyExc_ValueError);
Christian Heimes5c36da72020-11-20 09:40:12 +01005649 if (bases == NULL) {
5650 goto error;
5651 }
5652 add_exception(
Christian Heimes7f1305e2021-04-17 20:06:38 +02005653 state->PySSLCertVerificationErrorObject,
Christian Heimes5c36da72020-11-20 09:40:12 +01005654 "SSLCertVerificationError",
5655 SSLCertVerificationError_doc,
5656 bases
5657 );
5658 Py_CLEAR(bases);
5659
5660 add_exception(
Christian Heimes7f1305e2021-04-17 20:06:38 +02005661 state->PySSLZeroReturnErrorObject,
Christian Heimes5c36da72020-11-20 09:40:12 +01005662 "SSLZeroReturnError",
5663 SSLZeroReturnError_doc,
Christian Heimes7f1305e2021-04-17 20:06:38 +02005664 state->PySSLErrorObject
Christian Heimes5c36da72020-11-20 09:40:12 +01005665 );
5666
5667 add_exception(
Christian Heimes7f1305e2021-04-17 20:06:38 +02005668 state->PySSLWantWriteErrorObject,
Christian Heimes5c36da72020-11-20 09:40:12 +01005669 "SSLWantWriteError",
5670 SSLWantWriteError_doc,
Christian Heimes7f1305e2021-04-17 20:06:38 +02005671 state->PySSLErrorObject
Christian Heimes5c36da72020-11-20 09:40:12 +01005672 );
5673
5674 add_exception(
Christian Heimes7f1305e2021-04-17 20:06:38 +02005675 state->PySSLWantReadErrorObject,
Christian Heimes5c36da72020-11-20 09:40:12 +01005676 "SSLWantReadError",
5677 SSLWantReadError_doc,
Christian Heimes7f1305e2021-04-17 20:06:38 +02005678 state->PySSLErrorObject
Christian Heimes5c36da72020-11-20 09:40:12 +01005679 );
5680
5681 add_exception(
Christian Heimes7f1305e2021-04-17 20:06:38 +02005682 state->PySSLSyscallErrorObject,
Christian Heimes5c36da72020-11-20 09:40:12 +01005683 "SSLSyscallError",
5684 SSLSyscallError_doc,
Christian Heimes7f1305e2021-04-17 20:06:38 +02005685 state->PySSLErrorObject
Christian Heimes5c36da72020-11-20 09:40:12 +01005686 );
5687
5688 add_exception(
Christian Heimes7f1305e2021-04-17 20:06:38 +02005689 state->PySSLEOFErrorObject,
Christian Heimes5c36da72020-11-20 09:40:12 +01005690 "SSLEOFError",
5691 SSLEOFError_doc,
Christian Heimes7f1305e2021-04-17 20:06:38 +02005692 state->PySSLErrorObject
Christian Heimes5c36da72020-11-20 09:40:12 +01005693 );
5694#undef add_exception
5695
5696 return 0;
5697 error:
5698 Py_XDECREF(bases);
5699 return -1;
5700}
5701
5702static int
5703sslmodule_init_socketapi(PyObject *module)
5704{
Christian Heimes7f1305e2021-04-17 20:06:38 +02005705 _sslmodulestate *state = get_ssl_state(module);
5706 PySocketModule_APIObject *sockmod = PySocketModule_ImportModuleAndAPI();
Christian Heimes5c36da72020-11-20 09:40:12 +01005707
Christian Heimes7f1305e2021-04-17 20:06:38 +02005708 if ((sockmod == NULL) || (sockmod->Sock_Type == NULL)) {
Christian Heimes5c36da72020-11-20 09:40:12 +01005709 return -1;
Christian Heimes5c36da72020-11-20 09:40:12 +01005710 }
Christian Heimes7f1305e2021-04-17 20:06:38 +02005711 state->Sock_Type = sockmod->Sock_Type;
5712 Py_INCREF(state->Sock_Type);
Christian Heimes5c36da72020-11-20 09:40:12 +01005713 return 0;
5714}
Christian Heimesc941e622017-09-05 15:47:11 +02005715
Christian Heimes5c36da72020-11-20 09:40:12 +01005716static int
5717sslmodule_init_constants(PyObject *m)
5718{
Christian Heimes7f1305e2021-04-17 20:06:38 +02005719
Christian Heimes892d66e2018-01-29 14:10:18 +01005720 PyModule_AddStringConstant(m, "_DEFAULT_CIPHERS",
5721 PY_SSL_DEFAULT_CIPHER_STRING);
5722
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005723 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
5724 PY_SSL_ERROR_ZERO_RETURN);
5725 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
5726 PY_SSL_ERROR_WANT_READ);
5727 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
5728 PY_SSL_ERROR_WANT_WRITE);
5729 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
5730 PY_SSL_ERROR_WANT_X509_LOOKUP);
5731 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
5732 PY_SSL_ERROR_SYSCALL);
5733 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
5734 PY_SSL_ERROR_SSL);
5735 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
5736 PY_SSL_ERROR_WANT_CONNECT);
5737 /* non ssl.h errorcodes */
5738 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
5739 PY_SSL_ERROR_EOF);
5740 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
5741 PY_SSL_ERROR_INVALID_ERROR_CODE);
5742 /* cert requirements */
5743 PyModule_AddIntConstant(m, "CERT_NONE",
5744 PY_SSL_CERT_NONE);
5745 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
5746 PY_SSL_CERT_OPTIONAL);
5747 PyModule_AddIntConstant(m, "CERT_REQUIRED",
5748 PY_SSL_CERT_REQUIRED);
Christian Heimes22587792013-11-21 23:56:13 +01005749 /* CRL verification for verification_flags */
5750 PyModule_AddIntConstant(m, "VERIFY_DEFAULT",
5751 0);
5752 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_LEAF",
5753 X509_V_FLAG_CRL_CHECK);
5754 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_CHAIN",
5755 X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
5756 PyModule_AddIntConstant(m, "VERIFY_X509_STRICT",
5757 X509_V_FLAG_X509_STRICT);
Chris Burre0b4aa02021-03-18 09:24:01 +01005758 PyModule_AddIntConstant(m, "VERIFY_ALLOW_PROXY_CERTS",
5759 X509_V_FLAG_ALLOW_PROXY_CERTS);
Benjamin Peterson990fcaa2015-03-04 22:49:41 -05005760 PyModule_AddIntConstant(m, "VERIFY_X509_TRUSTED_FIRST",
5761 X509_V_FLAG_TRUSTED_FIRST);
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00005762
l0x64d97522021-04-19 13:51:18 +02005763#ifdef X509_V_FLAG_PARTIAL_CHAIN
5764 PyModule_AddIntConstant(m, "VERIFY_X509_PARTIAL_CHAIN",
5765 X509_V_FLAG_PARTIAL_CHAIN);
5766#endif
5767
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01005768 /* Alert Descriptions from ssl.h */
5769 /* note RESERVED constants no longer intended for use have been removed */
5770 /* http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-6 */
5771
5772#define ADD_AD_CONSTANT(s) \
5773 PyModule_AddIntConstant(m, "ALERT_DESCRIPTION_"#s, \
5774 SSL_AD_##s)
5775
5776 ADD_AD_CONSTANT(CLOSE_NOTIFY);
5777 ADD_AD_CONSTANT(UNEXPECTED_MESSAGE);
5778 ADD_AD_CONSTANT(BAD_RECORD_MAC);
5779 ADD_AD_CONSTANT(RECORD_OVERFLOW);
5780 ADD_AD_CONSTANT(DECOMPRESSION_FAILURE);
5781 ADD_AD_CONSTANT(HANDSHAKE_FAILURE);
5782 ADD_AD_CONSTANT(BAD_CERTIFICATE);
5783 ADD_AD_CONSTANT(UNSUPPORTED_CERTIFICATE);
5784 ADD_AD_CONSTANT(CERTIFICATE_REVOKED);
5785 ADD_AD_CONSTANT(CERTIFICATE_EXPIRED);
5786 ADD_AD_CONSTANT(CERTIFICATE_UNKNOWN);
5787 ADD_AD_CONSTANT(ILLEGAL_PARAMETER);
5788 ADD_AD_CONSTANT(UNKNOWN_CA);
5789 ADD_AD_CONSTANT(ACCESS_DENIED);
5790 ADD_AD_CONSTANT(DECODE_ERROR);
5791 ADD_AD_CONSTANT(DECRYPT_ERROR);
5792 ADD_AD_CONSTANT(PROTOCOL_VERSION);
5793 ADD_AD_CONSTANT(INSUFFICIENT_SECURITY);
5794 ADD_AD_CONSTANT(INTERNAL_ERROR);
5795 ADD_AD_CONSTANT(USER_CANCELLED);
5796 ADD_AD_CONSTANT(NO_RENEGOTIATION);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01005797 /* Not all constants are in old OpenSSL versions */
Antoine Pitrou912fbff2013-03-30 16:29:32 +01005798#ifdef SSL_AD_UNSUPPORTED_EXTENSION
5799 ADD_AD_CONSTANT(UNSUPPORTED_EXTENSION);
5800#endif
5801#ifdef SSL_AD_CERTIFICATE_UNOBTAINABLE
5802 ADD_AD_CONSTANT(CERTIFICATE_UNOBTAINABLE);
5803#endif
5804#ifdef SSL_AD_UNRECOGNIZED_NAME
5805 ADD_AD_CONSTANT(UNRECOGNIZED_NAME);
5806#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01005807#ifdef SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE
5808 ADD_AD_CONSTANT(BAD_CERTIFICATE_STATUS_RESPONSE);
5809#endif
5810#ifdef SSL_AD_BAD_CERTIFICATE_HASH_VALUE
5811 ADD_AD_CONSTANT(BAD_CERTIFICATE_HASH_VALUE);
5812#endif
5813#ifdef SSL_AD_UNKNOWN_PSK_IDENTITY
5814 ADD_AD_CONSTANT(UNKNOWN_PSK_IDENTITY);
5815#endif
5816
5817#undef ADD_AD_CONSTANT
5818
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005819 /* protocol versions */
Victor Stinner3de49192011-05-09 00:42:58 +02005820#ifndef OPENSSL_NO_SSL2
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005821 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
5822 PY_SSL_VERSION_SSL2);
Victor Stinner3de49192011-05-09 00:42:58 +02005823#endif
Benjamin Petersone32467c2014-12-05 21:59:35 -05005824#ifndef OPENSSL_NO_SSL3
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005825 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
5826 PY_SSL_VERSION_SSL3);
Benjamin Petersone32467c2014-12-05 21:59:35 -05005827#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005828 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
Christian Heimes598894f2016-09-05 23:19:05 +02005829 PY_SSL_VERSION_TLS);
5830 PyModule_AddIntConstant(m, "PROTOCOL_TLS",
5831 PY_SSL_VERSION_TLS);
Christian Heimes5fe668c2016-09-12 00:01:11 +02005832 PyModule_AddIntConstant(m, "PROTOCOL_TLS_CLIENT",
5833 PY_SSL_VERSION_TLS_CLIENT);
5834 PyModule_AddIntConstant(m, "PROTOCOL_TLS_SERVER",
5835 PY_SSL_VERSION_TLS_SERVER);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005836 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
5837 PY_SSL_VERSION_TLS1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01005838 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_1",
5839 PY_SSL_VERSION_TLS1_1);
5840 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_2",
5841 PY_SSL_VERSION_TLS1_2);
Antoine Pitrou04f6a322010-04-05 21:40:07 +00005842
Antoine Pitroub5218772010-05-21 09:56:06 +00005843 /* protocol options */
Antoine Pitrou3f366312012-01-27 09:50:45 +01005844 PyModule_AddIntConstant(m, "OP_ALL",
5845 SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
Antoine Pitroub5218772010-05-21 09:56:06 +00005846 PyModule_AddIntConstant(m, "OP_NO_SSLv2", SSL_OP_NO_SSLv2);
5847 PyModule_AddIntConstant(m, "OP_NO_SSLv3", SSL_OP_NO_SSLv3);
5848 PyModule_AddIntConstant(m, "OP_NO_TLSv1", SSL_OP_NO_TLSv1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01005849 PyModule_AddIntConstant(m, "OP_NO_TLSv1_1", SSL_OP_NO_TLSv1_1);
5850 PyModule_AddIntConstant(m, "OP_NO_TLSv1_2", SSL_OP_NO_TLSv1_2);
Christian Heimescb5b68a2017-09-07 18:07:00 -07005851#ifdef SSL_OP_NO_TLSv1_3
5852 PyModule_AddIntConstant(m, "OP_NO_TLSv1_3", SSL_OP_NO_TLSv1_3);
5853#else
5854 PyModule_AddIntConstant(m, "OP_NO_TLSv1_3", 0);
5855#endif
Antoine Pitrou6db49442011-12-19 13:27:11 +01005856 PyModule_AddIntConstant(m, "OP_CIPHER_SERVER_PREFERENCE",
5857 SSL_OP_CIPHER_SERVER_PREFERENCE);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01005858 PyModule_AddIntConstant(m, "OP_SINGLE_DH_USE", SSL_OP_SINGLE_DH_USE);
Christian Heimes99a65702016-09-10 23:44:53 +02005859 PyModule_AddIntConstant(m, "OP_NO_TICKET", SSL_OP_NO_TICKET);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01005860#ifdef SSL_OP_SINGLE_ECDH_USE
Antoine Pitrou923df6f2011-12-19 17:16:51 +01005861 PyModule_AddIntConstant(m, "OP_SINGLE_ECDH_USE", SSL_OP_SINGLE_ECDH_USE);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01005862#endif
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01005863#ifdef SSL_OP_NO_COMPRESSION
5864 PyModule_AddIntConstant(m, "OP_NO_COMPRESSION",
5865 SSL_OP_NO_COMPRESSION);
5866#endif
Christian Heimes05d9fe32018-02-27 08:55:39 +01005867#ifdef SSL_OP_ENABLE_MIDDLEBOX_COMPAT
5868 PyModule_AddIntConstant(m, "OP_ENABLE_MIDDLEBOX_COMPAT",
5869 SSL_OP_ENABLE_MIDDLEBOX_COMPAT);
5870#endif
Christian Heimes67c48012018-05-15 16:25:40 -04005871#ifdef SSL_OP_NO_RENEGOTIATION
5872 PyModule_AddIntConstant(m, "OP_NO_RENEGOTIATION",
5873 SSL_OP_NO_RENEGOTIATION);
5874#endif
Christian Heimes6f37ebc2021-04-09 17:59:21 +02005875#ifdef SSL_OP_IGNORE_UNEXPECTED_EOF
5876 PyModule_AddIntConstant(m, "OP_IGNORE_UNEXPECTED_EOF",
5877 SSL_OP_IGNORE_UNEXPECTED_EOF);
5878#endif
Antoine Pitroub5218772010-05-21 09:56:06 +00005879
Christian Heimes61d478c2018-01-27 15:51:38 +01005880#ifdef X509_CHECK_FLAG_ALWAYS_CHECK_SUBJECT
5881 PyModule_AddIntConstant(m, "HOSTFLAG_ALWAYS_CHECK_SUBJECT",
5882 X509_CHECK_FLAG_ALWAYS_CHECK_SUBJECT);
5883#endif
5884#ifdef X509_CHECK_FLAG_NEVER_CHECK_SUBJECT
5885 PyModule_AddIntConstant(m, "HOSTFLAG_NEVER_CHECK_SUBJECT",
5886 X509_CHECK_FLAG_NEVER_CHECK_SUBJECT);
5887#endif
5888#ifdef X509_CHECK_FLAG_NO_WILDCARDS
5889 PyModule_AddIntConstant(m, "HOSTFLAG_NO_WILDCARDS",
5890 X509_CHECK_FLAG_NO_WILDCARDS);
5891#endif
5892#ifdef X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS
5893 PyModule_AddIntConstant(m, "HOSTFLAG_NO_PARTIAL_WILDCARDS",
5894 X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS);
5895#endif
5896#ifdef X509_CHECK_FLAG_MULTI_LABEL_WILDCARDS
5897 PyModule_AddIntConstant(m, "HOSTFLAG_MULTI_LABEL_WILDCARDS",
5898 X509_CHECK_FLAG_MULTI_LABEL_WILDCARDS);
5899#endif
5900#ifdef X509_CHECK_FLAG_SINGLE_LABEL_SUBDOMAINS
5901 PyModule_AddIntConstant(m, "HOSTFLAG_SINGLE_LABEL_SUBDOMAINS",
5902 X509_CHECK_FLAG_SINGLE_LABEL_SUBDOMAINS);
5903#endif
5904
Christian Heimes666991f2021-04-26 15:01:40 +02005905 /* file types */
5906 PyModule_AddIntConstant(m, "ENCODING_PEM", PY_SSL_ENCODING_PEM);
5907 PyModule_AddIntConstant(m, "ENCODING_DER", PY_SSL_ENCODING_DER);
5908
Christian Heimes698dde12018-02-27 11:54:43 +01005909 /* protocol versions */
5910 PyModule_AddIntConstant(m, "PROTO_MINIMUM_SUPPORTED",
5911 PY_PROTO_MINIMUM_SUPPORTED);
5912 PyModule_AddIntConstant(m, "PROTO_MAXIMUM_SUPPORTED",
5913 PY_PROTO_MAXIMUM_SUPPORTED);
5914 PyModule_AddIntConstant(m, "PROTO_SSLv3", PY_PROTO_SSLv3);
5915 PyModule_AddIntConstant(m, "PROTO_TLSv1", PY_PROTO_TLSv1);
5916 PyModule_AddIntConstant(m, "PROTO_TLSv1_1", PY_PROTO_TLSv1_1);
5917 PyModule_AddIntConstant(m, "PROTO_TLSv1_2", PY_PROTO_TLSv1_2);
5918 PyModule_AddIntConstant(m, "PROTO_TLSv1_3", PY_PROTO_TLSv1_3);
Antoine Pitroud5323212010-10-22 18:19:07 +00005919
Victor Stinnerb37672d2018-11-22 03:37:50 +01005920#define addbool(m, key, value) \
5921 do { \
5922 PyObject *bool_obj = (value) ? Py_True : Py_False; \
5923 Py_INCREF(bool_obj); \
5924 PyModule_AddObject((m), (key), bool_obj); \
5925 } while (0)
Christian Heimes698dde12018-02-27 11:54:43 +01005926
Christian Heimes698dde12018-02-27 11:54:43 +01005927 addbool(m, "HAS_SNI", 1);
Christian Heimes698dde12018-02-27 11:54:43 +01005928 addbool(m, "HAS_TLS_UNIQUE", 1);
Christian Heimes698dde12018-02-27 11:54:43 +01005929 addbool(m, "HAS_ECDH", 1);
Christian Heimes698dde12018-02-27 11:54:43 +01005930 addbool(m, "HAS_NPN", 0);
Christian Heimes698dde12018-02-27 11:54:43 +01005931 addbool(m, "HAS_ALPN", 1);
Christian Heimes698dde12018-02-27 11:54:43 +01005932
5933#if defined(SSL2_VERSION) && !defined(OPENSSL_NO_SSL2)
5934 addbool(m, "HAS_SSLv2", 1);
5935#else
5936 addbool(m, "HAS_SSLv2", 0);
5937#endif
5938
5939#if defined(SSL3_VERSION) && !defined(OPENSSL_NO_SSL3)
5940 addbool(m, "HAS_SSLv3", 1);
5941#else
5942 addbool(m, "HAS_SSLv3", 0);
5943#endif
5944
5945#if defined(TLS1_VERSION) && !defined(OPENSSL_NO_TLS1)
5946 addbool(m, "HAS_TLSv1", 1);
5947#else
5948 addbool(m, "HAS_TLSv1", 0);
5949#endif
5950
5951#if defined(TLS1_1_VERSION) && !defined(OPENSSL_NO_TLS1_1)
5952 addbool(m, "HAS_TLSv1_1", 1);
5953#else
5954 addbool(m, "HAS_TLSv1_1", 0);
5955#endif
5956
5957#if defined(TLS1_2_VERSION) && !defined(OPENSSL_NO_TLS1_2)
5958 addbool(m, "HAS_TLSv1_2", 1);
5959#else
5960 addbool(m, "HAS_TLSv1_2", 0);
5961#endif
Benjamin Petersoncca27322015-01-23 16:35:37 -05005962
Christian Heimescb5b68a2017-09-07 18:07:00 -07005963#if defined(TLS1_3_VERSION) && !defined(OPENSSL_NO_TLS1_3)
Christian Heimes698dde12018-02-27 11:54:43 +01005964 addbool(m, "HAS_TLSv1_3", 1);
Christian Heimescb5b68a2017-09-07 18:07:00 -07005965#else
Christian Heimes698dde12018-02-27 11:54:43 +01005966 addbool(m, "HAS_TLSv1_3", 0);
Christian Heimescb5b68a2017-09-07 18:07:00 -07005967#endif
Christian Heimescb5b68a2017-09-07 18:07:00 -07005968
Christian Heimes5c36da72020-11-20 09:40:12 +01005969 return 0;
5970}
5971
Christian Heimes7f1305e2021-04-17 20:06:38 +02005972static int
5973sslmodule_init_errorcodes(PyObject *module)
5974{
5975 _sslmodulestate *state = get_ssl_state(module);
Christian Heimes5c36da72020-11-20 09:40:12 +01005976
Christian Heimes7f1305e2021-04-17 20:06:38 +02005977 struct py_ssl_error_code *errcode;
5978 struct py_ssl_library_code *libcode;
Christian Heimes5c36da72020-11-20 09:40:12 +01005979
Christian Heimes7f1305e2021-04-17 20:06:38 +02005980 /* Mappings for error codes */
5981 state->err_codes_to_names = PyDict_New();
5982 if (state->err_codes_to_names == NULL)
5983 return -1;
5984 state->err_names_to_codes = PyDict_New();
5985 if (state->err_names_to_codes == NULL)
5986 return -1;
5987 state->lib_codes_to_names = PyDict_New();
5988 if (state->lib_codes_to_names == NULL)
5989 return -1;
5990
5991 errcode = error_codes;
5992 while (errcode->mnemonic != NULL) {
5993 PyObject *mnemo, *key;
5994 mnemo = PyUnicode_FromString(errcode->mnemonic);
5995 key = Py_BuildValue("ii", errcode->library, errcode->reason);
5996 if (mnemo == NULL || key == NULL)
5997 return -1;
5998 if (PyDict_SetItem(state->err_codes_to_names, key, mnemo))
5999 return -1;
6000 if (PyDict_SetItem(state->err_names_to_codes, mnemo, key))
6001 return -1;
6002 Py_DECREF(key);
6003 Py_DECREF(mnemo);
6004 errcode++;
6005 }
6006
6007 libcode = library_codes;
6008 while (libcode->library != NULL) {
6009 PyObject *mnemo, *key;
6010 key = PyLong_FromLong(libcode->code);
6011 mnemo = PyUnicode_FromString(libcode->library);
6012 if (key == NULL || mnemo == NULL)
6013 return -1;
6014 if (PyDict_SetItem(state->lib_codes_to_names, key, mnemo))
6015 return -1;
6016 Py_DECREF(key);
6017 Py_DECREF(mnemo);
6018 libcode++;
6019 }
6020
6021 if (PyModule_AddObjectRef(module, "err_codes_to_names", state->err_codes_to_names))
6022 return -1;
6023 if (PyModule_AddObjectRef(module, "err_names_to_codes", state->err_names_to_codes))
6024 return -1;
6025 if (PyModule_AddObjectRef(module, "lib_codes_to_names", state->lib_codes_to_names))
6026 return -1;
6027
6028 return 0;
6029}
6030
6031static void
6032parse_openssl_version(unsigned long libver,
6033 unsigned int *major, unsigned int *minor,
6034 unsigned int *fix, unsigned int *patch,
6035 unsigned int *status)
6036{
6037 *status = libver & 0xF;
6038 libver >>= 4;
6039 *patch = libver & 0xFF;
6040 libver >>= 8;
6041 *fix = libver & 0xFF;
6042 libver >>= 8;
6043 *minor = libver & 0xFF;
6044 libver >>= 8;
6045 *major = libver & 0xFF;
6046}
6047
6048static int
6049sslmodule_init_versioninfo(PyObject *m)
6050{
6051 PyObject *r;
6052 unsigned long libver;
6053 unsigned int major, minor, fix, patch, status;
6054
6055 /* OpenSSL version */
6056 /* SSLeay() gives us the version of the library linked against,
6057 which could be different from the headers version.
6058 */
6059 libver = OpenSSL_version_num();
6060 r = PyLong_FromUnsignedLong(libver);
6061 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r))
6062 return -1;
6063
6064 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
6065 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
6066 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r))
6067 return -1;
6068
6069 r = PyUnicode_FromString(OpenSSL_version(OPENSSL_VERSION));
6070 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r))
6071 return -1;
6072
6073 libver = OPENSSL_VERSION_NUMBER;
6074 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
6075 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
6076 if (r == NULL || PyModule_AddObject(m, "_OPENSSL_API_VERSION", r))
6077 return -1;
6078
6079 return 0;
6080}
6081
6082static int
6083sslmodule_init_types(PyObject *module)
6084{
6085 _sslmodulestate *state = get_ssl_state(module);
6086
6087 state->PySSLContext_Type = (PyTypeObject *)PyType_FromModuleAndSpec(
6088 module, &PySSLContext_spec, NULL
6089 );
6090 if (state->PySSLContext_Type == NULL)
6091 return -1;
6092
6093 state->PySSLSocket_Type = (PyTypeObject *)PyType_FromModuleAndSpec(
6094 module, &PySSLSocket_spec, NULL
6095 );
6096 if (state->PySSLSocket_Type == NULL)
6097 return -1;
6098
6099 state->PySSLMemoryBIO_Type = (PyTypeObject *)PyType_FromModuleAndSpec(
6100 module, &PySSLMemoryBIO_spec, NULL
6101 );
6102 if (state->PySSLMemoryBIO_Type == NULL)
6103 return -1;
6104
6105 state->PySSLSession_Type = (PyTypeObject *)PyType_FromModuleAndSpec(
6106 module, &PySSLSession_spec, NULL
6107 );
6108 if (state->PySSLSession_Type == NULL)
6109 return -1;
6110
Christian Heimes666991f2021-04-26 15:01:40 +02006111 state->PySSLCertificate_Type = (PyTypeObject *)PyType_FromModuleAndSpec(
6112 module, &PySSLCertificate_spec, NULL
6113 );
6114 if (state->PySSLCertificate_Type == NULL)
6115 return -1;
6116
Christian Heimes7f1305e2021-04-17 20:06:38 +02006117 if (PyModule_AddType(module, state->PySSLContext_Type))
6118 return -1;
6119 if (PyModule_AddType(module, state->PySSLSocket_Type))
6120 return -1;
6121 if (PyModule_AddType(module, state->PySSLMemoryBIO_Type))
6122 return -1;
6123 if (PyModule_AddType(module, state->PySSLSession_Type))
6124 return -1;
Christian Heimes666991f2021-04-26 15:01:40 +02006125 if (PyModule_AddType(module, state->PySSLCertificate_Type))
6126 return -1;
Christian Heimes7f1305e2021-04-17 20:06:38 +02006127 return 0;
6128}
6129
6130static PyModuleDef_Slot sslmodule_slots[] = {
6131 {Py_mod_exec, sslmodule_init_types},
6132 {Py_mod_exec, sslmodule_init_exceptions},
6133 {Py_mod_exec, sslmodule_init_socketapi},
6134 {Py_mod_exec, sslmodule_init_errorcodes},
6135 {Py_mod_exec, sslmodule_init_constants},
6136 {Py_mod_exec, sslmodule_init_versioninfo},
6137 {0, NULL}
6138};
6139
6140static int
6141sslmodule_traverse(PyObject *m, visitproc visit, void *arg)
6142{
6143 _sslmodulestate *state = get_ssl_state(m);
6144
6145 Py_VISIT(state->PySSLContext_Type);
6146 Py_VISIT(state->PySSLSocket_Type);
6147 Py_VISIT(state->PySSLMemoryBIO_Type);
6148 Py_VISIT(state->PySSLSession_Type);
Christian Heimes666991f2021-04-26 15:01:40 +02006149 Py_VISIT(state->PySSLCertificate_Type);
Christian Heimes7f1305e2021-04-17 20:06:38 +02006150 Py_VISIT(state->PySSLErrorObject);
6151 Py_VISIT(state->PySSLCertVerificationErrorObject);
6152 Py_VISIT(state->PySSLZeroReturnErrorObject);
6153 Py_VISIT(state->PySSLWantReadErrorObject);
6154 Py_VISIT(state->PySSLWantWriteErrorObject);
6155 Py_VISIT(state->PySSLSyscallErrorObject);
6156 Py_VISIT(state->PySSLEOFErrorObject);
6157 Py_VISIT(state->err_codes_to_names);
6158 Py_VISIT(state->err_names_to_codes);
6159 Py_VISIT(state->lib_codes_to_names);
6160 Py_VISIT(state->Sock_Type);
6161
6162 return 0;
6163}
6164
6165static int
6166sslmodule_clear(PyObject *m)
6167{
6168 _sslmodulestate *state = get_ssl_state(m);
6169
6170 Py_CLEAR(state->PySSLContext_Type);
6171 Py_CLEAR(state->PySSLSocket_Type);
6172 Py_CLEAR(state->PySSLMemoryBIO_Type);
6173 Py_CLEAR(state->PySSLSession_Type);
Christian Heimes666991f2021-04-26 15:01:40 +02006174 Py_CLEAR(state->PySSLCertificate_Type);
Christian Heimes7f1305e2021-04-17 20:06:38 +02006175 Py_CLEAR(state->PySSLErrorObject);
6176 Py_CLEAR(state->PySSLCertVerificationErrorObject);
6177 Py_CLEAR(state->PySSLZeroReturnErrorObject);
6178 Py_CLEAR(state->PySSLWantReadErrorObject);
6179 Py_CLEAR(state->PySSLWantWriteErrorObject);
6180 Py_CLEAR(state->PySSLSyscallErrorObject);
6181 Py_CLEAR(state->PySSLEOFErrorObject);
6182 Py_CLEAR(state->err_codes_to_names);
6183 Py_CLEAR(state->err_names_to_codes);
6184 Py_CLEAR(state->lib_codes_to_names);
6185 Py_CLEAR(state->Sock_Type);
6186
6187 return 0;
6188}
6189
6190static void
6191sslmodule_free(void *m)
6192{
6193 sslmodule_clear((PyObject *)m);
6194}
6195
6196static struct PyModuleDef _sslmodule_def = {
Christian Heimes5c36da72020-11-20 09:40:12 +01006197 PyModuleDef_HEAD_INIT,
Christian Heimes7f1305e2021-04-17 20:06:38 +02006198 .m_name = "_ssl",
6199 .m_doc = module_doc,
6200 .m_size = sizeof(_sslmodulestate),
6201 .m_methods = PySSL_methods,
6202 .m_slots = sslmodule_slots,
6203 .m_traverse = sslmodule_traverse,
6204 .m_clear = sslmodule_clear,
6205 .m_free = sslmodule_free
Christian Heimes5c36da72020-11-20 09:40:12 +01006206};
6207
6208PyMODINIT_FUNC
6209PyInit__ssl(void)
6210{
Christian Heimes7f1305e2021-04-17 20:06:38 +02006211 return PyModuleDef_Init(&_sslmodule_def);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00006212}