blob: 15083279e24adb38ec1f8346bee52a12914dfd13 [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),
439 .flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
440 Py_TPFLAGS_IMMUTABLETYPE | Py_TPFLAGS_HAVE_GC),
441 .slots = sslerror_type_slots
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200442};
443
444static void
Christian Heimes7f1305e2021-04-17 20:06:38 +0200445fill_and_set_sslerror(_sslmodulestate *state,
446 PySSLSocket *sslsock, PyObject *type, int ssl_errno,
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700447 const char *errstr, int lineno, unsigned long errcode)
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200448{
449 PyObject *err_value = NULL, *reason_obj = NULL, *lib_obj = NULL;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700450 PyObject *verify_obj = NULL, *verify_code_obj = NULL;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200451 PyObject *init_value, *msg, *key;
452 _Py_IDENTIFIER(reason);
453 _Py_IDENTIFIER(library);
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700454 _Py_IDENTIFIER(verify_message);
455 _Py_IDENTIFIER(verify_code);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200456
457 if (errcode != 0) {
458 int lib, reason;
459
460 lib = ERR_GET_LIB(errcode);
461 reason = ERR_GET_REASON(errcode);
462 key = Py_BuildValue("ii", lib, reason);
463 if (key == NULL)
464 goto fail;
Christian Heimes7f1305e2021-04-17 20:06:38 +0200465 reason_obj = PyDict_GetItemWithError(state->err_codes_to_names, key);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200466 Py_DECREF(key);
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +0300467 if (reason_obj == NULL && PyErr_Occurred()) {
468 goto fail;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200469 }
470 key = PyLong_FromLong(lib);
471 if (key == NULL)
472 goto fail;
Christian Heimes7f1305e2021-04-17 20:06:38 +0200473 lib_obj = PyDict_GetItemWithError(state->lib_codes_to_names, key);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200474 Py_DECREF(key);
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +0300475 if (lib_obj == NULL && PyErr_Occurred()) {
476 goto fail;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200477 }
478 if (errstr == NULL)
479 errstr = ERR_reason_error_string(errcode);
480 }
481 if (errstr == NULL)
482 errstr = "unknown error";
483
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700484 /* verify code for cert validation error */
Christian Heimes7f1305e2021-04-17 20:06:38 +0200485 if ((sslsock != NULL) && (type == state->PySSLCertVerificationErrorObject)) {
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700486 const char *verify_str = NULL;
487 long verify_code;
488
489 verify_code = SSL_get_verify_result(sslsock->ssl);
490 verify_code_obj = PyLong_FromLong(verify_code);
491 if (verify_code_obj == NULL) {
492 goto fail;
493 }
494
495 switch (verify_code) {
496 case X509_V_ERR_HOSTNAME_MISMATCH:
497 verify_obj = PyUnicode_FromFormat(
498 "Hostname mismatch, certificate is not valid for '%S'.",
499 sslsock->server_hostname
500 );
501 break;
502 case X509_V_ERR_IP_ADDRESS_MISMATCH:
503 verify_obj = PyUnicode_FromFormat(
504 "IP address mismatch, certificate is not valid for '%S'.",
505 sslsock->server_hostname
506 );
507 break;
508 default:
509 verify_str = X509_verify_cert_error_string(verify_code);
510 if (verify_str != NULL) {
511 verify_obj = PyUnicode_FromString(verify_str);
512 } else {
513 verify_obj = Py_None;
514 Py_INCREF(verify_obj);
515 }
516 break;
517 }
518 if (verify_obj == NULL) {
519 goto fail;
520 }
521 }
522
523 if (verify_obj && reason_obj && lib_obj)
524 msg = PyUnicode_FromFormat("[%S: %S] %s: %S (_ssl.c:%d)",
525 lib_obj, reason_obj, errstr, verify_obj,
526 lineno);
527 else if (reason_obj && lib_obj)
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200528 msg = PyUnicode_FromFormat("[%S: %S] %s (_ssl.c:%d)",
529 lib_obj, reason_obj, errstr, lineno);
530 else if (lib_obj)
531 msg = PyUnicode_FromFormat("[%S] %s (_ssl.c:%d)",
532 lib_obj, errstr, lineno);
533 else
534 msg = PyUnicode_FromFormat("%s (_ssl.c:%d)", errstr, lineno);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200535 if (msg == NULL)
536 goto fail;
Victor Stinnerba9be472013-10-31 15:00:24 +0100537
Paul Monsonfb7e7502019-05-15 15:38:55 -0700538 init_value = Py_BuildValue("iN", ERR_GET_REASON(ssl_errno), msg);
Victor Stinnerba9be472013-10-31 15:00:24 +0100539 if (init_value == NULL)
540 goto fail;
541
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200542 err_value = PyObject_CallObject(type, init_value);
543 Py_DECREF(init_value);
544 if (err_value == NULL)
545 goto fail;
Victor Stinnerba9be472013-10-31 15:00:24 +0100546
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200547 if (reason_obj == NULL)
548 reason_obj = Py_None;
549 if (_PyObject_SetAttrId(err_value, &PyId_reason, reason_obj))
550 goto fail;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700551
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200552 if (lib_obj == NULL)
553 lib_obj = Py_None;
554 if (_PyObject_SetAttrId(err_value, &PyId_library, lib_obj))
555 goto fail;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700556
Christian Heimes7f1305e2021-04-17 20:06:38 +0200557 if ((sslsock != NULL) && (type == state->PySSLCertVerificationErrorObject)) {
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700558 /* Only set verify code / message for SSLCertVerificationError */
559 if (_PyObject_SetAttrId(err_value, &PyId_verify_code,
560 verify_code_obj))
561 goto fail;
562 if (_PyObject_SetAttrId(err_value, &PyId_verify_message, verify_obj))
563 goto fail;
564 }
565
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200566 PyErr_SetObject(type, err_value);
567fail:
568 Py_XDECREF(err_value);
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700569 Py_XDECREF(verify_code_obj);
570 Py_XDECREF(verify_obj);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200571}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000572
Christian Heimesc7f70692019-05-31 11:44:05 +0200573static int
574PySSL_ChainExceptions(PySSLSocket *sslsock) {
575 if (sslsock->exc_type == NULL)
576 return 0;
577
578 _PyErr_ChainExceptions(sslsock->exc_type, sslsock->exc_value, sslsock->exc_tb);
579 sslsock->exc_type = NULL;
580 sslsock->exc_value = NULL;
581 sslsock->exc_tb = NULL;
582 return -1;
583}
584
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000585static PyObject *
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700586PySSL_SetError(PySSLSocket *sslsock, int ret, const char *filename, int lineno)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000587{
Christian Heimes7f1305e2021-04-17 20:06:38 +0200588 PyObject *type;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200589 char *errstr = NULL;
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700590 _PySSLError err;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000591 enum py_ssl_error p = PY_SSL_ERROR_NONE;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200592 unsigned long e = 0;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000593
Christian Heimes7f1305e2021-04-17 20:06:38 +0200594 assert(sslsock != NULL);
595
596 _sslmodulestate *state = get_state_sock(sslsock);
597 type = state->PySSLErrorObject;
598
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000599 assert(ret <= 0);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200600 e = ERR_peek_last_error();
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000601
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700602 if (sslsock->ssl != NULL) {
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700603 err = sslsock->err;
Thomas Woutersed03b412007-08-28 21:37:11 +0000604
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700605 switch (err.ssl) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000606 case SSL_ERROR_ZERO_RETURN:
Antoine Pitrou41032a62011-10-27 23:56:55 +0200607 errstr = "TLS/SSL connection has been closed (EOF)";
Christian Heimes7f1305e2021-04-17 20:06:38 +0200608 type = state->PySSLZeroReturnErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000609 p = PY_SSL_ERROR_ZERO_RETURN;
610 break;
611 case SSL_ERROR_WANT_READ:
612 errstr = "The operation did not complete (read)";
Christian Heimes7f1305e2021-04-17 20:06:38 +0200613 type = state->PySSLWantReadErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000614 p = PY_SSL_ERROR_WANT_READ;
615 break;
616 case SSL_ERROR_WANT_WRITE:
617 p = PY_SSL_ERROR_WANT_WRITE;
Christian Heimes7f1305e2021-04-17 20:06:38 +0200618 type = state->PySSLWantWriteErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000619 errstr = "The operation did not complete (write)";
620 break;
621 case SSL_ERROR_WANT_X509_LOOKUP:
622 p = PY_SSL_ERROR_WANT_X509_LOOKUP;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000623 errstr = "The operation did not complete (X509 lookup)";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000624 break;
625 case SSL_ERROR_WANT_CONNECT:
626 p = PY_SSL_ERROR_WANT_CONNECT;
627 errstr = "The operation did not complete (connect)";
628 break;
629 case SSL_ERROR_SYSCALL:
630 {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000631 if (e == 0) {
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700632 PySocketSockObject *s = GET_SOCKET(sslsock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000633 if (ret == 0 || (((PyObject *)s) == Py_None)) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000634 p = PY_SSL_ERROR_EOF;
Christian Heimes7f1305e2021-04-17 20:06:38 +0200635 type = state->PySSLEOFErrorObject;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000636 errstr = "EOF occurred in violation of protocol";
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200637 } else if (s && ret == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000638 /* underlying BIO reported an I/O error */
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000639 ERR_clear_error();
Steve Dowere6eb48c2017-09-08 15:16:15 -0700640#ifdef MS_WINDOWS
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700641 if (err.ws) {
642 return PyErr_SetFromWindowsErr(err.ws);
643 }
Steve Dowere6eb48c2017-09-08 15:16:15 -0700644#endif
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700645 if (err.c) {
646 errno = err.c;
Steve Dowere6eb48c2017-09-08 15:16:15 -0700647 return PyErr_SetFromErrno(PyExc_OSError);
648 }
Dima Tisnek495bd032020-08-16 02:01:19 +0900649 else {
650 p = PY_SSL_ERROR_EOF;
Christian Heimes7f1305e2021-04-17 20:06:38 +0200651 type = state->PySSLEOFErrorObject;
Dima Tisnek495bd032020-08-16 02:01:19 +0900652 errstr = "EOF occurred in violation of protocol";
653 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000654 } else { /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000655 p = PY_SSL_ERROR_SYSCALL;
Christian Heimes7f1305e2021-04-17 20:06:38 +0200656 type = state->PySSLSyscallErrorObject;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000657 errstr = "Some I/O error occurred";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000658 }
659 } else {
660 p = PY_SSL_ERROR_SYSCALL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000661 }
662 break;
663 }
664 case SSL_ERROR_SSL:
665 {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000666 p = PY_SSL_ERROR_SSL;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700667 if (e == 0) {
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200668 /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000669 errstr = "A failure in the SSL library occurred";
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700670 }
671 if (ERR_GET_LIB(e) == ERR_LIB_SSL &&
672 ERR_GET_REASON(e) == SSL_R_CERTIFICATE_VERIFY_FAILED) {
Christian Heimes7f1305e2021-04-17 20:06:38 +0200673 type = state->PySSLCertVerificationErrorObject;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700674 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000675 break;
676 }
677 default:
678 p = PY_SSL_ERROR_INVALID_ERROR_CODE;
679 errstr = "Invalid error code";
680 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000681 }
Christian Heimes7f1305e2021-04-17 20:06:38 +0200682 fill_and_set_sslerror(state, sslsock, type, p, errstr, lineno, e);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000683 ERR_clear_error();
Christian Heimesc7f70692019-05-31 11:44:05 +0200684 PySSL_ChainExceptions(sslsock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000685 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000686}
687
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000688static PyObject *
Christian Heimes7f1305e2021-04-17 20:06:38 +0200689_setSSLError (_sslmodulestate *state, const char *errstr, int errcode, const char *filename, int lineno)
690{
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200691 if (errstr == NULL)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000692 errcode = ERR_peek_last_error();
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200693 else
694 errcode = 0;
Christian Heimes7f1305e2021-04-17 20:06:38 +0200695 fill_and_set_sslerror(state, NULL, state->PySSLErrorObject, errcode, errstr, lineno, errcode);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000696 ERR_clear_error();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000697 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000698}
699
Christian Heimes2875c602021-04-19 07:27:10 +0200700static int
701_ssl_deprecated(const char* name, int stacklevel) {
702 return PyErr_WarnFormat(
703 PyExc_DeprecationWarning, stacklevel,
704 "ssl module: %s is deprecated", name
705 );
706}
707
708#define PY_SSL_DEPRECATED(name, stacklevel, ret) \
709 if (_ssl_deprecated((name), (stacklevel)) == -1) return (ret)
710
Christian Heimes61d478c2018-01-27 15:51:38 +0100711/*
712 * SSL objects
713 */
714
715static int
716_ssl_configure_hostname(PySSLSocket *self, const char* server_hostname)
717{
718 int retval = -1;
719 ASN1_OCTET_STRING *ip;
720 PyObject *hostname;
721 size_t len;
722
723 assert(server_hostname);
724
725 /* Disable OpenSSL's special mode with leading dot in hostname:
726 * When name starts with a dot (e.g ".example.com"), it will be
727 * matched by a certificate valid for any sub-domain of name.
728 */
729 len = strlen(server_hostname);
730 if (len == 0 || *server_hostname == '.') {
731 PyErr_SetString(
732 PyExc_ValueError,
733 "server_hostname cannot be an empty string or start with a "
734 "leading dot.");
735 return retval;
736 }
737
738 /* inet_pton is not available on all platforms. */
739 ip = a2i_IPADDRESS(server_hostname);
740 if (ip == NULL) {
741 ERR_clear_error();
742 }
743
Christian Heimes11a14932018-02-24 02:35:08 +0100744 hostname = PyUnicode_Decode(server_hostname, len, "ascii", "strict");
Christian Heimes61d478c2018-01-27 15:51:38 +0100745 if (hostname == NULL) {
746 goto error;
747 }
748 self->server_hostname = hostname;
749
750 /* Only send SNI extension for non-IP hostnames */
751 if (ip == NULL) {
752 if (!SSL_set_tlsext_host_name(self->ssl, server_hostname)) {
Christian Heimes7f1305e2021-04-17 20:06:38 +0200753 _setSSLError(get_state_sock(self), NULL, 0, __FILE__, __LINE__);
Zackery Spytzc32f2972020-10-25 12:02:30 -0600754 goto error;
Christian Heimes61d478c2018-01-27 15:51:38 +0100755 }
756 }
757 if (self->ctx->check_hostname) {
758 X509_VERIFY_PARAM *param = SSL_get0_param(self->ssl);
759 if (ip == NULL) {
Christian Heimesd02ac252018-03-25 12:36:13 +0200760 if (!X509_VERIFY_PARAM_set1_host(param, server_hostname,
761 strlen(server_hostname))) {
Christian Heimes7f1305e2021-04-17 20:06:38 +0200762 _setSSLError(get_state_sock(self), NULL, 0, __FILE__, __LINE__);
Christian Heimes61d478c2018-01-27 15:51:38 +0100763 goto error;
764 }
765 } else {
Christian Heimesa871f692020-06-01 08:58:14 +0200766 if (!X509_VERIFY_PARAM_set1_ip(param, ASN1_STRING_get0_data(ip),
Christian Heimes61d478c2018-01-27 15:51:38 +0100767 ASN1_STRING_length(ip))) {
Christian Heimes7f1305e2021-04-17 20:06:38 +0200768 _setSSLError(get_state_sock(self), NULL, 0, __FILE__, __LINE__);
Christian Heimes61d478c2018-01-27 15:51:38 +0100769 goto error;
770 }
771 }
772 }
773 retval = 0;
774 error:
775 if (ip != NULL) {
776 ASN1_OCTET_STRING_free(ip);
777 }
778 return retval;
779}
780
Antoine Pitrou152efa22010-05-16 18:19:27 +0000781static PySSLSocket *
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100782newPySSLSocket(PySSLContext *sslctx, PySocketSockObject *sock,
Antoine Pitroud5323212010-10-22 18:19:07 +0000783 enum py_ssl_server_or_client socket_type,
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200784 char *server_hostname,
Christian Heimes141c5e82018-02-24 21:10:57 +0100785 PyObject *owner, PyObject *session,
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200786 PySSLMemoryBIO *inbio, PySSLMemoryBIO *outbio)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000787{
Antoine Pitrou152efa22010-05-16 18:19:27 +0000788 PySSLSocket *self;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100789 SSL_CTX *ctx = sslctx->ctx;
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700790 _PySSLError err = { 0 };
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000791
Miss Islington (bot)ea47a8a2021-05-27 09:25:22 -0700792 self = PyObject_GC_New(PySSLSocket,
793 get_state_ctx(sslctx)->PySSLSocket_Type);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000794 if (self == NULL)
795 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000796
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000797 self->ssl = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000798 self->Socket = NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100799 self->ctx = sslctx;
Nathaniel J. Smith65ece7c2017-06-07 23:30:43 -0700800 Py_INCREF(sslctx);
Antoine Pitrou860aee72013-09-29 19:52:45 +0200801 self->shutdown_seen_zero = 0;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200802 self->owner = NULL;
Benjamin Peterson81b9ecd2016-08-15 21:55:37 -0700803 self->server_hostname = NULL;
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700804 self->err = err;
Christian Heimesc7f70692019-05-31 11:44:05 +0200805 self->exc_type = NULL;
806 self->exc_value = NULL;
807 self->exc_tb = NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200808
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000809 /* Make sure the SSL error state is initialized */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000810 ERR_clear_error();
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000811
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000812 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitrou152efa22010-05-16 18:19:27 +0000813 self->ssl = SSL_new(ctx);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000814 PySSL_END_ALLOW_THREADS
Zackery Spytz4c49da02018-12-07 03:11:30 -0700815 if (self->ssl == NULL) {
816 Py_DECREF(self);
Christian Heimes7f1305e2021-04-17 20:06:38 +0200817 _setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
Zackery Spytz4c49da02018-12-07 03:11:30 -0700818 return NULL;
819 }
Christian Heimesb467d9a2021-04-17 10:07:19 +0200820 /* bpo43522 and OpenSSL < 1.1.1l: copy hostflags manually */
821#if !defined(LIBRESSL_VERSION_NUMBER) && OPENSSL_VERSION < 0x101010cf
822 X509_VERIFY_PARAM *ssl_params = SSL_get0_param(self->ssl);
823 X509_VERIFY_PARAM_set_hostflags(ssl_params, sslctx->hostflags);
824#endif
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200825 SSL_set_app_data(self->ssl, self);
826 if (sock) {
827 SSL_set_fd(self->ssl, Py_SAFE_DOWNCAST(sock->sock_fd, SOCKET_T, int));
828 } else {
829 /* BIOs are reference counted and SSL_set_bio borrows our reference.
830 * To prevent a double free in memory_bio_dealloc() we need to take an
831 * extra reference here. */
Christian Heimes598894f2016-09-05 23:19:05 +0200832 BIO_up_ref(inbio->bio);
833 BIO_up_ref(outbio->bio);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200834 SSL_set_bio(self->ssl, inbio->bio, outbio->bio);
835 }
Alex Gaynorf0422422018-05-14 11:51:45 -0400836 SSL_set_mode(self->ssl,
837 SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER | SSL_MODE_AUTO_RETRY);
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000838
Christian Heimesf0f59302019-07-01 08:29:17 +0200839#ifdef TLS1_3_VERSION
840 if (sslctx->post_handshake_auth == 1) {
841 if (socket_type == PY_SSL_SERVER) {
842 /* bpo-37428: OpenSSL does not ignore SSL_VERIFY_POST_HANDSHAKE.
843 * Set SSL_VERIFY_POST_HANDSHAKE flag only for server sockets and
844 * only in combination with SSL_VERIFY_PEER flag. */
845 int mode = SSL_get_verify_mode(self->ssl);
846 if (mode & SSL_VERIFY_PEER) {
847 int (*verify_cb)(int, X509_STORE_CTX *) = NULL;
848 verify_cb = SSL_get_verify_callback(self->ssl);
849 mode |= SSL_VERIFY_POST_HANDSHAKE;
850 SSL_set_verify(self->ssl, mode, verify_cb);
851 }
852 } else {
853 /* client socket */
854 SSL_set_post_handshake_auth(self->ssl, 1);
855 }
856 }
857#endif
858
Christian Heimes61d478c2018-01-27 15:51:38 +0100859 if (server_hostname != NULL) {
860 if (_ssl_configure_hostname(self, server_hostname) < 0) {
861 Py_DECREF(self);
862 return NULL;
863 }
864 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000865 /* If the socket is in non-blocking mode or timeout mode, set the BIO
866 * to non-blocking mode (blocking is the default)
867 */
Victor Stinnere2452312015-03-28 03:00:46 +0100868 if (sock && sock->sock_timeout >= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000869 BIO_set_nbio(SSL_get_rbio(self->ssl), 1);
870 BIO_set_nbio(SSL_get_wbio(self->ssl), 1);
871 }
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000872
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000873 PySSL_BEGIN_ALLOW_THREADS
874 if (socket_type == PY_SSL_CLIENT)
875 SSL_set_connect_state(self->ssl);
876 else
877 SSL_set_accept_state(self->ssl);
878 PySSL_END_ALLOW_THREADS
Martin v. Löwis09c35f72002-07-28 09:57:45 +0000879
Antoine Pitroud6494802011-07-21 01:11:30 +0200880 self->socket_type = socket_type;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200881 if (sock != NULL) {
882 self->Socket = PyWeakref_NewRef((PyObject *) sock, NULL);
883 if (self->Socket == NULL) {
884 Py_DECREF(self);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200885 return NULL;
886 }
Victor Stinnera9eb38f2013-10-31 16:35:38 +0100887 }
Christian Heimes141c5e82018-02-24 21:10:57 +0100888 if (owner && owner != Py_None) {
889 if (PySSL_set_owner(self, owner, NULL) == -1) {
890 Py_DECREF(self);
891 return NULL;
892 }
893 }
894 if (session && session != Py_None) {
895 if (PySSL_set_session(self, session, NULL) == -1) {
896 Py_DECREF(self);
897 return NULL;
898 }
899 }
Miss Islington (bot)ea47a8a2021-05-27 09:25:22 -0700900
901 PyObject_GC_Track(self);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000902 return self;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000903}
904
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000905/* SSL object methods */
906
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +0300907/*[clinic input]
908_ssl._SSLSocket.do_handshake
909[clinic start generated code]*/
910
911static PyObject *
912_ssl__SSLSocket_do_handshake_impl(PySSLSocket *self)
913/*[clinic end generated code: output=6c0898a8936548f6 input=d2d737de3df018c8]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000914{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000915 int ret;
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700916 _PySSLError err;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000917 int sockstate, nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200918 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +0200919 _PyTime_t timeout, deadline = 0;
920 int has_timeout;
Antoine Pitroud3f8ab82010-04-24 21:26:44 +0000921
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200922 if (sock) {
923 if (((PyObject*)sock) == Py_None) {
Christian Heimes7f1305e2021-04-17 20:06:38 +0200924 _setSSLError(get_state_sock(self),
925 "Underlying socket connection gone",
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200926 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
927 return NULL;
928 }
929 Py_INCREF(sock);
930
931 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +0100932 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200933 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
934 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000935 }
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000936
Victor Stinner14690702015-04-06 22:46:13 +0200937 timeout = GET_SOCKET_TIMEOUT(sock);
938 has_timeout = (timeout > 0);
939 if (has_timeout)
940 deadline = _PyTime_GetMonotonicClock() + timeout;
941
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000942 /* Actually negotiate SSL connection */
943 /* XXX If SSL_do_handshake() returns 0, it's also a failure. */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000944 do {
Bill Janssen6e027db2007-11-15 22:23:56 +0000945 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000946 ret = SSL_do_handshake(self->ssl);
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700947 err = _PySSL_errno(ret < 1, self->ssl, ret);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000948 PySSL_END_ALLOW_THREADS
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700949 self->err = err;
Victor Stinner4e3cfa42015-04-02 21:28:28 +0200950
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000951 if (PyErr_CheckSignals())
952 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +0200953
Victor Stinner14690702015-04-06 22:46:13 +0200954 if (has_timeout)
955 timeout = deadline - _PyTime_GetMonotonicClock();
956
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700957 if (err.ssl == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +0200958 sockstate = PySSL_select(sock, 0, timeout);
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700959 } else if (err.ssl == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +0200960 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000961 } else {
962 sockstate = SOCKET_OPERATION_OK;
963 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +0200964
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000965 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Christian Heimes03c8ddd2020-11-20 09:26:07 +0100966 PyErr_SetString(PyExc_TimeoutError,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000967 ERRSTR("The handshake operation timed out"));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000968 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000969 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
Christian Heimes7f1305e2021-04-17 20:06:38 +0200970 PyErr_SetString(get_state_sock(self)->PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000971 ERRSTR("Underlying socket has been closed."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000972 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000973 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
Christian Heimes7f1305e2021-04-17 20:06:38 +0200974 PyErr_SetString(get_state_sock(self)->PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000975 ERRSTR("Underlying socket too large for select()."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000976 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000977 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
978 break;
979 }
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700980 } while (err.ssl == SSL_ERROR_WANT_READ ||
981 err.ssl == SSL_ERROR_WANT_WRITE);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200982 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000983 if (ret < 1)
984 return PySSL_SetError(self, ret, __FILE__, __LINE__);
Christian Heimesc7f70692019-05-31 11:44:05 +0200985 if (PySSL_ChainExceptions(self) < 0)
986 return NULL;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200987 Py_RETURN_NONE;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000988error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200989 Py_XDECREF(sock);
Christian Heimesc7f70692019-05-31 11:44:05 +0200990 PySSL_ChainExceptions(self);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000991 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000992}
993
Thomas Woutersed03b412007-08-28 21:37:11 +0000994static PyObject *
Christian Heimes7f1305e2021-04-17 20:06:38 +0200995_asn1obj2py(_sslmodulestate *state, const ASN1_OBJECT *name, int no_name)
Serhiy Storchakae503ca52017-09-05 01:28:53 +0300996{
997 char buf[X509_NAME_MAXLEN];
998 char *namebuf = buf;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000999 int buflen;
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001000 PyObject *name_obj = NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001001
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001002 buflen = OBJ_obj2txt(namebuf, X509_NAME_MAXLEN, name, no_name);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001003 if (buflen < 0) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02001004 _setSSLError(state, NULL, 0, __FILE__, __LINE__);
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001005 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001006 }
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001007 /* initial buffer is too small for oid + terminating null byte */
1008 if (buflen > X509_NAME_MAXLEN - 1) {
1009 /* make OBJ_obj2txt() calculate the required buflen */
1010 buflen = OBJ_obj2txt(NULL, 0, name, no_name);
1011 /* allocate len + 1 for terminating NULL byte */
1012 namebuf = PyMem_Malloc(buflen + 1);
1013 if (namebuf == NULL) {
1014 PyErr_NoMemory();
1015 return NULL;
1016 }
1017 buflen = OBJ_obj2txt(namebuf, buflen + 1, name, no_name);
1018 if (buflen < 0) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02001019 _setSSLError(state, NULL, 0, __FILE__, __LINE__);
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001020 goto done;
1021 }
1022 }
1023 if (!buflen && no_name) {
1024 Py_INCREF(Py_None);
1025 name_obj = Py_None;
1026 }
1027 else {
1028 name_obj = PyUnicode_FromStringAndSize(namebuf, buflen);
1029 }
1030
1031 done:
1032 if (buf != namebuf) {
1033 PyMem_Free(namebuf);
1034 }
1035 return name_obj;
1036}
1037
1038static PyObject *
Christian Heimes7f1305e2021-04-17 20:06:38 +02001039_create_tuple_for_attribute(_sslmodulestate *state,
1040 ASN1_OBJECT *name, ASN1_STRING *value)
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001041{
1042 Py_ssize_t buflen;
1043 unsigned char *valuebuf = NULL;
1044 PyObject *attr;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001045
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001046 buflen = ASN1_STRING_to_UTF8(&valuebuf, value);
1047 if (buflen < 0) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02001048 _setSSLError(state, NULL, 0, __FILE__, __LINE__);
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001049 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001050 }
Christian Heimes7f1305e2021-04-17 20:06:38 +02001051 attr = Py_BuildValue("Ns#", _asn1obj2py(state, name, 0), valuebuf, buflen);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001052 OPENSSL_free(valuebuf);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001053 return attr;
Thomas Woutersed03b412007-08-28 21:37:11 +00001054}
1055
1056static PyObject *
Christian Heimes7f1305e2021-04-17 20:06:38 +02001057_create_tuple_for_X509_NAME (_sslmodulestate *state, X509_NAME *xname)
Thomas Woutersed03b412007-08-28 21:37:11 +00001058{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001059 PyObject *dn = NULL; /* tuple which represents the "distinguished name" */
1060 PyObject *rdn = NULL; /* tuple to hold a "relative distinguished name" */
1061 PyObject *rdnt;
1062 PyObject *attr = NULL; /* tuple to hold an attribute */
1063 int entry_count = X509_NAME_entry_count(xname);
1064 X509_NAME_ENTRY *entry;
1065 ASN1_OBJECT *name;
1066 ASN1_STRING *value;
1067 int index_counter;
1068 int rdn_level = -1;
1069 int retcode;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001070
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001071 dn = PyList_New(0);
1072 if (dn == NULL)
1073 return NULL;
1074 /* now create another tuple to hold the top-level RDN */
1075 rdn = PyList_New(0);
1076 if (rdn == NULL)
1077 goto fail0;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001078
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001079 for (index_counter = 0;
1080 index_counter < entry_count;
1081 index_counter++)
1082 {
1083 entry = X509_NAME_get_entry(xname, index_counter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001084
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001085 /* check to see if we've gotten to a new RDN */
1086 if (rdn_level >= 0) {
Christian Heimes598894f2016-09-05 23:19:05 +02001087 if (rdn_level != X509_NAME_ENTRY_set(entry)) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001088 /* yes, new RDN */
1089 /* add old RDN to DN */
1090 rdnt = PyList_AsTuple(rdn);
1091 Py_DECREF(rdn);
1092 if (rdnt == NULL)
1093 goto fail0;
1094 retcode = PyList_Append(dn, rdnt);
1095 Py_DECREF(rdnt);
1096 if (retcode < 0)
1097 goto fail0;
1098 /* create new RDN */
1099 rdn = PyList_New(0);
1100 if (rdn == NULL)
1101 goto fail0;
1102 }
1103 }
Christian Heimes598894f2016-09-05 23:19:05 +02001104 rdn_level = X509_NAME_ENTRY_set(entry);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001105
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001106 /* now add this attribute to the current RDN */
1107 name = X509_NAME_ENTRY_get_object(entry);
1108 value = X509_NAME_ENTRY_get_data(entry);
Christian Heimes7f1305e2021-04-17 20:06:38 +02001109 attr = _create_tuple_for_attribute(state, name, value);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001110 /*
1111 fprintf(stderr, "RDN level %d, attribute %s: %s\n",
1112 entry->set,
1113 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 0)),
1114 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 1)));
1115 */
1116 if (attr == NULL)
1117 goto fail1;
1118 retcode = PyList_Append(rdn, attr);
1119 Py_DECREF(attr);
1120 if (retcode < 0)
1121 goto fail1;
1122 }
1123 /* now, there's typically a dangling RDN */
Antoine Pitrou2f5a1632012-02-15 22:25:27 +01001124 if (rdn != NULL) {
1125 if (PyList_GET_SIZE(rdn) > 0) {
1126 rdnt = PyList_AsTuple(rdn);
1127 Py_DECREF(rdn);
1128 if (rdnt == NULL)
1129 goto fail0;
1130 retcode = PyList_Append(dn, rdnt);
1131 Py_DECREF(rdnt);
1132 if (retcode < 0)
1133 goto fail0;
1134 }
1135 else {
1136 Py_DECREF(rdn);
1137 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001138 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001139
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001140 /* convert list to tuple */
1141 rdnt = PyList_AsTuple(dn);
1142 Py_DECREF(dn);
1143 if (rdnt == NULL)
1144 return NULL;
1145 return rdnt;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001146
1147 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001148 Py_XDECREF(rdn);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001149
1150 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001151 Py_XDECREF(dn);
1152 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001153}
1154
1155static PyObject *
Christian Heimes7f1305e2021-04-17 20:06:38 +02001156_get_peer_alt_names (_sslmodulestate *state, X509 *certificate) {
Guido van Rossumf06628b2007-11-21 20:01:53 +00001157
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001158 /* this code follows the procedure outlined in
1159 OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print()
1160 function to extract the STACK_OF(GENERAL_NAME),
1161 then iterates through the stack to add the
1162 names. */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001163
Alex Gaynorb87c0df2017-06-06 07:53:11 -04001164 int j;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001165 PyObject *peer_alt_names = Py_None;
Christian Heimes60bf2fc2013-09-05 16:04:35 +02001166 PyObject *v = NULL, *t;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001167 GENERAL_NAMES *names = NULL;
1168 GENERAL_NAME *name;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001169 BIO *biobuf = NULL;
1170 char buf[2048];
1171 char *vptr;
1172 int len;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001173
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001174 if (certificate == NULL)
1175 return peer_alt_names;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001176
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001177 /* get a memory buffer */
1178 biobuf = BIO_new(BIO_s_mem());
Zackery Spytz4c49da02018-12-07 03:11:30 -07001179 if (biobuf == NULL) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02001180 PyErr_SetString(state->PySSLErrorObject, "failed to allocate BIO");
Zackery Spytz4c49da02018-12-07 03:11:30 -07001181 return NULL;
1182 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001183
Alex Gaynorb87c0df2017-06-06 07:53:11 -04001184 names = (GENERAL_NAMES *)X509_get_ext_d2i(
1185 certificate, NID_subject_alt_name, NULL, NULL);
1186 if (names != NULL) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001187 if (peer_alt_names == Py_None) {
1188 peer_alt_names = PyList_New(0);
1189 if (peer_alt_names == NULL)
1190 goto fail;
1191 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001192
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001193 for(j = 0; j < sk_GENERAL_NAME_num(names); j++) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001194 /* get a rendering of each name in the set of names */
Christian Heimes824f7f32013-08-17 00:54:47 +02001195 int gntype;
1196 ASN1_STRING *as = NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001197
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001198 name = sk_GENERAL_NAME_value(names, j);
Christian Heimes474afdd2013-08-17 17:18:56 +02001199 gntype = name->type;
Christian Heimes824f7f32013-08-17 00:54:47 +02001200 switch (gntype) {
1201 case GEN_DIRNAME:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001202 /* we special-case DirName as a tuple of
1203 tuples of attributes */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001204
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001205 t = PyTuple_New(2);
1206 if (t == NULL) {
1207 goto fail;
1208 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001209
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001210 v = PyUnicode_FromString("DirName");
1211 if (v == NULL) {
1212 Py_DECREF(t);
1213 goto fail;
1214 }
1215 PyTuple_SET_ITEM(t, 0, v);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001216
Christian Heimes7f1305e2021-04-17 20:06:38 +02001217 v = _create_tuple_for_X509_NAME(state, name->d.dirn);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001218 if (v == NULL) {
1219 Py_DECREF(t);
1220 goto fail;
1221 }
1222 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +02001223 break;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001224
Christian Heimes824f7f32013-08-17 00:54:47 +02001225 case GEN_EMAIL:
1226 case GEN_DNS:
1227 case GEN_URI:
1228 /* GENERAL_NAME_print() doesn't handle NULL bytes in ASN1_string
1229 correctly, CVE-2013-4238 */
1230 t = PyTuple_New(2);
1231 if (t == NULL)
1232 goto fail;
1233 switch (gntype) {
1234 case GEN_EMAIL:
1235 v = PyUnicode_FromString("email");
1236 as = name->d.rfc822Name;
1237 break;
1238 case GEN_DNS:
1239 v = PyUnicode_FromString("DNS");
1240 as = name->d.dNSName;
1241 break;
1242 case GEN_URI:
1243 v = PyUnicode_FromString("URI");
1244 as = name->d.uniformResourceIdentifier;
1245 break;
1246 }
1247 if (v == NULL) {
1248 Py_DECREF(t);
1249 goto fail;
1250 }
1251 PyTuple_SET_ITEM(t, 0, v);
Christian Heimesa871f692020-06-01 08:58:14 +02001252 v = PyUnicode_FromStringAndSize((char *)ASN1_STRING_get0_data(as),
Christian Heimes824f7f32013-08-17 00:54:47 +02001253 ASN1_STRING_length(as));
1254 if (v == NULL) {
1255 Py_DECREF(t);
1256 goto fail;
1257 }
1258 PyTuple_SET_ITEM(t, 1, v);
1259 break;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001260
Christian Heimes1c03abd2016-09-06 23:25:35 +02001261 case GEN_RID:
1262 t = PyTuple_New(2);
1263 if (t == NULL)
1264 goto fail;
1265
1266 v = PyUnicode_FromString("Registered ID");
1267 if (v == NULL) {
1268 Py_DECREF(t);
1269 goto fail;
1270 }
1271 PyTuple_SET_ITEM(t, 0, v);
1272
1273 len = i2t_ASN1_OBJECT(buf, sizeof(buf)-1, name->d.rid);
1274 if (len < 0) {
1275 Py_DECREF(t);
Christian Heimes7f1305e2021-04-17 20:06:38 +02001276 _setSSLError(state, NULL, 0, __FILE__, __LINE__);
Christian Heimes1c03abd2016-09-06 23:25:35 +02001277 goto fail;
1278 } else if (len >= (int)sizeof(buf)) {
1279 v = PyUnicode_FromString("<INVALID>");
1280 } else {
1281 v = PyUnicode_FromStringAndSize(buf, len);
1282 }
1283 if (v == NULL) {
1284 Py_DECREF(t);
1285 goto fail;
1286 }
1287 PyTuple_SET_ITEM(t, 1, v);
1288 break;
1289
Christian Heimes2b7de662019-12-07 17:59:36 +01001290 case GEN_IPADD:
1291 /* OpenSSL < 3.0.0 adds a trailing \n to IPv6. 3.0.0 removed
1292 * the trailing newline. Remove it in all versions
1293 */
1294 t = PyTuple_New(2);
1295 if (t == NULL)
1296 goto fail;
1297
1298 v = PyUnicode_FromString("IP Address");
1299 if (v == NULL) {
1300 Py_DECREF(t);
1301 goto fail;
1302 }
1303 PyTuple_SET_ITEM(t, 0, v);
1304
1305 if (name->d.ip->length == 4) {
1306 unsigned char *p = name->d.ip->data;
1307 v = PyUnicode_FromFormat(
1308 "%d.%d.%d.%d",
1309 p[0], p[1], p[2], p[3]
1310 );
1311 } else if (name->d.ip->length == 16) {
1312 /* PyUnicode_FromFormat() does not support %X */
1313 unsigned char *p = name->d.ip->data;
1314 len = sprintf(
1315 buf,
1316 "%X:%X:%X:%X:%X:%X:%X:%X",
1317 p[0] << 8 | p[1],
1318 p[2] << 8 | p[3],
1319 p[4] << 8 | p[5],
1320 p[6] << 8 | p[7],
1321 p[8] << 8 | p[9],
1322 p[10] << 8 | p[11],
1323 p[12] << 8 | p[13],
1324 p[14] << 8 | p[15]
1325 );
1326 v = PyUnicode_FromStringAndSize(buf, len);
1327 } else {
1328 v = PyUnicode_FromString("<invalid>");
1329 }
1330
1331 if (v == NULL) {
1332 Py_DECREF(t);
1333 goto fail;
1334 }
1335 PyTuple_SET_ITEM(t, 1, v);
1336 break;
1337
Christian Heimes824f7f32013-08-17 00:54:47 +02001338 default:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001339 /* for everything else, we use the OpenSSL print form */
Christian Heimes824f7f32013-08-17 00:54:47 +02001340 switch (gntype) {
1341 /* check for new general name type */
1342 case GEN_OTHERNAME:
1343 case GEN_X400:
1344 case GEN_EDIPARTY:
Christian Heimes824f7f32013-08-17 00:54:47 +02001345 case GEN_RID:
1346 break;
1347 default:
1348 if (PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
1349 "Unknown general name type %d",
1350 gntype) == -1) {
1351 goto fail;
1352 }
1353 break;
1354 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001355 (void) BIO_reset(biobuf);
1356 GENERAL_NAME_print(biobuf, name);
1357 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1358 if (len < 0) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02001359 _setSSLError(state, NULL, 0, __FILE__, __LINE__);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001360 goto fail;
1361 }
1362 vptr = strchr(buf, ':');
Christian Heimes1c03abd2016-09-06 23:25:35 +02001363 if (vptr == NULL) {
1364 PyErr_Format(PyExc_ValueError,
1365 "Invalid value %.200s",
1366 buf);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001367 goto fail;
Christian Heimes1c03abd2016-09-06 23:25:35 +02001368 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001369 t = PyTuple_New(2);
1370 if (t == NULL)
1371 goto fail;
1372 v = PyUnicode_FromStringAndSize(buf, (vptr - buf));
1373 if (v == NULL) {
1374 Py_DECREF(t);
1375 goto fail;
1376 }
1377 PyTuple_SET_ITEM(t, 0, v);
1378 v = PyUnicode_FromStringAndSize((vptr + 1),
1379 (len - (vptr - buf + 1)));
1380 if (v == NULL) {
1381 Py_DECREF(t);
1382 goto fail;
1383 }
1384 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +02001385 break;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001386 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001387
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001388 /* and add that rendering to the list */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001389
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001390 if (PyList_Append(peer_alt_names, t) < 0) {
1391 Py_DECREF(t);
1392 goto fail;
1393 }
1394 Py_DECREF(t);
1395 }
Antoine Pitrou116d6b92011-11-23 01:39:19 +01001396 sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001397 }
1398 BIO_free(biobuf);
1399 if (peer_alt_names != Py_None) {
1400 v = PyList_AsTuple(peer_alt_names);
1401 Py_DECREF(peer_alt_names);
1402 return v;
1403 } else {
1404 return peer_alt_names;
1405 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001406
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001407
1408 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001409 if (biobuf != NULL)
1410 BIO_free(biobuf);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001411
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001412 if (peer_alt_names != Py_None) {
1413 Py_XDECREF(peer_alt_names);
1414 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001415
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001416 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001417}
1418
1419static PyObject *
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001420_get_aia_uri(X509 *certificate, int nid) {
1421 PyObject *lst = NULL, *ostr = NULL;
1422 int i, result;
1423 AUTHORITY_INFO_ACCESS *info;
1424
1425 info = X509_get_ext_d2i(certificate, NID_info_access, NULL, NULL);
Benjamin Petersonf0c90382015-11-14 15:12:18 -08001426 if (info == NULL)
1427 return Py_None;
1428 if (sk_ACCESS_DESCRIPTION_num(info) == 0) {
1429 AUTHORITY_INFO_ACCESS_free(info);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001430 return Py_None;
1431 }
1432
1433 if ((lst = PyList_New(0)) == NULL) {
1434 goto fail;
1435 }
1436
1437 for (i = 0; i < sk_ACCESS_DESCRIPTION_num(info); i++) {
1438 ACCESS_DESCRIPTION *ad = sk_ACCESS_DESCRIPTION_value(info, i);
1439 ASN1_IA5STRING *uri;
1440
1441 if ((OBJ_obj2nid(ad->method) != nid) ||
1442 (ad->location->type != GEN_URI)) {
1443 continue;
1444 }
1445 uri = ad->location->d.uniformResourceIdentifier;
1446 ostr = PyUnicode_FromStringAndSize((char *)uri->data,
1447 uri->length);
1448 if (ostr == NULL) {
1449 goto fail;
1450 }
1451 result = PyList_Append(lst, ostr);
1452 Py_DECREF(ostr);
1453 if (result < 0) {
1454 goto fail;
1455 }
1456 }
1457 AUTHORITY_INFO_ACCESS_free(info);
1458
1459 /* convert to tuple or None */
1460 if (PyList_Size(lst) == 0) {
1461 Py_DECREF(lst);
1462 return Py_None;
1463 } else {
1464 PyObject *tup;
1465 tup = PyList_AsTuple(lst);
1466 Py_DECREF(lst);
1467 return tup;
1468 }
1469
1470 fail:
1471 AUTHORITY_INFO_ACCESS_free(info);
Christian Heimes18fc7be2013-11-21 23:57:49 +01001472 Py_XDECREF(lst);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001473 return NULL;
1474}
1475
1476static PyObject *
1477_get_crl_dp(X509 *certificate) {
1478 STACK_OF(DIST_POINT) *dps;
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001479 int i, j;
1480 PyObject *lst, *res = NULL;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001481
Christian Heimes598894f2016-09-05 23:19:05 +02001482 dps = X509_get_ext_d2i(certificate, NID_crl_distribution_points, NULL, NULL);
Christian Heimes949ec142013-11-21 16:26:51 +01001483
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001484 if (dps == NULL)
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001485 return Py_None;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001486
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001487 lst = PyList_New(0);
1488 if (lst == NULL)
1489 goto done;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001490
1491 for (i=0; i < sk_DIST_POINT_num(dps); i++) {
1492 DIST_POINT *dp;
1493 STACK_OF(GENERAL_NAME) *gns;
1494
1495 dp = sk_DIST_POINT_value(dps, i);
Christian Heimesa37f5242019-01-15 23:47:42 +01001496 if (dp->distpoint == NULL) {
1497 /* Ignore empty DP value, CVE-2019-5010 */
1498 continue;
1499 }
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001500 gns = dp->distpoint->name.fullname;
1501
1502 for (j=0; j < sk_GENERAL_NAME_num(gns); j++) {
1503 GENERAL_NAME *gn;
1504 ASN1_IA5STRING *uri;
1505 PyObject *ouri;
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001506 int err;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001507
1508 gn = sk_GENERAL_NAME_value(gns, j);
1509 if (gn->type != GEN_URI) {
1510 continue;
1511 }
1512 uri = gn->d.uniformResourceIdentifier;
1513 ouri = PyUnicode_FromStringAndSize((char *)uri->data,
1514 uri->length);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001515 if (ouri == NULL)
1516 goto done;
1517
1518 err = PyList_Append(lst, ouri);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001519 Py_DECREF(ouri);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001520 if (err < 0)
1521 goto done;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001522 }
1523 }
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001524
1525 /* Convert to tuple. */
1526 res = (PyList_GET_SIZE(lst) > 0) ? PyList_AsTuple(lst) : Py_None;
1527
1528 done:
1529 Py_XDECREF(lst);
Olivier Vielpeau2849cc32017-04-14 21:06:07 -04001530 CRL_DIST_POINTS_free(dps);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001531 return res;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001532}
1533
1534static PyObject *
Christian Heimes7f1305e2021-04-17 20:06:38 +02001535_decode_certificate(_sslmodulestate *state, X509 *certificate) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001536
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001537 PyObject *retval = NULL;
1538 BIO *biobuf = NULL;
1539 PyObject *peer;
1540 PyObject *peer_alt_names = NULL;
1541 PyObject *issuer;
1542 PyObject *version;
1543 PyObject *sn_obj;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001544 PyObject *obj;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001545 ASN1_INTEGER *serialNumber;
1546 char buf[2048];
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001547 int len, result;
Christian Heimesa871f692020-06-01 08:58:14 +02001548 const ASN1_TIME *notBefore, *notAfter;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001549 PyObject *pnotBefore, *pnotAfter;
Thomas Woutersed03b412007-08-28 21:37:11 +00001550
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001551 retval = PyDict_New();
1552 if (retval == NULL)
1553 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001554
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001555 peer = _create_tuple_for_X509_NAME(
Christian Heimes7f1305e2021-04-17 20:06:38 +02001556 state,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001557 X509_get_subject_name(certificate));
1558 if (peer == NULL)
1559 goto fail0;
1560 if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) {
1561 Py_DECREF(peer);
1562 goto fail0;
1563 }
1564 Py_DECREF(peer);
Thomas Woutersed03b412007-08-28 21:37:11 +00001565
Antoine Pitroufb046912010-11-09 20:21:19 +00001566 issuer = _create_tuple_for_X509_NAME(
Christian Heimes7f1305e2021-04-17 20:06:38 +02001567 state,
Antoine Pitroufb046912010-11-09 20:21:19 +00001568 X509_get_issuer_name(certificate));
1569 if (issuer == NULL)
1570 goto fail0;
1571 if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001572 Py_DECREF(issuer);
Antoine Pitroufb046912010-11-09 20:21:19 +00001573 goto fail0;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001574 }
Antoine Pitroufb046912010-11-09 20:21:19 +00001575 Py_DECREF(issuer);
1576
1577 version = PyLong_FromLong(X509_get_version(certificate) + 1);
Christian Heimes5962bef2013-07-26 15:51:18 +02001578 if (version == NULL)
1579 goto fail0;
Antoine Pitroufb046912010-11-09 20:21:19 +00001580 if (PyDict_SetItemString(retval, "version", version) < 0) {
1581 Py_DECREF(version);
1582 goto fail0;
1583 }
1584 Py_DECREF(version);
Guido van Rossumf06628b2007-11-21 20:01:53 +00001585
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001586 /* get a memory buffer */
1587 biobuf = BIO_new(BIO_s_mem());
Zackery Spytz4c49da02018-12-07 03:11:30 -07001588 if (biobuf == NULL) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02001589 PyErr_SetString(state->PySSLErrorObject, "failed to allocate BIO");
Zackery Spytz4c49da02018-12-07 03:11:30 -07001590 goto fail0;
1591 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001592
Antoine Pitroufb046912010-11-09 20:21:19 +00001593 (void) BIO_reset(biobuf);
1594 serialNumber = X509_get_serialNumber(certificate);
1595 /* should not exceed 20 octets, 160 bits, so buf is big enough */
1596 i2a_ASN1_INTEGER(biobuf, serialNumber);
1597 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1598 if (len < 0) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02001599 _setSSLError(state, NULL, 0, __FILE__, __LINE__);
Antoine Pitroufb046912010-11-09 20:21:19 +00001600 goto fail1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001601 }
Antoine Pitroufb046912010-11-09 20:21:19 +00001602 sn_obj = PyUnicode_FromStringAndSize(buf, len);
1603 if (sn_obj == NULL)
1604 goto fail1;
1605 if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) {
1606 Py_DECREF(sn_obj);
1607 goto fail1;
1608 }
1609 Py_DECREF(sn_obj);
1610
1611 (void) BIO_reset(biobuf);
Christian Heimesa871f692020-06-01 08:58:14 +02001612 notBefore = X509_get0_notBefore(certificate);
Antoine Pitroufb046912010-11-09 20:21:19 +00001613 ASN1_TIME_print(biobuf, notBefore);
1614 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1615 if (len < 0) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02001616 _setSSLError(state, NULL, 0, __FILE__, __LINE__);
Antoine Pitroufb046912010-11-09 20:21:19 +00001617 goto fail1;
1618 }
1619 pnotBefore = PyUnicode_FromStringAndSize(buf, len);
1620 if (pnotBefore == NULL)
1621 goto fail1;
1622 if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) {
1623 Py_DECREF(pnotBefore);
1624 goto fail1;
1625 }
1626 Py_DECREF(pnotBefore);
Thomas Woutersed03b412007-08-28 21:37:11 +00001627
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001628 (void) BIO_reset(biobuf);
Christian Heimesa871f692020-06-01 08:58:14 +02001629 notAfter = X509_get0_notAfter(certificate);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001630 ASN1_TIME_print(biobuf, notAfter);
1631 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1632 if (len < 0) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02001633 _setSSLError(state, NULL, 0, __FILE__, __LINE__);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001634 goto fail1;
1635 }
1636 pnotAfter = PyUnicode_FromStringAndSize(buf, len);
1637 if (pnotAfter == NULL)
1638 goto fail1;
1639 if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) {
1640 Py_DECREF(pnotAfter);
1641 goto fail1;
1642 }
1643 Py_DECREF(pnotAfter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001644
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001645 /* Now look for subjectAltName */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001646
Christian Heimes7f1305e2021-04-17 20:06:38 +02001647 peer_alt_names = _get_peer_alt_names(state, certificate);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001648 if (peer_alt_names == NULL)
1649 goto fail1;
1650 else if (peer_alt_names != Py_None) {
1651 if (PyDict_SetItemString(retval, "subjectAltName",
1652 peer_alt_names) < 0) {
1653 Py_DECREF(peer_alt_names);
1654 goto fail1;
1655 }
1656 Py_DECREF(peer_alt_names);
1657 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001658
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001659 /* Authority Information Access: OCSP URIs */
1660 obj = _get_aia_uri(certificate, NID_ad_OCSP);
1661 if (obj == NULL) {
1662 goto fail1;
1663 } else if (obj != Py_None) {
1664 result = PyDict_SetItemString(retval, "OCSP", obj);
1665 Py_DECREF(obj);
1666 if (result < 0) {
1667 goto fail1;
1668 }
1669 }
1670
1671 obj = _get_aia_uri(certificate, NID_ad_ca_issuers);
1672 if (obj == NULL) {
1673 goto fail1;
1674 } else if (obj != Py_None) {
1675 result = PyDict_SetItemString(retval, "caIssuers", obj);
1676 Py_DECREF(obj);
1677 if (result < 0) {
1678 goto fail1;
1679 }
1680 }
1681
1682 /* CDP (CRL distribution points) */
1683 obj = _get_crl_dp(certificate);
1684 if (obj == NULL) {
1685 goto fail1;
1686 } else if (obj != Py_None) {
1687 result = PyDict_SetItemString(retval, "crlDistributionPoints", obj);
1688 Py_DECREF(obj);
1689 if (result < 0) {
1690 goto fail1;
1691 }
1692 }
1693
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001694 BIO_free(biobuf);
1695 return retval;
Thomas Woutersed03b412007-08-28 21:37:11 +00001696
1697 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001698 if (biobuf != NULL)
1699 BIO_free(biobuf);
Thomas Woutersed03b412007-08-28 21:37:11 +00001700 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001701 Py_XDECREF(retval);
1702 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001703}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001704
Christian Heimes9a5395a2013-06-17 15:44:12 +02001705static PyObject *
Christian Heimes7f1305e2021-04-17 20:06:38 +02001706_certificate_to_der(_sslmodulestate *state, X509 *certificate)
Christian Heimes9a5395a2013-06-17 15:44:12 +02001707{
1708 unsigned char *bytes_buf = NULL;
1709 int len;
1710 PyObject *retval;
1711
1712 bytes_buf = NULL;
1713 len = i2d_X509(certificate, &bytes_buf);
1714 if (len < 0) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02001715 _setSSLError(state, NULL, 0, __FILE__, __LINE__);
Christian Heimes9a5395a2013-06-17 15:44:12 +02001716 return NULL;
1717 }
1718 /* this is actually an immutable bytes sequence */
1719 retval = PyBytes_FromStringAndSize((const char *) bytes_buf, len);
1720 OPENSSL_free(bytes_buf);
1721 return retval;
1722}
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001723
Christian Heimes666991f2021-04-26 15:01:40 +02001724#include "_ssl/misc.c"
1725#include "_ssl/cert.c"
1726
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001727/*[clinic input]
1728_ssl._test_decode_cert
1729 path: object(converter="PyUnicode_FSConverter")
1730 /
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001731
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001732[clinic start generated code]*/
1733
1734static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001735_ssl__test_decode_cert_impl(PyObject *module, PyObject *path)
1736/*[clinic end generated code: output=96becb9abb23c091 input=cdeaaf02d4346628]*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001737{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001738 PyObject *retval = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001739 X509 *x=NULL;
1740 BIO *cert;
Christian Heimes7f1305e2021-04-17 20:06:38 +02001741 _sslmodulestate *state = get_ssl_state(module);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001742
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001743 if ((cert=BIO_new(BIO_s_file())) == NULL) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02001744 PyErr_SetString(state->PySSLErrorObject,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001745 "Can't malloc memory to read file");
1746 goto fail0;
1747 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001748
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001749 if (BIO_read_filename(cert, PyBytes_AsString(path)) <= 0) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02001750 PyErr_SetString(state->PySSLErrorObject,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001751 "Can't open file");
1752 goto fail0;
1753 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001754
Alex Gaynor40dad952019-08-15 08:31:28 -04001755 x = PEM_read_bio_X509(cert, NULL, NULL, NULL);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001756 if (x == NULL) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02001757 PyErr_SetString(state->PySSLErrorObject,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001758 "Error decoding PEM-encoded file");
1759 goto fail0;
1760 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001761
Christian Heimes7f1305e2021-04-17 20:06:38 +02001762 retval = _decode_certificate(state, x);
Mark Dickinsonee55df52010-08-03 18:31:54 +00001763 X509_free(x);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001764
1765 fail0:
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001766 Py_DECREF(path);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001767 if (cert != NULL) BIO_free(cert);
1768 return retval;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001769}
1770
1771
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001772/*[clinic input]
Christian Heimes141c5e82018-02-24 21:10:57 +01001773_ssl._SSLSocket.getpeercert
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001774 der as binary_mode: bool = False
1775 /
1776
1777Returns the certificate for the peer.
1778
1779If no certificate was provided, returns None. If a certificate was
1780provided, but not validated, returns an empty dictionary. Otherwise
1781returns a dict containing information about the peer certificate.
1782
1783If the optional argument is True, returns a DER-encoded copy of the
1784peer certificate, or None if no certificate was provided. This will
1785return the certificate even if it wasn't validated.
1786[clinic start generated code]*/
1787
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001788static PyObject *
Christian Heimes141c5e82018-02-24 21:10:57 +01001789_ssl__SSLSocket_getpeercert_impl(PySSLSocket *self, int binary_mode)
1790/*[clinic end generated code: output=1f0ab66dfb693c88 input=c0fbe802e57629b7]*/
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001791{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001792 int verification;
Christian Heimes66dc33b2017-05-23 16:02:02 -07001793 X509 *peer_cert;
1794 PyObject *result;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001795
Christian Heimes66dc33b2017-05-23 16:02:02 -07001796 if (!SSL_is_init_finished(self->ssl)) {
Antoine Pitrou20b85552013-09-29 19:50:53 +02001797 PyErr_SetString(PyExc_ValueError,
1798 "handshake not done yet");
1799 return NULL;
1800 }
Christian Heimes66dc33b2017-05-23 16:02:02 -07001801 peer_cert = SSL_get_peer_certificate(self->ssl);
1802 if (peer_cert == NULL)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001803 Py_RETURN_NONE;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001804
Antoine Pitrou721738f2012-08-15 23:20:39 +02001805 if (binary_mode) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001806 /* return cert in DER-encoded format */
Christian Heimes7f1305e2021-04-17 20:06:38 +02001807 result = _certificate_to_der(get_state_sock(self), peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001808 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00001809 verification = SSL_CTX_get_verify_mode(SSL_get_SSL_CTX(self->ssl));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001810 if ((verification & SSL_VERIFY_PEER) == 0)
Christian Heimes66dc33b2017-05-23 16:02:02 -07001811 result = PyDict_New();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001812 else
Christian Heimes7f1305e2021-04-17 20:06:38 +02001813 result = _decode_certificate(get_state_sock(self), peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001814 }
Christian Heimes66dc33b2017-05-23 16:02:02 -07001815 X509_free(peer_cert);
1816 return result;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001817}
1818
Christian Heimes666991f2021-04-26 15:01:40 +02001819/*[clinic input]
1820_ssl._SSLSocket.get_verified_chain
1821
1822[clinic start generated code]*/
1823
1824static PyObject *
1825_ssl__SSLSocket_get_verified_chain_impl(PySSLSocket *self)
1826/*[clinic end generated code: output=802421163cdc3110 input=5fb0714f77e2bd51]*/
1827{
1828 /* borrowed reference */
1829 STACK_OF(X509) *chain = SSL_get0_verified_chain(self->ssl);
1830 if (chain == NULL) {
1831 Py_RETURN_NONE;
1832 }
1833 return _PySSL_CertificateFromX509Stack(self->ctx->state, chain, 1);
1834}
1835
1836/*[clinic input]
1837_ssl._SSLSocket.get_unverified_chain
1838
1839[clinic start generated code]*/
1840
1841static PyObject *
1842_ssl__SSLSocket_get_unverified_chain_impl(PySSLSocket *self)
1843/*[clinic end generated code: output=5acdae414e13f913 input=78c33c360c635cb5]*/
1844{
1845 PyObject *retval;
1846 /* borrowed reference */
1847 /* TODO: include SSL_get_peer_certificate() for server-side sockets */
1848 STACK_OF(X509) *chain = SSL_get_peer_cert_chain(self->ssl);
1849 if (chain == NULL) {
1850 Py_RETURN_NONE;
1851 }
1852 retval = _PySSL_CertificateFromX509Stack(self->ctx->state, chain, 1);
1853 if (retval == NULL) {
1854 return NULL;
1855 }
1856 /* OpenSSL does not include peer cert for server side connections */
1857 if (self->socket_type == PY_SSL_SERVER) {
1858 PyObject *peerobj = NULL;
1859 X509 *peer = SSL_get_peer_certificate(self->ssl);
1860
1861 if (peer == NULL) {
1862 peerobj = Py_None;
1863 Py_INCREF(peerobj);
1864 } else {
1865 /* consume X509 reference on success */
1866 peerobj = _PySSL_CertificateFromX509(self->ctx->state, peer, 0);
1867 if (peerobj == NULL) {
1868 X509_free(peer);
1869 Py_DECREF(retval);
1870 return NULL;
1871 }
1872 }
1873 int res = PyList_Insert(retval, 0, peerobj);
1874 Py_DECREF(peerobj);
1875 if (res < 0) {
1876 Py_DECREF(retval);
1877 return NULL;
1878 }
1879 }
1880 return retval;
1881}
1882
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001883static PyObject *
1884cipher_to_tuple(const SSL_CIPHER *cipher)
1885{
1886 const char *cipher_name, *cipher_protocol;
1887 PyObject *v, *retval = PyTuple_New(3);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001888 if (retval == NULL)
1889 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001890
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001891 cipher_name = SSL_CIPHER_get_name(cipher);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001892 if (cipher_name == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001893 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001894 PyTuple_SET_ITEM(retval, 0, Py_None);
1895 } else {
1896 v = PyUnicode_FromString(cipher_name);
1897 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001898 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001899 PyTuple_SET_ITEM(retval, 0, v);
1900 }
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001901
1902 cipher_protocol = SSL_CIPHER_get_version(cipher);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001903 if (cipher_protocol == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001904 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001905 PyTuple_SET_ITEM(retval, 1, Py_None);
1906 } else {
1907 v = PyUnicode_FromString(cipher_protocol);
1908 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001909 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001910 PyTuple_SET_ITEM(retval, 1, v);
1911 }
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001912
1913 v = PyLong_FromLong(SSL_CIPHER_get_bits(cipher, NULL));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001914 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001915 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001916 PyTuple_SET_ITEM(retval, 2, v);
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001917
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001918 return retval;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001919
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001920 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001921 Py_DECREF(retval);
1922 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001923}
1924
Christian Heimes25bfcd52016-09-06 00:04:45 +02001925static PyObject *
1926cipher_to_dict(const SSL_CIPHER *cipher)
1927{
1928 const char *cipher_name, *cipher_protocol;
1929
1930 unsigned long cipher_id;
1931 int alg_bits, strength_bits, len;
1932 char buf[512] = {0};
Christian Heimes25bfcd52016-09-06 00:04:45 +02001933 int aead, nid;
1934 const char *skcipher = NULL, *digest = NULL, *kx = NULL, *auth = NULL;
Christian Heimes25bfcd52016-09-06 00:04:45 +02001935
1936 /* can be NULL */
1937 cipher_name = SSL_CIPHER_get_name(cipher);
1938 cipher_protocol = SSL_CIPHER_get_version(cipher);
1939 cipher_id = SSL_CIPHER_get_id(cipher);
1940 SSL_CIPHER_description(cipher, buf, sizeof(buf) - 1);
Segev Finer5cff6372017-07-27 01:19:17 +03001941 /* Downcast to avoid a warning. Safe since buf is always 512 bytes */
1942 len = (int)strlen(buf);
Christian Heimes25bfcd52016-09-06 00:04:45 +02001943 if (len > 1 && buf[len-1] == '\n')
1944 buf[len-1] = '\0';
1945 strength_bits = SSL_CIPHER_get_bits(cipher, &alg_bits);
1946
Christian Heimes25bfcd52016-09-06 00:04:45 +02001947 aead = SSL_CIPHER_is_aead(cipher);
1948 nid = SSL_CIPHER_get_cipher_nid(cipher);
1949 skcipher = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1950 nid = SSL_CIPHER_get_digest_nid(cipher);
1951 digest = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1952 nid = SSL_CIPHER_get_kx_nid(cipher);
1953 kx = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1954 nid = SSL_CIPHER_get_auth_nid(cipher);
1955 auth = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
Christian Heimes25bfcd52016-09-06 00:04:45 +02001956
Victor Stinner410b9882016-09-12 12:00:23 +02001957 return Py_BuildValue(
Christian Heimes25bfcd52016-09-06 00:04:45 +02001958 "{sksssssssisi"
Christian Heimes25bfcd52016-09-06 00:04:45 +02001959 "sOssssssss"
Christian Heimes25bfcd52016-09-06 00:04:45 +02001960 "}",
1961 "id", cipher_id,
1962 "name", cipher_name,
1963 "protocol", cipher_protocol,
1964 "description", buf,
1965 "strength_bits", strength_bits,
1966 "alg_bits", alg_bits
Christian Heimes25bfcd52016-09-06 00:04:45 +02001967 ,"aead", aead ? Py_True : Py_False,
1968 "symmetric", skcipher,
1969 "digest", digest,
1970 "kea", kx,
1971 "auth", auth
Christian Heimes25bfcd52016-09-06 00:04:45 +02001972 );
Christian Heimes25bfcd52016-09-06 00:04:45 +02001973}
Christian Heimes25bfcd52016-09-06 00:04:45 +02001974
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001975/*[clinic input]
1976_ssl._SSLSocket.shared_ciphers
1977[clinic start generated code]*/
1978
1979static PyObject *
1980_ssl__SSLSocket_shared_ciphers_impl(PySSLSocket *self)
1981/*[clinic end generated code: output=3d174ead2e42c4fd input=0bfe149da8fe6306]*/
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001982{
1983 STACK_OF(SSL_CIPHER) *ciphers;
1984 int i;
1985 PyObject *res;
1986
Christian Heimes598894f2016-09-05 23:19:05 +02001987 ciphers = SSL_get_ciphers(self->ssl);
1988 if (!ciphers)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001989 Py_RETURN_NONE;
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001990 res = PyList_New(sk_SSL_CIPHER_num(ciphers));
1991 if (!res)
1992 return NULL;
1993 for (i = 0; i < sk_SSL_CIPHER_num(ciphers); i++) {
1994 PyObject *tup = cipher_to_tuple(sk_SSL_CIPHER_value(ciphers, i));
1995 if (!tup) {
1996 Py_DECREF(res);
1997 return NULL;
1998 }
1999 PyList_SET_ITEM(res, i, tup);
2000 }
2001 return res;
2002}
2003
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002004/*[clinic input]
2005_ssl._SSLSocket.cipher
2006[clinic start generated code]*/
2007
2008static PyObject *
2009_ssl__SSLSocket_cipher_impl(PySSLSocket *self)
2010/*[clinic end generated code: output=376417c16d0e5815 input=548fb0e27243796d]*/
Benjamin Peterson4cb17812015-01-07 11:14:26 -06002011{
2012 const SSL_CIPHER *current;
2013
2014 if (self->ssl == NULL)
2015 Py_RETURN_NONE;
2016 current = SSL_get_current_cipher(self->ssl);
2017 if (current == NULL)
2018 Py_RETURN_NONE;
2019 return cipher_to_tuple(current);
2020}
2021
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002022/*[clinic input]
2023_ssl._SSLSocket.version
2024[clinic start generated code]*/
2025
2026static PyObject *
2027_ssl__SSLSocket_version_impl(PySSLSocket *self)
2028/*[clinic end generated code: output=178aed33193b2cdb input=900186a503436fd6]*/
Antoine Pitrou47e40422014-09-04 21:00:10 +02002029{
2030 const char *version;
2031
2032 if (self->ssl == NULL)
2033 Py_RETURN_NONE;
Christian Heimes68771112017-09-05 21:55:40 -07002034 if (!SSL_is_init_finished(self->ssl)) {
2035 /* handshake not finished */
2036 Py_RETURN_NONE;
2037 }
Antoine Pitrou47e40422014-09-04 21:00:10 +02002038 version = SSL_get_version(self->ssl);
2039 if (!strcmp(version, "unknown"))
2040 Py_RETURN_NONE;
2041 return PyUnicode_FromString(version);
2042}
2043
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002044/*[clinic input]
2045_ssl._SSLSocket.selected_alpn_protocol
2046[clinic start generated code]*/
2047
2048static PyObject *
2049_ssl__SSLSocket_selected_alpn_protocol_impl(PySSLSocket *self)
2050/*[clinic end generated code: output=ec33688b303d250f input=442de30e35bc2913]*/
2051{
Benjamin Petersoncca27322015-01-23 16:35:37 -05002052 const unsigned char *out;
2053 unsigned int outlen;
2054
2055 SSL_get0_alpn_selected(self->ssl, &out, &outlen);
2056
2057 if (out == NULL)
2058 Py_RETURN_NONE;
2059 return PyUnicode_FromStringAndSize((char *)out, outlen);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002060}
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002061
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002062/*[clinic input]
2063_ssl._SSLSocket.compression
2064[clinic start generated code]*/
2065
2066static PyObject *
2067_ssl__SSLSocket_compression_impl(PySSLSocket *self)
2068/*[clinic end generated code: output=bd16cb1bb4646ae7 input=5d059d0a2bbc32c8]*/
2069{
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01002070#ifdef OPENSSL_NO_COMP
2071 Py_RETURN_NONE;
2072#else
2073 const COMP_METHOD *comp_method;
2074 const char *short_name;
2075
2076 if (self->ssl == NULL)
2077 Py_RETURN_NONE;
2078 comp_method = SSL_get_current_compression(self->ssl);
Christian Heimes598894f2016-09-05 23:19:05 +02002079 if (comp_method == NULL || COMP_get_type(comp_method) == NID_undef)
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01002080 Py_RETURN_NONE;
Christian Heimes281e5f82016-09-06 01:10:39 +02002081 short_name = OBJ_nid2sn(COMP_get_type(comp_method));
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01002082 if (short_name == NULL)
2083 Py_RETURN_NONE;
2084 return PyUnicode_DecodeFSDefault(short_name);
2085#endif
2086}
2087
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002088static PySSLContext *PySSL_get_context(PySSLSocket *self, void *closure) {
2089 Py_INCREF(self->ctx);
2090 return self->ctx;
2091}
2092
2093static int PySSL_set_context(PySSLSocket *self, PyObject *value,
2094 void *closure) {
2095
Christian Heimes7f1305e2021-04-17 20:06:38 +02002096 if (PyObject_TypeCheck(value, self->ctx->state->PySSLContext_Type)) {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002097 Py_INCREF(value);
Serhiy Storchaka57a01d32016-04-10 18:05:40 +03002098 Py_SETREF(self->ctx, (PySSLContext *)value);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002099 SSL_set_SSL_CTX(self->ssl, self->ctx->ctx);
Christian Heimes77cde502021-03-21 16:13:09 +01002100 /* Set SSL* internal msg_callback to state of new context's state */
2101 SSL_set_msg_callback(
2102 self->ssl,
2103 self->ctx->msg_cb ? _PySSL_msg_callback : NULL
2104 );
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002105 } else {
Ned Deily4531ec72018-06-11 20:26:28 -04002106 PyErr_SetString(PyExc_TypeError, "The value must be a SSLContext");
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002107 return -1;
2108 }
2109
2110 return 0;
2111}
2112
2113PyDoc_STRVAR(PySSL_set_context_doc,
2114"_setter_context(ctx)\n\
2115\
2116This changes the context associated with the SSLSocket. This is typically\n\
Christian Heimes11a14932018-02-24 02:35:08 +01002117used from within a callback function set by the sni_callback\n\
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002118on the SSLContext to change the certificate information associated with the\n\
2119SSLSocket before the cryptographic exchange handshake messages\n");
2120
2121
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002122static PyObject *
2123PySSL_get_server_side(PySSLSocket *self, void *c)
2124{
2125 return PyBool_FromLong(self->socket_type == PY_SSL_SERVER);
2126}
2127
2128PyDoc_STRVAR(PySSL_get_server_side_doc,
2129"Whether this is a server-side socket.");
2130
2131static PyObject *
2132PySSL_get_server_hostname(PySSLSocket *self, void *c)
2133{
2134 if (self->server_hostname == NULL)
2135 Py_RETURN_NONE;
2136 Py_INCREF(self->server_hostname);
2137 return self->server_hostname;
2138}
2139
2140PyDoc_STRVAR(PySSL_get_server_hostname_doc,
2141"The currently set server hostname (for SNI).");
2142
2143static PyObject *
2144PySSL_get_owner(PySSLSocket *self, void *c)
2145{
2146 PyObject *owner;
2147
2148 if (self->owner == NULL)
2149 Py_RETURN_NONE;
2150
2151 owner = PyWeakref_GetObject(self->owner);
2152 Py_INCREF(owner);
2153 return owner;
2154}
2155
2156static int
2157PySSL_set_owner(PySSLSocket *self, PyObject *value, void *c)
2158{
Serhiy Storchaka48842712016-04-06 09:45:48 +03002159 Py_XSETREF(self->owner, PyWeakref_NewRef(value, NULL));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002160 if (self->owner == NULL)
2161 return -1;
2162 return 0;
2163}
2164
2165PyDoc_STRVAR(PySSL_get_owner_doc,
2166"The Python-level owner of this object.\
2167Passed as \"self\" in servername callback.");
2168
Christian Heimesc7f70692019-05-31 11:44:05 +02002169static int
2170PySSL_traverse(PySSLSocket *self, visitproc visit, void *arg)
2171{
2172 Py_VISIT(self->exc_type);
2173 Py_VISIT(self->exc_value);
2174 Py_VISIT(self->exc_tb);
Miss Islington (bot)ea47a8a2021-05-27 09:25:22 -07002175 Py_VISIT(Py_TYPE(self));
Christian Heimesc7f70692019-05-31 11:44:05 +02002176 return 0;
2177}
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002178
Christian Heimesc7f70692019-05-31 11:44:05 +02002179static int
2180PySSL_clear(PySSLSocket *self)
2181{
2182 Py_CLEAR(self->exc_type);
2183 Py_CLEAR(self->exc_value);
2184 Py_CLEAR(self->exc_tb);
2185 return 0;
2186}
2187
2188static void
2189PySSL_dealloc(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002190{
Christian Heimes5c36da72020-11-20 09:40:12 +01002191 PyTypeObject *tp = Py_TYPE(self);
Miss Islington (bot)ea47a8a2021-05-27 09:25:22 -07002192 PyObject_GC_UnTrack(self);
2193 if (self->ssl) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002194 SSL_free(self->ssl);
Miss Islington (bot)ea47a8a2021-05-27 09:25:22 -07002195 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002196 Py_XDECREF(self->Socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002197 Py_XDECREF(self->ctx);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002198 Py_XDECREF(self->server_hostname);
2199 Py_XDECREF(self->owner);
Miss Islington (bot)ea47a8a2021-05-27 09:25:22 -07002200 PyObject_GC_Del(self);
Christian Heimes5c36da72020-11-20 09:40:12 +01002201 Py_DECREF(tp);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002202}
2203
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002204/* If the socket has a timeout, do a select()/poll() on the socket.
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002205 The argument writing indicates the direction.
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00002206 Returns one of the possibilities in the timeout_state enum (above).
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002207 */
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00002208
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002209static int
Victor Stinner14690702015-04-06 22:46:13 +02002210PySSL_select(PySocketSockObject *s, int writing, _PyTime_t timeout)
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002211{
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002212 int rc;
2213#ifdef HAVE_POLL
2214 struct pollfd pollfd;
2215 _PyTime_t ms;
2216#else
2217 int nfds;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002218 fd_set fds;
2219 struct timeval tv;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002220#endif
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002221
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002222 /* Nothing to do unless we're in timeout mode (not non-blocking) */
Victor Stinner14690702015-04-06 22:46:13 +02002223 if ((s == NULL) || (timeout == 0))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002224 return SOCKET_IS_NONBLOCKING;
Victor Stinner14690702015-04-06 22:46:13 +02002225 else if (timeout < 0) {
2226 if (s->sock_timeout > 0)
2227 return SOCKET_HAS_TIMED_OUT;
2228 else
2229 return SOCKET_IS_BLOCKING;
2230 }
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002231
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002232 /* Guard against closed socket */
Victor Stinner524714e2016-07-22 17:43:59 +02002233 if (s->sock_fd == INVALID_SOCKET)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002234 return SOCKET_HAS_BEEN_CLOSED;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002235
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002236 /* Prefer poll, if available, since you can poll() any fd
2237 * which can't be done with select(). */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002238#ifdef HAVE_POLL
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002239 pollfd.fd = s->sock_fd;
2240 pollfd.events = writing ? POLLOUT : POLLIN;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002241
Victor Stinner14690702015-04-06 22:46:13 +02002242 /* timeout is in seconds, poll() uses milliseconds */
2243 ms = (int)_PyTime_AsMilliseconds(timeout, _PyTime_ROUND_CEILING);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002244 assert(ms <= INT_MAX);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002245
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002246 PySSL_BEGIN_ALLOW_THREADS
2247 rc = poll(&pollfd, 1, (int)ms);
2248 PySSL_END_ALLOW_THREADS
2249#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002250 /* Guard against socket too large for select*/
Charles-François Nataliaa26b272011-08-28 17:51:43 +02002251 if (!_PyIsSelectable_fd(s->sock_fd))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002252 return SOCKET_TOO_LARGE_FOR_SELECT;
Neal Norwitz082b2df2006-02-07 07:04:46 +00002253
Victor Stinner14690702015-04-06 22:46:13 +02002254 _PyTime_AsTimeval_noraise(timeout, &tv, _PyTime_ROUND_CEILING);
Victor Stinnere2452312015-03-28 03:00:46 +01002255
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002256 FD_ZERO(&fds);
2257 FD_SET(s->sock_fd, &fds);
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002258
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002259 /* Wait until the socket becomes ready */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002260 PySSL_BEGIN_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002261 nfds = Py_SAFE_DOWNCAST(s->sock_fd+1, SOCKET_T, int);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002262 if (writing)
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002263 rc = select(nfds, NULL, &fds, NULL, &tv);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002264 else
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002265 rc = select(nfds, &fds, NULL, NULL, &tv);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002266 PySSL_END_ALLOW_THREADS
Bill Janssen6e027db2007-11-15 22:23:56 +00002267#endif
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002268
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002269 /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
2270 (when we are able to write or when there's something to read) */
2271 return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002272}
2273
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002274/*[clinic input]
2275_ssl._SSLSocket.write
2276 b: Py_buffer
2277 /
2278
2279Writes the bytes-like object b into the SSL object.
2280
2281Returns the number of bytes written.
2282[clinic start generated code]*/
2283
2284static PyObject *
2285_ssl__SSLSocket_write_impl(PySSLSocket *self, Py_buffer *b)
2286/*[clinic end generated code: output=aa7a6be5527358d8 input=77262d994fe5100a]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002287{
Christian Heimes89d15502021-04-19 06:55:30 +02002288 size_t count = 0;
2289 int retval;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002290 int sockstate;
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002291 _PySSLError err;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002292 int nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002293 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002294 _PyTime_t timeout, deadline = 0;
2295 int has_timeout;
Bill Janssen54cc54c2007-12-14 22:08:56 +00002296
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002297 if (sock != NULL) {
2298 if (((PyObject*)sock) == Py_None) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02002299 _setSSLError(get_state_sock(self),
2300 "Underlying socket connection gone",
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002301 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2302 return NULL;
2303 }
2304 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002305 }
2306
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002307 if (sock != NULL) {
2308 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002309 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002310 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2311 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
2312 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002313
Victor Stinner14690702015-04-06 22:46:13 +02002314 timeout = GET_SOCKET_TIMEOUT(sock);
2315 has_timeout = (timeout > 0);
2316 if (has_timeout)
2317 deadline = _PyTime_GetMonotonicClock() + timeout;
2318
2319 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002320 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Christian Heimes03c8ddd2020-11-20 09:26:07 +01002321 PyErr_SetString(PyExc_TimeoutError,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002322 "The write operation timed out");
2323 goto error;
2324 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02002325 PyErr_SetString(get_state_sock(self)->PySSLErrorObject,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002326 "Underlying socket has been closed.");
2327 goto error;
2328 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02002329 PyErr_SetString(get_state_sock(self)->PySSLErrorObject,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002330 "Underlying socket too large for select().");
2331 goto error;
2332 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002333
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002334 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002335 PySSL_BEGIN_ALLOW_THREADS
Christian Heimes89d15502021-04-19 06:55:30 +02002336 retval = SSL_write_ex(self->ssl, b->buf, (int)b->len, &count);
2337 err = _PySSL_errno(retval == 0, self->ssl, retval);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002338 PySSL_END_ALLOW_THREADS
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002339 self->err = err;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002340
2341 if (PyErr_CheckSignals())
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002342 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002343
Victor Stinner14690702015-04-06 22:46:13 +02002344 if (has_timeout)
2345 timeout = deadline - _PyTime_GetMonotonicClock();
2346
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002347 if (err.ssl == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +02002348 sockstate = PySSL_select(sock, 0, timeout);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002349 } else if (err.ssl == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +02002350 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002351 } else {
2352 sockstate = SOCKET_OPERATION_OK;
2353 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002354
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002355 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Christian Heimes03c8ddd2020-11-20 09:26:07 +01002356 PyErr_SetString(PyExc_TimeoutError,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002357 "The write operation timed out");
2358 goto error;
2359 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02002360 PyErr_SetString(get_state_sock(self)->PySSLErrorObject,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002361 "Underlying socket has been closed.");
2362 goto error;
2363 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
2364 break;
2365 }
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002366 } while (err.ssl == SSL_ERROR_WANT_READ ||
2367 err.ssl == SSL_ERROR_WANT_WRITE);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002368
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002369 Py_XDECREF(sock);
Christian Heimes89d15502021-04-19 06:55:30 +02002370 if (retval == 0)
2371 return PySSL_SetError(self, retval, __FILE__, __LINE__);
Christian Heimesc7f70692019-05-31 11:44:05 +02002372 if (PySSL_ChainExceptions(self) < 0)
2373 return NULL;
Christian Heimes89d15502021-04-19 06:55:30 +02002374 return PyLong_FromSize_t(count);
Antoine Pitrou7d7aede2009-11-25 18:55:32 +00002375error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002376 Py_XDECREF(sock);
Christian Heimesc7f70692019-05-31 11:44:05 +02002377 PySSL_ChainExceptions(self);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002378 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002379}
2380
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002381/*[clinic input]
2382_ssl._SSLSocket.pending
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002383
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002384Returns the number of already decrypted bytes available for read, pending on the connection.
2385[clinic start generated code]*/
2386
2387static PyObject *
2388_ssl__SSLSocket_pending_impl(PySSLSocket *self)
2389/*[clinic end generated code: output=983d9fecdc308a83 input=2b77487d6dfd597f]*/
Bill Janssen6e027db2007-11-15 22:23:56 +00002390{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002391 int count = 0;
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002392 _PySSLError err;
Bill Janssen6e027db2007-11-15 22:23:56 +00002393
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002394 PySSL_BEGIN_ALLOW_THREADS
2395 count = SSL_pending(self->ssl);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002396 err = _PySSL_errno(count < 0, self->ssl, count);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002397 PySSL_END_ALLOW_THREADS
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002398 self->err = err;
2399
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002400 if (count < 0)
2401 return PySSL_SetError(self, count, __FILE__, __LINE__);
2402 else
2403 return PyLong_FromLong(count);
Bill Janssen6e027db2007-11-15 22:23:56 +00002404}
2405
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002406/*[clinic input]
2407_ssl._SSLSocket.read
2408 size as len: int
2409 [
Larry Hastingsdbfdc382015-05-04 06:59:46 -07002410 buffer: Py_buffer(accept={rwbuffer})
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002411 ]
2412 /
Bill Janssen6e027db2007-11-15 22:23:56 +00002413
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002414Read up to size bytes from the SSL socket.
2415[clinic start generated code]*/
2416
2417static PyObject *
2418_ssl__SSLSocket_read_impl(PySSLSocket *self, int len, int group_right_1,
2419 Py_buffer *buffer)
Larry Hastingsdbfdc382015-05-04 06:59:46 -07002420/*[clinic end generated code: output=00097776cec2a0af input=ff157eb918d0905b]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002421{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002422 PyObject *dest = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002423 char *mem;
Christian Heimes89d15502021-04-19 06:55:30 +02002424 size_t count = 0;
2425 int retval;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002426 int sockstate;
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002427 _PySSLError err;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002428 int nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002429 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002430 _PyTime_t timeout, deadline = 0;
2431 int has_timeout;
Bill Janssen54cc54c2007-12-14 22:08:56 +00002432
Martin Panter5503d472016-03-27 05:35:19 +00002433 if (!group_right_1 && len < 0) {
2434 PyErr_SetString(PyExc_ValueError, "size should not be negative");
2435 return NULL;
2436 }
2437
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002438 if (sock != NULL) {
2439 if (((PyObject*)sock) == Py_None) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02002440 _setSSLError(get_state_sock(self),
2441 "Underlying socket connection gone",
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002442 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2443 return NULL;
2444 }
2445 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002446 }
2447
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002448 if (!group_right_1) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002449 dest = PyBytes_FromStringAndSize(NULL, len);
2450 if (dest == NULL)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002451 goto error;
Martin Panterbed7f1a2016-07-11 00:17:13 +00002452 if (len == 0) {
2453 Py_XDECREF(sock);
2454 return dest;
2455 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002456 mem = PyBytes_AS_STRING(dest);
2457 }
2458 else {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002459 mem = buffer->buf;
2460 if (len <= 0 || len > buffer->len) {
2461 len = (int) buffer->len;
2462 if (buffer->len != len) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002463 PyErr_SetString(PyExc_OverflowError,
2464 "maximum length can't fit in a C 'int'");
2465 goto error;
2466 }
Martin Panterbed7f1a2016-07-11 00:17:13 +00002467 if (len == 0) {
2468 count = 0;
2469 goto done;
2470 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002471 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002472 }
2473
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002474 if (sock != NULL) {
2475 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002476 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002477 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2478 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
2479 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002480
Victor Stinner14690702015-04-06 22:46:13 +02002481 timeout = GET_SOCKET_TIMEOUT(sock);
2482 has_timeout = (timeout > 0);
2483 if (has_timeout)
2484 deadline = _PyTime_GetMonotonicClock() + timeout;
2485
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002486 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002487 PySSL_BEGIN_ALLOW_THREADS
Christian Heimes89d15502021-04-19 06:55:30 +02002488 retval = SSL_read_ex(self->ssl, mem, len, &count);
2489 err = _PySSL_errno(retval == 0, self->ssl, retval);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002490 PySSL_END_ALLOW_THREADS
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002491 self->err = err;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002492
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002493 if (PyErr_CheckSignals())
2494 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002495
Victor Stinner14690702015-04-06 22:46:13 +02002496 if (has_timeout)
2497 timeout = deadline - _PyTime_GetMonotonicClock();
2498
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002499 if (err.ssl == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +02002500 sockstate = PySSL_select(sock, 0, timeout);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002501 } else if (err.ssl == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +02002502 sockstate = PySSL_select(sock, 1, timeout);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002503 } else if (err.ssl == SSL_ERROR_ZERO_RETURN &&
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002504 SSL_get_shutdown(self->ssl) == SSL_RECEIVED_SHUTDOWN)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002505 {
2506 count = 0;
2507 goto done;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002508 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002509 else
2510 sockstate = SOCKET_OPERATION_OK;
2511
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002512 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Christian Heimes03c8ddd2020-11-20 09:26:07 +01002513 PyErr_SetString(PyExc_TimeoutError,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002514 "The read operation timed out");
2515 goto error;
2516 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
2517 break;
2518 }
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002519 } while (err.ssl == SSL_ERROR_WANT_READ ||
2520 err.ssl == SSL_ERROR_WANT_WRITE);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002521
Christian Heimes89d15502021-04-19 06:55:30 +02002522 if (retval == 0) {
2523 PySSL_SetError(self, retval, __FILE__, __LINE__);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002524 goto error;
2525 }
Christian Heimesc7f70692019-05-31 11:44:05 +02002526 if (self->exc_type != NULL)
2527 goto error;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002528
2529done:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002530 Py_XDECREF(sock);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002531 if (!group_right_1) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002532 _PyBytes_Resize(&dest, count);
2533 return dest;
2534 }
2535 else {
Christian Heimes89d15502021-04-19 06:55:30 +02002536 return PyLong_FromSize_t(count);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002537 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002538
2539error:
Christian Heimesc7f70692019-05-31 11:44:05 +02002540 PySSL_ChainExceptions(self);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002541 Py_XDECREF(sock);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002542 if (!group_right_1)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002543 Py_XDECREF(dest);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002544 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002545}
2546
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002547/*[clinic input]
2548_ssl._SSLSocket.shutdown
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002549
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002550Does the SSL shutdown handshake with the remote end.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002551[clinic start generated code]*/
2552
2553static PyObject *
2554_ssl__SSLSocket_shutdown_impl(PySSLSocket *self)
Christian Heimes141c5e82018-02-24 21:10:57 +01002555/*[clinic end generated code: output=ca1aa7ed9d25ca42 input=11d39e69b0a2bf4a]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00002556{
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002557 _PySSLError err;
2558 int sockstate, nonblocking, ret;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002559 int zeros = 0;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002560 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002561 _PyTime_t timeout, deadline = 0;
2562 int has_timeout;
Bill Janssen40a0f662008-08-12 16:56:25 +00002563
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002564 if (sock != NULL) {
2565 /* Guard against closed socket */
Victor Stinner524714e2016-07-22 17:43:59 +02002566 if ((((PyObject*)sock) == Py_None) || (sock->sock_fd == INVALID_SOCKET)) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02002567 _setSSLError(get_state_sock(self),
2568 "Underlying socket connection gone",
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002569 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2570 return NULL;
2571 }
2572 Py_INCREF(sock);
2573
2574 /* Just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002575 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002576 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2577 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002578 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002579
Victor Stinner14690702015-04-06 22:46:13 +02002580 timeout = GET_SOCKET_TIMEOUT(sock);
2581 has_timeout = (timeout > 0);
2582 if (has_timeout)
2583 deadline = _PyTime_GetMonotonicClock() + timeout;
2584
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002585 while (1) {
2586 PySSL_BEGIN_ALLOW_THREADS
2587 /* Disable read-ahead so that unwrap can work correctly.
2588 * Otherwise OpenSSL might read in too much data,
2589 * eating clear text data that happens to be
2590 * transmitted after the SSL shutdown.
Ezio Melotti85a86292013-08-17 16:57:41 +03002591 * Should be safe to call repeatedly every time this
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002592 * function is used and the shutdown_seen_zero != 0
2593 * condition is met.
2594 */
2595 if (self->shutdown_seen_zero)
2596 SSL_set_read_ahead(self->ssl, 0);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002597 ret = SSL_shutdown(self->ssl);
2598 err = _PySSL_errno(ret < 0, self->ssl, ret);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002599 PySSL_END_ALLOW_THREADS
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002600 self->err = err;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002601
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002602 /* If err == 1, a secure shutdown with SSL_shutdown() is complete */
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002603 if (ret > 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002604 break;
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002605 if (ret == 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002606 /* Don't loop endlessly; instead preserve legacy
2607 behaviour of trying SSL_shutdown() only twice.
2608 This looks necessary for OpenSSL < 0.9.8m */
2609 if (++zeros > 1)
2610 break;
2611 /* Shutdown was sent, now try receiving */
2612 self->shutdown_seen_zero = 1;
2613 continue;
Bill Janssen40a0f662008-08-12 16:56:25 +00002614 }
2615
Victor Stinner14690702015-04-06 22:46:13 +02002616 if (has_timeout)
2617 timeout = deadline - _PyTime_GetMonotonicClock();
2618
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002619 /* Possibly retry shutdown until timeout or failure */
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002620 if (err.ssl == SSL_ERROR_WANT_READ)
Victor Stinner14690702015-04-06 22:46:13 +02002621 sockstate = PySSL_select(sock, 0, timeout);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002622 else if (err.ssl == SSL_ERROR_WANT_WRITE)
Victor Stinner14690702015-04-06 22:46:13 +02002623 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002624 else
2625 break;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002626
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002627 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002628 if (err.ssl == SSL_ERROR_WANT_READ)
Christian Heimes03c8ddd2020-11-20 09:26:07 +01002629 PyErr_SetString(PyExc_TimeoutError,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002630 "The read operation timed out");
2631 else
Christian Heimes03c8ddd2020-11-20 09:26:07 +01002632 PyErr_SetString(PyExc_TimeoutError,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002633 "The write operation timed out");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002634 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002635 }
2636 else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02002637 PyErr_SetString(get_state_sock(self)->PySSLErrorObject,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002638 "Underlying socket too large for select().");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002639 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002640 }
2641 else if (sockstate != SOCKET_OPERATION_OK)
2642 /* Retain the SSL error code */
2643 break;
2644 }
Nathaniel J. Smithc0da5822018-09-21 21:44:12 -07002645 if (ret < 0) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002646 Py_XDECREF(sock);
Christian Heimesc7f70692019-05-31 11:44:05 +02002647 PySSL_SetError(self, ret, __FILE__, __LINE__);
2648 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002649 }
Christian Heimesc7f70692019-05-31 11:44:05 +02002650 if (self->exc_type != NULL)
2651 goto error;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002652 if (sock)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002653 /* It's already INCREF'ed */
2654 return (PyObject *) sock;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002655 else
2656 Py_RETURN_NONE;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002657
2658error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002659 Py_XDECREF(sock);
Christian Heimesc7f70692019-05-31 11:44:05 +02002660 PySSL_ChainExceptions(self);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002661 return NULL;
Bill Janssen40a0f662008-08-12 16:56:25 +00002662}
2663
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002664/*[clinic input]
Christian Heimes141c5e82018-02-24 21:10:57 +01002665_ssl._SSLSocket.get_channel_binding
2666 cb_type: str = "tls-unique"
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002667
Christian Heimes141c5e82018-02-24 21:10:57 +01002668Get channel binding data for current connection.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002669
Christian Heimes141c5e82018-02-24 21:10:57 +01002670Raise ValueError if the requested `cb_type` is not supported. Return bytes
2671of the data or None if the data is not available (e.g. before the handshake).
2672Only 'tls-unique' channel binding data from RFC 5929 is supported.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002673[clinic start generated code]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00002674
Antoine Pitroud6494802011-07-21 01:11:30 +02002675static PyObject *
Christian Heimes141c5e82018-02-24 21:10:57 +01002676_ssl__SSLSocket_get_channel_binding_impl(PySSLSocket *self,
2677 const char *cb_type)
2678/*[clinic end generated code: output=34bac9acb6a61d31 input=08b7e43b99c17d41]*/
Antoine Pitroud6494802011-07-21 01:11:30 +02002679{
Antoine Pitroud6494802011-07-21 01:11:30 +02002680 char buf[PySSL_CB_MAXLEN];
Victor Stinner9ee02032013-06-23 15:08:23 +02002681 size_t len;
Antoine Pitroud6494802011-07-21 01:11:30 +02002682
Christian Heimes141c5e82018-02-24 21:10:57 +01002683 if (strcmp(cb_type, "tls-unique") == 0) {
2684 if (SSL_session_reused(self->ssl) ^ !self->socket_type) {
2685 /* if session is resumed XOR we are the client */
2686 len = SSL_get_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2687 }
2688 else {
2689 /* if a new session XOR we are the server */
2690 len = SSL_get_peer_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2691 }
Antoine Pitroud6494802011-07-21 01:11:30 +02002692 }
2693 else {
Christian Heimes141c5e82018-02-24 21:10:57 +01002694 PyErr_Format(
2695 PyExc_ValueError,
2696 "'%s' channel binding type not implemented",
2697 cb_type
2698 );
2699 return NULL;
Antoine Pitroud6494802011-07-21 01:11:30 +02002700 }
2701
2702 /* It cannot be negative in current OpenSSL version as of July 2011 */
Antoine Pitroud6494802011-07-21 01:11:30 +02002703 if (len == 0)
2704 Py_RETURN_NONE;
2705
Christian Heimes141c5e82018-02-24 21:10:57 +01002706 return PyBytes_FromStringAndSize(buf, len);
Antoine Pitroud6494802011-07-21 01:11:30 +02002707}
2708
Christian Heimes9fb051f2018-09-23 08:32:31 +02002709/*[clinic input]
2710_ssl._SSLSocket.verify_client_post_handshake
2711
2712Initiate TLS 1.3 post-handshake authentication
2713[clinic start generated code]*/
2714
2715static PyObject *
2716_ssl__SSLSocket_verify_client_post_handshake_impl(PySSLSocket *self)
2717/*[clinic end generated code: output=532147f3b1341425 input=6bfa874810a3d889]*/
2718{
2719#ifdef TLS1_3_VERSION
2720 int err = SSL_verify_client_post_handshake(self->ssl);
2721 if (err == 0)
Christian Heimes7f1305e2021-04-17 20:06:38 +02002722 return _setSSLError(get_state_sock(self), NULL, 0, __FILE__, __LINE__);
Christian Heimes9fb051f2018-09-23 08:32:31 +02002723 else
2724 Py_RETURN_NONE;
2725#else
2726 PyErr_SetString(PyExc_NotImplementedError,
2727 "Post-handshake auth is not supported by your "
2728 "OpenSSL version.");
2729 return NULL;
2730#endif
2731}
2732
Christian Heimes99a65702016-09-10 23:44:53 +02002733static SSL_SESSION*
2734_ssl_session_dup(SSL_SESSION *session) {
2735 SSL_SESSION *newsession = NULL;
2736 int slen;
2737 unsigned char *senc = NULL, *p;
2738 const unsigned char *const_p;
2739
2740 if (session == NULL) {
2741 PyErr_SetString(PyExc_ValueError, "Invalid session");
2742 goto error;
2743 }
2744
2745 /* get length */
2746 slen = i2d_SSL_SESSION(session, NULL);
2747 if (slen == 0 || slen > 0xFF00) {
2748 PyErr_SetString(PyExc_ValueError, "i2d() failed.");
2749 goto error;
2750 }
2751 if ((senc = PyMem_Malloc(slen)) == NULL) {
2752 PyErr_NoMemory();
2753 goto error;
2754 }
2755 p = senc;
2756 if (!i2d_SSL_SESSION(session, &p)) {
2757 PyErr_SetString(PyExc_ValueError, "i2d() failed.");
2758 goto error;
2759 }
2760 const_p = senc;
2761 newsession = d2i_SSL_SESSION(NULL, &const_p, slen);
2762 if (session == NULL) {
2763 goto error;
2764 }
2765 PyMem_Free(senc);
2766 return newsession;
2767 error:
2768 if (senc != NULL) {
2769 PyMem_Free(senc);
2770 }
2771 return NULL;
2772}
Christian Heimes99a65702016-09-10 23:44:53 +02002773
2774static PyObject *
2775PySSL_get_session(PySSLSocket *self, void *closure) {
2776 /* get_session can return sessions from a server-side connection,
2777 * it does not check for handshake done or client socket. */
2778 PySSLSession *pysess;
2779 SSL_SESSION *session;
2780
Christian Heimes99a65702016-09-10 23:44:53 +02002781 /* duplicate session as workaround for session bug in OpenSSL 1.1.0,
2782 * https://github.com/openssl/openssl/issues/1550 */
2783 session = SSL_get0_session(self->ssl); /* borrowed reference */
2784 if (session == NULL) {
2785 Py_RETURN_NONE;
2786 }
2787 if ((session = _ssl_session_dup(session)) == NULL) {
2788 return NULL;
2789 }
Christian Heimes99a65702016-09-10 23:44:53 +02002790 session = SSL_get1_session(self->ssl);
2791 if (session == NULL) {
2792 Py_RETURN_NONE;
2793 }
Christian Heimes7f1305e2021-04-17 20:06:38 +02002794 pysess = PyObject_GC_New(PySSLSession, self->ctx->state->PySSLSession_Type);
Christian Heimes99a65702016-09-10 23:44:53 +02002795 if (pysess == NULL) {
2796 SSL_SESSION_free(session);
2797 return NULL;
2798 }
2799
2800 assert(self->ctx);
2801 pysess->ctx = self->ctx;
2802 Py_INCREF(pysess->ctx);
2803 pysess->session = session;
Christian Heimesa5d07652016-09-24 10:48:05 +02002804 PyObject_GC_Track(pysess);
Christian Heimes99a65702016-09-10 23:44:53 +02002805 return (PyObject *)pysess;
2806}
2807
2808static int PySSL_set_session(PySSLSocket *self, PyObject *value,
2809 void *closure)
2810 {
2811 PySSLSession *pysess;
Christian Heimes99a65702016-09-10 23:44:53 +02002812 SSL_SESSION *session;
Christian Heimes99a65702016-09-10 23:44:53 +02002813 int result;
2814
Christian Heimes7f1305e2021-04-17 20:06:38 +02002815 if (!Py_IS_TYPE(value, get_state_sock(self)->PySSLSession_Type)) {
Ned Deily4531ec72018-06-11 20:26:28 -04002816 PyErr_SetString(PyExc_TypeError, "Value is not a SSLSession.");
Christian Heimes99a65702016-09-10 23:44:53 +02002817 return -1;
2818 }
2819 pysess = (PySSLSession *)value;
2820
2821 if (self->ctx->ctx != pysess->ctx->ctx) {
2822 PyErr_SetString(PyExc_ValueError,
2823 "Session refers to a different SSLContext.");
2824 return -1;
2825 }
2826 if (self->socket_type != PY_SSL_CLIENT) {
2827 PyErr_SetString(PyExc_ValueError,
2828 "Cannot set session for server-side SSLSocket.");
2829 return -1;
2830 }
Christian Heimes66dc33b2017-05-23 16:02:02 -07002831 if (SSL_is_init_finished(self->ssl)) {
Christian Heimes99a65702016-09-10 23:44:53 +02002832 PyErr_SetString(PyExc_ValueError,
2833 "Cannot set session after handshake.");
2834 return -1;
2835 }
Christian Heimes99a65702016-09-10 23:44:53 +02002836 /* duplicate session */
2837 if ((session = _ssl_session_dup(pysess->session)) == NULL) {
2838 return -1;
2839 }
2840 result = SSL_set_session(self->ssl, session);
2841 /* free duplicate, SSL_set_session() bumps ref count */
2842 SSL_SESSION_free(session);
Christian Heimes99a65702016-09-10 23:44:53 +02002843 if (result == 0) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02002844 _setSSLError(get_state_sock(self), NULL, 0, __FILE__, __LINE__);
Christian Heimes99a65702016-09-10 23:44:53 +02002845 return -1;
2846 }
2847 return 0;
2848}
2849
2850PyDoc_STRVAR(PySSL_set_session_doc,
2851"_setter_session(session)\n\
2852\
2853Get / set SSLSession.");
2854
2855static PyObject *
2856PySSL_get_session_reused(PySSLSocket *self, void *closure) {
2857 if (SSL_session_reused(self->ssl)) {
2858 Py_RETURN_TRUE;
2859 } else {
2860 Py_RETURN_FALSE;
2861 }
2862}
2863
2864PyDoc_STRVAR(PySSL_get_session_reused_doc,
2865"Was the client session reused during handshake?");
2866
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002867static PyGetSetDef ssl_getsetlist[] = {
2868 {"context", (getter) PySSL_get_context,
2869 (setter) PySSL_set_context, PySSL_set_context_doc},
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002870 {"server_side", (getter) PySSL_get_server_side, NULL,
2871 PySSL_get_server_side_doc},
2872 {"server_hostname", (getter) PySSL_get_server_hostname, NULL,
2873 PySSL_get_server_hostname_doc},
2874 {"owner", (getter) PySSL_get_owner, (setter) PySSL_set_owner,
2875 PySSL_get_owner_doc},
Christian Heimes99a65702016-09-10 23:44:53 +02002876 {"session", (getter) PySSL_get_session,
2877 (setter) PySSL_set_session, PySSL_set_session_doc},
2878 {"session_reused", (getter) PySSL_get_session_reused, NULL,
2879 PySSL_get_session_reused_doc},
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002880 {NULL}, /* sentinel */
2881};
2882
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002883static PyMethodDef PySSLMethods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002884 _SSL__SSLSOCKET_DO_HANDSHAKE_METHODDEF
2885 _SSL__SSLSOCKET_WRITE_METHODDEF
2886 _SSL__SSLSOCKET_READ_METHODDEF
2887 _SSL__SSLSOCKET_PENDING_METHODDEF
Christian Heimes141c5e82018-02-24 21:10:57 +01002888 _SSL__SSLSOCKET_GETPEERCERT_METHODDEF
2889 _SSL__SSLSOCKET_GET_CHANNEL_BINDING_METHODDEF
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002890 _SSL__SSLSOCKET_CIPHER_METHODDEF
2891 _SSL__SSLSOCKET_SHARED_CIPHERS_METHODDEF
2892 _SSL__SSLSOCKET_VERSION_METHODDEF
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002893 _SSL__SSLSOCKET_SELECTED_ALPN_PROTOCOL_METHODDEF
2894 _SSL__SSLSOCKET_COMPRESSION_METHODDEF
2895 _SSL__SSLSOCKET_SHUTDOWN_METHODDEF
Christian Heimes9fb051f2018-09-23 08:32:31 +02002896 _SSL__SSLSOCKET_VERIFY_CLIENT_POST_HANDSHAKE_METHODDEF
Christian Heimes666991f2021-04-26 15:01:40 +02002897 _SSL__SSLSOCKET_GET_UNVERIFIED_CHAIN_METHODDEF
2898 _SSL__SSLSOCKET_GET_VERIFIED_CHAIN_METHODDEF
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002899 {NULL, NULL}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002900};
2901
Christian Heimes5c36da72020-11-20 09:40:12 +01002902static PyType_Slot PySSLSocket_slots[] = {
2903 {Py_tp_methods, PySSLMethods},
2904 {Py_tp_getset, ssl_getsetlist},
2905 {Py_tp_dealloc, PySSL_dealloc},
2906 {Py_tp_traverse, PySSL_traverse},
2907 {Py_tp_clear, PySSL_clear},
2908 {0, 0},
2909};
2910
2911static PyType_Spec PySSLSocket_spec = {
Miss Islington (bot)ea47a8a2021-05-27 09:25:22 -07002912 .name = "_ssl._SSLSocket",
2913 .basicsize = sizeof(PySSLSocket),
2914 .flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_IMMUTABLETYPE |
2915 Py_TPFLAGS_HAVE_GC),
2916 .slots = PySSLSocket_slots,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002917};
2918
Antoine Pitrou152efa22010-05-16 18:19:27 +00002919/*
2920 * _SSLContext objects
2921 */
2922
Christian Heimes5fe668c2016-09-12 00:01:11 +02002923static int
Christian Heimes9fb051f2018-09-23 08:32:31 +02002924_set_verify_mode(PySSLContext *self, enum py_ssl_cert_requirements n)
Christian Heimes5fe668c2016-09-12 00:01:11 +02002925{
2926 int mode;
2927 int (*verify_cb)(int, X509_STORE_CTX *) = NULL;
2928
2929 switch(n) {
2930 case PY_SSL_CERT_NONE:
2931 mode = SSL_VERIFY_NONE;
2932 break;
2933 case PY_SSL_CERT_OPTIONAL:
2934 mode = SSL_VERIFY_PEER;
2935 break;
2936 case PY_SSL_CERT_REQUIRED:
2937 mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
2938 break;
2939 default:
2940 PyErr_SetString(PyExc_ValueError,
2941 "invalid value for verify_mode");
2942 return -1;
2943 }
Christian Heimesf0f59302019-07-01 08:29:17 +02002944
2945 /* bpo-37428: newPySSLSocket() sets SSL_VERIFY_POST_HANDSHAKE flag for
2946 * server sockets and SSL_set_post_handshake_auth() for client. */
2947
Christian Heimes5fe668c2016-09-12 00:01:11 +02002948 /* keep current verify cb */
Christian Heimes9fb051f2018-09-23 08:32:31 +02002949 verify_cb = SSL_CTX_get_verify_callback(self->ctx);
2950 SSL_CTX_set_verify(self->ctx, mode, verify_cb);
Christian Heimes5fe668c2016-09-12 00:01:11 +02002951 return 0;
2952}
2953
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002954/*[clinic input]
2955@classmethod
2956_ssl._SSLContext.__new__
2957 protocol as proto_version: int
2958 /
2959[clinic start generated code]*/
2960
Antoine Pitrou152efa22010-05-16 18:19:27 +00002961static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002962_ssl__SSLContext_impl(PyTypeObject *type, int proto_version)
2963/*[clinic end generated code: output=2cf0d7a0741b6bd1 input=8d58a805b95fc534]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00002964{
Antoine Pitrou152efa22010-05-16 18:19:27 +00002965 PySSLContext *self;
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01002966 long options;
Christian Heimes2875c602021-04-19 07:27:10 +02002967 const SSL_METHOD *method = NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002968 SSL_CTX *ctx = NULL;
Christian Heimes61d478c2018-01-27 15:51:38 +01002969 X509_VERIFY_PARAM *params;
Christian Heimes358cfd42016-09-10 22:43:48 +02002970 int result;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002971
Christian Heimes7f1305e2021-04-17 20:06:38 +02002972 /* slower approach, walk MRO and get borrowed reference to module.
2973 * _PyType_GetModuleByDef is required for SSLContext subclasses */
2974 PyObject *module = _PyType_GetModuleByDef(type, &_sslmodule_def);
2975 if (module == NULL) {
2976 PyErr_SetString(PyExc_RuntimeError,
2977 "Cannot find internal module state");
2978 return NULL;
2979 }
2980
Christian Heimes6e8cda92020-05-16 03:33:05 +02002981 switch(proto_version) {
2982#if defined(SSL3_VERSION) && !defined(OPENSSL_NO_SSL3)
2983 case PY_SSL_VERSION_SSL3:
Christian Heimes2875c602021-04-19 07:27:10 +02002984 PY_SSL_DEPRECATED("PROTOCOL_SSLv3", 2, NULL);
2985 method = SSLv3_method();
Christian Heimes6e8cda92020-05-16 03:33:05 +02002986 break;
Benjamin Petersone32467c2014-12-05 21:59:35 -05002987#endif
Christian Heimesa871f692020-06-01 08:58:14 +02002988#if (defined(TLS1_VERSION) && \
2989 !defined(OPENSSL_NO_TLS1) && \
2990 !defined(OPENSSL_NO_TLS1_METHOD))
Christian Heimes6e8cda92020-05-16 03:33:05 +02002991 case PY_SSL_VERSION_TLS1:
Christian Heimes2875c602021-04-19 07:27:10 +02002992 PY_SSL_DEPRECATED("PROTOCOL_TLSv1", 2, NULL);
2993 method = TLSv1_method();
Christian Heimes6e8cda92020-05-16 03:33:05 +02002994 break;
Victor Stinner3de49192011-05-09 00:42:58 +02002995#endif
Christian Heimesa871f692020-06-01 08:58:14 +02002996#if (defined(TLS1_1_VERSION) && \
2997 !defined(OPENSSL_NO_TLS1_1) && \
2998 !defined(OPENSSL_NO_TLS1_1_METHOD))
Christian Heimes6e8cda92020-05-16 03:33:05 +02002999 case PY_SSL_VERSION_TLS1_1:
Christian Heimes2875c602021-04-19 07:27:10 +02003000 PY_SSL_DEPRECATED("PROTOCOL_TLSv1_1", 2, NULL);
3001 method = TLSv1_1_method();
Christian Heimes6e8cda92020-05-16 03:33:05 +02003002 break;
3003#endif
Christian Heimesa871f692020-06-01 08:58:14 +02003004#if (defined(TLS1_2_VERSION) && \
3005 !defined(OPENSSL_NO_TLS1_2) && \
3006 !defined(OPENSSL_NO_TLS1_2_METHOD))
Christian Heimes6e8cda92020-05-16 03:33:05 +02003007 case PY_SSL_VERSION_TLS1_2:
Christian Heimes2875c602021-04-19 07:27:10 +02003008 PY_SSL_DEPRECATED("PROTOCOL_TLSv1_2", 2, NULL);
3009 method = TLSv1_2_method();
Christian Heimes6e8cda92020-05-16 03:33:05 +02003010 break;
3011#endif
3012 case PY_SSL_VERSION_TLS:
Christian Heimes2875c602021-04-19 07:27:10 +02003013 PY_SSL_DEPRECATED("PROTOCOL_TLS", 2, NULL);
3014 method = TLS_method();
Christian Heimes6e8cda92020-05-16 03:33:05 +02003015 break;
3016 case PY_SSL_VERSION_TLS_CLIENT:
Christian Heimes2875c602021-04-19 07:27:10 +02003017 method = TLS_client_method();
Christian Heimes6e8cda92020-05-16 03:33:05 +02003018 break;
3019 case PY_SSL_VERSION_TLS_SERVER:
Christian Heimes2875c602021-04-19 07:27:10 +02003020 method = TLS_server_method();
Christian Heimes6e8cda92020-05-16 03:33:05 +02003021 break;
3022 default:
Christian Heimes2875c602021-04-19 07:27:10 +02003023 method = NULL;
Christian Heimes6e8cda92020-05-16 03:33:05 +02003024 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003025
Christian Heimes2875c602021-04-19 07:27:10 +02003026 if (method == NULL) {
3027 PyErr_Format(PyExc_ValueError,
3028 "invalid or unsupported protocol version %i",
3029 proto_version);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003030 return NULL;
3031 }
Christian Heimes2875c602021-04-19 07:27:10 +02003032
3033 PySSL_BEGIN_ALLOW_THREADS
3034 ctx = SSL_CTX_new(method);
3035 PySSL_END_ALLOW_THREADS
3036
Antoine Pitrou152efa22010-05-16 18:19:27 +00003037 if (ctx == NULL) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02003038 _setSSLError(get_ssl_state(module), NULL, 0, __FILE__, __LINE__);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003039 return NULL;
3040 }
3041
3042 assert(type != NULL && type->tp_alloc != NULL);
3043 self = (PySSLContext *) type->tp_alloc(type, 0);
3044 if (self == NULL) {
3045 SSL_CTX_free(ctx);
3046 return NULL;
3047 }
3048 self->ctx = ctx;
Christian Heimes61d478c2018-01-27 15:51:38 +01003049 self->hostflags = X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS;
Christian Heimes11a14932018-02-24 02:35:08 +01003050 self->protocol = proto_version;
Christian Heimesc7f70692019-05-31 11:44:05 +02003051 self->msg_cb = NULL;
Christian Heimesc7f70692019-05-31 11:44:05 +02003052 self->keylog_filename = NULL;
3053 self->keylog_bio = NULL;
Benjamin Petersoncca27322015-01-23 16:35:37 -05003054 self->alpn_protocols = NULL;
Christian Heimes11a14932018-02-24 02:35:08 +01003055 self->set_sni_cb = NULL;
Christian Heimes7f1305e2021-04-17 20:06:38 +02003056 self->state = get_ssl_state(module);
3057
Christian Heimes1aa9a752013-12-02 02:41:19 +01003058 /* Don't check host name by default */
Christian Heimes5fe668c2016-09-12 00:01:11 +02003059 if (proto_version == PY_SSL_VERSION_TLS_CLIENT) {
3060 self->check_hostname = 1;
Christian Heimes9fb051f2018-09-23 08:32:31 +02003061 if (_set_verify_mode(self, PY_SSL_CERT_REQUIRED) == -1) {
Christian Heimes5fe668c2016-09-12 00:01:11 +02003062 Py_DECREF(self);
3063 return NULL;
3064 }
3065 } else {
3066 self->check_hostname = 0;
Christian Heimes9fb051f2018-09-23 08:32:31 +02003067 if (_set_verify_mode(self, PY_SSL_CERT_NONE) == -1) {
Christian Heimes5fe668c2016-09-12 00:01:11 +02003068 Py_DECREF(self);
3069 return NULL;
3070 }
3071 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003072 /* Defaults */
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01003073 options = SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
3074 if (proto_version != PY_SSL_VERSION_SSL2)
3075 options |= SSL_OP_NO_SSLv2;
Benjamin Petersona9dcdab2015-11-11 22:38:41 -08003076 if (proto_version != PY_SSL_VERSION_SSL3)
3077 options |= SSL_OP_NO_SSLv3;
Christian Heimes358cfd42016-09-10 22:43:48 +02003078 /* Minimal security flags for server and client side context.
3079 * Client sockets ignore server-side parameters. */
3080#ifdef SSL_OP_NO_COMPRESSION
3081 options |= SSL_OP_NO_COMPRESSION;
3082#endif
3083#ifdef SSL_OP_CIPHER_SERVER_PREFERENCE
3084 options |= SSL_OP_CIPHER_SERVER_PREFERENCE;
3085#endif
3086#ifdef SSL_OP_SINGLE_DH_USE
3087 options |= SSL_OP_SINGLE_DH_USE;
3088#endif
3089#ifdef SSL_OP_SINGLE_ECDH_USE
3090 options |= SSL_OP_SINGLE_ECDH_USE;
3091#endif
Christian Heimes6f37ebc2021-04-09 17:59:21 +02003092#ifdef SSL_OP_IGNORE_UNEXPECTED_EOF
3093 /* Make OpenSSL 3.0.0 behave like 1.1.1 */
3094 options |= SSL_OP_IGNORE_UNEXPECTED_EOF;
3095#endif
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01003096 SSL_CTX_set_options(self->ctx, options);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003097
Semen Zhydenko1295e112017-10-15 21:28:31 +02003098 /* A bare minimum cipher list without completely broken cipher suites.
Christian Heimes358cfd42016-09-10 22:43:48 +02003099 * It's far from perfect but gives users a better head start. */
3100 if (proto_version != PY_SSL_VERSION_SSL2) {
Christian Heimes892d66e2018-01-29 14:10:18 +01003101#if PY_SSL_DEFAULT_CIPHERS == 2
3102 /* stick to OpenSSL's default settings */
3103 result = 1;
3104#else
3105 result = SSL_CTX_set_cipher_list(ctx, PY_SSL_DEFAULT_CIPHER_STRING);
3106#endif
Christian Heimes358cfd42016-09-10 22:43:48 +02003107 } else {
3108 /* SSLv2 needs MD5 */
3109 result = SSL_CTX_set_cipher_list(ctx, "HIGH:!aNULL:!eNULL");
3110 }
3111 if (result == 0) {
3112 Py_DECREF(self);
3113 ERR_clear_error();
Christian Heimes7f1305e2021-04-17 20:06:38 +02003114 PyErr_SetString(get_state_ctx(self)->PySSLErrorObject,
Christian Heimes358cfd42016-09-10 22:43:48 +02003115 "No cipher can be selected.");
Christian Heimese9832522021-05-01 20:53:10 +02003116 goto error;
Christian Heimes358cfd42016-09-10 22:43:48 +02003117 }
Christian Heimese9832522021-05-01 20:53:10 +02003118#ifdef PY_SSL_MIN_PROTOCOL
3119 switch(proto_version) {
3120 case PY_SSL_VERSION_TLS:
3121 case PY_SSL_VERSION_TLS_CLIENT:
3122 case PY_SSL_VERSION_TLS_SERVER:
3123 result = SSL_CTX_set_min_proto_version(ctx, PY_SSL_MIN_PROTOCOL);
3124 if (result == 0) {
3125 PyErr_Format(PyExc_ValueError,
3126 "Failed to set minimum protocol 0x%x",
3127 PY_SSL_MIN_PROTOCOL);
3128 goto error;
3129 }
3130 break;
3131 default:
3132 break;
3133 }
3134#endif
Christian Heimes358cfd42016-09-10 22:43:48 +02003135
Benjamin Peterson3b1a8b32016-01-07 21:37:37 -08003136 /* Set SSL_MODE_RELEASE_BUFFERS. This potentially greatly reduces memory
Christian Heimes39258d32021-04-17 11:36:35 +02003137 usage for no cost at all. */
3138 SSL_CTX_set_mode(self->ctx, SSL_MODE_RELEASE_BUFFERS);
Antoine Pitrou0bebbc32014-03-22 18:13:50 +01003139
Antoine Pitroufc113ee2010-10-13 12:46:13 +00003140#define SID_CTX "Python"
3141 SSL_CTX_set_session_id_context(self->ctx, (const unsigned char *) SID_CTX,
3142 sizeof(SID_CTX));
3143#undef SID_CTX
3144
Christian Heimes61d478c2018-01-27 15:51:38 +01003145 params = SSL_CTX_get0_param(self->ctx);
Christian Heimes61d478c2018-01-27 15:51:38 +01003146 /* Improve trust chain building when cross-signed intermediate
3147 certificates are present. See https://bugs.python.org/issue23476. */
3148 X509_VERIFY_PARAM_set_flags(params, X509_V_FLAG_TRUSTED_FIRST);
Christian Heimes61d478c2018-01-27 15:51:38 +01003149 X509_VERIFY_PARAM_set_hostflags(params, self->hostflags);
Benjamin Petersonfdb19712015-03-04 22:11:12 -05003150
Christian Heimes9fb051f2018-09-23 08:32:31 +02003151#ifdef TLS1_3_VERSION
3152 self->post_handshake_auth = 0;
3153 SSL_CTX_set_post_handshake_auth(self->ctx, self->post_handshake_auth);
3154#endif
3155
Antoine Pitrou152efa22010-05-16 18:19:27 +00003156 return (PyObject *)self;
Christian Heimese9832522021-05-01 20:53:10 +02003157 error:
3158 Py_XDECREF(self);
3159 ERR_clear_error();
3160 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003161}
3162
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003163static int
3164context_traverse(PySSLContext *self, visitproc visit, void *arg)
3165{
Christian Heimes11a14932018-02-24 02:35:08 +01003166 Py_VISIT(self->set_sni_cb);
Christian Heimesc7f70692019-05-31 11:44:05 +02003167 Py_VISIT(self->msg_cb);
Miss Islington (bot)ea47a8a2021-05-27 09:25:22 -07003168 Py_VISIT(Py_TYPE(self));
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003169 return 0;
3170}
3171
3172static int
3173context_clear(PySSLContext *self)
3174{
Christian Heimes11a14932018-02-24 02:35:08 +01003175 Py_CLEAR(self->set_sni_cb);
Christian Heimesc7f70692019-05-31 11:44:05 +02003176 Py_CLEAR(self->msg_cb);
Christian Heimesc7f70692019-05-31 11:44:05 +02003177 Py_CLEAR(self->keylog_filename);
3178 if (self->keylog_bio != NULL) {
3179 PySSL_BEGIN_ALLOW_THREADS
3180 BIO_free_all(self->keylog_bio);
3181 PySSL_END_ALLOW_THREADS
3182 self->keylog_bio = NULL;
3183 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003184 return 0;
3185}
3186
Antoine Pitrou152efa22010-05-16 18:19:27 +00003187static void
3188context_dealloc(PySSLContext *self)
3189{
Christian Heimes5c36da72020-11-20 09:40:12 +01003190 PyTypeObject *tp = Py_TYPE(self);
INADA Naokia6296d32017-08-24 14:55:17 +09003191 /* bpo-31095: UnTrack is needed before calling any callbacks */
3192 PyObject_GC_UnTrack(self);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003193 context_clear(self);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003194 SSL_CTX_free(self->ctx);
Christian Heimes39258d32021-04-17 11:36:35 +02003195 PyMem_FREE(self->alpn_protocols);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003196 Py_TYPE(self)->tp_free(self);
Christian Heimes5c36da72020-11-20 09:40:12 +01003197 Py_DECREF(tp);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003198}
3199
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003200/*[clinic input]
3201_ssl._SSLContext.set_ciphers
3202 cipherlist: str
3203 /
3204[clinic start generated code]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003205
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003206static PyObject *
3207_ssl__SSLContext_set_ciphers_impl(PySSLContext *self, const char *cipherlist)
3208/*[clinic end generated code: output=3a3162f3557c0f3f input=a7ac931b9f3ca7fc]*/
3209{
3210 int ret = SSL_CTX_set_cipher_list(self->ctx, cipherlist);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003211 if (ret == 0) {
Antoine Pitrou65ec8ae2010-05-16 19:56:32 +00003212 /* Clearing the error queue is necessary on some OpenSSL versions,
3213 otherwise the error will be reported again when another SSL call
3214 is done. */
3215 ERR_clear_error();
Christian Heimes7f1305e2021-04-17 20:06:38 +02003216 PyErr_SetString(get_state_ctx(self)->PySSLErrorObject,
Antoine Pitrou152efa22010-05-16 18:19:27 +00003217 "No cipher can be selected.");
3218 return NULL;
3219 }
3220 Py_RETURN_NONE;
3221}
3222
Christian Heimes25bfcd52016-09-06 00:04:45 +02003223/*[clinic input]
3224_ssl._SSLContext.get_ciphers
3225[clinic start generated code]*/
3226
3227static PyObject *
3228_ssl__SSLContext_get_ciphers_impl(PySSLContext *self)
3229/*[clinic end generated code: output=a56e4d68a406dfc4 input=a2aadc9af89b79c5]*/
3230{
3231 SSL *ssl = NULL;
3232 STACK_OF(SSL_CIPHER) *sk = NULL;
Christian Heimes99a65702016-09-10 23:44:53 +02003233 const SSL_CIPHER *cipher;
Christian Heimes25bfcd52016-09-06 00:04:45 +02003234 int i=0;
3235 PyObject *result = NULL, *dct;
3236
3237 ssl = SSL_new(self->ctx);
3238 if (ssl == NULL) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02003239 _setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
Christian Heimes25bfcd52016-09-06 00:04:45 +02003240 goto exit;
3241 }
3242 sk = SSL_get_ciphers(ssl);
3243
3244 result = PyList_New(sk_SSL_CIPHER_num(sk));
3245 if (result == NULL) {
3246 goto exit;
3247 }
3248
3249 for (i = 0; i < sk_SSL_CIPHER_num(sk); i++) {
3250 cipher = sk_SSL_CIPHER_value(sk, i);
3251 dct = cipher_to_dict(cipher);
3252 if (dct == NULL) {
3253 Py_CLEAR(result);
3254 goto exit;
3255 }
3256 PyList_SET_ITEM(result, i, dct);
3257 }
3258
3259 exit:
3260 if (ssl != NULL)
3261 SSL_free(ssl);
3262 return result;
3263
3264}
Christian Heimes25bfcd52016-09-06 00:04:45 +02003265
3266
Benjamin Petersoncca27322015-01-23 16:35:37 -05003267static int
Benjamin Peterson88615022015-01-23 17:30:26 -05003268do_protocol_selection(int alpn, unsigned char **out, unsigned char *outlen,
3269 const unsigned char *server_protocols, unsigned int server_protocols_len,
3270 const unsigned char *client_protocols, unsigned int client_protocols_len)
Benjamin Petersoncca27322015-01-23 16:35:37 -05003271{
Benjamin Peterson88615022015-01-23 17:30:26 -05003272 int ret;
3273 if (client_protocols == NULL) {
3274 client_protocols = (unsigned char *)"";
3275 client_protocols_len = 0;
3276 }
3277 if (server_protocols == NULL) {
3278 server_protocols = (unsigned char *)"";
3279 server_protocols_len = 0;
Benjamin Petersoncca27322015-01-23 16:35:37 -05003280 }
3281
Benjamin Peterson88615022015-01-23 17:30:26 -05003282 ret = SSL_select_next_proto(out, outlen,
3283 server_protocols, server_protocols_len,
3284 client_protocols, client_protocols_len);
3285 if (alpn && ret != OPENSSL_NPN_NEGOTIATED)
3286 return SSL_TLSEXT_ERR_NOACK;
Benjamin Petersoncca27322015-01-23 16:35:37 -05003287
3288 return SSL_TLSEXT_ERR_OK;
3289}
3290
Benjamin Petersoncca27322015-01-23 16:35:37 -05003291static int
3292_selectALPN_cb(SSL *s,
3293 const unsigned char **out, unsigned char *outlen,
3294 const unsigned char *client_protocols, unsigned int client_protocols_len,
3295 void *args)
3296{
3297 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Peterson88615022015-01-23 17:30:26 -05003298 return do_protocol_selection(1, (unsigned char **)out, outlen,
3299 ctx->alpn_protocols, ctx->alpn_protocols_len,
3300 client_protocols, client_protocols_len);
Benjamin Petersoncca27322015-01-23 16:35:37 -05003301}
Benjamin Petersoncca27322015-01-23 16:35:37 -05003302
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003303/*[clinic input]
3304_ssl._SSLContext._set_alpn_protocols
3305 protos: Py_buffer
3306 /
3307[clinic start generated code]*/
3308
Benjamin Petersoncca27322015-01-23 16:35:37 -05003309static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003310_ssl__SSLContext__set_alpn_protocols_impl(PySSLContext *self,
3311 Py_buffer *protos)
3312/*[clinic end generated code: output=87599a7f76651a9b input=9bba964595d519be]*/
Benjamin Petersoncca27322015-01-23 16:35:37 -05003313{
Victor Stinner5a615592017-09-14 01:10:30 -07003314 if ((size_t)protos->len > UINT_MAX) {
Segev Finer5cff6372017-07-27 01:19:17 +03003315 PyErr_Format(PyExc_OverflowError,
Serhiy Storchakad53fe5f2019-03-13 22:59:55 +02003316 "protocols longer than %u bytes", UINT_MAX);
Segev Finer5cff6372017-07-27 01:19:17 +03003317 return NULL;
3318 }
3319
Victor Stinner00d7abd2020-12-01 09:56:42 +01003320 PyMem_Free(self->alpn_protocols);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003321 self->alpn_protocols = PyMem_Malloc(protos->len);
Benjamin Petersoncca27322015-01-23 16:35:37 -05003322 if (!self->alpn_protocols)
3323 return PyErr_NoMemory();
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003324 memcpy(self->alpn_protocols, protos->buf, protos->len);
Segev Finer5cff6372017-07-27 01:19:17 +03003325 self->alpn_protocols_len = (unsigned int)protos->len;
Benjamin Petersoncca27322015-01-23 16:35:37 -05003326
3327 if (SSL_CTX_set_alpn_protos(self->ctx, self->alpn_protocols, self->alpn_protocols_len))
3328 return PyErr_NoMemory();
3329 SSL_CTX_set_alpn_select_cb(self->ctx, _selectALPN_cb, self);
3330
Benjamin Petersoncca27322015-01-23 16:35:37 -05003331 Py_RETURN_NONE;
Benjamin Petersoncca27322015-01-23 16:35:37 -05003332}
3333
Antoine Pitrou152efa22010-05-16 18:19:27 +00003334static PyObject *
3335get_verify_mode(PySSLContext *self, void *c)
3336{
Christian Heimes9fb051f2018-09-23 08:32:31 +02003337 /* ignore SSL_VERIFY_CLIENT_ONCE and SSL_VERIFY_POST_HANDSHAKE */
3338 int mask = (SSL_VERIFY_NONE | SSL_VERIFY_PEER |
3339 SSL_VERIFY_FAIL_IF_NO_PEER_CERT);
3340 switch (SSL_CTX_get_verify_mode(self->ctx) & mask) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003341 case SSL_VERIFY_NONE:
3342 return PyLong_FromLong(PY_SSL_CERT_NONE);
3343 case SSL_VERIFY_PEER:
3344 return PyLong_FromLong(PY_SSL_CERT_OPTIONAL);
3345 case SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT:
3346 return PyLong_FromLong(PY_SSL_CERT_REQUIRED);
3347 }
Christian Heimes7f1305e2021-04-17 20:06:38 +02003348 PyErr_SetString(get_state_ctx(self)->PySSLErrorObject,
Antoine Pitrou152efa22010-05-16 18:19:27 +00003349 "invalid return value from SSL_CTX_get_verify_mode");
3350 return NULL;
3351}
3352
3353static int
3354set_verify_mode(PySSLContext *self, PyObject *arg, void *c)
3355{
Christian Heimes5fe668c2016-09-12 00:01:11 +02003356 int n;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003357 if (!PyArg_Parse(arg, "i", &n))
3358 return -1;
Christian Heimes5fe668c2016-09-12 00:01:11 +02003359 if (n == PY_SSL_CERT_NONE && self->check_hostname) {
Christian Heimes1aa9a752013-12-02 02:41:19 +01003360 PyErr_SetString(PyExc_ValueError,
3361 "Cannot set verify_mode to CERT_NONE when "
3362 "check_hostname is enabled.");
3363 return -1;
3364 }
Christian Heimes9fb051f2018-09-23 08:32:31 +02003365 return _set_verify_mode(self, n);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003366}
3367
3368static PyObject *
Christian Heimes22587792013-11-21 23:56:13 +01003369get_verify_flags(PySSLContext *self, void *c)
3370{
Christian Heimes598894f2016-09-05 23:19:05 +02003371 X509_VERIFY_PARAM *param;
Christian Heimes22587792013-11-21 23:56:13 +01003372 unsigned long flags;
3373
Christian Heimes61d478c2018-01-27 15:51:38 +01003374 param = SSL_CTX_get0_param(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02003375 flags = X509_VERIFY_PARAM_get_flags(param);
Christian Heimes22587792013-11-21 23:56:13 +01003376 return PyLong_FromUnsignedLong(flags);
3377}
3378
3379static int
3380set_verify_flags(PySSLContext *self, PyObject *arg, void *c)
3381{
Christian Heimes598894f2016-09-05 23:19:05 +02003382 X509_VERIFY_PARAM *param;
Christian Heimes22587792013-11-21 23:56:13 +01003383 unsigned long new_flags, flags, set, clear;
3384
3385 if (!PyArg_Parse(arg, "k", &new_flags))
3386 return -1;
Christian Heimes61d478c2018-01-27 15:51:38 +01003387 param = SSL_CTX_get0_param(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02003388 flags = X509_VERIFY_PARAM_get_flags(param);
Christian Heimes22587792013-11-21 23:56:13 +01003389 clear = flags & ~new_flags;
3390 set = ~flags & new_flags;
3391 if (clear) {
Christian Heimes598894f2016-09-05 23:19:05 +02003392 if (!X509_VERIFY_PARAM_clear_flags(param, clear)) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02003393 _setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
Christian Heimes22587792013-11-21 23:56:13 +01003394 return -1;
3395 }
3396 }
3397 if (set) {
Christian Heimes598894f2016-09-05 23:19:05 +02003398 if (!X509_VERIFY_PARAM_set_flags(param, set)) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02003399 _setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
Christian Heimes22587792013-11-21 23:56:13 +01003400 return -1;
3401 }
3402 }
3403 return 0;
3404}
3405
Christian Heimes698dde12018-02-27 11:54:43 +01003406/* Getter and setter for protocol version */
Christian Heimes698dde12018-02-27 11:54:43 +01003407static int
3408set_min_max_proto_version(PySSLContext *self, PyObject *arg, int what)
3409{
3410 long v;
3411 int result;
3412
3413 if (!PyArg_Parse(arg, "l", &v))
3414 return -1;
3415 if (v > INT_MAX) {
3416 PyErr_SetString(PyExc_OverflowError, "Option is too long");
3417 return -1;
3418 }
3419
3420 switch(self->protocol) {
3421 case PY_SSL_VERSION_TLS_CLIENT: /* fall through */
3422 case PY_SSL_VERSION_TLS_SERVER: /* fall through */
3423 case PY_SSL_VERSION_TLS:
3424 break;
3425 default:
3426 PyErr_SetString(
3427 PyExc_ValueError,
3428 "The context's protocol doesn't support modification of "
3429 "highest and lowest version."
3430 );
3431 return -1;
3432 }
3433
Christian Heimes2875c602021-04-19 07:27:10 +02003434 /* check for deprecations and supported values */
3435 switch(v) {
3436 case PY_PROTO_SSLv3:
3437 PY_SSL_DEPRECATED("TLSVersion.SSLv3", 2, -1);
3438 break;
3439 case PY_PROTO_TLSv1:
3440 PY_SSL_DEPRECATED("TLSVersion.TLSv1", 2, -1);
3441 break;
3442 case PY_PROTO_TLSv1_1:
3443 PY_SSL_DEPRECATED("TLSVersion.TLSv1_1", 2, -1);
3444 break;
3445 case PY_PROTO_MINIMUM_SUPPORTED:
3446 case PY_PROTO_MAXIMUM_SUPPORTED:
3447 case PY_PROTO_TLSv1_2:
3448 case PY_PROTO_TLSv1_3:
3449 /* ok */
3450 break;
3451 default:
3452 PyErr_Format(PyExc_ValueError,
3453 "Unsupported TLS/SSL version 0x%x", v);
3454 return -1;
3455 }
3456
Christian Heimes698dde12018-02-27 11:54:43 +01003457 if (what == 0) {
3458 switch(v) {
3459 case PY_PROTO_MINIMUM_SUPPORTED:
3460 v = 0;
3461 break;
3462 case PY_PROTO_MAXIMUM_SUPPORTED:
3463 /* Emulate max for set_min_proto_version */
3464 v = PY_PROTO_MAXIMUM_AVAILABLE;
3465 break;
3466 default:
3467 break;
3468 }
3469 result = SSL_CTX_set_min_proto_version(self->ctx, v);
3470 }
3471 else {
3472 switch(v) {
3473 case PY_PROTO_MAXIMUM_SUPPORTED:
3474 v = 0;
3475 break;
3476 case PY_PROTO_MINIMUM_SUPPORTED:
3477 /* Emulate max for set_min_proto_version */
3478 v = PY_PROTO_MINIMUM_AVAILABLE;
3479 break;
3480 default:
3481 break;
3482 }
3483 result = SSL_CTX_set_max_proto_version(self->ctx, v);
3484 }
3485 if (result == 0) {
3486 PyErr_Format(PyExc_ValueError,
3487 "Unsupported protocol version 0x%x", v);
3488 return -1;
3489 }
3490 return 0;
3491}
3492
3493static PyObject *
3494get_minimum_version(PySSLContext *self, void *c)
3495{
3496 int v = SSL_CTX_ctrl(self->ctx, SSL_CTRL_GET_MIN_PROTO_VERSION, 0, NULL);
3497 if (v == 0) {
3498 v = PY_PROTO_MINIMUM_SUPPORTED;
3499 }
3500 return PyLong_FromLong(v);
3501}
3502
3503static int
3504set_minimum_version(PySSLContext *self, PyObject *arg, void *c)
3505{
3506 return set_min_max_proto_version(self, arg, 0);
3507}
3508
3509static PyObject *
3510get_maximum_version(PySSLContext *self, void *c)
3511{
3512 int v = SSL_CTX_ctrl(self->ctx, SSL_CTRL_GET_MAX_PROTO_VERSION, 0, NULL);
3513 if (v == 0) {
3514 v = PY_PROTO_MAXIMUM_SUPPORTED;
3515 }
3516 return PyLong_FromLong(v);
3517}
3518
3519static int
3520set_maximum_version(PySSLContext *self, PyObject *arg, void *c)
3521{
3522 return set_min_max_proto_version(self, arg, 1);
3523}
Christian Heimes698dde12018-02-27 11:54:43 +01003524
Christian Heimes39258d32021-04-17 11:36:35 +02003525#ifdef TLS1_3_VERSION
Christian Heimes78c7d522019-06-03 21:00:10 +02003526static PyObject *
3527get_num_tickets(PySSLContext *self, void *c)
3528{
Victor Stinner76611c72019-07-09 13:30:52 +02003529 return PyLong_FromSize_t(SSL_CTX_get_num_tickets(self->ctx));
Christian Heimes78c7d522019-06-03 21:00:10 +02003530}
3531
3532static int
3533set_num_tickets(PySSLContext *self, PyObject *arg, void *c)
3534{
3535 long num;
3536 if (!PyArg_Parse(arg, "l", &num))
3537 return -1;
3538 if (num < 0) {
3539 PyErr_SetString(PyExc_ValueError, "value must be non-negative");
3540 return -1;
3541 }
3542 if (self->protocol != PY_SSL_VERSION_TLS_SERVER) {
3543 PyErr_SetString(PyExc_ValueError,
3544 "SSLContext is not a server context.");
3545 return -1;
3546 }
3547 if (SSL_CTX_set_num_tickets(self->ctx, num) != 1) {
3548 PyErr_SetString(PyExc_ValueError, "failed to set num tickets.");
3549 return -1;
3550 }
3551 return 0;
3552}
3553
3554PyDoc_STRVAR(PySSLContext_num_tickets_doc,
3555"Control the number of TLSv1.3 session tickets");
Christian Heimes39258d32021-04-17 11:36:35 +02003556#endif /* TLS1_3_VERSION */
Christian Heimes78c7d522019-06-03 21:00:10 +02003557
matthewhughes9348e836bb2020-07-17 09:59:15 +01003558static PyObject *
3559get_security_level(PySSLContext *self, void *c)
3560{
3561 return PyLong_FromLong(SSL_CTX_get_security_level(self->ctx));
3562}
3563PyDoc_STRVAR(PySSLContext_security_level_doc, "The current security level");
matthewhughes9348e836bb2020-07-17 09:59:15 +01003564
Christian Heimes22587792013-11-21 23:56:13 +01003565static PyObject *
Antoine Pitroub5218772010-05-21 09:56:06 +00003566get_options(PySSLContext *self, void *c)
3567{
3568 return PyLong_FromLong(SSL_CTX_get_options(self->ctx));
3569}
3570
3571static int
3572set_options(PySSLContext *self, PyObject *arg, void *c)
3573{
3574 long new_opts, opts, set, clear;
Christian Heimes2875c602021-04-19 07:27:10 +02003575 long opt_no = (
3576 SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1 |
3577 SSL_OP_NO_TLSv1_1 | SSL_OP_NO_TLSv1_2 | SSL_OP_NO_TLSv1_2
3578 );
3579
Antoine Pitroub5218772010-05-21 09:56:06 +00003580 if (!PyArg_Parse(arg, "l", &new_opts))
3581 return -1;
3582 opts = SSL_CTX_get_options(self->ctx);
3583 clear = opts & ~new_opts;
3584 set = ~opts & new_opts;
Christian Heimes2875c602021-04-19 07:27:10 +02003585
3586 if ((set & opt_no) != 0) {
3587 if (_ssl_deprecated("Setting OP_NO_SSL* or SSL_NO_TLS* options is "
3588 "deprecated", 2) < 0) {
3589 return -1;
3590 }
3591 }
Antoine Pitroub5218772010-05-21 09:56:06 +00003592 if (clear) {
Antoine Pitroub5218772010-05-21 09:56:06 +00003593 SSL_CTX_clear_options(self->ctx, clear);
Antoine Pitroub5218772010-05-21 09:56:06 +00003594 }
3595 if (set)
3596 SSL_CTX_set_options(self->ctx, set);
3597 return 0;
3598}
3599
Christian Heimes1aa9a752013-12-02 02:41:19 +01003600static PyObject *
Christian Heimes61d478c2018-01-27 15:51:38 +01003601get_host_flags(PySSLContext *self, void *c)
3602{
3603 return PyLong_FromUnsignedLong(self->hostflags);
3604}
3605
3606static int
3607set_host_flags(PySSLContext *self, PyObject *arg, void *c)
3608{
3609 X509_VERIFY_PARAM *param;
3610 unsigned int new_flags = 0;
3611
3612 if (!PyArg_Parse(arg, "I", &new_flags))
3613 return -1;
3614
3615 param = SSL_CTX_get0_param(self->ctx);
3616 self->hostflags = new_flags;
3617 X509_VERIFY_PARAM_set_hostflags(param, new_flags);
3618 return 0;
3619}
3620
3621static PyObject *
Christian Heimes1aa9a752013-12-02 02:41:19 +01003622get_check_hostname(PySSLContext *self, void *c)
3623{
3624 return PyBool_FromLong(self->check_hostname);
3625}
3626
3627static int
3628set_check_hostname(PySSLContext *self, PyObject *arg, void *c)
3629{
3630 int check_hostname;
3631 if (!PyArg_Parse(arg, "p", &check_hostname))
3632 return -1;
3633 if (check_hostname &&
3634 SSL_CTX_get_verify_mode(self->ctx) == SSL_VERIFY_NONE) {
Christian Heimese82c0342017-09-15 20:29:57 +02003635 /* check_hostname = True sets verify_mode = CERT_REQUIRED */
Christian Heimes9fb051f2018-09-23 08:32:31 +02003636 if (_set_verify_mode(self, PY_SSL_CERT_REQUIRED) == -1) {
Christian Heimese82c0342017-09-15 20:29:57 +02003637 return -1;
3638 }
Christian Heimes1aa9a752013-12-02 02:41:19 +01003639 }
3640 self->check_hostname = check_hostname;
3641 return 0;
3642}
3643
Christian Heimes11a14932018-02-24 02:35:08 +01003644static PyObject *
Christian Heimes9fb051f2018-09-23 08:32:31 +02003645get_post_handshake_auth(PySSLContext *self, void *c) {
3646#if TLS1_3_VERSION
3647 return PyBool_FromLong(self->post_handshake_auth);
3648#else
3649 Py_RETURN_NONE;
3650#endif
3651}
3652
3653#if TLS1_3_VERSION
3654static int
3655set_post_handshake_auth(PySSLContext *self, PyObject *arg, void *c) {
Zackery Spytz842acaa2018-12-17 07:52:45 -07003656 if (arg == NULL) {
3657 PyErr_SetString(PyExc_AttributeError, "cannot delete attribute");
3658 return -1;
3659 }
Christian Heimes9fb051f2018-09-23 08:32:31 +02003660 int pha = PyObject_IsTrue(arg);
3661
3662 if (pha == -1) {
3663 return -1;
3664 }
3665 self->post_handshake_auth = pha;
3666
Christian Heimesf0f59302019-07-01 08:29:17 +02003667 /* bpo-37428: newPySSLSocket() sets SSL_VERIFY_POST_HANDSHAKE flag for
3668 * server sockets and SSL_set_post_handshake_auth() for client. */
Christian Heimes9fb051f2018-09-23 08:32:31 +02003669
3670 return 0;
3671}
3672#endif
3673
3674static PyObject *
Christian Heimes11a14932018-02-24 02:35:08 +01003675get_protocol(PySSLContext *self, void *c) {
3676 return PyLong_FromLong(self->protocol);
3677}
Christian Heimes1aa9a752013-12-02 02:41:19 +01003678
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003679typedef struct {
3680 PyThreadState *thread_state;
3681 PyObject *callable;
3682 char *password;
Victor Stinner9ee02032013-06-23 15:08:23 +02003683 int size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003684 int error;
3685} _PySSLPasswordInfo;
3686
3687static int
3688_pwinfo_set(_PySSLPasswordInfo *pw_info, PyObject* password,
3689 const char *bad_type_error)
3690{
3691 /* Set the password and size fields of a _PySSLPasswordInfo struct
3692 from a unicode, bytes, or byte array object.
3693 The password field will be dynamically allocated and must be freed
3694 by the caller */
3695 PyObject *password_bytes = NULL;
3696 const char *data = NULL;
3697 Py_ssize_t size;
3698
3699 if (PyUnicode_Check(password)) {
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03003700 password_bytes = PyUnicode_AsUTF8String(password);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003701 if (!password_bytes) {
3702 goto error;
3703 }
3704 data = PyBytes_AS_STRING(password_bytes);
3705 size = PyBytes_GET_SIZE(password_bytes);
3706 } else if (PyBytes_Check(password)) {
3707 data = PyBytes_AS_STRING(password);
3708 size = PyBytes_GET_SIZE(password);
3709 } else if (PyByteArray_Check(password)) {
3710 data = PyByteArray_AS_STRING(password);
3711 size = PyByteArray_GET_SIZE(password);
3712 } else {
3713 PyErr_SetString(PyExc_TypeError, bad_type_error);
3714 goto error;
3715 }
3716
Victor Stinner9ee02032013-06-23 15:08:23 +02003717 if (size > (Py_ssize_t)INT_MAX) {
3718 PyErr_Format(PyExc_ValueError,
3719 "password cannot be longer than %d bytes", INT_MAX);
3720 goto error;
3721 }
3722
Victor Stinner11ebff22013-07-07 17:07:52 +02003723 PyMem_Free(pw_info->password);
3724 pw_info->password = PyMem_Malloc(size);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003725 if (!pw_info->password) {
3726 PyErr_SetString(PyExc_MemoryError,
3727 "unable to allocate password buffer");
3728 goto error;
3729 }
3730 memcpy(pw_info->password, data, size);
Victor Stinner9ee02032013-06-23 15:08:23 +02003731 pw_info->size = (int)size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003732
3733 Py_XDECREF(password_bytes);
3734 return 1;
3735
3736error:
3737 Py_XDECREF(password_bytes);
3738 return 0;
3739}
3740
3741static int
3742_password_callback(char *buf, int size, int rwflag, void *userdata)
3743{
3744 _PySSLPasswordInfo *pw_info = (_PySSLPasswordInfo*) userdata;
3745 PyObject *fn_ret = NULL;
3746
3747 PySSL_END_ALLOW_THREADS_S(pw_info->thread_state);
3748
Christian Heimesd3b73f32021-04-09 15:23:38 +02003749 if (pw_info->error) {
3750 /* already failed previously. OpenSSL 3.0.0-alpha14 invokes the
3751 * callback multiple times which can lead to fatal Python error in
3752 * exception check. */
3753 goto error;
3754 }
3755
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003756 if (pw_info->callable) {
Victor Stinnerf17c3de2016-12-06 18:46:19 +01003757 fn_ret = _PyObject_CallNoArg(pw_info->callable);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003758 if (!fn_ret) {
3759 /* TODO: It would be nice to move _ctypes_add_traceback() into the
3760 core python API, so we could use it to add a frame here */
3761 goto error;
3762 }
3763
3764 if (!_pwinfo_set(pw_info, fn_ret,
3765 "password callback must return a string")) {
3766 goto error;
3767 }
3768 Py_CLEAR(fn_ret);
3769 }
3770
3771 if (pw_info->size > size) {
3772 PyErr_Format(PyExc_ValueError,
3773 "password cannot be longer than %d bytes", size);
3774 goto error;
3775 }
3776
3777 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
3778 memcpy(buf, pw_info->password, pw_info->size);
3779 return pw_info->size;
3780
3781error:
3782 Py_XDECREF(fn_ret);
3783 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
3784 pw_info->error = 1;
3785 return -1;
3786}
3787
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003788/*[clinic input]
3789_ssl._SSLContext.load_cert_chain
3790 certfile: object
Serhiy Storchaka279f4462019-09-14 12:24:05 +03003791 keyfile: object = None
3792 password: object = None
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003793
3794[clinic start generated code]*/
3795
Antoine Pitroub5218772010-05-21 09:56:06 +00003796static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003797_ssl__SSLContext_load_cert_chain_impl(PySSLContext *self, PyObject *certfile,
3798 PyObject *keyfile, PyObject *password)
Serhiy Storchaka279f4462019-09-14 12:24:05 +03003799/*[clinic end generated code: output=9480bc1c380e2095 input=30bc7e967ea01a58]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003800{
Antoine Pitrou152efa22010-05-16 18:19:27 +00003801 PyObject *certfile_bytes = NULL, *keyfile_bytes = NULL;
Christian Heimes598894f2016-09-05 23:19:05 +02003802 pem_password_cb *orig_passwd_cb = SSL_CTX_get_default_passwd_cb(self->ctx);
3803 void *orig_passwd_userdata = SSL_CTX_get_default_passwd_cb_userdata(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003804 _PySSLPasswordInfo pw_info = { NULL, NULL, NULL, 0, 0 };
Antoine Pitrou152efa22010-05-16 18:19:27 +00003805 int r;
3806
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003807 errno = 0;
Antoine Pitrou67e8e562010-09-01 20:55:41 +00003808 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00003809 if (keyfile == Py_None)
3810 keyfile = NULL;
3811 if (!PyUnicode_FSConverter(certfile, &certfile_bytes)) {
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03003812 if (PyErr_ExceptionMatches(PyExc_TypeError)) {
3813 PyErr_SetString(PyExc_TypeError,
3814 "certfile should be a valid filesystem path");
3815 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003816 return NULL;
3817 }
3818 if (keyfile && !PyUnicode_FSConverter(keyfile, &keyfile_bytes)) {
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03003819 if (PyErr_ExceptionMatches(PyExc_TypeError)) {
3820 PyErr_SetString(PyExc_TypeError,
3821 "keyfile should be a valid filesystem path");
3822 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003823 goto error;
3824 }
Serhiy Storchaka279f4462019-09-14 12:24:05 +03003825 if (password != Py_None) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003826 if (PyCallable_Check(password)) {
3827 pw_info.callable = password;
3828 } else if (!_pwinfo_set(&pw_info, password,
3829 "password should be a string or callable")) {
3830 goto error;
3831 }
3832 SSL_CTX_set_default_passwd_cb(self->ctx, _password_callback);
3833 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, &pw_info);
3834 }
3835 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003836 r = SSL_CTX_use_certificate_chain_file(self->ctx,
3837 PyBytes_AS_STRING(certfile_bytes));
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003838 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003839 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003840 if (pw_info.error) {
3841 ERR_clear_error();
3842 /* the password callback has already set the error information */
3843 }
3844 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00003845 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03003846 PyErr_SetFromErrno(PyExc_OSError);
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003847 }
3848 else {
Christian Heimes7f1305e2021-04-17 20:06:38 +02003849 _setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003850 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003851 goto error;
3852 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003853 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou9c254862011-04-03 18:15:34 +02003854 r = SSL_CTX_use_PrivateKey_file(self->ctx,
Antoine Pitrou152efa22010-05-16 18:19:27 +00003855 PyBytes_AS_STRING(keyfile ? keyfile_bytes : certfile_bytes),
3856 SSL_FILETYPE_PEM);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003857 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
3858 Py_CLEAR(keyfile_bytes);
3859 Py_CLEAR(certfile_bytes);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003860 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003861 if (pw_info.error) {
3862 ERR_clear_error();
3863 /* the password callback has already set the error information */
3864 }
3865 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00003866 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03003867 PyErr_SetFromErrno(PyExc_OSError);
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003868 }
3869 else {
Christian Heimes7f1305e2021-04-17 20:06:38 +02003870 _setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003871 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003872 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003873 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003874 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003875 r = SSL_CTX_check_private_key(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003876 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003877 if (r != 1) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02003878 _setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003879 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003880 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003881 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
3882 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02003883 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003884 Py_RETURN_NONE;
3885
3886error:
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003887 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
3888 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02003889 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003890 Py_XDECREF(keyfile_bytes);
3891 Py_XDECREF(certfile_bytes);
3892 return NULL;
3893}
3894
Christian Heimesefff7062013-11-21 03:35:02 +01003895/* internal helper function, returns -1 on error
3896 */
3897static int
Serhiy Storchaka8f87eef2020-04-12 14:58:27 +03003898_add_ca_certs(PySSLContext *self, const void *data, Py_ssize_t len,
Christian Heimesefff7062013-11-21 03:35:02 +01003899 int filetype)
3900{
3901 BIO *biobuf = NULL;
3902 X509_STORE *store;
Christian Heimesb9ad88b2021-04-23 13:51:40 +02003903 int retval = -1, err, loaded = 0;
Christian Heimesefff7062013-11-21 03:35:02 +01003904
3905 assert(filetype == SSL_FILETYPE_ASN1 || filetype == SSL_FILETYPE_PEM);
3906
3907 if (len <= 0) {
3908 PyErr_SetString(PyExc_ValueError,
3909 "Empty certificate data");
3910 return -1;
3911 } else if (len > INT_MAX) {
3912 PyErr_SetString(PyExc_OverflowError,
3913 "Certificate data is too long.");
3914 return -1;
3915 }
3916
Christian Heimes1dbf61f2013-11-22 00:34:18 +01003917 biobuf = BIO_new_mem_buf(data, (int)len);
Christian Heimesefff7062013-11-21 03:35:02 +01003918 if (biobuf == NULL) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02003919 _setSSLError(get_state_ctx(self), "Can't allocate buffer", 0, __FILE__, __LINE__);
Christian Heimesefff7062013-11-21 03:35:02 +01003920 return -1;
3921 }
3922
3923 store = SSL_CTX_get_cert_store(self->ctx);
3924 assert(store != NULL);
3925
3926 while (1) {
3927 X509 *cert = NULL;
3928 int r;
3929
3930 if (filetype == SSL_FILETYPE_ASN1) {
3931 cert = d2i_X509_bio(biobuf, NULL);
3932 } else {
3933 cert = PEM_read_bio_X509(biobuf, NULL,
Christian Heimes598894f2016-09-05 23:19:05 +02003934 SSL_CTX_get_default_passwd_cb(self->ctx),
3935 SSL_CTX_get_default_passwd_cb_userdata(self->ctx)
3936 );
Christian Heimesefff7062013-11-21 03:35:02 +01003937 }
3938 if (cert == NULL) {
3939 break;
3940 }
3941 r = X509_STORE_add_cert(store, cert);
3942 X509_free(cert);
3943 if (!r) {
3944 err = ERR_peek_last_error();
3945 if ((ERR_GET_LIB(err) == ERR_LIB_X509) &&
3946 (ERR_GET_REASON(err) == X509_R_CERT_ALREADY_IN_HASH_TABLE)) {
3947 /* cert already in hash table, not an error */
3948 ERR_clear_error();
3949 } else {
3950 break;
3951 }
3952 }
3953 loaded++;
3954 }
3955
3956 err = ERR_peek_last_error();
Christian Heimesb9ad88b2021-04-23 13:51:40 +02003957 if (loaded == 0) {
3958 const char *msg = NULL;
3959 if (filetype == SSL_FILETYPE_PEM) {
3960 msg = "no start line: cadata does not contain a certificate";
3961 } else {
3962 msg = "not enough data: cadata does not contain a certificate";
3963 }
3964 _setSSLError(get_state_ctx(self), msg, 0, __FILE__, __LINE__);
3965 retval = -1;
3966 } else if ((filetype == SSL_FILETYPE_ASN1) &&
3967 (ERR_GET_LIB(err) == ERR_LIB_ASN1) &&
3968 (ERR_GET_REASON(err) == ASN1_R_HEADER_TOO_LONG)) {
Christian Heimesefff7062013-11-21 03:35:02 +01003969 /* EOF ASN1 file, not an error */
3970 ERR_clear_error();
3971 retval = 0;
3972 } else if ((filetype == SSL_FILETYPE_PEM) &&
Christian Heimesefff7062013-11-21 03:35:02 +01003973 (ERR_GET_LIB(err) == ERR_LIB_PEM) &&
3974 (ERR_GET_REASON(err) == PEM_R_NO_START_LINE)) {
3975 /* EOF PEM file, not an error */
3976 ERR_clear_error();
3977 retval = 0;
Christian Heimesb9ad88b2021-04-23 13:51:40 +02003978 } else if (err != 0) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02003979 _setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
Christian Heimesefff7062013-11-21 03:35:02 +01003980 retval = -1;
Christian Heimesb9ad88b2021-04-23 13:51:40 +02003981 } else {
3982 retval = 0;
Christian Heimesefff7062013-11-21 03:35:02 +01003983 }
3984
3985 BIO_free(biobuf);
3986 return retval;
3987}
3988
3989
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003990/*[clinic input]
3991_ssl._SSLContext.load_verify_locations
Serhiy Storchaka279f4462019-09-14 12:24:05 +03003992 cafile: object = None
3993 capath: object = None
3994 cadata: object = None
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003995
3996[clinic start generated code]*/
3997
Antoine Pitrou152efa22010-05-16 18:19:27 +00003998static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003999_ssl__SSLContext_load_verify_locations_impl(PySSLContext *self,
4000 PyObject *cafile,
4001 PyObject *capath,
4002 PyObject *cadata)
Serhiy Storchaka279f4462019-09-14 12:24:05 +03004003/*[clinic end generated code: output=454c7e41230ca551 input=42ecfe258233e194]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004004{
Antoine Pitrou152efa22010-05-16 18:19:27 +00004005 PyObject *cafile_bytes = NULL, *capath_bytes = NULL;
4006 const char *cafile_buf = NULL, *capath_buf = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01004007 int r = 0, ok = 1;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004008
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00004009 errno = 0;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004010 if (cafile == Py_None)
4011 cafile = NULL;
4012 if (capath == Py_None)
4013 capath = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01004014 if (cadata == Py_None)
4015 cadata = NULL;
4016
4017 if (cafile == NULL && capath == NULL && cadata == NULL) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00004018 PyErr_SetString(PyExc_TypeError,
Christian Heimesefff7062013-11-21 03:35:02 +01004019 "cafile, capath and cadata cannot be all omitted");
4020 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004021 }
4022 if (cafile && !PyUnicode_FSConverter(cafile, &cafile_bytes)) {
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03004023 if (PyErr_ExceptionMatches(PyExc_TypeError)) {
4024 PyErr_SetString(PyExc_TypeError,
4025 "cafile should be a valid filesystem path");
4026 }
Christian Heimesefff7062013-11-21 03:35:02 +01004027 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004028 }
4029 if (capath && !PyUnicode_FSConverter(capath, &capath_bytes)) {
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03004030 if (PyErr_ExceptionMatches(PyExc_TypeError)) {
4031 PyErr_SetString(PyExc_TypeError,
4032 "capath should be a valid filesystem path");
4033 }
Christian Heimesefff7062013-11-21 03:35:02 +01004034 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004035 }
Christian Heimesefff7062013-11-21 03:35:02 +01004036
4037 /* validata cadata type and load cadata */
4038 if (cadata) {
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03004039 if (PyUnicode_Check(cadata)) {
4040 PyObject *cadata_ascii = PyUnicode_AsASCIIString(cadata);
4041 if (cadata_ascii == NULL) {
4042 if (PyErr_ExceptionMatches(PyExc_UnicodeEncodeError)) {
4043 goto invalid_cadata;
4044 }
4045 goto error;
4046 }
4047 r = _add_ca_certs(self,
4048 PyBytes_AS_STRING(cadata_ascii),
4049 PyBytes_GET_SIZE(cadata_ascii),
4050 SSL_FILETYPE_PEM);
4051 Py_DECREF(cadata_ascii);
4052 if (r == -1) {
4053 goto error;
4054 }
4055 }
4056 else if (PyObject_CheckBuffer(cadata)) {
4057 Py_buffer buf;
4058 if (PyObject_GetBuffer(cadata, &buf, PyBUF_SIMPLE)) {
4059 goto error;
4060 }
Christian Heimesefff7062013-11-21 03:35:02 +01004061 if (!PyBuffer_IsContiguous(&buf, 'C') || buf.ndim > 1) {
4062 PyBuffer_Release(&buf);
4063 PyErr_SetString(PyExc_TypeError,
4064 "cadata should be a contiguous buffer with "
4065 "a single dimension");
4066 goto error;
4067 }
4068 r = _add_ca_certs(self, buf.buf, buf.len, SSL_FILETYPE_ASN1);
4069 PyBuffer_Release(&buf);
4070 if (r == -1) {
4071 goto error;
4072 }
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03004073 }
4074 else {
4075 invalid_cadata:
4076 PyErr_SetString(PyExc_TypeError,
4077 "cadata should be an ASCII string or a "
4078 "bytes-like object");
4079 goto error;
Christian Heimesefff7062013-11-21 03:35:02 +01004080 }
4081 }
4082
4083 /* load cafile or capath */
4084 if (cafile || capath) {
4085 if (cafile)
4086 cafile_buf = PyBytes_AS_STRING(cafile_bytes);
4087 if (capath)
4088 capath_buf = PyBytes_AS_STRING(capath_bytes);
4089 PySSL_BEGIN_ALLOW_THREADS
4090 r = SSL_CTX_load_verify_locations(self->ctx, cafile_buf, capath_buf);
4091 PySSL_END_ALLOW_THREADS
4092 if (r != 1) {
Christian Heimesefff7062013-11-21 03:35:02 +01004093 if (errno != 0) {
4094 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03004095 PyErr_SetFromErrno(PyExc_OSError);
Christian Heimesefff7062013-11-21 03:35:02 +01004096 }
4097 else {
Christian Heimes7f1305e2021-04-17 20:06:38 +02004098 _setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
Christian Heimesefff7062013-11-21 03:35:02 +01004099 }
4100 goto error;
4101 }
4102 }
4103 goto end;
4104
4105 error:
4106 ok = 0;
4107 end:
Antoine Pitrou152efa22010-05-16 18:19:27 +00004108 Py_XDECREF(cafile_bytes);
4109 Py_XDECREF(capath_bytes);
Christian Heimesefff7062013-11-21 03:35:02 +01004110 if (ok) {
4111 Py_RETURN_NONE;
4112 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00004113 return NULL;
4114 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00004115}
4116
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004117/*[clinic input]
4118_ssl._SSLContext.load_dh_params
4119 path as filepath: object
4120 /
4121
4122[clinic start generated code]*/
4123
Antoine Pitrou152efa22010-05-16 18:19:27 +00004124static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004125_ssl__SSLContext_load_dh_params(PySSLContext *self, PyObject *filepath)
4126/*[clinic end generated code: output=1c8e57a38e055af0 input=c8871f3c796ae1d6]*/
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004127{
4128 FILE *f;
4129 DH *dh;
4130
Victor Stinnerdaf45552013-08-28 00:53:59 +02004131 f = _Py_fopen_obj(filepath, "rb");
Victor Stinnere42ccd22015-03-18 01:39:23 +01004132 if (f == NULL)
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004133 return NULL;
Victor Stinnere42ccd22015-03-18 01:39:23 +01004134
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004135 errno = 0;
4136 PySSL_BEGIN_ALLOW_THREADS
4137 dh = PEM_read_DHparams(f, NULL, NULL, NULL);
Antoine Pitrou457a2292013-01-12 21:43:45 +01004138 fclose(f);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004139 PySSL_END_ALLOW_THREADS
4140 if (dh == NULL) {
4141 if (errno != 0) {
4142 ERR_clear_error();
4143 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
4144 }
4145 else {
Christian Heimes7f1305e2021-04-17 20:06:38 +02004146 _setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004147 }
4148 return NULL;
4149 }
Zackery Spytzaebc0492020-07-07 22:21:58 -06004150 if (!SSL_CTX_set_tmp_dh(self->ctx, dh)) {
4151 DH_free(dh);
Christian Heimes7f1305e2021-04-17 20:06:38 +02004152 return _setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
Zackery Spytzaebc0492020-07-07 22:21:58 -06004153 }
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004154 DH_free(dh);
4155 Py_RETURN_NONE;
4156}
4157
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004158/*[clinic input]
4159_ssl._SSLContext._wrap_socket
Christian Heimes7f1305e2021-04-17 20:06:38 +02004160 sock: object(subclass_of="get_state_ctx(self)->Sock_Type")
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004161 server_side: int
4162 server_hostname as hostname_obj: object = None
Christian Heimes141c5e82018-02-24 21:10:57 +01004163 *
4164 owner: object = None
4165 session: object = None
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004166
4167[clinic start generated code]*/
4168
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004169static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004170_ssl__SSLContext__wrap_socket_impl(PySSLContext *self, PyObject *sock,
Christian Heimes141c5e82018-02-24 21:10:57 +01004171 int server_side, PyObject *hostname_obj,
4172 PyObject *owner, PyObject *session)
Christian Heimes7f1305e2021-04-17 20:06:38 +02004173/*[clinic end generated code: output=f103f238633940b4 input=f5916eadbc6eae81]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004174{
Antoine Pitroud5323212010-10-22 18:19:07 +00004175 char *hostname = NULL;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004176 PyObject *res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004177
Antoine Pitroud5323212010-10-22 18:19:07 +00004178 /* server_hostname is either None (or absent), or to be encoded
Christian Heimesd02ac252018-03-25 12:36:13 +02004179 as IDN A-label (ASCII str) without NULL bytes. */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004180 if (hostname_obj != Py_None) {
Christian Heimes11a14932018-02-24 02:35:08 +01004181 if (!PyArg_Parse(hostname_obj, "es", "ascii", &hostname))
Antoine Pitroud5323212010-10-22 18:19:07 +00004182 return NULL;
Antoine Pitroud5323212010-10-22 18:19:07 +00004183 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00004184
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004185 res = (PyObject *) newPySSLSocket(self, (PySocketSockObject *)sock,
4186 server_side, hostname,
Christian Heimes141c5e82018-02-24 21:10:57 +01004187 owner, session,
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004188 NULL, NULL);
Antoine Pitroud5323212010-10-22 18:19:07 +00004189 if (hostname != NULL)
4190 PyMem_Free(hostname);
4191 return res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004192}
4193
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004194/*[clinic input]
4195_ssl._SSLContext._wrap_bio
Christian Heimes7f1305e2021-04-17 20:06:38 +02004196 incoming: object(subclass_of="get_state_ctx(self)->PySSLMemoryBIO_Type", type="PySSLMemoryBIO *")
4197 outgoing: object(subclass_of="get_state_ctx(self)->PySSLMemoryBIO_Type", type="PySSLMemoryBIO *")
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004198 server_side: int
4199 server_hostname as hostname_obj: object = None
Christian Heimes141c5e82018-02-24 21:10:57 +01004200 *
4201 owner: object = None
4202 session: object = None
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004203
4204[clinic start generated code]*/
4205
Antoine Pitroub0182c82010-10-12 20:09:02 +00004206static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004207_ssl__SSLContext__wrap_bio_impl(PySSLContext *self, PySSLMemoryBIO *incoming,
4208 PySSLMemoryBIO *outgoing, int server_side,
Christian Heimes141c5e82018-02-24 21:10:57 +01004209 PyObject *hostname_obj, PyObject *owner,
4210 PyObject *session)
Christian Heimes7f1305e2021-04-17 20:06:38 +02004211/*[clinic end generated code: output=5c5d6d9b41f99332 input=331edeec9c738382]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004212{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004213 char *hostname = NULL;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004214 PyObject *res;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004215
4216 /* server_hostname is either None (or absent), or to be encoded
Christian Heimesd02ac252018-03-25 12:36:13 +02004217 as IDN A-label (ASCII str) without NULL bytes. */
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004218 if (hostname_obj != Py_None) {
Christian Heimes11a14932018-02-24 02:35:08 +01004219 if (!PyArg_Parse(hostname_obj, "es", "ascii", &hostname))
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004220 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004221 }
4222
4223 res = (PyObject *) newPySSLSocket(self, NULL, server_side, hostname,
Christian Heimes141c5e82018-02-24 21:10:57 +01004224 owner, session,
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004225 incoming, outgoing);
4226
4227 PyMem_Free(hostname);
4228 return res;
4229}
4230
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004231/*[clinic input]
4232_ssl._SSLContext.session_stats
4233[clinic start generated code]*/
4234
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004235static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004236_ssl__SSLContext_session_stats_impl(PySSLContext *self)
4237/*[clinic end generated code: output=0d96411c42893bfb input=7e0a81fb11102c8b]*/
Antoine Pitroub0182c82010-10-12 20:09:02 +00004238{
4239 int r;
4240 PyObject *value, *stats = PyDict_New();
4241 if (!stats)
4242 return NULL;
4243
4244#define ADD_STATS(SSL_NAME, KEY_NAME) \
4245 value = PyLong_FromLong(SSL_CTX_sess_ ## SSL_NAME (self->ctx)); \
4246 if (value == NULL) \
4247 goto error; \
4248 r = PyDict_SetItemString(stats, KEY_NAME, value); \
4249 Py_DECREF(value); \
4250 if (r < 0) \
4251 goto error;
4252
4253 ADD_STATS(number, "number");
4254 ADD_STATS(connect, "connect");
4255 ADD_STATS(connect_good, "connect_good");
4256 ADD_STATS(connect_renegotiate, "connect_renegotiate");
4257 ADD_STATS(accept, "accept");
4258 ADD_STATS(accept_good, "accept_good");
4259 ADD_STATS(accept_renegotiate, "accept_renegotiate");
4260 ADD_STATS(accept, "accept");
4261 ADD_STATS(hits, "hits");
4262 ADD_STATS(misses, "misses");
4263 ADD_STATS(timeouts, "timeouts");
4264 ADD_STATS(cache_full, "cache_full");
4265
4266#undef ADD_STATS
4267
4268 return stats;
4269
4270error:
4271 Py_DECREF(stats);
4272 return NULL;
4273}
4274
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004275/*[clinic input]
4276_ssl._SSLContext.set_default_verify_paths
4277[clinic start generated code]*/
4278
Antoine Pitrou664c2d12010-11-17 20:29:42 +00004279static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004280_ssl__SSLContext_set_default_verify_paths_impl(PySSLContext *self)
4281/*[clinic end generated code: output=0bee74e6e09deaaa input=35f3408021463d74]*/
Antoine Pitrou664c2d12010-11-17 20:29:42 +00004282{
4283 if (!SSL_CTX_set_default_verify_paths(self->ctx)) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02004284 _setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
Antoine Pitrou664c2d12010-11-17 20:29:42 +00004285 return NULL;
4286 }
4287 Py_RETURN_NONE;
4288}
4289
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004290/*[clinic input]
4291_ssl._SSLContext.set_ecdh_curve
4292 name: object
4293 /
4294
4295[clinic start generated code]*/
4296
Antoine Pitrou923df6f2011-12-19 17:16:51 +01004297static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004298_ssl__SSLContext_set_ecdh_curve(PySSLContext *self, PyObject *name)
4299/*[clinic end generated code: output=23022c196e40d7d2 input=c2bafb6f6e34726b]*/
Antoine Pitrou923df6f2011-12-19 17:16:51 +01004300{
4301 PyObject *name_bytes;
4302 int nid;
4303 EC_KEY *key;
4304
4305 if (!PyUnicode_FSConverter(name, &name_bytes))
4306 return NULL;
4307 assert(PyBytes_Check(name_bytes));
4308 nid = OBJ_sn2nid(PyBytes_AS_STRING(name_bytes));
4309 Py_DECREF(name_bytes);
4310 if (nid == 0) {
4311 PyErr_Format(PyExc_ValueError,
4312 "unknown elliptic curve name %R", name);
4313 return NULL;
4314 }
4315 key = EC_KEY_new_by_curve_name(nid);
4316 if (key == NULL) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02004317 _setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
Antoine Pitrou923df6f2011-12-19 17:16:51 +01004318 return NULL;
4319 }
4320 SSL_CTX_set_tmp_ecdh(self->ctx, key);
4321 EC_KEY_free(key);
4322 Py_RETURN_NONE;
4323}
4324
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004325static int
4326_servername_callback(SSL *s, int *al, void *args)
4327{
4328 int ret;
Christian Heimes7f1305e2021-04-17 20:06:38 +02004329 PySSLContext *sslctx = (PySSLContext *) args;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004330 PySSLSocket *ssl;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004331 PyObject *result;
4332 /* The high-level ssl.SSLSocket object */
4333 PyObject *ssl_socket;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004334 const char *servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
Stefan Krah20d60802013-01-17 17:07:17 +01004335 PyGILState_STATE gstate = PyGILState_Ensure();
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004336
Christian Heimes7f1305e2021-04-17 20:06:38 +02004337 if (sslctx->set_sni_cb == NULL) {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004338 /* remove race condition in this the call back while if removing the
4339 * callback is in progress */
4340 PyGILState_Release(gstate);
Antoine Pitrou5dd12a52013-01-06 15:25:36 +01004341 return SSL_TLSEXT_ERR_OK;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004342 }
4343
4344 ssl = SSL_get_app_data(s);
Christian Heimes7f1305e2021-04-17 20:06:38 +02004345 assert(Py_IS_TYPE(ssl, get_state_ctx(sslctx)->PySSLSocket_Type));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004346
Serhiy Storchakaf51d7152015-11-02 14:40:41 +02004347 /* The servername callback expects an argument that represents the current
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004348 * SSL connection and that has a .context attribute that can be changed to
4349 * identify the requested hostname. Since the official API is the Python
4350 * level API we want to pass the callback a Python level object rather than
4351 * a _ssl.SSLSocket instance. If there's an "owner" (typically an
4352 * SSLObject) that will be passed. Otherwise if there's a socket then that
4353 * will be passed. If both do not exist only then the C-level object is
4354 * passed. */
4355 if (ssl->owner)
4356 ssl_socket = PyWeakref_GetObject(ssl->owner);
4357 else if (ssl->Socket)
4358 ssl_socket = PyWeakref_GetObject(ssl->Socket);
4359 else
4360 ssl_socket = (PyObject *) ssl;
4361
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004362 Py_INCREF(ssl_socket);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004363 if (ssl_socket == Py_None)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004364 goto error;
Victor Stinner7e001512013-06-25 00:44:31 +02004365
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004366 if (servername == NULL) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02004367 result = PyObject_CallFunctionObjArgs(sslctx->set_sni_cb, ssl_socket,
4368 Py_None, sslctx, NULL);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004369 }
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004370 else {
Christian Heimes11a14932018-02-24 02:35:08 +01004371 PyObject *servername_bytes;
4372 PyObject *servername_str;
4373
4374 servername_bytes = PyBytes_FromString(servername);
4375 if (servername_bytes == NULL) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02004376 PyErr_WriteUnraisable((PyObject *) sslctx);
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004377 goto error;
4378 }
Christian Heimes11a14932018-02-24 02:35:08 +01004379 /* server_hostname was encoded to an A-label by our caller; put it
4380 * back into a str object, but still as an A-label (bpo-28414)
4381 */
4382 servername_str = PyUnicode_FromEncodedObject(servername_bytes, "ascii", NULL);
Christian Heimes11a14932018-02-24 02:35:08 +01004383 if (servername_str == NULL) {
4384 PyErr_WriteUnraisable(servername_bytes);
Zackery Spytzee96f322020-07-09 04:00:21 -06004385 Py_DECREF(servername_bytes);
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004386 goto error;
4387 }
Zackery Spytzee96f322020-07-09 04:00:21 -06004388 Py_DECREF(servername_bytes);
Christian Heimes11a14932018-02-24 02:35:08 +01004389 result = PyObject_CallFunctionObjArgs(
Christian Heimes7f1305e2021-04-17 20:06:38 +02004390 sslctx->set_sni_cb, ssl_socket, servername_str,
4391 sslctx, NULL);
Christian Heimes11a14932018-02-24 02:35:08 +01004392 Py_DECREF(servername_str);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004393 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004394 Py_DECREF(ssl_socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004395
4396 if (result == NULL) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02004397 PyErr_WriteUnraisable(sslctx->set_sni_cb);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004398 *al = SSL_AD_HANDSHAKE_FAILURE;
4399 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
4400 }
4401 else {
Christian Heimes11a14932018-02-24 02:35:08 +01004402 /* Result may be None, a SSLContext or an integer
4403 * None and SSLContext are OK, integer or other values are an error.
4404 */
4405 if (result == Py_None) {
4406 ret = SSL_TLSEXT_ERR_OK;
4407 } else {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004408 *al = (int) PyLong_AsLong(result);
4409 if (PyErr_Occurred()) {
4410 PyErr_WriteUnraisable(result);
4411 *al = SSL_AD_INTERNAL_ERROR;
4412 }
4413 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
4414 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004415 Py_DECREF(result);
4416 }
4417
4418 PyGILState_Release(gstate);
4419 return ret;
4420
4421error:
4422 Py_DECREF(ssl_socket);
4423 *al = SSL_AD_INTERNAL_ERROR;
4424 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
4425 PyGILState_Release(gstate);
4426 return ret;
4427}
4428
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004429static PyObject *
Christian Heimes11a14932018-02-24 02:35:08 +01004430get_sni_callback(PySSLContext *self, void *c)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004431{
Christian Heimes11a14932018-02-24 02:35:08 +01004432 PyObject *cb = self->set_sni_cb;
4433 if (cb == NULL) {
4434 Py_RETURN_NONE;
4435 }
4436 Py_INCREF(cb);
4437 return cb;
4438}
4439
4440static int
4441set_sni_callback(PySSLContext *self, PyObject *arg, void *c)
4442{
4443 if (self->protocol == PY_SSL_VERSION_TLS_CLIENT) {
4444 PyErr_SetString(PyExc_ValueError,
4445 "sni_callback cannot be set on TLS_CLIENT context");
4446 return -1;
4447 }
Christian Heimes11a14932018-02-24 02:35:08 +01004448 Py_CLEAR(self->set_sni_cb);
4449 if (arg == Py_None) {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004450 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
4451 }
4452 else {
Christian Heimes11a14932018-02-24 02:35:08 +01004453 if (!PyCallable_Check(arg)) {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004454 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
4455 PyErr_SetString(PyExc_TypeError,
4456 "not a callable object");
Christian Heimes11a14932018-02-24 02:35:08 +01004457 return -1;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004458 }
Christian Heimes11a14932018-02-24 02:35:08 +01004459 Py_INCREF(arg);
4460 self->set_sni_cb = arg;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004461 SSL_CTX_set_tlsext_servername_callback(self->ctx, _servername_callback);
4462 SSL_CTX_set_tlsext_servername_arg(self->ctx, self);
4463 }
Christian Heimes11a14932018-02-24 02:35:08 +01004464 return 0;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004465}
4466
Christian Heimes11a14932018-02-24 02:35:08 +01004467PyDoc_STRVAR(PySSLContext_sni_callback_doc,
4468"Set a callback that will be called when a server name is provided by the SSL/TLS client in the SNI extension.\n\
4469\n\
4470If the argument is None then the callback is disabled. The method is called\n\
4471with the SSLSocket, the server name as a string, and the SSLContext object.\n\
4472See RFC 6066 for details of the SNI extension.");
4473
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004474/*[clinic input]
4475_ssl._SSLContext.cert_store_stats
4476
4477Returns quantities of loaded X.509 certificates.
4478
4479X.509 certificates with a CA extension and certificate revocation lists
4480inside the context's cert store.
4481
4482NOTE: Certificates in a capath directory aren't loaded unless they have
4483been used at least once.
4484[clinic start generated code]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004485
4486static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004487_ssl__SSLContext_cert_store_stats_impl(PySSLContext *self)
4488/*[clinic end generated code: output=5f356f4d9cca874d input=eb40dd0f6d0e40cf]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004489{
4490 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02004491 STACK_OF(X509_OBJECT) *objs;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004492 X509_OBJECT *obj;
Christian Heimes598894f2016-09-05 23:19:05 +02004493 int x509 = 0, crl = 0, ca = 0, i;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004494
4495 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02004496 objs = X509_STORE_get0_objects(store);
4497 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
4498 obj = sk_X509_OBJECT_value(objs, i);
4499 switch (X509_OBJECT_get_type(obj)) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004500 case X509_LU_X509:
4501 x509++;
Christian Heimes598894f2016-09-05 23:19:05 +02004502 if (X509_check_ca(X509_OBJECT_get0_X509(obj))) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004503 ca++;
4504 }
4505 break;
4506 case X509_LU_CRL:
4507 crl++;
4508 break;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004509 default:
4510 /* Ignore X509_LU_FAIL, X509_LU_RETRY, X509_LU_PKEY.
4511 * As far as I can tell they are internal states and never
4512 * stored in a cert store */
4513 break;
4514 }
4515 }
4516 return Py_BuildValue("{sisisi}", "x509", x509, "crl", crl,
4517 "x509_ca", ca);
4518}
4519
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004520/*[clinic input]
4521_ssl._SSLContext.get_ca_certs
4522 binary_form: bool = False
4523
4524Returns a list of dicts with information of loaded CA certs.
4525
4526If the optional argument is True, returns a DER-encoded copy of the CA
4527certificate.
4528
4529NOTE: Certificates in a capath directory aren't loaded unless they have
4530been used at least once.
4531[clinic start generated code]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004532
4533static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004534_ssl__SSLContext_get_ca_certs_impl(PySSLContext *self, int binary_form)
4535/*[clinic end generated code: output=0d58f148f37e2938 input=6887b5a09b7f9076]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004536{
4537 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02004538 STACK_OF(X509_OBJECT) *objs;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004539 PyObject *ci = NULL, *rlist = NULL;
4540 int i;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004541
4542 if ((rlist = PyList_New(0)) == NULL) {
4543 return NULL;
4544 }
4545
4546 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02004547 objs = X509_STORE_get0_objects(store);
4548 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004549 X509_OBJECT *obj;
4550 X509 *cert;
4551
Christian Heimes598894f2016-09-05 23:19:05 +02004552 obj = sk_X509_OBJECT_value(objs, i);
4553 if (X509_OBJECT_get_type(obj) != X509_LU_X509) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004554 /* not a x509 cert */
4555 continue;
4556 }
4557 /* CA for any purpose */
Christian Heimes598894f2016-09-05 23:19:05 +02004558 cert = X509_OBJECT_get0_X509(obj);
Christian Heimes9a5395a2013-06-17 15:44:12 +02004559 if (!X509_check_ca(cert)) {
4560 continue;
4561 }
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004562 if (binary_form) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02004563 ci = _certificate_to_der(get_state_ctx(self), cert);
Christian Heimes9a5395a2013-06-17 15:44:12 +02004564 } else {
Christian Heimes7f1305e2021-04-17 20:06:38 +02004565 ci = _decode_certificate(get_state_ctx(self), cert);
Christian Heimes9a5395a2013-06-17 15:44:12 +02004566 }
4567 if (ci == NULL) {
4568 goto error;
4569 }
4570 if (PyList_Append(rlist, ci) == -1) {
4571 goto error;
4572 }
4573 Py_CLEAR(ci);
4574 }
4575 return rlist;
4576
4577 error:
4578 Py_XDECREF(ci);
4579 Py_XDECREF(rlist);
4580 return NULL;
4581}
4582
4583
Antoine Pitrou152efa22010-05-16 18:19:27 +00004584static PyGetSetDef context_getsetlist[] = {
Christian Heimes1aa9a752013-12-02 02:41:19 +01004585 {"check_hostname", (getter) get_check_hostname,
4586 (setter) set_check_hostname, NULL},
Christian Heimes61d478c2018-01-27 15:51:38 +01004587 {"_host_flags", (getter) get_host_flags,
4588 (setter) set_host_flags, NULL},
Christian Heimes698dde12018-02-27 11:54:43 +01004589 {"minimum_version", (getter) get_minimum_version,
4590 (setter) set_minimum_version, NULL},
4591 {"maximum_version", (getter) get_maximum_version,
4592 (setter) set_maximum_version, NULL},
Christian Heimesc7f70692019-05-31 11:44:05 +02004593 {"keylog_filename", (getter) _PySSLContext_get_keylog_filename,
4594 (setter) _PySSLContext_set_keylog_filename, NULL},
Christian Heimesc7f70692019-05-31 11:44:05 +02004595 {"_msg_callback", (getter) _PySSLContext_get_msg_callback,
4596 (setter) _PySSLContext_set_msg_callback, NULL},
Christian Heimes11a14932018-02-24 02:35:08 +01004597 {"sni_callback", (getter) get_sni_callback,
Christian Heimes698dde12018-02-27 11:54:43 +01004598 (setter) set_sni_callback, PySSLContext_sni_callback_doc},
Christian Heimes39258d32021-04-17 11:36:35 +02004599#ifdef TLS1_3_VERSION
Christian Heimes78c7d522019-06-03 21:00:10 +02004600 {"num_tickets", (getter) get_num_tickets,
4601 (setter) set_num_tickets, PySSLContext_num_tickets_doc},
4602#endif
Antoine Pitroub5218772010-05-21 09:56:06 +00004603 {"options", (getter) get_options,
4604 (setter) set_options, NULL},
Christian Heimes9fb051f2018-09-23 08:32:31 +02004605 {"post_handshake_auth", (getter) get_post_handshake_auth,
4606#ifdef TLS1_3_VERSION
4607 (setter) set_post_handshake_auth,
4608#else
4609 NULL,
4610#endif
4611 NULL},
Christian Heimes11a14932018-02-24 02:35:08 +01004612 {"protocol", (getter) get_protocol,
4613 NULL, NULL},
Christian Heimes22587792013-11-21 23:56:13 +01004614 {"verify_flags", (getter) get_verify_flags,
4615 (setter) set_verify_flags, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00004616 {"verify_mode", (getter) get_verify_mode,
4617 (setter) set_verify_mode, NULL},
matthewhughes9348e836bb2020-07-17 09:59:15 +01004618 {"security_level", (getter) get_security_level,
4619 NULL, PySSLContext_security_level_doc},
Antoine Pitrou152efa22010-05-16 18:19:27 +00004620 {NULL}, /* sentinel */
4621};
4622
4623static struct PyMethodDef context_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004624 _SSL__SSLCONTEXT__WRAP_SOCKET_METHODDEF
4625 _SSL__SSLCONTEXT__WRAP_BIO_METHODDEF
4626 _SSL__SSLCONTEXT_SET_CIPHERS_METHODDEF
4627 _SSL__SSLCONTEXT__SET_ALPN_PROTOCOLS_METHODDEF
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004628 _SSL__SSLCONTEXT_LOAD_CERT_CHAIN_METHODDEF
4629 _SSL__SSLCONTEXT_LOAD_DH_PARAMS_METHODDEF
4630 _SSL__SSLCONTEXT_LOAD_VERIFY_LOCATIONS_METHODDEF
4631 _SSL__SSLCONTEXT_SESSION_STATS_METHODDEF
4632 _SSL__SSLCONTEXT_SET_DEFAULT_VERIFY_PATHS_METHODDEF
4633 _SSL__SSLCONTEXT_SET_ECDH_CURVE_METHODDEF
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004634 _SSL__SSLCONTEXT_CERT_STORE_STATS_METHODDEF
4635 _SSL__SSLCONTEXT_GET_CA_CERTS_METHODDEF
Christian Heimes25bfcd52016-09-06 00:04:45 +02004636 _SSL__SSLCONTEXT_GET_CIPHERS_METHODDEF
Antoine Pitrou152efa22010-05-16 18:19:27 +00004637 {NULL, NULL} /* sentinel */
4638};
4639
Christian Heimes5c36da72020-11-20 09:40:12 +01004640static PyType_Slot PySSLContext_slots[] = {
4641 {Py_tp_methods, context_methods},
4642 {Py_tp_getset, context_getsetlist},
4643 {Py_tp_new, _ssl__SSLContext},
4644 {Py_tp_dealloc, context_dealloc},
4645 {Py_tp_traverse, context_traverse},
4646 {Py_tp_clear, context_clear},
4647 {0, 0},
4648};
4649
4650static PyType_Spec PySSLContext_spec = {
Miss Islington (bot)ea47a8a2021-05-27 09:25:22 -07004651 .name = "_ssl._SSLContext",
4652 .basicsize = sizeof(PySSLContext),
4653 .flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC |
4654 Py_TPFLAGS_IMMUTABLETYPE),
4655 .slots = PySSLContext_slots,
Antoine Pitrou152efa22010-05-16 18:19:27 +00004656};
4657
4658
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004659/*
4660 * MemoryBIO objects
4661 */
4662
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004663/*[clinic input]
4664@classmethod
4665_ssl.MemoryBIO.__new__
4666
4667[clinic start generated code]*/
4668
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004669static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004670_ssl_MemoryBIO_impl(PyTypeObject *type)
4671/*[clinic end generated code: output=8820a58db78330ac input=26d22e4909ecb1b5]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004672{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004673 BIO *bio;
4674 PySSLMemoryBIO *self;
4675
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004676 bio = BIO_new(BIO_s_mem());
4677 if (bio == NULL) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02004678 PyErr_SetString(PyExc_MemoryError, "failed to allocate BIO");
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004679 return NULL;
4680 }
4681 /* Since our BIO is non-blocking an empty read() does not indicate EOF,
4682 * just that no data is currently available. The SSL routines should retry
4683 * the read, which we can achieve by calling BIO_set_retry_read(). */
4684 BIO_set_retry_read(bio);
4685 BIO_set_mem_eof_return(bio, -1);
4686
4687 assert(type != NULL && type->tp_alloc != NULL);
4688 self = (PySSLMemoryBIO *) type->tp_alloc(type, 0);
4689 if (self == NULL) {
4690 BIO_free(bio);
4691 return NULL;
4692 }
4693 self->bio = bio;
4694 self->eof_written = 0;
4695
4696 return (PyObject *) self;
4697}
4698
Miss Islington (bot)ea47a8a2021-05-27 09:25:22 -07004699static int
4700memory_bio_traverse(PySSLMemoryBIO *self, visitproc visit, void *arg)
4701{
4702 Py_VISIT(Py_TYPE(self));
4703 return 0;
4704}
4705
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004706static void
4707memory_bio_dealloc(PySSLMemoryBIO *self)
4708{
Christian Heimes5c36da72020-11-20 09:40:12 +01004709 PyTypeObject *tp = Py_TYPE(self);
Miss Islington (bot)ea47a8a2021-05-27 09:25:22 -07004710 PyObject_GC_UnTrack(self);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004711 BIO_free(self->bio);
4712 Py_TYPE(self)->tp_free(self);
Christian Heimes5c36da72020-11-20 09:40:12 +01004713 Py_DECREF(tp);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004714}
4715
4716static PyObject *
4717memory_bio_get_pending(PySSLMemoryBIO *self, void *c)
4718{
Segev Finer5cff6372017-07-27 01:19:17 +03004719 return PyLong_FromSize_t(BIO_ctrl_pending(self->bio));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004720}
4721
4722PyDoc_STRVAR(PySSL_memory_bio_pending_doc,
4723"The number of bytes pending in the memory BIO.");
4724
4725static PyObject *
4726memory_bio_get_eof(PySSLMemoryBIO *self, void *c)
4727{
4728 return PyBool_FromLong((BIO_ctrl_pending(self->bio) == 0)
4729 && self->eof_written);
4730}
4731
4732PyDoc_STRVAR(PySSL_memory_bio_eof_doc,
4733"Whether the memory BIO is at EOF.");
4734
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004735/*[clinic input]
4736_ssl.MemoryBIO.read
4737 size as len: int = -1
4738 /
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004739
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004740Read up to size bytes from the memory BIO.
4741
4742If size is not specified, read the entire buffer.
4743If the return value is an empty bytes instance, this means either
4744EOF or that no data is available. Use the "eof" property to
4745distinguish between the two.
4746[clinic start generated code]*/
4747
4748static PyObject *
4749_ssl_MemoryBIO_read_impl(PySSLMemoryBIO *self, int len)
4750/*[clinic end generated code: output=a657aa1e79cd01b3 input=574d7be06a902366]*/
4751{
4752 int avail, nbytes;
4753 PyObject *result;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004754
Segev Finer5cff6372017-07-27 01:19:17 +03004755 avail = (int)Py_MIN(BIO_ctrl_pending(self->bio), INT_MAX);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004756 if ((len < 0) || (len > avail))
4757 len = avail;
4758
4759 result = PyBytes_FromStringAndSize(NULL, len);
4760 if ((result == NULL) || (len == 0))
4761 return result;
4762
4763 nbytes = BIO_read(self->bio, PyBytes_AS_STRING(result), len);
Zackery Spytz365ad2e2018-10-06 11:41:45 -06004764 if (nbytes < 0) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02004765 _sslmodulestate *state = get_state_mbio(self);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004766 Py_DECREF(result);
Christian Heimes7f1305e2021-04-17 20:06:38 +02004767 _setSSLError(state, NULL, 0, __FILE__, __LINE__);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004768 return NULL;
4769 }
4770
Zackery Spytz365ad2e2018-10-06 11:41:45 -06004771 /* There should never be any short reads but check anyway. */
4772 if (nbytes < len) {
4773 _PyBytes_Resize(&result, nbytes);
4774 }
4775
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004776 return result;
4777}
4778
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004779/*[clinic input]
4780_ssl.MemoryBIO.write
4781 b: Py_buffer
4782 /
4783
4784Writes the bytes b into the memory BIO.
4785
4786Returns the number of bytes written.
4787[clinic start generated code]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004788
4789static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004790_ssl_MemoryBIO_write_impl(PySSLMemoryBIO *self, Py_buffer *b)
4791/*[clinic end generated code: output=156ec59110d75935 input=e45757b3e17c4808]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004792{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004793 int nbytes;
4794
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004795 if (b->len > INT_MAX) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004796 PyErr_Format(PyExc_OverflowError,
4797 "string longer than %d bytes", INT_MAX);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004798 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004799 }
4800
4801 if (self->eof_written) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02004802 PyObject *module = PyType_GetModule(Py_TYPE(self));
4803 if (module == NULL)
4804 return NULL;
4805 PyErr_SetString(get_ssl_state(module)->PySSLErrorObject,
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004806 "cannot write() after write_eof()");
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004807 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004808 }
4809
Segev Finer5cff6372017-07-27 01:19:17 +03004810 nbytes = BIO_write(self->bio, b->buf, (int)b->len);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004811 if (nbytes < 0) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02004812 _sslmodulestate *state = get_state_mbio(self);
4813 _setSSLError(state, NULL, 0, __FILE__, __LINE__);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004814 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004815 }
4816
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004817 return PyLong_FromLong(nbytes);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004818}
4819
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004820/*[clinic input]
4821_ssl.MemoryBIO.write_eof
4822
4823Write an EOF marker to the memory BIO.
4824
4825When all data has been read, the "eof" property will be True.
4826[clinic start generated code]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004827
4828static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004829_ssl_MemoryBIO_write_eof_impl(PySSLMemoryBIO *self)
4830/*[clinic end generated code: output=d4106276ccd1ed34 input=56a945f1d29e8bd6]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004831{
4832 self->eof_written = 1;
4833 /* After an EOF is written, a zero return from read() should be a real EOF
4834 * i.e. it should not be retried. Clear the SHOULD_RETRY flag. */
4835 BIO_clear_retry_flags(self->bio);
4836 BIO_set_mem_eof_return(self->bio, 0);
4837
4838 Py_RETURN_NONE;
4839}
4840
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004841static PyGetSetDef memory_bio_getsetlist[] = {
4842 {"pending", (getter) memory_bio_get_pending, NULL,
4843 PySSL_memory_bio_pending_doc},
4844 {"eof", (getter) memory_bio_get_eof, NULL,
4845 PySSL_memory_bio_eof_doc},
4846 {NULL}, /* sentinel */
4847};
4848
4849static struct PyMethodDef memory_bio_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004850 _SSL_MEMORYBIO_READ_METHODDEF
4851 _SSL_MEMORYBIO_WRITE_METHODDEF
4852 _SSL_MEMORYBIO_WRITE_EOF_METHODDEF
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004853 {NULL, NULL} /* sentinel */
4854};
4855
Christian Heimes5c36da72020-11-20 09:40:12 +01004856static PyType_Slot PySSLMemoryBIO_slots[] = {
4857 {Py_tp_methods, memory_bio_methods},
4858 {Py_tp_getset, memory_bio_getsetlist},
4859 {Py_tp_new, _ssl_MemoryBIO},
4860 {Py_tp_dealloc, memory_bio_dealloc},
Miss Islington (bot)ea47a8a2021-05-27 09:25:22 -07004861 {Py_tp_traverse, memory_bio_traverse},
Christian Heimes5c36da72020-11-20 09:40:12 +01004862 {0, 0},
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004863};
4864
Christian Heimes5c36da72020-11-20 09:40:12 +01004865static PyType_Spec PySSLMemoryBIO_spec = {
Miss Islington (bot)ea47a8a2021-05-27 09:25:22 -07004866 .name = "_ssl.MemoryBIO",
4867 .basicsize = sizeof(PySSLMemoryBIO),
4868 .flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_IMMUTABLETYPE |
4869 Py_TPFLAGS_HAVE_GC),
4870 .slots = PySSLMemoryBIO_slots,
Christian Heimes5c36da72020-11-20 09:40:12 +01004871};
Antoine Pitrou152efa22010-05-16 18:19:27 +00004872
Christian Heimes99a65702016-09-10 23:44:53 +02004873/*
4874 * SSL Session object
4875 */
4876
4877static void
4878PySSLSession_dealloc(PySSLSession *self)
4879{
Christian Heimes5c36da72020-11-20 09:40:12 +01004880 PyTypeObject *tp = Py_TYPE(self);
INADA Naokia6296d32017-08-24 14:55:17 +09004881 /* bpo-31095: UnTrack is needed before calling any callbacks */
Christian Heimesa5d07652016-09-24 10:48:05 +02004882 PyObject_GC_UnTrack(self);
Christian Heimes99a65702016-09-10 23:44:53 +02004883 Py_XDECREF(self->ctx);
4884 if (self->session != NULL) {
4885 SSL_SESSION_free(self->session);
4886 }
Christian Heimesa5d07652016-09-24 10:48:05 +02004887 PyObject_GC_Del(self);
Christian Heimes5c36da72020-11-20 09:40:12 +01004888 Py_DECREF(tp);
Christian Heimes99a65702016-09-10 23:44:53 +02004889}
4890
4891static PyObject *
4892PySSLSession_richcompare(PyObject *left, PyObject *right, int op)
4893{
4894 int result;
Christian Heimes7f1305e2021-04-17 20:06:38 +02004895 PyTypeObject *sesstype = ((PySSLSession*)left)->ctx->state->PySSLSession_Type;
Christian Heimes99a65702016-09-10 23:44:53 +02004896
4897 if (left == NULL || right == NULL) {
4898 PyErr_BadInternalCall();
4899 return NULL;
4900 }
4901
Christian Heimes7f1305e2021-04-17 20:06:38 +02004902 if (!Py_IS_TYPE(left, sesstype) || !Py_IS_TYPE(right, sesstype)) {
Christian Heimes99a65702016-09-10 23:44:53 +02004903 Py_RETURN_NOTIMPLEMENTED;
4904 }
4905
4906 if (left == right) {
4907 result = 0;
4908 } else {
4909 const unsigned char *left_id, *right_id;
4910 unsigned int left_len, right_len;
4911 left_id = SSL_SESSION_get_id(((PySSLSession *)left)->session,
4912 &left_len);
4913 right_id = SSL_SESSION_get_id(((PySSLSession *)right)->session,
4914 &right_len);
4915 if (left_len == right_len) {
4916 result = memcmp(left_id, right_id, left_len);
4917 } else {
4918 result = 1;
4919 }
4920 }
4921
4922 switch (op) {
4923 case Py_EQ:
4924 if (result == 0) {
4925 Py_RETURN_TRUE;
4926 } else {
4927 Py_RETURN_FALSE;
4928 }
4929 break;
4930 case Py_NE:
4931 if (result != 0) {
4932 Py_RETURN_TRUE;
4933 } else {
4934 Py_RETURN_FALSE;
4935 }
4936 break;
4937 case Py_LT:
4938 case Py_LE:
4939 case Py_GT:
4940 case Py_GE:
4941 Py_RETURN_NOTIMPLEMENTED;
4942 break;
4943 default:
4944 PyErr_BadArgument();
4945 return NULL;
4946 }
4947}
4948
4949static int
4950PySSLSession_traverse(PySSLSession *self, visitproc visit, void *arg)
4951{
4952 Py_VISIT(self->ctx);
Miss Islington (bot)ea47a8a2021-05-27 09:25:22 -07004953 Py_VISIT(Py_TYPE(self));
Christian Heimes99a65702016-09-10 23:44:53 +02004954 return 0;
4955}
4956
4957static int
4958PySSLSession_clear(PySSLSession *self)
4959{
4960 Py_CLEAR(self->ctx);
4961 return 0;
4962}
4963
4964
4965static PyObject *
4966PySSLSession_get_time(PySSLSession *self, void *closure) {
4967 return PyLong_FromLong(SSL_SESSION_get_time(self->session));
4968}
4969
4970PyDoc_STRVAR(PySSLSession_get_time_doc,
4971"Session creation time (seconds since epoch).");
4972
4973
4974static PyObject *
4975PySSLSession_get_timeout(PySSLSession *self, void *closure) {
4976 return PyLong_FromLong(SSL_SESSION_get_timeout(self->session));
4977}
4978
4979PyDoc_STRVAR(PySSLSession_get_timeout_doc,
4980"Session timeout (delta in seconds).");
4981
4982
4983static PyObject *
4984PySSLSession_get_ticket_lifetime_hint(PySSLSession *self, void *closure) {
4985 unsigned long hint = SSL_SESSION_get_ticket_lifetime_hint(self->session);
4986 return PyLong_FromUnsignedLong(hint);
4987}
4988
4989PyDoc_STRVAR(PySSLSession_get_ticket_lifetime_hint_doc,
4990"Ticket life time hint.");
4991
4992
4993static PyObject *
4994PySSLSession_get_session_id(PySSLSession *self, void *closure) {
4995 const unsigned char *id;
4996 unsigned int len;
4997 id = SSL_SESSION_get_id(self->session, &len);
4998 return PyBytes_FromStringAndSize((const char *)id, len);
4999}
5000
5001PyDoc_STRVAR(PySSLSession_get_session_id_doc,
5002"Session id");
5003
5004
5005static PyObject *
5006PySSLSession_get_has_ticket(PySSLSession *self, void *closure) {
5007 if (SSL_SESSION_has_ticket(self->session)) {
5008 Py_RETURN_TRUE;
5009 } else {
5010 Py_RETURN_FALSE;
5011 }
5012}
5013
5014PyDoc_STRVAR(PySSLSession_get_has_ticket_doc,
5015"Does the session contain a ticket?");
5016
5017
5018static PyGetSetDef PySSLSession_getsetlist[] = {
5019 {"has_ticket", (getter) PySSLSession_get_has_ticket, NULL,
5020 PySSLSession_get_has_ticket_doc},
5021 {"id", (getter) PySSLSession_get_session_id, NULL,
5022 PySSLSession_get_session_id_doc},
5023 {"ticket_lifetime_hint", (getter) PySSLSession_get_ticket_lifetime_hint,
5024 NULL, PySSLSession_get_ticket_lifetime_hint_doc},
5025 {"time", (getter) PySSLSession_get_time, NULL,
5026 PySSLSession_get_time_doc},
5027 {"timeout", (getter) PySSLSession_get_timeout, NULL,
5028 PySSLSession_get_timeout_doc},
5029 {NULL}, /* sentinel */
5030};
5031
Christian Heimes5c36da72020-11-20 09:40:12 +01005032static PyType_Slot PySSLSession_slots[] = {
5033 {Py_tp_getset,PySSLSession_getsetlist},
5034 {Py_tp_richcompare, PySSLSession_richcompare},
5035 {Py_tp_dealloc, PySSLSession_dealloc},
5036 {Py_tp_traverse, PySSLSession_traverse},
5037 {Py_tp_clear, PySSLSession_clear},
5038 {0, 0},
5039};
5040
5041static PyType_Spec PySSLSession_spec = {
Miss Islington (bot)ea47a8a2021-05-27 09:25:22 -07005042 .name = "_ssl.SSLSession",
5043 .basicsize = sizeof(PySSLSession),
5044 .flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
5045 Py_TPFLAGS_IMMUTABLETYPE),
5046 .slots = PySSLSession_slots,
Christian Heimes99a65702016-09-10 23:44:53 +02005047};
5048
5049
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005050/* helper routines for seeding the SSL PRNG */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005051/*[clinic input]
5052_ssl.RAND_add
Larry Hastingsdbfdc382015-05-04 06:59:46 -07005053 string as view: Py_buffer(accept={str, buffer})
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005054 entropy: double
5055 /
5056
5057Mix string into the OpenSSL PRNG state.
5058
5059entropy (a float) is a lower bound on the entropy contained in
Chandan Kumar63c2c8a2017-06-09 15:13:58 +05305060string. See RFC 4086.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005061[clinic start generated code]*/
5062
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005063static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005064_ssl_RAND_add_impl(PyObject *module, Py_buffer *view, double entropy)
Serhiy Storchaka5f31d5c2017-06-10 13:13:51 +03005065/*[clinic end generated code: output=e6dd48df9c9024e9 input=5c33017422828f5c]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005066{
Serhiy Storchaka8490f5a2015-03-20 09:00:36 +02005067 const char *buf;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02005068 Py_ssize_t len, written;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005069
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005070 buf = (const char *)view->buf;
5071 len = view->len;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02005072 do {
5073 written = Py_MIN(len, INT_MAX);
5074 RAND_add(buf, (int)written, entropy);
5075 buf += written;
5076 len -= written;
5077 } while (len);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02005078 Py_RETURN_NONE;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005079}
5080
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005081static PyObject *
Christian Heimes7f1305e2021-04-17 20:06:38 +02005082PySSL_RAND(PyObject *module, int len, int pseudo)
Victor Stinner99c8b162011-05-24 12:05:19 +02005083{
5084 int ok;
5085 PyObject *bytes;
5086 unsigned long err;
5087 const char *errstr;
5088 PyObject *v;
5089
Victor Stinner1e81a392013-12-19 16:47:04 +01005090 if (len < 0) {
5091 PyErr_SetString(PyExc_ValueError, "num must be positive");
5092 return NULL;
5093 }
5094
Victor Stinner99c8b162011-05-24 12:05:19 +02005095 bytes = PyBytes_FromStringAndSize(NULL, len);
5096 if (bytes == NULL)
5097 return NULL;
5098 if (pseudo) {
Christian Heimesa871f692020-06-01 08:58:14 +02005099 ok = RAND_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
Victor Stinner99c8b162011-05-24 12:05:19 +02005100 if (ok == 0 || ok == 1)
5101 return Py_BuildValue("NO", bytes, ok == 1 ? Py_True : Py_False);
5102 }
5103 else {
5104 ok = RAND_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
5105 if (ok == 1)
5106 return bytes;
5107 }
5108 Py_DECREF(bytes);
5109
5110 err = ERR_get_error();
5111 errstr = ERR_reason_error_string(err);
5112 v = Py_BuildValue("(ks)", err, errstr);
5113 if (v != NULL) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02005114 PyErr_SetObject(get_ssl_state(module)->PySSLErrorObject, v);
Victor Stinner99c8b162011-05-24 12:05:19 +02005115 Py_DECREF(v);
5116 }
5117 return NULL;
5118}
5119
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005120/*[clinic input]
5121_ssl.RAND_bytes
5122 n: int
5123 /
5124
5125Generate n cryptographically strong pseudo-random bytes.
5126[clinic start generated code]*/
5127
Victor Stinner99c8b162011-05-24 12:05:19 +02005128static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005129_ssl_RAND_bytes_impl(PyObject *module, int n)
5130/*[clinic end generated code: output=977da635e4838bc7 input=678ddf2872dfebfc]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02005131{
Christian Heimes7f1305e2021-04-17 20:06:38 +02005132 return PySSL_RAND(module, n, 0);
Victor Stinner99c8b162011-05-24 12:05:19 +02005133}
5134
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005135/*[clinic input]
5136_ssl.RAND_pseudo_bytes
5137 n: int
5138 /
5139
5140Generate n pseudo-random bytes.
5141
5142Return a pair (bytes, is_cryptographic). is_cryptographic is True
5143if the bytes generated are cryptographically strong.
5144[clinic start generated code]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02005145
5146static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005147_ssl_RAND_pseudo_bytes_impl(PyObject *module, int n)
5148/*[clinic end generated code: output=b1509e937000e52d input=58312bd53f9bbdd0]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02005149{
Christian Heimes2875c602021-04-19 07:27:10 +02005150 PY_SSL_DEPRECATED("RAND_pseudo_bytes", 1, NULL);
Christian Heimes7f1305e2021-04-17 20:06:38 +02005151 return PySSL_RAND(module, n, 1);
Victor Stinner99c8b162011-05-24 12:05:19 +02005152}
5153
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005154/*[clinic input]
5155_ssl.RAND_status
5156
Zackery Spytz7d37b862021-04-23 10:07:37 -06005157Returns True if the OpenSSL PRNG has been seeded with enough data and False if not.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005158
5159It is necessary to seed the PRNG with RAND_add() on some platforms before
5160using the ssl() function.
5161[clinic start generated code]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02005162
5163static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005164_ssl_RAND_status_impl(PyObject *module)
Zackery Spytz7d37b862021-04-23 10:07:37 -06005165/*[clinic end generated code: output=7e0aaa2d39fdc1ad input=d5ae5aea52f36e01]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005166{
Zackery Spytz7d37b862021-04-23 10:07:37 -06005167 return PyBool_FromLong(RAND_status());
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005168}
5169
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005170/*[clinic input]
5171_ssl.get_default_verify_paths
5172
5173Return search paths and environment vars that are used by SSLContext's set_default_verify_paths() to load default CAs.
5174
5175The values are 'cert_file_env', 'cert_file', 'cert_dir_env', 'cert_dir'.
5176[clinic start generated code]*/
Christian Heimes6d7ad132013-06-09 18:02:55 +02005177
5178static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005179_ssl_get_default_verify_paths_impl(PyObject *module)
5180/*[clinic end generated code: output=e5b62a466271928b input=5210c953d98c3eb5]*/
Christian Heimes6d7ad132013-06-09 18:02:55 +02005181{
5182 PyObject *ofile_env = NULL;
5183 PyObject *ofile = NULL;
5184 PyObject *odir_env = NULL;
5185 PyObject *odir = NULL;
5186
Benjamin Petersond113c962015-07-18 10:59:13 -07005187#define CONVERT(info, target) { \
Christian Heimes6d7ad132013-06-09 18:02:55 +02005188 const char *tmp = (info); \
5189 target = NULL; \
5190 if (!tmp) { Py_INCREF(Py_None); target = Py_None; } \
5191 else if ((target = PyUnicode_DecodeFSDefault(tmp)) == NULL) { \
5192 target = PyBytes_FromString(tmp); } \
5193 if (!target) goto error; \
Benjamin Peterson025a1fd2015-11-14 15:12:38 -08005194 }
Christian Heimes6d7ad132013-06-09 18:02:55 +02005195
Benjamin Petersond113c962015-07-18 10:59:13 -07005196 CONVERT(X509_get_default_cert_file_env(), ofile_env);
5197 CONVERT(X509_get_default_cert_file(), ofile);
5198 CONVERT(X509_get_default_cert_dir_env(), odir_env);
5199 CONVERT(X509_get_default_cert_dir(), odir);
5200#undef CONVERT
Christian Heimes6d7ad132013-06-09 18:02:55 +02005201
Christian Heimes200bb1b2013-06-14 15:14:29 +02005202 return Py_BuildValue("NNNN", ofile_env, ofile, odir_env, odir);
Christian Heimes6d7ad132013-06-09 18:02:55 +02005203
5204 error:
5205 Py_XDECREF(ofile_env);
5206 Py_XDECREF(ofile);
5207 Py_XDECREF(odir_env);
5208 Py_XDECREF(odir);
5209 return NULL;
5210}
5211
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005212static PyObject*
Christian Heimes7f1305e2021-04-17 20:06:38 +02005213asn1obj2py(_sslmodulestate *state, ASN1_OBJECT *obj)
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005214{
5215 int nid;
5216 const char *ln, *sn;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005217
5218 nid = OBJ_obj2nid(obj);
5219 if (nid == NID_undef) {
5220 PyErr_Format(PyExc_ValueError, "Unknown object");
5221 return NULL;
5222 }
5223 sn = OBJ_nid2sn(nid);
5224 ln = OBJ_nid2ln(nid);
Christian Heimes7f1305e2021-04-17 20:06:38 +02005225 return Py_BuildValue("issN", nid, sn, ln, _asn1obj2py(state, obj, 1));
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005226}
5227
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005228/*[clinic input]
5229_ssl.txt2obj
5230 txt: str
5231 name: bool = False
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005232
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005233Lookup NID, short name, long name and OID of an ASN1_OBJECT.
5234
5235By default objects are looked up by OID. With name=True short and
5236long name are also matched.
5237[clinic start generated code]*/
5238
5239static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005240_ssl_txt2obj_impl(PyObject *module, const char *txt, int name)
5241/*[clinic end generated code: output=c38e3991347079c1 input=1c1e7d0aa7c48602]*/
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005242{
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005243 PyObject *result = NULL;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005244 ASN1_OBJECT *obj;
5245
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005246 obj = OBJ_txt2obj(txt, name ? 0 : 1);
5247 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01005248 PyErr_Format(PyExc_ValueError, "unknown object '%.100s'", txt);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005249 return NULL;
5250 }
Christian Heimes7f1305e2021-04-17 20:06:38 +02005251 result = asn1obj2py(get_ssl_state(module), obj);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005252 ASN1_OBJECT_free(obj);
5253 return result;
5254}
5255
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005256/*[clinic input]
5257_ssl.nid2obj
5258 nid: int
5259 /
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005260
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005261Lookup NID, short name, long name and OID of an ASN1_OBJECT by NID.
5262[clinic start generated code]*/
5263
5264static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005265_ssl_nid2obj_impl(PyObject *module, int nid)
5266/*[clinic end generated code: output=4a98ab691cd4f84a input=51787a3bee7d8f98]*/
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005267{
5268 PyObject *result = NULL;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005269 ASN1_OBJECT *obj;
5270
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005271 if (nid < NID_undef) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01005272 PyErr_SetString(PyExc_ValueError, "NID must be positive.");
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005273 return NULL;
5274 }
5275 obj = OBJ_nid2obj(nid);
5276 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01005277 PyErr_Format(PyExc_ValueError, "unknown NID %i", nid);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005278 return NULL;
5279 }
Christian Heimes7f1305e2021-04-17 20:06:38 +02005280 result = asn1obj2py(get_ssl_state(module), obj);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005281 ASN1_OBJECT_free(obj);
5282 return result;
5283}
5284
Christian Heimes46bebee2013-06-09 19:03:31 +02005285#ifdef _MSC_VER
Christian Heimes44109d72013-11-22 01:51:30 +01005286
5287static PyObject*
5288certEncodingType(DWORD encodingType)
5289{
5290 static PyObject *x509_asn = NULL;
5291 static PyObject *pkcs_7_asn = NULL;
5292
5293 if (x509_asn == NULL) {
5294 x509_asn = PyUnicode_InternFromString("x509_asn");
5295 if (x509_asn == NULL)
5296 return NULL;
5297 }
5298 if (pkcs_7_asn == NULL) {
5299 pkcs_7_asn = PyUnicode_InternFromString("pkcs_7_asn");
5300 if (pkcs_7_asn == NULL)
5301 return NULL;
5302 }
5303 switch(encodingType) {
5304 case X509_ASN_ENCODING:
5305 Py_INCREF(x509_asn);
5306 return x509_asn;
5307 case PKCS_7_ASN_ENCODING:
5308 Py_INCREF(pkcs_7_asn);
5309 return pkcs_7_asn;
5310 default:
5311 return PyLong_FromLong(encodingType);
5312 }
5313}
5314
5315static PyObject*
5316parseKeyUsage(PCCERT_CONTEXT pCertCtx, DWORD flags)
5317{
5318 CERT_ENHKEY_USAGE *usage;
5319 DWORD size, error, i;
5320 PyObject *retval;
5321
5322 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, NULL, &size)) {
5323 error = GetLastError();
5324 if (error == CRYPT_E_NOT_FOUND) {
5325 Py_RETURN_TRUE;
5326 }
5327 return PyErr_SetFromWindowsErr(error);
5328 }
5329
5330 usage = (CERT_ENHKEY_USAGE*)PyMem_Malloc(size);
5331 if (usage == NULL) {
5332 return PyErr_NoMemory();
5333 }
5334
5335 /* Now get the actual enhanced usage property */
5336 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, usage, &size)) {
5337 PyMem_Free(usage);
5338 error = GetLastError();
5339 if (error == CRYPT_E_NOT_FOUND) {
5340 Py_RETURN_TRUE;
5341 }
5342 return PyErr_SetFromWindowsErr(error);
5343 }
Christian Heimes915cd3f2019-09-09 18:06:55 +02005344 retval = PyFrozenSet_New(NULL);
Christian Heimes44109d72013-11-22 01:51:30 +01005345 if (retval == NULL) {
5346 goto error;
5347 }
5348 for (i = 0; i < usage->cUsageIdentifier; ++i) {
5349 if (usage->rgpszUsageIdentifier[i]) {
5350 PyObject *oid;
5351 int err;
5352 oid = PyUnicode_FromString(usage->rgpszUsageIdentifier[i]);
5353 if (oid == NULL) {
5354 Py_CLEAR(retval);
5355 goto error;
5356 }
5357 err = PySet_Add(retval, oid);
5358 Py_DECREF(oid);
5359 if (err == -1) {
5360 Py_CLEAR(retval);
5361 goto error;
5362 }
5363 }
5364 }
5365 error:
5366 PyMem_Free(usage);
5367 return retval;
5368}
5369
kctherookied93fbbf2019-03-29 00:59:06 +07005370static HCERTSTORE
5371ssl_collect_certificates(const char *store_name)
5372{
5373/* this function collects the system certificate stores listed in
5374 * system_stores into a collection certificate store for being
5375 * enumerated. The store must be readable to be added to the
5376 * store collection.
5377 */
5378
5379 HCERTSTORE hCollectionStore = NULL, hSystemStore = NULL;
5380 static DWORD system_stores[] = {
5381 CERT_SYSTEM_STORE_LOCAL_MACHINE,
5382 CERT_SYSTEM_STORE_LOCAL_MACHINE_ENTERPRISE,
5383 CERT_SYSTEM_STORE_LOCAL_MACHINE_GROUP_POLICY,
5384 CERT_SYSTEM_STORE_CURRENT_USER,
5385 CERT_SYSTEM_STORE_CURRENT_USER_GROUP_POLICY,
5386 CERT_SYSTEM_STORE_SERVICES,
5387 CERT_SYSTEM_STORE_USERS};
5388 size_t i, storesAdded;
5389 BOOL result;
5390
5391 hCollectionStore = CertOpenStore(CERT_STORE_PROV_COLLECTION, 0,
5392 (HCRYPTPROV)NULL, 0, NULL);
5393 if (!hCollectionStore) {
5394 return NULL;
5395 }
5396 storesAdded = 0;
5397 for (i = 0; i < sizeof(system_stores) / sizeof(DWORD); i++) {
5398 hSystemStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0,
5399 (HCRYPTPROV)NULL,
5400 CERT_STORE_READONLY_FLAG |
5401 system_stores[i], store_name);
5402 if (hSystemStore) {
5403 result = CertAddStoreToCollection(hCollectionStore, hSystemStore,
5404 CERT_PHYSICAL_STORE_ADD_ENABLE_FLAG, 0);
5405 if (result) {
5406 ++storesAdded;
5407 }
neoneneed701292019-09-09 21:33:43 +09005408 CertCloseStore(hSystemStore, 0); /* flag must be 0 */
kctherookied93fbbf2019-03-29 00:59:06 +07005409 }
5410 }
5411 if (storesAdded == 0) {
5412 CertCloseStore(hCollectionStore, CERT_CLOSE_STORE_FORCE_FLAG);
5413 return NULL;
5414 }
5415
5416 return hCollectionStore;
5417}
5418
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005419/*[clinic input]
5420_ssl.enum_certificates
5421 store_name: str
5422
5423Retrieve certificates from Windows' cert store.
5424
5425store_name may be one of 'CA', 'ROOT' or 'MY'. The system may provide
5426more cert storages, too. The function returns a list of (bytes,
5427encoding_type, trust) tuples. The encoding_type flag can be interpreted
5428with X509_ASN_ENCODING or PKCS_7_ASN_ENCODING. The trust setting is either
5429a set of OIDs or the boolean True.
5430[clinic start generated code]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00005431
Christian Heimes46bebee2013-06-09 19:03:31 +02005432static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005433_ssl_enum_certificates_impl(PyObject *module, const char *store_name)
5434/*[clinic end generated code: output=5134dc8bb3a3c893 input=915f60d70461ea4e]*/
Christian Heimes46bebee2013-06-09 19:03:31 +02005435{
kctherookied93fbbf2019-03-29 00:59:06 +07005436 HCERTSTORE hCollectionStore = NULL;
Christian Heimes44109d72013-11-22 01:51:30 +01005437 PCCERT_CONTEXT pCertCtx = NULL;
5438 PyObject *keyusage = NULL, *cert = NULL, *enc = NULL, *tup = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02005439 PyObject *result = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02005440
Christian Heimes915cd3f2019-09-09 18:06:55 +02005441 result = PySet_New(NULL);
Christian Heimes44109d72013-11-22 01:51:30 +01005442 if (result == NULL) {
5443 return NULL;
5444 }
kctherookied93fbbf2019-03-29 00:59:06 +07005445 hCollectionStore = ssl_collect_certificates(store_name);
5446 if (hCollectionStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02005447 Py_DECREF(result);
5448 return PyErr_SetFromWindowsErr(GetLastError());
5449 }
5450
kctherookied93fbbf2019-03-29 00:59:06 +07005451 while (pCertCtx = CertEnumCertificatesInStore(hCollectionStore, pCertCtx)) {
Christian Heimes44109d72013-11-22 01:51:30 +01005452 cert = PyBytes_FromStringAndSize((const char*)pCertCtx->pbCertEncoded,
5453 pCertCtx->cbCertEncoded);
5454 if (!cert) {
5455 Py_CLEAR(result);
5456 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02005457 }
Christian Heimes44109d72013-11-22 01:51:30 +01005458 if ((enc = certEncodingType(pCertCtx->dwCertEncodingType)) == NULL) {
5459 Py_CLEAR(result);
5460 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02005461 }
Christian Heimes44109d72013-11-22 01:51:30 +01005462 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG);
5463 if (keyusage == Py_True) {
5464 Py_DECREF(keyusage);
5465 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_EXT_ONLY_ENHKEY_USAGE_FLAG);
Christian Heimes46bebee2013-06-09 19:03:31 +02005466 }
Christian Heimes44109d72013-11-22 01:51:30 +01005467 if (keyusage == NULL) {
5468 Py_CLEAR(result);
5469 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02005470 }
Christian Heimes44109d72013-11-22 01:51:30 +01005471 if ((tup = PyTuple_New(3)) == NULL) {
5472 Py_CLEAR(result);
5473 break;
5474 }
5475 PyTuple_SET_ITEM(tup, 0, cert);
5476 cert = NULL;
5477 PyTuple_SET_ITEM(tup, 1, enc);
5478 enc = NULL;
5479 PyTuple_SET_ITEM(tup, 2, keyusage);
5480 keyusage = NULL;
Christian Heimes915cd3f2019-09-09 18:06:55 +02005481 if (PySet_Add(result, tup) == -1) {
5482 Py_CLEAR(result);
5483 Py_CLEAR(tup);
5484 break;
Christian Heimes44109d72013-11-22 01:51:30 +01005485 }
5486 Py_CLEAR(tup);
5487 }
5488 if (pCertCtx) {
5489 /* loop ended with an error, need to clean up context manually */
5490 CertFreeCertificateContext(pCertCtx);
Christian Heimes46bebee2013-06-09 19:03:31 +02005491 }
5492
5493 /* In error cases cert, enc and tup may not be NULL */
5494 Py_XDECREF(cert);
5495 Py_XDECREF(enc);
Christian Heimes44109d72013-11-22 01:51:30 +01005496 Py_XDECREF(keyusage);
Christian Heimes46bebee2013-06-09 19:03:31 +02005497 Py_XDECREF(tup);
5498
kctherookied93fbbf2019-03-29 00:59:06 +07005499 /* CERT_CLOSE_STORE_FORCE_FLAG forces freeing of memory for all contexts
5500 associated with the store, in this case our collection store and the
5501 associated system stores. */
5502 if (!CertCloseStore(hCollectionStore, CERT_CLOSE_STORE_FORCE_FLAG)) {
Christian Heimes46bebee2013-06-09 19:03:31 +02005503 /* This error case might shadow another exception.*/
Christian Heimes44109d72013-11-22 01:51:30 +01005504 Py_XDECREF(result);
5505 return PyErr_SetFromWindowsErr(GetLastError());
5506 }
kctherookied93fbbf2019-03-29 00:59:06 +07005507
Christian Heimes915cd3f2019-09-09 18:06:55 +02005508 /* convert set to list */
5509 if (result == NULL) {
5510 return NULL;
5511 } else {
5512 PyObject *lst = PySequence_List(result);
5513 Py_DECREF(result);
5514 return lst;
5515 }
Christian Heimes44109d72013-11-22 01:51:30 +01005516}
5517
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005518/*[clinic input]
5519_ssl.enum_crls
5520 store_name: str
5521
5522Retrieve CRLs from Windows' cert store.
5523
5524store_name may be one of 'CA', 'ROOT' or 'MY'. The system may provide
5525more cert storages, too. The function returns a list of (bytes,
5526encoding_type) tuples. The encoding_type flag can be interpreted with
5527X509_ASN_ENCODING or PKCS_7_ASN_ENCODING.
5528[clinic start generated code]*/
Christian Heimes44109d72013-11-22 01:51:30 +01005529
5530static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005531_ssl_enum_crls_impl(PyObject *module, const char *store_name)
5532/*[clinic end generated code: output=bce467f60ccd03b6 input=a1f1d7629f1c5d3d]*/
Christian Heimes44109d72013-11-22 01:51:30 +01005533{
kctherookied93fbbf2019-03-29 00:59:06 +07005534 HCERTSTORE hCollectionStore = NULL;
Christian Heimes44109d72013-11-22 01:51:30 +01005535 PCCRL_CONTEXT pCrlCtx = NULL;
5536 PyObject *crl = NULL, *enc = NULL, *tup = NULL;
5537 PyObject *result = NULL;
5538
Christian Heimes915cd3f2019-09-09 18:06:55 +02005539 result = PySet_New(NULL);
Christian Heimes44109d72013-11-22 01:51:30 +01005540 if (result == NULL) {
5541 return NULL;
5542 }
kctherookied93fbbf2019-03-29 00:59:06 +07005543 hCollectionStore = ssl_collect_certificates(store_name);
5544 if (hCollectionStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02005545 Py_DECREF(result);
5546 return PyErr_SetFromWindowsErr(GetLastError());
5547 }
Christian Heimes44109d72013-11-22 01:51:30 +01005548
kctherookied93fbbf2019-03-29 00:59:06 +07005549 while (pCrlCtx = CertEnumCRLsInStore(hCollectionStore, pCrlCtx)) {
Christian Heimes44109d72013-11-22 01:51:30 +01005550 crl = PyBytes_FromStringAndSize((const char*)pCrlCtx->pbCrlEncoded,
5551 pCrlCtx->cbCrlEncoded);
5552 if (!crl) {
5553 Py_CLEAR(result);
5554 break;
5555 }
5556 if ((enc = certEncodingType(pCrlCtx->dwCertEncodingType)) == NULL) {
5557 Py_CLEAR(result);
5558 break;
5559 }
5560 if ((tup = PyTuple_New(2)) == NULL) {
5561 Py_CLEAR(result);
5562 break;
5563 }
5564 PyTuple_SET_ITEM(tup, 0, crl);
5565 crl = NULL;
5566 PyTuple_SET_ITEM(tup, 1, enc);
5567 enc = NULL;
5568
Christian Heimes915cd3f2019-09-09 18:06:55 +02005569 if (PySet_Add(result, tup) == -1) {
5570 Py_CLEAR(result);
5571 Py_CLEAR(tup);
5572 break;
Christian Heimes44109d72013-11-22 01:51:30 +01005573 }
5574 Py_CLEAR(tup);
Christian Heimes46bebee2013-06-09 19:03:31 +02005575 }
Christian Heimes44109d72013-11-22 01:51:30 +01005576 if (pCrlCtx) {
5577 /* loop ended with an error, need to clean up context manually */
5578 CertFreeCRLContext(pCrlCtx);
5579 }
5580
5581 /* In error cases cert, enc and tup may not be NULL */
5582 Py_XDECREF(crl);
5583 Py_XDECREF(enc);
5584 Py_XDECREF(tup);
5585
kctherookied93fbbf2019-03-29 00:59:06 +07005586 /* CERT_CLOSE_STORE_FORCE_FLAG forces freeing of memory for all contexts
5587 associated with the store, in this case our collection store and the
5588 associated system stores. */
5589 if (!CertCloseStore(hCollectionStore, CERT_CLOSE_STORE_FORCE_FLAG)) {
Christian Heimes44109d72013-11-22 01:51:30 +01005590 /* This error case might shadow another exception.*/
5591 Py_XDECREF(result);
5592 return PyErr_SetFromWindowsErr(GetLastError());
5593 }
Christian Heimes915cd3f2019-09-09 18:06:55 +02005594 /* convert set to list */
5595 if (result == NULL) {
5596 return NULL;
5597 } else {
5598 PyObject *lst = PySequence_List(result);
5599 Py_DECREF(result);
5600 return lst;
5601 }
Christian Heimes46bebee2013-06-09 19:03:31 +02005602}
Christian Heimes44109d72013-11-22 01:51:30 +01005603
5604#endif /* _MSC_VER */
Bill Janssen40a0f662008-08-12 16:56:25 +00005605
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005606/* List of functions exported by this module. */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005607static PyMethodDef PySSL_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005608 _SSL__TEST_DECODE_CERT_METHODDEF
5609 _SSL_RAND_ADD_METHODDEF
5610 _SSL_RAND_BYTES_METHODDEF
5611 _SSL_RAND_PSEUDO_BYTES_METHODDEF
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005612 _SSL_RAND_STATUS_METHODDEF
5613 _SSL_GET_DEFAULT_VERIFY_PATHS_METHODDEF
5614 _SSL_ENUM_CERTIFICATES_METHODDEF
5615 _SSL_ENUM_CRLS_METHODDEF
5616 _SSL_TXT2OBJ_METHODDEF
5617 _SSL_NID2OBJ_METHODDEF
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005618 {NULL, NULL} /* Sentinel */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005619};
5620
5621
Christian Heimes7f1305e2021-04-17 20:06:38 +02005622PyDoc_STRVAR(module_doc,
5623"Implementation module for SSL socket operations. See the socket module\n\
5624for documentation.");
Christian Heimes5c36da72020-11-20 09:40:12 +01005625
5626static int
5627sslmodule_init_exceptions(PyObject *module)
5628{
Christian Heimes7f1305e2021-04-17 20:06:38 +02005629 _sslmodulestate *state = get_ssl_state(module);
Christian Heimes5c36da72020-11-20 09:40:12 +01005630 PyObject *bases = NULL;
5631
Christian Heimes7f1305e2021-04-17 20:06:38 +02005632#define add_exception(exc, name, doc, base) \
5633do { \
5634 (exc) = PyErr_NewExceptionWithDoc("ssl." name, (doc), (base), NULL); \
5635 if ((state) == NULL) goto error; \
5636 if (PyModule_AddObjectRef(module, name, exc) < 0) goto error; \
Christian Heimes5c36da72020-11-20 09:40:12 +01005637} while(0)
5638
Christian Heimes7f1305e2021-04-17 20:06:38 +02005639 state->PySSLErrorObject = PyType_FromSpecWithBases(
5640 &sslerror_type_spec, PyExc_OSError);
5641 if (state->PySSLErrorObject == NULL) {
Christian Heimes5c36da72020-11-20 09:40:12 +01005642 goto error;
5643 }
Christian Heimes7f1305e2021-04-17 20:06:38 +02005644 if (PyModule_AddObjectRef(module, "SSLError", state->PySSLErrorObject) < 0) {
Christian Heimes5c36da72020-11-20 09:40:12 +01005645 goto error;
5646 }
5647
5648 /* ssl.CertificateError used to be a subclass of ValueError */
Christian Heimes7f1305e2021-04-17 20:06:38 +02005649 bases = PyTuple_Pack(2, state->PySSLErrorObject, PyExc_ValueError);
Christian Heimes5c36da72020-11-20 09:40:12 +01005650 if (bases == NULL) {
5651 goto error;
5652 }
5653 add_exception(
Christian Heimes7f1305e2021-04-17 20:06:38 +02005654 state->PySSLCertVerificationErrorObject,
Christian Heimes5c36da72020-11-20 09:40:12 +01005655 "SSLCertVerificationError",
5656 SSLCertVerificationError_doc,
5657 bases
5658 );
5659 Py_CLEAR(bases);
5660
5661 add_exception(
Christian Heimes7f1305e2021-04-17 20:06:38 +02005662 state->PySSLZeroReturnErrorObject,
Christian Heimes5c36da72020-11-20 09:40:12 +01005663 "SSLZeroReturnError",
5664 SSLZeroReturnError_doc,
Christian Heimes7f1305e2021-04-17 20:06:38 +02005665 state->PySSLErrorObject
Christian Heimes5c36da72020-11-20 09:40:12 +01005666 );
5667
5668 add_exception(
Christian Heimes7f1305e2021-04-17 20:06:38 +02005669 state->PySSLWantWriteErrorObject,
Christian Heimes5c36da72020-11-20 09:40:12 +01005670 "SSLWantWriteError",
5671 SSLWantWriteError_doc,
Christian Heimes7f1305e2021-04-17 20:06:38 +02005672 state->PySSLErrorObject
Christian Heimes5c36da72020-11-20 09:40:12 +01005673 );
5674
5675 add_exception(
Christian Heimes7f1305e2021-04-17 20:06:38 +02005676 state->PySSLWantReadErrorObject,
Christian Heimes5c36da72020-11-20 09:40:12 +01005677 "SSLWantReadError",
5678 SSLWantReadError_doc,
Christian Heimes7f1305e2021-04-17 20:06:38 +02005679 state->PySSLErrorObject
Christian Heimes5c36da72020-11-20 09:40:12 +01005680 );
5681
5682 add_exception(
Christian Heimes7f1305e2021-04-17 20:06:38 +02005683 state->PySSLSyscallErrorObject,
Christian Heimes5c36da72020-11-20 09:40:12 +01005684 "SSLSyscallError",
5685 SSLSyscallError_doc,
Christian Heimes7f1305e2021-04-17 20:06:38 +02005686 state->PySSLErrorObject
Christian Heimes5c36da72020-11-20 09:40:12 +01005687 );
5688
5689 add_exception(
Christian Heimes7f1305e2021-04-17 20:06:38 +02005690 state->PySSLEOFErrorObject,
Christian Heimes5c36da72020-11-20 09:40:12 +01005691 "SSLEOFError",
5692 SSLEOFError_doc,
Christian Heimes7f1305e2021-04-17 20:06:38 +02005693 state->PySSLErrorObject
Christian Heimes5c36da72020-11-20 09:40:12 +01005694 );
5695#undef add_exception
5696
5697 return 0;
5698 error:
5699 Py_XDECREF(bases);
5700 return -1;
5701}
5702
5703static int
5704sslmodule_init_socketapi(PyObject *module)
5705{
Christian Heimes7f1305e2021-04-17 20:06:38 +02005706 _sslmodulestate *state = get_ssl_state(module);
5707 PySocketModule_APIObject *sockmod = PySocketModule_ImportModuleAndAPI();
Christian Heimes5c36da72020-11-20 09:40:12 +01005708
Christian Heimes7f1305e2021-04-17 20:06:38 +02005709 if ((sockmod == NULL) || (sockmod->Sock_Type == NULL)) {
Christian Heimes5c36da72020-11-20 09:40:12 +01005710 return -1;
Christian Heimes5c36da72020-11-20 09:40:12 +01005711 }
Christian Heimes7f1305e2021-04-17 20:06:38 +02005712 state->Sock_Type = sockmod->Sock_Type;
5713 Py_INCREF(state->Sock_Type);
Christian Heimes5c36da72020-11-20 09:40:12 +01005714 return 0;
5715}
Christian Heimesc941e622017-09-05 15:47:11 +02005716
Christian Heimes5c36da72020-11-20 09:40:12 +01005717static int
5718sslmodule_init_constants(PyObject *m)
5719{
Christian Heimes7f1305e2021-04-17 20:06:38 +02005720
Christian Heimes892d66e2018-01-29 14:10:18 +01005721 PyModule_AddStringConstant(m, "_DEFAULT_CIPHERS",
5722 PY_SSL_DEFAULT_CIPHER_STRING);
5723
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005724 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
5725 PY_SSL_ERROR_ZERO_RETURN);
5726 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
5727 PY_SSL_ERROR_WANT_READ);
5728 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
5729 PY_SSL_ERROR_WANT_WRITE);
5730 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
5731 PY_SSL_ERROR_WANT_X509_LOOKUP);
5732 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
5733 PY_SSL_ERROR_SYSCALL);
5734 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
5735 PY_SSL_ERROR_SSL);
5736 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
5737 PY_SSL_ERROR_WANT_CONNECT);
5738 /* non ssl.h errorcodes */
5739 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
5740 PY_SSL_ERROR_EOF);
5741 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
5742 PY_SSL_ERROR_INVALID_ERROR_CODE);
5743 /* cert requirements */
5744 PyModule_AddIntConstant(m, "CERT_NONE",
5745 PY_SSL_CERT_NONE);
5746 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
5747 PY_SSL_CERT_OPTIONAL);
5748 PyModule_AddIntConstant(m, "CERT_REQUIRED",
5749 PY_SSL_CERT_REQUIRED);
Christian Heimes22587792013-11-21 23:56:13 +01005750 /* CRL verification for verification_flags */
5751 PyModule_AddIntConstant(m, "VERIFY_DEFAULT",
5752 0);
5753 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_LEAF",
5754 X509_V_FLAG_CRL_CHECK);
5755 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_CHAIN",
5756 X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
5757 PyModule_AddIntConstant(m, "VERIFY_X509_STRICT",
5758 X509_V_FLAG_X509_STRICT);
Chris Burre0b4aa02021-03-18 09:24:01 +01005759 PyModule_AddIntConstant(m, "VERIFY_ALLOW_PROXY_CERTS",
5760 X509_V_FLAG_ALLOW_PROXY_CERTS);
Benjamin Peterson990fcaa2015-03-04 22:49:41 -05005761 PyModule_AddIntConstant(m, "VERIFY_X509_TRUSTED_FIRST",
5762 X509_V_FLAG_TRUSTED_FIRST);
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00005763
l0x64d97522021-04-19 13:51:18 +02005764#ifdef X509_V_FLAG_PARTIAL_CHAIN
5765 PyModule_AddIntConstant(m, "VERIFY_X509_PARTIAL_CHAIN",
5766 X509_V_FLAG_PARTIAL_CHAIN);
5767#endif
5768
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01005769 /* Alert Descriptions from ssl.h */
5770 /* note RESERVED constants no longer intended for use have been removed */
5771 /* http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-6 */
5772
5773#define ADD_AD_CONSTANT(s) \
5774 PyModule_AddIntConstant(m, "ALERT_DESCRIPTION_"#s, \
5775 SSL_AD_##s)
5776
5777 ADD_AD_CONSTANT(CLOSE_NOTIFY);
5778 ADD_AD_CONSTANT(UNEXPECTED_MESSAGE);
5779 ADD_AD_CONSTANT(BAD_RECORD_MAC);
5780 ADD_AD_CONSTANT(RECORD_OVERFLOW);
5781 ADD_AD_CONSTANT(DECOMPRESSION_FAILURE);
5782 ADD_AD_CONSTANT(HANDSHAKE_FAILURE);
5783 ADD_AD_CONSTANT(BAD_CERTIFICATE);
5784 ADD_AD_CONSTANT(UNSUPPORTED_CERTIFICATE);
5785 ADD_AD_CONSTANT(CERTIFICATE_REVOKED);
5786 ADD_AD_CONSTANT(CERTIFICATE_EXPIRED);
5787 ADD_AD_CONSTANT(CERTIFICATE_UNKNOWN);
5788 ADD_AD_CONSTANT(ILLEGAL_PARAMETER);
5789 ADD_AD_CONSTANT(UNKNOWN_CA);
5790 ADD_AD_CONSTANT(ACCESS_DENIED);
5791 ADD_AD_CONSTANT(DECODE_ERROR);
5792 ADD_AD_CONSTANT(DECRYPT_ERROR);
5793 ADD_AD_CONSTANT(PROTOCOL_VERSION);
5794 ADD_AD_CONSTANT(INSUFFICIENT_SECURITY);
5795 ADD_AD_CONSTANT(INTERNAL_ERROR);
5796 ADD_AD_CONSTANT(USER_CANCELLED);
5797 ADD_AD_CONSTANT(NO_RENEGOTIATION);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01005798 /* Not all constants are in old OpenSSL versions */
Antoine Pitrou912fbff2013-03-30 16:29:32 +01005799#ifdef SSL_AD_UNSUPPORTED_EXTENSION
5800 ADD_AD_CONSTANT(UNSUPPORTED_EXTENSION);
5801#endif
5802#ifdef SSL_AD_CERTIFICATE_UNOBTAINABLE
5803 ADD_AD_CONSTANT(CERTIFICATE_UNOBTAINABLE);
5804#endif
5805#ifdef SSL_AD_UNRECOGNIZED_NAME
5806 ADD_AD_CONSTANT(UNRECOGNIZED_NAME);
5807#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01005808#ifdef SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE
5809 ADD_AD_CONSTANT(BAD_CERTIFICATE_STATUS_RESPONSE);
5810#endif
5811#ifdef SSL_AD_BAD_CERTIFICATE_HASH_VALUE
5812 ADD_AD_CONSTANT(BAD_CERTIFICATE_HASH_VALUE);
5813#endif
5814#ifdef SSL_AD_UNKNOWN_PSK_IDENTITY
5815 ADD_AD_CONSTANT(UNKNOWN_PSK_IDENTITY);
5816#endif
5817
5818#undef ADD_AD_CONSTANT
5819
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005820 /* protocol versions */
Victor Stinner3de49192011-05-09 00:42:58 +02005821#ifndef OPENSSL_NO_SSL2
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005822 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
5823 PY_SSL_VERSION_SSL2);
Victor Stinner3de49192011-05-09 00:42:58 +02005824#endif
Benjamin Petersone32467c2014-12-05 21:59:35 -05005825#ifndef OPENSSL_NO_SSL3
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005826 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
5827 PY_SSL_VERSION_SSL3);
Benjamin Petersone32467c2014-12-05 21:59:35 -05005828#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005829 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
Christian Heimes598894f2016-09-05 23:19:05 +02005830 PY_SSL_VERSION_TLS);
5831 PyModule_AddIntConstant(m, "PROTOCOL_TLS",
5832 PY_SSL_VERSION_TLS);
Christian Heimes5fe668c2016-09-12 00:01:11 +02005833 PyModule_AddIntConstant(m, "PROTOCOL_TLS_CLIENT",
5834 PY_SSL_VERSION_TLS_CLIENT);
5835 PyModule_AddIntConstant(m, "PROTOCOL_TLS_SERVER",
5836 PY_SSL_VERSION_TLS_SERVER);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005837 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
5838 PY_SSL_VERSION_TLS1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01005839 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_1",
5840 PY_SSL_VERSION_TLS1_1);
5841 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_2",
5842 PY_SSL_VERSION_TLS1_2);
Antoine Pitrou04f6a322010-04-05 21:40:07 +00005843
Antoine Pitroub5218772010-05-21 09:56:06 +00005844 /* protocol options */
Antoine Pitrou3f366312012-01-27 09:50:45 +01005845 PyModule_AddIntConstant(m, "OP_ALL",
5846 SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
Antoine Pitroub5218772010-05-21 09:56:06 +00005847 PyModule_AddIntConstant(m, "OP_NO_SSLv2", SSL_OP_NO_SSLv2);
5848 PyModule_AddIntConstant(m, "OP_NO_SSLv3", SSL_OP_NO_SSLv3);
5849 PyModule_AddIntConstant(m, "OP_NO_TLSv1", SSL_OP_NO_TLSv1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01005850 PyModule_AddIntConstant(m, "OP_NO_TLSv1_1", SSL_OP_NO_TLSv1_1);
5851 PyModule_AddIntConstant(m, "OP_NO_TLSv1_2", SSL_OP_NO_TLSv1_2);
Christian Heimescb5b68a2017-09-07 18:07:00 -07005852#ifdef SSL_OP_NO_TLSv1_3
5853 PyModule_AddIntConstant(m, "OP_NO_TLSv1_3", SSL_OP_NO_TLSv1_3);
5854#else
5855 PyModule_AddIntConstant(m, "OP_NO_TLSv1_3", 0);
5856#endif
Antoine Pitrou6db49442011-12-19 13:27:11 +01005857 PyModule_AddIntConstant(m, "OP_CIPHER_SERVER_PREFERENCE",
5858 SSL_OP_CIPHER_SERVER_PREFERENCE);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01005859 PyModule_AddIntConstant(m, "OP_SINGLE_DH_USE", SSL_OP_SINGLE_DH_USE);
Christian Heimes99a65702016-09-10 23:44:53 +02005860 PyModule_AddIntConstant(m, "OP_NO_TICKET", SSL_OP_NO_TICKET);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01005861#ifdef SSL_OP_SINGLE_ECDH_USE
Antoine Pitrou923df6f2011-12-19 17:16:51 +01005862 PyModule_AddIntConstant(m, "OP_SINGLE_ECDH_USE", SSL_OP_SINGLE_ECDH_USE);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01005863#endif
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01005864#ifdef SSL_OP_NO_COMPRESSION
5865 PyModule_AddIntConstant(m, "OP_NO_COMPRESSION",
5866 SSL_OP_NO_COMPRESSION);
5867#endif
Christian Heimes05d9fe32018-02-27 08:55:39 +01005868#ifdef SSL_OP_ENABLE_MIDDLEBOX_COMPAT
5869 PyModule_AddIntConstant(m, "OP_ENABLE_MIDDLEBOX_COMPAT",
5870 SSL_OP_ENABLE_MIDDLEBOX_COMPAT);
5871#endif
Christian Heimes67c48012018-05-15 16:25:40 -04005872#ifdef SSL_OP_NO_RENEGOTIATION
5873 PyModule_AddIntConstant(m, "OP_NO_RENEGOTIATION",
5874 SSL_OP_NO_RENEGOTIATION);
5875#endif
Christian Heimes6f37ebc2021-04-09 17:59:21 +02005876#ifdef SSL_OP_IGNORE_UNEXPECTED_EOF
5877 PyModule_AddIntConstant(m, "OP_IGNORE_UNEXPECTED_EOF",
5878 SSL_OP_IGNORE_UNEXPECTED_EOF);
5879#endif
Antoine Pitroub5218772010-05-21 09:56:06 +00005880
Christian Heimes61d478c2018-01-27 15:51:38 +01005881#ifdef X509_CHECK_FLAG_ALWAYS_CHECK_SUBJECT
5882 PyModule_AddIntConstant(m, "HOSTFLAG_ALWAYS_CHECK_SUBJECT",
5883 X509_CHECK_FLAG_ALWAYS_CHECK_SUBJECT);
5884#endif
5885#ifdef X509_CHECK_FLAG_NEVER_CHECK_SUBJECT
5886 PyModule_AddIntConstant(m, "HOSTFLAG_NEVER_CHECK_SUBJECT",
5887 X509_CHECK_FLAG_NEVER_CHECK_SUBJECT);
5888#endif
5889#ifdef X509_CHECK_FLAG_NO_WILDCARDS
5890 PyModule_AddIntConstant(m, "HOSTFLAG_NO_WILDCARDS",
5891 X509_CHECK_FLAG_NO_WILDCARDS);
5892#endif
5893#ifdef X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS
5894 PyModule_AddIntConstant(m, "HOSTFLAG_NO_PARTIAL_WILDCARDS",
5895 X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS);
5896#endif
5897#ifdef X509_CHECK_FLAG_MULTI_LABEL_WILDCARDS
5898 PyModule_AddIntConstant(m, "HOSTFLAG_MULTI_LABEL_WILDCARDS",
5899 X509_CHECK_FLAG_MULTI_LABEL_WILDCARDS);
5900#endif
5901#ifdef X509_CHECK_FLAG_SINGLE_LABEL_SUBDOMAINS
5902 PyModule_AddIntConstant(m, "HOSTFLAG_SINGLE_LABEL_SUBDOMAINS",
5903 X509_CHECK_FLAG_SINGLE_LABEL_SUBDOMAINS);
5904#endif
5905
Christian Heimes666991f2021-04-26 15:01:40 +02005906 /* file types */
5907 PyModule_AddIntConstant(m, "ENCODING_PEM", PY_SSL_ENCODING_PEM);
5908 PyModule_AddIntConstant(m, "ENCODING_DER", PY_SSL_ENCODING_DER);
5909
Christian Heimes698dde12018-02-27 11:54:43 +01005910 /* protocol versions */
5911 PyModule_AddIntConstant(m, "PROTO_MINIMUM_SUPPORTED",
5912 PY_PROTO_MINIMUM_SUPPORTED);
5913 PyModule_AddIntConstant(m, "PROTO_MAXIMUM_SUPPORTED",
5914 PY_PROTO_MAXIMUM_SUPPORTED);
5915 PyModule_AddIntConstant(m, "PROTO_SSLv3", PY_PROTO_SSLv3);
5916 PyModule_AddIntConstant(m, "PROTO_TLSv1", PY_PROTO_TLSv1);
5917 PyModule_AddIntConstant(m, "PROTO_TLSv1_1", PY_PROTO_TLSv1_1);
5918 PyModule_AddIntConstant(m, "PROTO_TLSv1_2", PY_PROTO_TLSv1_2);
5919 PyModule_AddIntConstant(m, "PROTO_TLSv1_3", PY_PROTO_TLSv1_3);
Antoine Pitroud5323212010-10-22 18:19:07 +00005920
Victor Stinnerb37672d2018-11-22 03:37:50 +01005921#define addbool(m, key, value) \
5922 do { \
5923 PyObject *bool_obj = (value) ? Py_True : Py_False; \
5924 Py_INCREF(bool_obj); \
5925 PyModule_AddObject((m), (key), bool_obj); \
5926 } while (0)
Christian Heimes698dde12018-02-27 11:54:43 +01005927
Christian Heimes698dde12018-02-27 11:54:43 +01005928 addbool(m, "HAS_SNI", 1);
Christian Heimes698dde12018-02-27 11:54:43 +01005929 addbool(m, "HAS_TLS_UNIQUE", 1);
Christian Heimes698dde12018-02-27 11:54:43 +01005930 addbool(m, "HAS_ECDH", 1);
Christian Heimes698dde12018-02-27 11:54:43 +01005931 addbool(m, "HAS_NPN", 0);
Christian Heimes698dde12018-02-27 11:54:43 +01005932 addbool(m, "HAS_ALPN", 1);
Christian Heimes698dde12018-02-27 11:54:43 +01005933
5934#if defined(SSL2_VERSION) && !defined(OPENSSL_NO_SSL2)
5935 addbool(m, "HAS_SSLv2", 1);
5936#else
5937 addbool(m, "HAS_SSLv2", 0);
5938#endif
5939
5940#if defined(SSL3_VERSION) && !defined(OPENSSL_NO_SSL3)
5941 addbool(m, "HAS_SSLv3", 1);
5942#else
5943 addbool(m, "HAS_SSLv3", 0);
5944#endif
5945
5946#if defined(TLS1_VERSION) && !defined(OPENSSL_NO_TLS1)
5947 addbool(m, "HAS_TLSv1", 1);
5948#else
5949 addbool(m, "HAS_TLSv1", 0);
5950#endif
5951
5952#if defined(TLS1_1_VERSION) && !defined(OPENSSL_NO_TLS1_1)
5953 addbool(m, "HAS_TLSv1_1", 1);
5954#else
5955 addbool(m, "HAS_TLSv1_1", 0);
5956#endif
5957
5958#if defined(TLS1_2_VERSION) && !defined(OPENSSL_NO_TLS1_2)
5959 addbool(m, "HAS_TLSv1_2", 1);
5960#else
5961 addbool(m, "HAS_TLSv1_2", 0);
5962#endif
Benjamin Petersoncca27322015-01-23 16:35:37 -05005963
Christian Heimescb5b68a2017-09-07 18:07:00 -07005964#if defined(TLS1_3_VERSION) && !defined(OPENSSL_NO_TLS1_3)
Christian Heimes698dde12018-02-27 11:54:43 +01005965 addbool(m, "HAS_TLSv1_3", 1);
Christian Heimescb5b68a2017-09-07 18:07:00 -07005966#else
Christian Heimes698dde12018-02-27 11:54:43 +01005967 addbool(m, "HAS_TLSv1_3", 0);
Christian Heimescb5b68a2017-09-07 18:07:00 -07005968#endif
Christian Heimescb5b68a2017-09-07 18:07:00 -07005969
Christian Heimes5c36da72020-11-20 09:40:12 +01005970 return 0;
5971}
5972
Christian Heimes7f1305e2021-04-17 20:06:38 +02005973static int
5974sslmodule_init_errorcodes(PyObject *module)
5975{
5976 _sslmodulestate *state = get_ssl_state(module);
Christian Heimes5c36da72020-11-20 09:40:12 +01005977
Christian Heimes7f1305e2021-04-17 20:06:38 +02005978 struct py_ssl_error_code *errcode;
5979 struct py_ssl_library_code *libcode;
Christian Heimes5c36da72020-11-20 09:40:12 +01005980
Christian Heimes7f1305e2021-04-17 20:06:38 +02005981 /* Mappings for error codes */
5982 state->err_codes_to_names = PyDict_New();
5983 if (state->err_codes_to_names == NULL)
5984 return -1;
5985 state->err_names_to_codes = PyDict_New();
5986 if (state->err_names_to_codes == NULL)
5987 return -1;
5988 state->lib_codes_to_names = PyDict_New();
5989 if (state->lib_codes_to_names == NULL)
5990 return -1;
5991
5992 errcode = error_codes;
5993 while (errcode->mnemonic != NULL) {
5994 PyObject *mnemo, *key;
5995 mnemo = PyUnicode_FromString(errcode->mnemonic);
5996 key = Py_BuildValue("ii", errcode->library, errcode->reason);
5997 if (mnemo == NULL || key == NULL)
5998 return -1;
5999 if (PyDict_SetItem(state->err_codes_to_names, key, mnemo))
6000 return -1;
6001 if (PyDict_SetItem(state->err_names_to_codes, mnemo, key))
6002 return -1;
6003 Py_DECREF(key);
6004 Py_DECREF(mnemo);
6005 errcode++;
6006 }
6007
6008 libcode = library_codes;
6009 while (libcode->library != NULL) {
6010 PyObject *mnemo, *key;
6011 key = PyLong_FromLong(libcode->code);
6012 mnemo = PyUnicode_FromString(libcode->library);
6013 if (key == NULL || mnemo == NULL)
6014 return -1;
6015 if (PyDict_SetItem(state->lib_codes_to_names, key, mnemo))
6016 return -1;
6017 Py_DECREF(key);
6018 Py_DECREF(mnemo);
6019 libcode++;
6020 }
6021
6022 if (PyModule_AddObjectRef(module, "err_codes_to_names", state->err_codes_to_names))
6023 return -1;
6024 if (PyModule_AddObjectRef(module, "err_names_to_codes", state->err_names_to_codes))
6025 return -1;
6026 if (PyModule_AddObjectRef(module, "lib_codes_to_names", state->lib_codes_to_names))
6027 return -1;
6028
6029 return 0;
6030}
6031
6032static void
6033parse_openssl_version(unsigned long libver,
6034 unsigned int *major, unsigned int *minor,
6035 unsigned int *fix, unsigned int *patch,
6036 unsigned int *status)
6037{
6038 *status = libver & 0xF;
6039 libver >>= 4;
6040 *patch = libver & 0xFF;
6041 libver >>= 8;
6042 *fix = libver & 0xFF;
6043 libver >>= 8;
6044 *minor = libver & 0xFF;
6045 libver >>= 8;
6046 *major = libver & 0xFF;
6047}
6048
6049static int
6050sslmodule_init_versioninfo(PyObject *m)
6051{
6052 PyObject *r;
6053 unsigned long libver;
6054 unsigned int major, minor, fix, patch, status;
6055
6056 /* OpenSSL version */
6057 /* SSLeay() gives us the version of the library linked against,
6058 which could be different from the headers version.
6059 */
6060 libver = OpenSSL_version_num();
6061 r = PyLong_FromUnsignedLong(libver);
6062 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r))
6063 return -1;
6064
6065 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
6066 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
6067 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r))
6068 return -1;
6069
6070 r = PyUnicode_FromString(OpenSSL_version(OPENSSL_VERSION));
6071 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r))
6072 return -1;
6073
6074 libver = OPENSSL_VERSION_NUMBER;
6075 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
6076 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
6077 if (r == NULL || PyModule_AddObject(m, "_OPENSSL_API_VERSION", r))
6078 return -1;
6079
6080 return 0;
6081}
6082
6083static int
6084sslmodule_init_types(PyObject *module)
6085{
6086 _sslmodulestate *state = get_ssl_state(module);
6087
6088 state->PySSLContext_Type = (PyTypeObject *)PyType_FromModuleAndSpec(
6089 module, &PySSLContext_spec, NULL
6090 );
6091 if (state->PySSLContext_Type == NULL)
6092 return -1;
6093
6094 state->PySSLSocket_Type = (PyTypeObject *)PyType_FromModuleAndSpec(
6095 module, &PySSLSocket_spec, NULL
6096 );
6097 if (state->PySSLSocket_Type == NULL)
6098 return -1;
6099
6100 state->PySSLMemoryBIO_Type = (PyTypeObject *)PyType_FromModuleAndSpec(
6101 module, &PySSLMemoryBIO_spec, NULL
6102 );
6103 if (state->PySSLMemoryBIO_Type == NULL)
6104 return -1;
6105
6106 state->PySSLSession_Type = (PyTypeObject *)PyType_FromModuleAndSpec(
6107 module, &PySSLSession_spec, NULL
6108 );
6109 if (state->PySSLSession_Type == NULL)
6110 return -1;
6111
Christian Heimes666991f2021-04-26 15:01:40 +02006112 state->PySSLCertificate_Type = (PyTypeObject *)PyType_FromModuleAndSpec(
6113 module, &PySSLCertificate_spec, NULL
6114 );
6115 if (state->PySSLCertificate_Type == NULL)
6116 return -1;
6117
Christian Heimes7f1305e2021-04-17 20:06:38 +02006118 if (PyModule_AddType(module, state->PySSLContext_Type))
6119 return -1;
6120 if (PyModule_AddType(module, state->PySSLSocket_Type))
6121 return -1;
6122 if (PyModule_AddType(module, state->PySSLMemoryBIO_Type))
6123 return -1;
6124 if (PyModule_AddType(module, state->PySSLSession_Type))
6125 return -1;
Christian Heimes666991f2021-04-26 15:01:40 +02006126 if (PyModule_AddType(module, state->PySSLCertificate_Type))
6127 return -1;
Christian Heimes7f1305e2021-04-17 20:06:38 +02006128 return 0;
6129}
6130
6131static PyModuleDef_Slot sslmodule_slots[] = {
6132 {Py_mod_exec, sslmodule_init_types},
6133 {Py_mod_exec, sslmodule_init_exceptions},
6134 {Py_mod_exec, sslmodule_init_socketapi},
6135 {Py_mod_exec, sslmodule_init_errorcodes},
6136 {Py_mod_exec, sslmodule_init_constants},
6137 {Py_mod_exec, sslmodule_init_versioninfo},
6138 {0, NULL}
6139};
6140
6141static int
6142sslmodule_traverse(PyObject *m, visitproc visit, void *arg)
6143{
6144 _sslmodulestate *state = get_ssl_state(m);
6145
6146 Py_VISIT(state->PySSLContext_Type);
6147 Py_VISIT(state->PySSLSocket_Type);
6148 Py_VISIT(state->PySSLMemoryBIO_Type);
6149 Py_VISIT(state->PySSLSession_Type);
Christian Heimes666991f2021-04-26 15:01:40 +02006150 Py_VISIT(state->PySSLCertificate_Type);
Christian Heimes7f1305e2021-04-17 20:06:38 +02006151 Py_VISIT(state->PySSLErrorObject);
6152 Py_VISIT(state->PySSLCertVerificationErrorObject);
6153 Py_VISIT(state->PySSLZeroReturnErrorObject);
6154 Py_VISIT(state->PySSLWantReadErrorObject);
6155 Py_VISIT(state->PySSLWantWriteErrorObject);
6156 Py_VISIT(state->PySSLSyscallErrorObject);
6157 Py_VISIT(state->PySSLEOFErrorObject);
6158 Py_VISIT(state->err_codes_to_names);
6159 Py_VISIT(state->err_names_to_codes);
6160 Py_VISIT(state->lib_codes_to_names);
6161 Py_VISIT(state->Sock_Type);
6162
6163 return 0;
6164}
6165
6166static int
6167sslmodule_clear(PyObject *m)
6168{
6169 _sslmodulestate *state = get_ssl_state(m);
6170
6171 Py_CLEAR(state->PySSLContext_Type);
6172 Py_CLEAR(state->PySSLSocket_Type);
6173 Py_CLEAR(state->PySSLMemoryBIO_Type);
6174 Py_CLEAR(state->PySSLSession_Type);
Christian Heimes666991f2021-04-26 15:01:40 +02006175 Py_CLEAR(state->PySSLCertificate_Type);
Christian Heimes7f1305e2021-04-17 20:06:38 +02006176 Py_CLEAR(state->PySSLErrorObject);
6177 Py_CLEAR(state->PySSLCertVerificationErrorObject);
6178 Py_CLEAR(state->PySSLZeroReturnErrorObject);
6179 Py_CLEAR(state->PySSLWantReadErrorObject);
6180 Py_CLEAR(state->PySSLWantWriteErrorObject);
6181 Py_CLEAR(state->PySSLSyscallErrorObject);
6182 Py_CLEAR(state->PySSLEOFErrorObject);
6183 Py_CLEAR(state->err_codes_to_names);
6184 Py_CLEAR(state->err_names_to_codes);
6185 Py_CLEAR(state->lib_codes_to_names);
6186 Py_CLEAR(state->Sock_Type);
6187
6188 return 0;
6189}
6190
6191static void
6192sslmodule_free(void *m)
6193{
6194 sslmodule_clear((PyObject *)m);
6195}
6196
6197static struct PyModuleDef _sslmodule_def = {
Christian Heimes5c36da72020-11-20 09:40:12 +01006198 PyModuleDef_HEAD_INIT,
Christian Heimes7f1305e2021-04-17 20:06:38 +02006199 .m_name = "_ssl",
6200 .m_doc = module_doc,
6201 .m_size = sizeof(_sslmodulestate),
6202 .m_methods = PySSL_methods,
6203 .m_slots = sslmodule_slots,
6204 .m_traverse = sslmodule_traverse,
6205 .m_clear = sslmodule_clear,
6206 .m_free = sslmodule_free
Christian Heimes5c36da72020-11-20 09:40:12 +01006207};
6208
6209PyMODINIT_FUNC
6210PyInit__ssl(void)
6211{
Christian Heimes7f1305e2021-04-17 20:06:38 +02006212 return PyModuleDef_Init(&_sslmodule_def);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00006213}