blob: 5f03214ea3eedce141395439329c1d3dbb8b567b [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 = {
437 "ssl.SSLError",
438 sizeof(PyOSErrorObject),
439 0,
Christian Heimes91554e42021-05-02 09:47:45 +0200440 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_IMMUTABLETYPE,
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200441 sslerror_type_slots
442};
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
Christian Heimes7f1305e2021-04-17 20:06:38 +0200792 self = PyObject_New(PySSLSocket, get_state_ctx(sslctx)->PySSLSocket_Type);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000793 if (self == NULL)
794 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000795
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000796 self->ssl = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000797 self->Socket = NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100798 self->ctx = sslctx;
Nathaniel J. Smith65ece7c2017-06-07 23:30:43 -0700799 Py_INCREF(sslctx);
Antoine Pitrou860aee72013-09-29 19:52:45 +0200800 self->shutdown_seen_zero = 0;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200801 self->owner = NULL;
Benjamin Peterson81b9ecd2016-08-15 21:55:37 -0700802 self->server_hostname = NULL;
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700803 self->err = err;
Christian Heimesc7f70692019-05-31 11:44:05 +0200804 self->exc_type = NULL;
805 self->exc_value = NULL;
806 self->exc_tb = NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200807
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000808 /* Make sure the SSL error state is initialized */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000809 ERR_clear_error();
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000810
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000811 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitrou152efa22010-05-16 18:19:27 +0000812 self->ssl = SSL_new(ctx);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000813 PySSL_END_ALLOW_THREADS
Zackery Spytz4c49da02018-12-07 03:11:30 -0700814 if (self->ssl == NULL) {
815 Py_DECREF(self);
Christian Heimes7f1305e2021-04-17 20:06:38 +0200816 _setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
Zackery Spytz4c49da02018-12-07 03:11:30 -0700817 return NULL;
818 }
Christian Heimesb467d9a2021-04-17 10:07:19 +0200819 /* bpo43522 and OpenSSL < 1.1.1l: copy hostflags manually */
820#if !defined(LIBRESSL_VERSION_NUMBER) && OPENSSL_VERSION < 0x101010cf
821 X509_VERIFY_PARAM *ssl_params = SSL_get0_param(self->ssl);
822 X509_VERIFY_PARAM_set_hostflags(ssl_params, sslctx->hostflags);
823#endif
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200824 SSL_set_app_data(self->ssl, self);
825 if (sock) {
826 SSL_set_fd(self->ssl, Py_SAFE_DOWNCAST(sock->sock_fd, SOCKET_T, int));
827 } else {
828 /* BIOs are reference counted and SSL_set_bio borrows our reference.
829 * To prevent a double free in memory_bio_dealloc() we need to take an
830 * extra reference here. */
Christian Heimes598894f2016-09-05 23:19:05 +0200831 BIO_up_ref(inbio->bio);
832 BIO_up_ref(outbio->bio);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200833 SSL_set_bio(self->ssl, inbio->bio, outbio->bio);
834 }
Alex Gaynorf0422422018-05-14 11:51:45 -0400835 SSL_set_mode(self->ssl,
836 SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER | SSL_MODE_AUTO_RETRY);
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000837
Christian Heimesf0f59302019-07-01 08:29:17 +0200838#ifdef TLS1_3_VERSION
839 if (sslctx->post_handshake_auth == 1) {
840 if (socket_type == PY_SSL_SERVER) {
841 /* bpo-37428: OpenSSL does not ignore SSL_VERIFY_POST_HANDSHAKE.
842 * Set SSL_VERIFY_POST_HANDSHAKE flag only for server sockets and
843 * only in combination with SSL_VERIFY_PEER flag. */
844 int mode = SSL_get_verify_mode(self->ssl);
845 if (mode & SSL_VERIFY_PEER) {
846 int (*verify_cb)(int, X509_STORE_CTX *) = NULL;
847 verify_cb = SSL_get_verify_callback(self->ssl);
848 mode |= SSL_VERIFY_POST_HANDSHAKE;
849 SSL_set_verify(self->ssl, mode, verify_cb);
850 }
851 } else {
852 /* client socket */
853 SSL_set_post_handshake_auth(self->ssl, 1);
854 }
855 }
856#endif
857
Christian Heimes61d478c2018-01-27 15:51:38 +0100858 if (server_hostname != NULL) {
859 if (_ssl_configure_hostname(self, server_hostname) < 0) {
860 Py_DECREF(self);
861 return NULL;
862 }
863 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000864 /* If the socket is in non-blocking mode or timeout mode, set the BIO
865 * to non-blocking mode (blocking is the default)
866 */
Victor Stinnere2452312015-03-28 03:00:46 +0100867 if (sock && sock->sock_timeout >= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000868 BIO_set_nbio(SSL_get_rbio(self->ssl), 1);
869 BIO_set_nbio(SSL_get_wbio(self->ssl), 1);
870 }
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000871
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000872 PySSL_BEGIN_ALLOW_THREADS
873 if (socket_type == PY_SSL_CLIENT)
874 SSL_set_connect_state(self->ssl);
875 else
876 SSL_set_accept_state(self->ssl);
877 PySSL_END_ALLOW_THREADS
Martin v. Löwis09c35f72002-07-28 09:57:45 +0000878
Antoine Pitroud6494802011-07-21 01:11:30 +0200879 self->socket_type = socket_type;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200880 if (sock != NULL) {
881 self->Socket = PyWeakref_NewRef((PyObject *) sock, NULL);
882 if (self->Socket == NULL) {
883 Py_DECREF(self);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200884 return NULL;
885 }
Victor Stinnera9eb38f2013-10-31 16:35:38 +0100886 }
Christian Heimes141c5e82018-02-24 21:10:57 +0100887 if (owner && owner != Py_None) {
888 if (PySSL_set_owner(self, owner, NULL) == -1) {
889 Py_DECREF(self);
890 return NULL;
891 }
892 }
893 if (session && session != Py_None) {
894 if (PySSL_set_session(self, session, NULL) == -1) {
895 Py_DECREF(self);
896 return NULL;
897 }
898 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000899 return self;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000900}
901
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000902/* SSL object methods */
903
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +0300904/*[clinic input]
905_ssl._SSLSocket.do_handshake
906[clinic start generated code]*/
907
908static PyObject *
909_ssl__SSLSocket_do_handshake_impl(PySSLSocket *self)
910/*[clinic end generated code: output=6c0898a8936548f6 input=d2d737de3df018c8]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000911{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000912 int ret;
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700913 _PySSLError err;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000914 int sockstate, nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200915 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +0200916 _PyTime_t timeout, deadline = 0;
917 int has_timeout;
Antoine Pitroud3f8ab82010-04-24 21:26:44 +0000918
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200919 if (sock) {
920 if (((PyObject*)sock) == Py_None) {
Christian Heimes7f1305e2021-04-17 20:06:38 +0200921 _setSSLError(get_state_sock(self),
922 "Underlying socket connection gone",
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200923 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
924 return NULL;
925 }
926 Py_INCREF(sock);
927
928 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +0100929 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200930 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
931 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000932 }
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000933
Victor Stinner14690702015-04-06 22:46:13 +0200934 timeout = GET_SOCKET_TIMEOUT(sock);
935 has_timeout = (timeout > 0);
936 if (has_timeout)
937 deadline = _PyTime_GetMonotonicClock() + timeout;
938
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000939 /* Actually negotiate SSL connection */
940 /* XXX If SSL_do_handshake() returns 0, it's also a failure. */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000941 do {
Bill Janssen6e027db2007-11-15 22:23:56 +0000942 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000943 ret = SSL_do_handshake(self->ssl);
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700944 err = _PySSL_errno(ret < 1, self->ssl, ret);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000945 PySSL_END_ALLOW_THREADS
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700946 self->err = err;
Victor Stinner4e3cfa42015-04-02 21:28:28 +0200947
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000948 if (PyErr_CheckSignals())
949 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +0200950
Victor Stinner14690702015-04-06 22:46:13 +0200951 if (has_timeout)
952 timeout = deadline - _PyTime_GetMonotonicClock();
953
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700954 if (err.ssl == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +0200955 sockstate = PySSL_select(sock, 0, timeout);
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700956 } else if (err.ssl == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +0200957 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000958 } else {
959 sockstate = SOCKET_OPERATION_OK;
960 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +0200961
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000962 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Christian Heimes03c8ddd2020-11-20 09:26:07 +0100963 PyErr_SetString(PyExc_TimeoutError,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000964 ERRSTR("The handshake operation timed out"));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000965 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000966 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
Christian Heimes7f1305e2021-04-17 20:06:38 +0200967 PyErr_SetString(get_state_sock(self)->PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000968 ERRSTR("Underlying socket has been closed."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000969 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000970 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
Christian Heimes7f1305e2021-04-17 20:06:38 +0200971 PyErr_SetString(get_state_sock(self)->PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000972 ERRSTR("Underlying socket too large for select()."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000973 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000974 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
975 break;
976 }
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700977 } while (err.ssl == SSL_ERROR_WANT_READ ||
978 err.ssl == SSL_ERROR_WANT_WRITE);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200979 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000980 if (ret < 1)
981 return PySSL_SetError(self, ret, __FILE__, __LINE__);
Christian Heimesc7f70692019-05-31 11:44:05 +0200982 if (PySSL_ChainExceptions(self) < 0)
983 return NULL;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200984 Py_RETURN_NONE;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000985error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200986 Py_XDECREF(sock);
Christian Heimesc7f70692019-05-31 11:44:05 +0200987 PySSL_ChainExceptions(self);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000988 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000989}
990
Thomas Woutersed03b412007-08-28 21:37:11 +0000991static PyObject *
Christian Heimes7f1305e2021-04-17 20:06:38 +0200992_asn1obj2py(_sslmodulestate *state, const ASN1_OBJECT *name, int no_name)
Serhiy Storchakae503ca52017-09-05 01:28:53 +0300993{
994 char buf[X509_NAME_MAXLEN];
995 char *namebuf = buf;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000996 int buflen;
Serhiy Storchakae503ca52017-09-05 01:28:53 +0300997 PyObject *name_obj = NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000998
Serhiy Storchakae503ca52017-09-05 01:28:53 +0300999 buflen = OBJ_obj2txt(namebuf, X509_NAME_MAXLEN, name, no_name);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001000 if (buflen < 0) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02001001 _setSSLError(state, NULL, 0, __FILE__, __LINE__);
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001002 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001003 }
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001004 /* initial buffer is too small for oid + terminating null byte */
1005 if (buflen > X509_NAME_MAXLEN - 1) {
1006 /* make OBJ_obj2txt() calculate the required buflen */
1007 buflen = OBJ_obj2txt(NULL, 0, name, no_name);
1008 /* allocate len + 1 for terminating NULL byte */
1009 namebuf = PyMem_Malloc(buflen + 1);
1010 if (namebuf == NULL) {
1011 PyErr_NoMemory();
1012 return NULL;
1013 }
1014 buflen = OBJ_obj2txt(namebuf, buflen + 1, name, no_name);
1015 if (buflen < 0) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02001016 _setSSLError(state, NULL, 0, __FILE__, __LINE__);
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001017 goto done;
1018 }
1019 }
1020 if (!buflen && no_name) {
1021 Py_INCREF(Py_None);
1022 name_obj = Py_None;
1023 }
1024 else {
1025 name_obj = PyUnicode_FromStringAndSize(namebuf, buflen);
1026 }
1027
1028 done:
1029 if (buf != namebuf) {
1030 PyMem_Free(namebuf);
1031 }
1032 return name_obj;
1033}
1034
1035static PyObject *
Christian Heimes7f1305e2021-04-17 20:06:38 +02001036_create_tuple_for_attribute(_sslmodulestate *state,
1037 ASN1_OBJECT *name, ASN1_STRING *value)
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001038{
1039 Py_ssize_t buflen;
1040 unsigned char *valuebuf = NULL;
1041 PyObject *attr;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001042
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001043 buflen = ASN1_STRING_to_UTF8(&valuebuf, value);
1044 if (buflen < 0) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02001045 _setSSLError(state, NULL, 0, __FILE__, __LINE__);
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001046 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001047 }
Christian Heimes7f1305e2021-04-17 20:06:38 +02001048 attr = Py_BuildValue("Ns#", _asn1obj2py(state, name, 0), valuebuf, buflen);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001049 OPENSSL_free(valuebuf);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001050 return attr;
Thomas Woutersed03b412007-08-28 21:37:11 +00001051}
1052
1053static PyObject *
Christian Heimes7f1305e2021-04-17 20:06:38 +02001054_create_tuple_for_X509_NAME (_sslmodulestate *state, X509_NAME *xname)
Thomas Woutersed03b412007-08-28 21:37:11 +00001055{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001056 PyObject *dn = NULL; /* tuple which represents the "distinguished name" */
1057 PyObject *rdn = NULL; /* tuple to hold a "relative distinguished name" */
1058 PyObject *rdnt;
1059 PyObject *attr = NULL; /* tuple to hold an attribute */
1060 int entry_count = X509_NAME_entry_count(xname);
1061 X509_NAME_ENTRY *entry;
1062 ASN1_OBJECT *name;
1063 ASN1_STRING *value;
1064 int index_counter;
1065 int rdn_level = -1;
1066 int retcode;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001067
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001068 dn = PyList_New(0);
1069 if (dn == NULL)
1070 return NULL;
1071 /* now create another tuple to hold the top-level RDN */
1072 rdn = PyList_New(0);
1073 if (rdn == NULL)
1074 goto fail0;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001075
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001076 for (index_counter = 0;
1077 index_counter < entry_count;
1078 index_counter++)
1079 {
1080 entry = X509_NAME_get_entry(xname, index_counter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001081
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001082 /* check to see if we've gotten to a new RDN */
1083 if (rdn_level >= 0) {
Christian Heimes598894f2016-09-05 23:19:05 +02001084 if (rdn_level != X509_NAME_ENTRY_set(entry)) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001085 /* yes, new RDN */
1086 /* add old RDN to DN */
1087 rdnt = PyList_AsTuple(rdn);
1088 Py_DECREF(rdn);
1089 if (rdnt == NULL)
1090 goto fail0;
1091 retcode = PyList_Append(dn, rdnt);
1092 Py_DECREF(rdnt);
1093 if (retcode < 0)
1094 goto fail0;
1095 /* create new RDN */
1096 rdn = PyList_New(0);
1097 if (rdn == NULL)
1098 goto fail0;
1099 }
1100 }
Christian Heimes598894f2016-09-05 23:19:05 +02001101 rdn_level = X509_NAME_ENTRY_set(entry);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001102
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001103 /* now add this attribute to the current RDN */
1104 name = X509_NAME_ENTRY_get_object(entry);
1105 value = X509_NAME_ENTRY_get_data(entry);
Christian Heimes7f1305e2021-04-17 20:06:38 +02001106 attr = _create_tuple_for_attribute(state, name, value);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001107 /*
1108 fprintf(stderr, "RDN level %d, attribute %s: %s\n",
1109 entry->set,
1110 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 0)),
1111 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 1)));
1112 */
1113 if (attr == NULL)
1114 goto fail1;
1115 retcode = PyList_Append(rdn, attr);
1116 Py_DECREF(attr);
1117 if (retcode < 0)
1118 goto fail1;
1119 }
1120 /* now, there's typically a dangling RDN */
Antoine Pitrou2f5a1632012-02-15 22:25:27 +01001121 if (rdn != NULL) {
1122 if (PyList_GET_SIZE(rdn) > 0) {
1123 rdnt = PyList_AsTuple(rdn);
1124 Py_DECREF(rdn);
1125 if (rdnt == NULL)
1126 goto fail0;
1127 retcode = PyList_Append(dn, rdnt);
1128 Py_DECREF(rdnt);
1129 if (retcode < 0)
1130 goto fail0;
1131 }
1132 else {
1133 Py_DECREF(rdn);
1134 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001135 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001136
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001137 /* convert list to tuple */
1138 rdnt = PyList_AsTuple(dn);
1139 Py_DECREF(dn);
1140 if (rdnt == NULL)
1141 return NULL;
1142 return rdnt;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001143
1144 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001145 Py_XDECREF(rdn);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001146
1147 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001148 Py_XDECREF(dn);
1149 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001150}
1151
1152static PyObject *
Christian Heimes7f1305e2021-04-17 20:06:38 +02001153_get_peer_alt_names (_sslmodulestate *state, X509 *certificate) {
Guido van Rossumf06628b2007-11-21 20:01:53 +00001154
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001155 /* this code follows the procedure outlined in
1156 OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print()
1157 function to extract the STACK_OF(GENERAL_NAME),
1158 then iterates through the stack to add the
1159 names. */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001160
Alex Gaynorb87c0df2017-06-06 07:53:11 -04001161 int j;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001162 PyObject *peer_alt_names = Py_None;
Christian Heimes60bf2fc2013-09-05 16:04:35 +02001163 PyObject *v = NULL, *t;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001164 GENERAL_NAMES *names = NULL;
1165 GENERAL_NAME *name;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001166 BIO *biobuf = NULL;
1167 char buf[2048];
1168 char *vptr;
1169 int len;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001170
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001171 if (certificate == NULL)
1172 return peer_alt_names;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001173
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001174 /* get a memory buffer */
1175 biobuf = BIO_new(BIO_s_mem());
Zackery Spytz4c49da02018-12-07 03:11:30 -07001176 if (biobuf == NULL) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02001177 PyErr_SetString(state->PySSLErrorObject, "failed to allocate BIO");
Zackery Spytz4c49da02018-12-07 03:11:30 -07001178 return NULL;
1179 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001180
Alex Gaynorb87c0df2017-06-06 07:53:11 -04001181 names = (GENERAL_NAMES *)X509_get_ext_d2i(
1182 certificate, NID_subject_alt_name, NULL, NULL);
1183 if (names != NULL) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001184 if (peer_alt_names == Py_None) {
1185 peer_alt_names = PyList_New(0);
1186 if (peer_alt_names == NULL)
1187 goto fail;
1188 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001189
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001190 for(j = 0; j < sk_GENERAL_NAME_num(names); j++) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001191 /* get a rendering of each name in the set of names */
Christian Heimes824f7f32013-08-17 00:54:47 +02001192 int gntype;
1193 ASN1_STRING *as = NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001194
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001195 name = sk_GENERAL_NAME_value(names, j);
Christian Heimes474afdd2013-08-17 17:18:56 +02001196 gntype = name->type;
Christian Heimes824f7f32013-08-17 00:54:47 +02001197 switch (gntype) {
1198 case GEN_DIRNAME:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001199 /* we special-case DirName as a tuple of
1200 tuples of attributes */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001201
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001202 t = PyTuple_New(2);
1203 if (t == NULL) {
1204 goto fail;
1205 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001206
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001207 v = PyUnicode_FromString("DirName");
1208 if (v == NULL) {
1209 Py_DECREF(t);
1210 goto fail;
1211 }
1212 PyTuple_SET_ITEM(t, 0, v);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001213
Christian Heimes7f1305e2021-04-17 20:06:38 +02001214 v = _create_tuple_for_X509_NAME(state, name->d.dirn);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001215 if (v == NULL) {
1216 Py_DECREF(t);
1217 goto fail;
1218 }
1219 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +02001220 break;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001221
Christian Heimes824f7f32013-08-17 00:54:47 +02001222 case GEN_EMAIL:
1223 case GEN_DNS:
1224 case GEN_URI:
1225 /* GENERAL_NAME_print() doesn't handle NULL bytes in ASN1_string
1226 correctly, CVE-2013-4238 */
1227 t = PyTuple_New(2);
1228 if (t == NULL)
1229 goto fail;
1230 switch (gntype) {
1231 case GEN_EMAIL:
1232 v = PyUnicode_FromString("email");
1233 as = name->d.rfc822Name;
1234 break;
1235 case GEN_DNS:
1236 v = PyUnicode_FromString("DNS");
1237 as = name->d.dNSName;
1238 break;
1239 case GEN_URI:
1240 v = PyUnicode_FromString("URI");
1241 as = name->d.uniformResourceIdentifier;
1242 break;
1243 }
1244 if (v == NULL) {
1245 Py_DECREF(t);
1246 goto fail;
1247 }
1248 PyTuple_SET_ITEM(t, 0, v);
Christian Heimesa871f692020-06-01 08:58:14 +02001249 v = PyUnicode_FromStringAndSize((char *)ASN1_STRING_get0_data(as),
Christian Heimes824f7f32013-08-17 00:54:47 +02001250 ASN1_STRING_length(as));
1251 if (v == NULL) {
1252 Py_DECREF(t);
1253 goto fail;
1254 }
1255 PyTuple_SET_ITEM(t, 1, v);
1256 break;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001257
Christian Heimes1c03abd2016-09-06 23:25:35 +02001258 case GEN_RID:
1259 t = PyTuple_New(2);
1260 if (t == NULL)
1261 goto fail;
1262
1263 v = PyUnicode_FromString("Registered ID");
1264 if (v == NULL) {
1265 Py_DECREF(t);
1266 goto fail;
1267 }
1268 PyTuple_SET_ITEM(t, 0, v);
1269
1270 len = i2t_ASN1_OBJECT(buf, sizeof(buf)-1, name->d.rid);
1271 if (len < 0) {
1272 Py_DECREF(t);
Christian Heimes7f1305e2021-04-17 20:06:38 +02001273 _setSSLError(state, NULL, 0, __FILE__, __LINE__);
Christian Heimes1c03abd2016-09-06 23:25:35 +02001274 goto fail;
1275 } else if (len >= (int)sizeof(buf)) {
1276 v = PyUnicode_FromString("<INVALID>");
1277 } else {
1278 v = PyUnicode_FromStringAndSize(buf, len);
1279 }
1280 if (v == NULL) {
1281 Py_DECREF(t);
1282 goto fail;
1283 }
1284 PyTuple_SET_ITEM(t, 1, v);
1285 break;
1286
Christian Heimes2b7de662019-12-07 17:59:36 +01001287 case GEN_IPADD:
1288 /* OpenSSL < 3.0.0 adds a trailing \n to IPv6. 3.0.0 removed
1289 * the trailing newline. Remove it in all versions
1290 */
1291 t = PyTuple_New(2);
1292 if (t == NULL)
1293 goto fail;
1294
1295 v = PyUnicode_FromString("IP Address");
1296 if (v == NULL) {
1297 Py_DECREF(t);
1298 goto fail;
1299 }
1300 PyTuple_SET_ITEM(t, 0, v);
1301
1302 if (name->d.ip->length == 4) {
1303 unsigned char *p = name->d.ip->data;
1304 v = PyUnicode_FromFormat(
1305 "%d.%d.%d.%d",
1306 p[0], p[1], p[2], p[3]
1307 );
1308 } else if (name->d.ip->length == 16) {
1309 /* PyUnicode_FromFormat() does not support %X */
1310 unsigned char *p = name->d.ip->data;
1311 len = sprintf(
1312 buf,
1313 "%X:%X:%X:%X:%X:%X:%X:%X",
1314 p[0] << 8 | p[1],
1315 p[2] << 8 | p[3],
1316 p[4] << 8 | p[5],
1317 p[6] << 8 | p[7],
1318 p[8] << 8 | p[9],
1319 p[10] << 8 | p[11],
1320 p[12] << 8 | p[13],
1321 p[14] << 8 | p[15]
1322 );
1323 v = PyUnicode_FromStringAndSize(buf, len);
1324 } else {
1325 v = PyUnicode_FromString("<invalid>");
1326 }
1327
1328 if (v == NULL) {
1329 Py_DECREF(t);
1330 goto fail;
1331 }
1332 PyTuple_SET_ITEM(t, 1, v);
1333 break;
1334
Christian Heimes824f7f32013-08-17 00:54:47 +02001335 default:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001336 /* for everything else, we use the OpenSSL print form */
Christian Heimes824f7f32013-08-17 00:54:47 +02001337 switch (gntype) {
1338 /* check for new general name type */
1339 case GEN_OTHERNAME:
1340 case GEN_X400:
1341 case GEN_EDIPARTY:
Christian Heimes824f7f32013-08-17 00:54:47 +02001342 case GEN_RID:
1343 break;
1344 default:
1345 if (PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
1346 "Unknown general name type %d",
1347 gntype) == -1) {
1348 goto fail;
1349 }
1350 break;
1351 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001352 (void) BIO_reset(biobuf);
1353 GENERAL_NAME_print(biobuf, name);
1354 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1355 if (len < 0) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02001356 _setSSLError(state, NULL, 0, __FILE__, __LINE__);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001357 goto fail;
1358 }
1359 vptr = strchr(buf, ':');
Christian Heimes1c03abd2016-09-06 23:25:35 +02001360 if (vptr == NULL) {
1361 PyErr_Format(PyExc_ValueError,
1362 "Invalid value %.200s",
1363 buf);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001364 goto fail;
Christian Heimes1c03abd2016-09-06 23:25:35 +02001365 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001366 t = PyTuple_New(2);
1367 if (t == NULL)
1368 goto fail;
1369 v = PyUnicode_FromStringAndSize(buf, (vptr - buf));
1370 if (v == NULL) {
1371 Py_DECREF(t);
1372 goto fail;
1373 }
1374 PyTuple_SET_ITEM(t, 0, v);
1375 v = PyUnicode_FromStringAndSize((vptr + 1),
1376 (len - (vptr - buf + 1)));
1377 if (v == NULL) {
1378 Py_DECREF(t);
1379 goto fail;
1380 }
1381 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +02001382 break;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001383 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001384
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001385 /* and add that rendering to the list */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001386
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001387 if (PyList_Append(peer_alt_names, t) < 0) {
1388 Py_DECREF(t);
1389 goto fail;
1390 }
1391 Py_DECREF(t);
1392 }
Antoine Pitrou116d6b92011-11-23 01:39:19 +01001393 sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001394 }
1395 BIO_free(biobuf);
1396 if (peer_alt_names != Py_None) {
1397 v = PyList_AsTuple(peer_alt_names);
1398 Py_DECREF(peer_alt_names);
1399 return v;
1400 } else {
1401 return peer_alt_names;
1402 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001403
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001404
1405 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001406 if (biobuf != NULL)
1407 BIO_free(biobuf);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001408
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001409 if (peer_alt_names != Py_None) {
1410 Py_XDECREF(peer_alt_names);
1411 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001412
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001413 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001414}
1415
1416static PyObject *
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001417_get_aia_uri(X509 *certificate, int nid) {
1418 PyObject *lst = NULL, *ostr = NULL;
1419 int i, result;
1420 AUTHORITY_INFO_ACCESS *info;
1421
1422 info = X509_get_ext_d2i(certificate, NID_info_access, NULL, NULL);
Benjamin Petersonf0c90382015-11-14 15:12:18 -08001423 if (info == NULL)
1424 return Py_None;
1425 if (sk_ACCESS_DESCRIPTION_num(info) == 0) {
1426 AUTHORITY_INFO_ACCESS_free(info);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001427 return Py_None;
1428 }
1429
1430 if ((lst = PyList_New(0)) == NULL) {
1431 goto fail;
1432 }
1433
1434 for (i = 0; i < sk_ACCESS_DESCRIPTION_num(info); i++) {
1435 ACCESS_DESCRIPTION *ad = sk_ACCESS_DESCRIPTION_value(info, i);
1436 ASN1_IA5STRING *uri;
1437
1438 if ((OBJ_obj2nid(ad->method) != nid) ||
1439 (ad->location->type != GEN_URI)) {
1440 continue;
1441 }
1442 uri = ad->location->d.uniformResourceIdentifier;
1443 ostr = PyUnicode_FromStringAndSize((char *)uri->data,
1444 uri->length);
1445 if (ostr == NULL) {
1446 goto fail;
1447 }
1448 result = PyList_Append(lst, ostr);
1449 Py_DECREF(ostr);
1450 if (result < 0) {
1451 goto fail;
1452 }
1453 }
1454 AUTHORITY_INFO_ACCESS_free(info);
1455
1456 /* convert to tuple or None */
1457 if (PyList_Size(lst) == 0) {
1458 Py_DECREF(lst);
1459 return Py_None;
1460 } else {
1461 PyObject *tup;
1462 tup = PyList_AsTuple(lst);
1463 Py_DECREF(lst);
1464 return tup;
1465 }
1466
1467 fail:
1468 AUTHORITY_INFO_ACCESS_free(info);
Christian Heimes18fc7be2013-11-21 23:57:49 +01001469 Py_XDECREF(lst);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001470 return NULL;
1471}
1472
1473static PyObject *
1474_get_crl_dp(X509 *certificate) {
1475 STACK_OF(DIST_POINT) *dps;
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001476 int i, j;
1477 PyObject *lst, *res = NULL;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001478
Christian Heimes598894f2016-09-05 23:19:05 +02001479 dps = X509_get_ext_d2i(certificate, NID_crl_distribution_points, NULL, NULL);
Christian Heimes949ec142013-11-21 16:26:51 +01001480
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001481 if (dps == NULL)
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001482 return Py_None;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001483
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001484 lst = PyList_New(0);
1485 if (lst == NULL)
1486 goto done;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001487
1488 for (i=0; i < sk_DIST_POINT_num(dps); i++) {
1489 DIST_POINT *dp;
1490 STACK_OF(GENERAL_NAME) *gns;
1491
1492 dp = sk_DIST_POINT_value(dps, i);
Christian Heimesa37f5242019-01-15 23:47:42 +01001493 if (dp->distpoint == NULL) {
1494 /* Ignore empty DP value, CVE-2019-5010 */
1495 continue;
1496 }
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001497 gns = dp->distpoint->name.fullname;
1498
1499 for (j=0; j < sk_GENERAL_NAME_num(gns); j++) {
1500 GENERAL_NAME *gn;
1501 ASN1_IA5STRING *uri;
1502 PyObject *ouri;
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001503 int err;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001504
1505 gn = sk_GENERAL_NAME_value(gns, j);
1506 if (gn->type != GEN_URI) {
1507 continue;
1508 }
1509 uri = gn->d.uniformResourceIdentifier;
1510 ouri = PyUnicode_FromStringAndSize((char *)uri->data,
1511 uri->length);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001512 if (ouri == NULL)
1513 goto done;
1514
1515 err = PyList_Append(lst, ouri);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001516 Py_DECREF(ouri);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001517 if (err < 0)
1518 goto done;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001519 }
1520 }
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001521
1522 /* Convert to tuple. */
1523 res = (PyList_GET_SIZE(lst) > 0) ? PyList_AsTuple(lst) : Py_None;
1524
1525 done:
1526 Py_XDECREF(lst);
Olivier Vielpeau2849cc32017-04-14 21:06:07 -04001527 CRL_DIST_POINTS_free(dps);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001528 return res;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001529}
1530
1531static PyObject *
Christian Heimes7f1305e2021-04-17 20:06:38 +02001532_decode_certificate(_sslmodulestate *state, X509 *certificate) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001533
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001534 PyObject *retval = NULL;
1535 BIO *biobuf = NULL;
1536 PyObject *peer;
1537 PyObject *peer_alt_names = NULL;
1538 PyObject *issuer;
1539 PyObject *version;
1540 PyObject *sn_obj;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001541 PyObject *obj;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001542 ASN1_INTEGER *serialNumber;
1543 char buf[2048];
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001544 int len, result;
Christian Heimesa871f692020-06-01 08:58:14 +02001545 const ASN1_TIME *notBefore, *notAfter;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001546 PyObject *pnotBefore, *pnotAfter;
Thomas Woutersed03b412007-08-28 21:37:11 +00001547
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001548 retval = PyDict_New();
1549 if (retval == NULL)
1550 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001551
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001552 peer = _create_tuple_for_X509_NAME(
Christian Heimes7f1305e2021-04-17 20:06:38 +02001553 state,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001554 X509_get_subject_name(certificate));
1555 if (peer == NULL)
1556 goto fail0;
1557 if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) {
1558 Py_DECREF(peer);
1559 goto fail0;
1560 }
1561 Py_DECREF(peer);
Thomas Woutersed03b412007-08-28 21:37:11 +00001562
Antoine Pitroufb046912010-11-09 20:21:19 +00001563 issuer = _create_tuple_for_X509_NAME(
Christian Heimes7f1305e2021-04-17 20:06:38 +02001564 state,
Antoine Pitroufb046912010-11-09 20:21:19 +00001565 X509_get_issuer_name(certificate));
1566 if (issuer == NULL)
1567 goto fail0;
1568 if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001569 Py_DECREF(issuer);
Antoine Pitroufb046912010-11-09 20:21:19 +00001570 goto fail0;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001571 }
Antoine Pitroufb046912010-11-09 20:21:19 +00001572 Py_DECREF(issuer);
1573
1574 version = PyLong_FromLong(X509_get_version(certificate) + 1);
Christian Heimes5962bef2013-07-26 15:51:18 +02001575 if (version == NULL)
1576 goto fail0;
Antoine Pitroufb046912010-11-09 20:21:19 +00001577 if (PyDict_SetItemString(retval, "version", version) < 0) {
1578 Py_DECREF(version);
1579 goto fail0;
1580 }
1581 Py_DECREF(version);
Guido van Rossumf06628b2007-11-21 20:01:53 +00001582
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001583 /* get a memory buffer */
1584 biobuf = BIO_new(BIO_s_mem());
Zackery Spytz4c49da02018-12-07 03:11:30 -07001585 if (biobuf == NULL) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02001586 PyErr_SetString(state->PySSLErrorObject, "failed to allocate BIO");
Zackery Spytz4c49da02018-12-07 03:11:30 -07001587 goto fail0;
1588 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001589
Antoine Pitroufb046912010-11-09 20:21:19 +00001590 (void) BIO_reset(biobuf);
1591 serialNumber = X509_get_serialNumber(certificate);
1592 /* should not exceed 20 octets, 160 bits, so buf is big enough */
1593 i2a_ASN1_INTEGER(biobuf, serialNumber);
1594 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1595 if (len < 0) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02001596 _setSSLError(state, NULL, 0, __FILE__, __LINE__);
Antoine Pitroufb046912010-11-09 20:21:19 +00001597 goto fail1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001598 }
Antoine Pitroufb046912010-11-09 20:21:19 +00001599 sn_obj = PyUnicode_FromStringAndSize(buf, len);
1600 if (sn_obj == NULL)
1601 goto fail1;
1602 if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) {
1603 Py_DECREF(sn_obj);
1604 goto fail1;
1605 }
1606 Py_DECREF(sn_obj);
1607
1608 (void) BIO_reset(biobuf);
Christian Heimesa871f692020-06-01 08:58:14 +02001609 notBefore = X509_get0_notBefore(certificate);
Antoine Pitroufb046912010-11-09 20:21:19 +00001610 ASN1_TIME_print(biobuf, notBefore);
1611 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1612 if (len < 0) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02001613 _setSSLError(state, NULL, 0, __FILE__, __LINE__);
Antoine Pitroufb046912010-11-09 20:21:19 +00001614 goto fail1;
1615 }
1616 pnotBefore = PyUnicode_FromStringAndSize(buf, len);
1617 if (pnotBefore == NULL)
1618 goto fail1;
1619 if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) {
1620 Py_DECREF(pnotBefore);
1621 goto fail1;
1622 }
1623 Py_DECREF(pnotBefore);
Thomas Woutersed03b412007-08-28 21:37:11 +00001624
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001625 (void) BIO_reset(biobuf);
Christian Heimesa871f692020-06-01 08:58:14 +02001626 notAfter = X509_get0_notAfter(certificate);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001627 ASN1_TIME_print(biobuf, notAfter);
1628 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1629 if (len < 0) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02001630 _setSSLError(state, NULL, 0, __FILE__, __LINE__);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001631 goto fail1;
1632 }
1633 pnotAfter = PyUnicode_FromStringAndSize(buf, len);
1634 if (pnotAfter == NULL)
1635 goto fail1;
1636 if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) {
1637 Py_DECREF(pnotAfter);
1638 goto fail1;
1639 }
1640 Py_DECREF(pnotAfter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001641
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001642 /* Now look for subjectAltName */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001643
Christian Heimes7f1305e2021-04-17 20:06:38 +02001644 peer_alt_names = _get_peer_alt_names(state, certificate);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001645 if (peer_alt_names == NULL)
1646 goto fail1;
1647 else if (peer_alt_names != Py_None) {
1648 if (PyDict_SetItemString(retval, "subjectAltName",
1649 peer_alt_names) < 0) {
1650 Py_DECREF(peer_alt_names);
1651 goto fail1;
1652 }
1653 Py_DECREF(peer_alt_names);
1654 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001655
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001656 /* Authority Information Access: OCSP URIs */
1657 obj = _get_aia_uri(certificate, NID_ad_OCSP);
1658 if (obj == NULL) {
1659 goto fail1;
1660 } else if (obj != Py_None) {
1661 result = PyDict_SetItemString(retval, "OCSP", obj);
1662 Py_DECREF(obj);
1663 if (result < 0) {
1664 goto fail1;
1665 }
1666 }
1667
1668 obj = _get_aia_uri(certificate, NID_ad_ca_issuers);
1669 if (obj == NULL) {
1670 goto fail1;
1671 } else if (obj != Py_None) {
1672 result = PyDict_SetItemString(retval, "caIssuers", obj);
1673 Py_DECREF(obj);
1674 if (result < 0) {
1675 goto fail1;
1676 }
1677 }
1678
1679 /* CDP (CRL distribution points) */
1680 obj = _get_crl_dp(certificate);
1681 if (obj == NULL) {
1682 goto fail1;
1683 } else if (obj != Py_None) {
1684 result = PyDict_SetItemString(retval, "crlDistributionPoints", obj);
1685 Py_DECREF(obj);
1686 if (result < 0) {
1687 goto fail1;
1688 }
1689 }
1690
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001691 BIO_free(biobuf);
1692 return retval;
Thomas Woutersed03b412007-08-28 21:37:11 +00001693
1694 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001695 if (biobuf != NULL)
1696 BIO_free(biobuf);
Thomas Woutersed03b412007-08-28 21:37:11 +00001697 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001698 Py_XDECREF(retval);
1699 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001700}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001701
Christian Heimes9a5395a2013-06-17 15:44:12 +02001702static PyObject *
Christian Heimes7f1305e2021-04-17 20:06:38 +02001703_certificate_to_der(_sslmodulestate *state, X509 *certificate)
Christian Heimes9a5395a2013-06-17 15:44:12 +02001704{
1705 unsigned char *bytes_buf = NULL;
1706 int len;
1707 PyObject *retval;
1708
1709 bytes_buf = NULL;
1710 len = i2d_X509(certificate, &bytes_buf);
1711 if (len < 0) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02001712 _setSSLError(state, NULL, 0, __FILE__, __LINE__);
Christian Heimes9a5395a2013-06-17 15:44:12 +02001713 return NULL;
1714 }
1715 /* this is actually an immutable bytes sequence */
1716 retval = PyBytes_FromStringAndSize((const char *) bytes_buf, len);
1717 OPENSSL_free(bytes_buf);
1718 return retval;
1719}
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001720
Christian Heimes666991f2021-04-26 15:01:40 +02001721#include "_ssl/misc.c"
1722#include "_ssl/cert.c"
1723
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001724/*[clinic input]
1725_ssl._test_decode_cert
1726 path: object(converter="PyUnicode_FSConverter")
1727 /
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001728
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001729[clinic start generated code]*/
1730
1731static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001732_ssl__test_decode_cert_impl(PyObject *module, PyObject *path)
1733/*[clinic end generated code: output=96becb9abb23c091 input=cdeaaf02d4346628]*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001734{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001735 PyObject *retval = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001736 X509 *x=NULL;
1737 BIO *cert;
Christian Heimes7f1305e2021-04-17 20:06:38 +02001738 _sslmodulestate *state = get_ssl_state(module);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001739
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001740 if ((cert=BIO_new(BIO_s_file())) == NULL) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02001741 PyErr_SetString(state->PySSLErrorObject,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001742 "Can't malloc memory to read file");
1743 goto fail0;
1744 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001745
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001746 if (BIO_read_filename(cert, PyBytes_AsString(path)) <= 0) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02001747 PyErr_SetString(state->PySSLErrorObject,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001748 "Can't open file");
1749 goto fail0;
1750 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001751
Alex Gaynor40dad952019-08-15 08:31:28 -04001752 x = PEM_read_bio_X509(cert, NULL, NULL, NULL);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001753 if (x == NULL) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02001754 PyErr_SetString(state->PySSLErrorObject,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001755 "Error decoding PEM-encoded file");
1756 goto fail0;
1757 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001758
Christian Heimes7f1305e2021-04-17 20:06:38 +02001759 retval = _decode_certificate(state, x);
Mark Dickinsonee55df52010-08-03 18:31:54 +00001760 X509_free(x);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001761
1762 fail0:
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001763 Py_DECREF(path);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001764 if (cert != NULL) BIO_free(cert);
1765 return retval;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001766}
1767
1768
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001769/*[clinic input]
Christian Heimes141c5e82018-02-24 21:10:57 +01001770_ssl._SSLSocket.getpeercert
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001771 der as binary_mode: bool = False
1772 /
1773
1774Returns the certificate for the peer.
1775
1776If no certificate was provided, returns None. If a certificate was
1777provided, but not validated, returns an empty dictionary. Otherwise
1778returns a dict containing information about the peer certificate.
1779
1780If the optional argument is True, returns a DER-encoded copy of the
1781peer certificate, or None if no certificate was provided. This will
1782return the certificate even if it wasn't validated.
1783[clinic start generated code]*/
1784
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001785static PyObject *
Christian Heimes141c5e82018-02-24 21:10:57 +01001786_ssl__SSLSocket_getpeercert_impl(PySSLSocket *self, int binary_mode)
1787/*[clinic end generated code: output=1f0ab66dfb693c88 input=c0fbe802e57629b7]*/
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001788{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001789 int verification;
Christian Heimes66dc33b2017-05-23 16:02:02 -07001790 X509 *peer_cert;
1791 PyObject *result;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001792
Christian Heimes66dc33b2017-05-23 16:02:02 -07001793 if (!SSL_is_init_finished(self->ssl)) {
Antoine Pitrou20b85552013-09-29 19:50:53 +02001794 PyErr_SetString(PyExc_ValueError,
1795 "handshake not done yet");
1796 return NULL;
1797 }
Christian Heimes66dc33b2017-05-23 16:02:02 -07001798 peer_cert = SSL_get_peer_certificate(self->ssl);
1799 if (peer_cert == NULL)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001800 Py_RETURN_NONE;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001801
Antoine Pitrou721738f2012-08-15 23:20:39 +02001802 if (binary_mode) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001803 /* return cert in DER-encoded format */
Christian Heimes7f1305e2021-04-17 20:06:38 +02001804 result = _certificate_to_der(get_state_sock(self), peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001805 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00001806 verification = SSL_CTX_get_verify_mode(SSL_get_SSL_CTX(self->ssl));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001807 if ((verification & SSL_VERIFY_PEER) == 0)
Christian Heimes66dc33b2017-05-23 16:02:02 -07001808 result = PyDict_New();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001809 else
Christian Heimes7f1305e2021-04-17 20:06:38 +02001810 result = _decode_certificate(get_state_sock(self), peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001811 }
Christian Heimes66dc33b2017-05-23 16:02:02 -07001812 X509_free(peer_cert);
1813 return result;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001814}
1815
Christian Heimes666991f2021-04-26 15:01:40 +02001816/*[clinic input]
1817_ssl._SSLSocket.get_verified_chain
1818
1819[clinic start generated code]*/
1820
1821static PyObject *
1822_ssl__SSLSocket_get_verified_chain_impl(PySSLSocket *self)
1823/*[clinic end generated code: output=802421163cdc3110 input=5fb0714f77e2bd51]*/
1824{
1825 /* borrowed reference */
1826 STACK_OF(X509) *chain = SSL_get0_verified_chain(self->ssl);
1827 if (chain == NULL) {
1828 Py_RETURN_NONE;
1829 }
1830 return _PySSL_CertificateFromX509Stack(self->ctx->state, chain, 1);
1831}
1832
1833/*[clinic input]
1834_ssl._SSLSocket.get_unverified_chain
1835
1836[clinic start generated code]*/
1837
1838static PyObject *
1839_ssl__SSLSocket_get_unverified_chain_impl(PySSLSocket *self)
1840/*[clinic end generated code: output=5acdae414e13f913 input=78c33c360c635cb5]*/
1841{
1842 PyObject *retval;
1843 /* borrowed reference */
1844 /* TODO: include SSL_get_peer_certificate() for server-side sockets */
1845 STACK_OF(X509) *chain = SSL_get_peer_cert_chain(self->ssl);
1846 if (chain == NULL) {
1847 Py_RETURN_NONE;
1848 }
1849 retval = _PySSL_CertificateFromX509Stack(self->ctx->state, chain, 1);
1850 if (retval == NULL) {
1851 return NULL;
1852 }
1853 /* OpenSSL does not include peer cert for server side connections */
1854 if (self->socket_type == PY_SSL_SERVER) {
1855 PyObject *peerobj = NULL;
1856 X509 *peer = SSL_get_peer_certificate(self->ssl);
1857
1858 if (peer == NULL) {
1859 peerobj = Py_None;
1860 Py_INCREF(peerobj);
1861 } else {
1862 /* consume X509 reference on success */
1863 peerobj = _PySSL_CertificateFromX509(self->ctx->state, peer, 0);
1864 if (peerobj == NULL) {
1865 X509_free(peer);
1866 Py_DECREF(retval);
1867 return NULL;
1868 }
1869 }
1870 int res = PyList_Insert(retval, 0, peerobj);
1871 Py_DECREF(peerobj);
1872 if (res < 0) {
1873 Py_DECREF(retval);
1874 return NULL;
1875 }
1876 }
1877 return retval;
1878}
1879
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001880static PyObject *
1881cipher_to_tuple(const SSL_CIPHER *cipher)
1882{
1883 const char *cipher_name, *cipher_protocol;
1884 PyObject *v, *retval = PyTuple_New(3);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001885 if (retval == NULL)
1886 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001887
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001888 cipher_name = SSL_CIPHER_get_name(cipher);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001889 if (cipher_name == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001890 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001891 PyTuple_SET_ITEM(retval, 0, Py_None);
1892 } else {
1893 v = PyUnicode_FromString(cipher_name);
1894 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001895 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001896 PyTuple_SET_ITEM(retval, 0, v);
1897 }
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001898
1899 cipher_protocol = SSL_CIPHER_get_version(cipher);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001900 if (cipher_protocol == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001901 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001902 PyTuple_SET_ITEM(retval, 1, Py_None);
1903 } else {
1904 v = PyUnicode_FromString(cipher_protocol);
1905 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001906 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001907 PyTuple_SET_ITEM(retval, 1, v);
1908 }
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001909
1910 v = PyLong_FromLong(SSL_CIPHER_get_bits(cipher, NULL));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001911 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001912 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001913 PyTuple_SET_ITEM(retval, 2, v);
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001914
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001915 return retval;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001916
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001917 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001918 Py_DECREF(retval);
1919 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001920}
1921
Christian Heimes25bfcd52016-09-06 00:04:45 +02001922static PyObject *
1923cipher_to_dict(const SSL_CIPHER *cipher)
1924{
1925 const char *cipher_name, *cipher_protocol;
1926
1927 unsigned long cipher_id;
1928 int alg_bits, strength_bits, len;
1929 char buf[512] = {0};
Christian Heimes25bfcd52016-09-06 00:04:45 +02001930 int aead, nid;
1931 const char *skcipher = NULL, *digest = NULL, *kx = NULL, *auth = NULL;
Christian Heimes25bfcd52016-09-06 00:04:45 +02001932
1933 /* can be NULL */
1934 cipher_name = SSL_CIPHER_get_name(cipher);
1935 cipher_protocol = SSL_CIPHER_get_version(cipher);
1936 cipher_id = SSL_CIPHER_get_id(cipher);
1937 SSL_CIPHER_description(cipher, buf, sizeof(buf) - 1);
Segev Finer5cff6372017-07-27 01:19:17 +03001938 /* Downcast to avoid a warning. Safe since buf is always 512 bytes */
1939 len = (int)strlen(buf);
Christian Heimes25bfcd52016-09-06 00:04:45 +02001940 if (len > 1 && buf[len-1] == '\n')
1941 buf[len-1] = '\0';
1942 strength_bits = SSL_CIPHER_get_bits(cipher, &alg_bits);
1943
Christian Heimes25bfcd52016-09-06 00:04:45 +02001944 aead = SSL_CIPHER_is_aead(cipher);
1945 nid = SSL_CIPHER_get_cipher_nid(cipher);
1946 skcipher = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1947 nid = SSL_CIPHER_get_digest_nid(cipher);
1948 digest = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1949 nid = SSL_CIPHER_get_kx_nid(cipher);
1950 kx = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1951 nid = SSL_CIPHER_get_auth_nid(cipher);
1952 auth = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
Christian Heimes25bfcd52016-09-06 00:04:45 +02001953
Victor Stinner410b9882016-09-12 12:00:23 +02001954 return Py_BuildValue(
Christian Heimes25bfcd52016-09-06 00:04:45 +02001955 "{sksssssssisi"
Christian Heimes25bfcd52016-09-06 00:04:45 +02001956 "sOssssssss"
Christian Heimes25bfcd52016-09-06 00:04:45 +02001957 "}",
1958 "id", cipher_id,
1959 "name", cipher_name,
1960 "protocol", cipher_protocol,
1961 "description", buf,
1962 "strength_bits", strength_bits,
1963 "alg_bits", alg_bits
Christian Heimes25bfcd52016-09-06 00:04:45 +02001964 ,"aead", aead ? Py_True : Py_False,
1965 "symmetric", skcipher,
1966 "digest", digest,
1967 "kea", kx,
1968 "auth", auth
Christian Heimes25bfcd52016-09-06 00:04:45 +02001969 );
Christian Heimes25bfcd52016-09-06 00:04:45 +02001970}
Christian Heimes25bfcd52016-09-06 00:04:45 +02001971
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001972/*[clinic input]
1973_ssl._SSLSocket.shared_ciphers
1974[clinic start generated code]*/
1975
1976static PyObject *
1977_ssl__SSLSocket_shared_ciphers_impl(PySSLSocket *self)
1978/*[clinic end generated code: output=3d174ead2e42c4fd input=0bfe149da8fe6306]*/
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001979{
1980 STACK_OF(SSL_CIPHER) *ciphers;
1981 int i;
1982 PyObject *res;
1983
Christian Heimes598894f2016-09-05 23:19:05 +02001984 ciphers = SSL_get_ciphers(self->ssl);
1985 if (!ciphers)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001986 Py_RETURN_NONE;
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001987 res = PyList_New(sk_SSL_CIPHER_num(ciphers));
1988 if (!res)
1989 return NULL;
1990 for (i = 0; i < sk_SSL_CIPHER_num(ciphers); i++) {
1991 PyObject *tup = cipher_to_tuple(sk_SSL_CIPHER_value(ciphers, i));
1992 if (!tup) {
1993 Py_DECREF(res);
1994 return NULL;
1995 }
1996 PyList_SET_ITEM(res, i, tup);
1997 }
1998 return res;
1999}
2000
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002001/*[clinic input]
2002_ssl._SSLSocket.cipher
2003[clinic start generated code]*/
2004
2005static PyObject *
2006_ssl__SSLSocket_cipher_impl(PySSLSocket *self)
2007/*[clinic end generated code: output=376417c16d0e5815 input=548fb0e27243796d]*/
Benjamin Peterson4cb17812015-01-07 11:14:26 -06002008{
2009 const SSL_CIPHER *current;
2010
2011 if (self->ssl == NULL)
2012 Py_RETURN_NONE;
2013 current = SSL_get_current_cipher(self->ssl);
2014 if (current == NULL)
2015 Py_RETURN_NONE;
2016 return cipher_to_tuple(current);
2017}
2018
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002019/*[clinic input]
2020_ssl._SSLSocket.version
2021[clinic start generated code]*/
2022
2023static PyObject *
2024_ssl__SSLSocket_version_impl(PySSLSocket *self)
2025/*[clinic end generated code: output=178aed33193b2cdb input=900186a503436fd6]*/
Antoine Pitrou47e40422014-09-04 21:00:10 +02002026{
2027 const char *version;
2028
2029 if (self->ssl == NULL)
2030 Py_RETURN_NONE;
Christian Heimes68771112017-09-05 21:55:40 -07002031 if (!SSL_is_init_finished(self->ssl)) {
2032 /* handshake not finished */
2033 Py_RETURN_NONE;
2034 }
Antoine Pitrou47e40422014-09-04 21:00:10 +02002035 version = SSL_get_version(self->ssl);
2036 if (!strcmp(version, "unknown"))
2037 Py_RETURN_NONE;
2038 return PyUnicode_FromString(version);
2039}
2040
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002041/*[clinic input]
2042_ssl._SSLSocket.selected_alpn_protocol
2043[clinic start generated code]*/
2044
2045static PyObject *
2046_ssl__SSLSocket_selected_alpn_protocol_impl(PySSLSocket *self)
2047/*[clinic end generated code: output=ec33688b303d250f input=442de30e35bc2913]*/
2048{
Benjamin Petersoncca27322015-01-23 16:35:37 -05002049 const unsigned char *out;
2050 unsigned int outlen;
2051
2052 SSL_get0_alpn_selected(self->ssl, &out, &outlen);
2053
2054 if (out == NULL)
2055 Py_RETURN_NONE;
2056 return PyUnicode_FromStringAndSize((char *)out, outlen);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002057}
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002058
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002059/*[clinic input]
2060_ssl._SSLSocket.compression
2061[clinic start generated code]*/
2062
2063static PyObject *
2064_ssl__SSLSocket_compression_impl(PySSLSocket *self)
2065/*[clinic end generated code: output=bd16cb1bb4646ae7 input=5d059d0a2bbc32c8]*/
2066{
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01002067#ifdef OPENSSL_NO_COMP
2068 Py_RETURN_NONE;
2069#else
2070 const COMP_METHOD *comp_method;
2071 const char *short_name;
2072
2073 if (self->ssl == NULL)
2074 Py_RETURN_NONE;
2075 comp_method = SSL_get_current_compression(self->ssl);
Christian Heimes598894f2016-09-05 23:19:05 +02002076 if (comp_method == NULL || COMP_get_type(comp_method) == NID_undef)
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01002077 Py_RETURN_NONE;
Christian Heimes281e5f82016-09-06 01:10:39 +02002078 short_name = OBJ_nid2sn(COMP_get_type(comp_method));
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01002079 if (short_name == NULL)
2080 Py_RETURN_NONE;
2081 return PyUnicode_DecodeFSDefault(short_name);
2082#endif
2083}
2084
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002085static PySSLContext *PySSL_get_context(PySSLSocket *self, void *closure) {
2086 Py_INCREF(self->ctx);
2087 return self->ctx;
2088}
2089
2090static int PySSL_set_context(PySSLSocket *self, PyObject *value,
2091 void *closure) {
2092
Christian Heimes7f1305e2021-04-17 20:06:38 +02002093 if (PyObject_TypeCheck(value, self->ctx->state->PySSLContext_Type)) {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002094 Py_INCREF(value);
Serhiy Storchaka57a01d32016-04-10 18:05:40 +03002095 Py_SETREF(self->ctx, (PySSLContext *)value);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002096 SSL_set_SSL_CTX(self->ssl, self->ctx->ctx);
Christian Heimes77cde502021-03-21 16:13:09 +01002097 /* Set SSL* internal msg_callback to state of new context's state */
2098 SSL_set_msg_callback(
2099 self->ssl,
2100 self->ctx->msg_cb ? _PySSL_msg_callback : NULL
2101 );
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002102 } else {
Ned Deily4531ec72018-06-11 20:26:28 -04002103 PyErr_SetString(PyExc_TypeError, "The value must be a SSLContext");
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002104 return -1;
2105 }
2106
2107 return 0;
2108}
2109
2110PyDoc_STRVAR(PySSL_set_context_doc,
2111"_setter_context(ctx)\n\
2112\
2113This changes the context associated with the SSLSocket. This is typically\n\
Christian Heimes11a14932018-02-24 02:35:08 +01002114used from within a callback function set by the sni_callback\n\
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002115on the SSLContext to change the certificate information associated with the\n\
2116SSLSocket before the cryptographic exchange handshake messages\n");
2117
2118
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002119static PyObject *
2120PySSL_get_server_side(PySSLSocket *self, void *c)
2121{
2122 return PyBool_FromLong(self->socket_type == PY_SSL_SERVER);
2123}
2124
2125PyDoc_STRVAR(PySSL_get_server_side_doc,
2126"Whether this is a server-side socket.");
2127
2128static PyObject *
2129PySSL_get_server_hostname(PySSLSocket *self, void *c)
2130{
2131 if (self->server_hostname == NULL)
2132 Py_RETURN_NONE;
2133 Py_INCREF(self->server_hostname);
2134 return self->server_hostname;
2135}
2136
2137PyDoc_STRVAR(PySSL_get_server_hostname_doc,
2138"The currently set server hostname (for SNI).");
2139
2140static PyObject *
2141PySSL_get_owner(PySSLSocket *self, void *c)
2142{
2143 PyObject *owner;
2144
2145 if (self->owner == NULL)
2146 Py_RETURN_NONE;
2147
2148 owner = PyWeakref_GetObject(self->owner);
2149 Py_INCREF(owner);
2150 return owner;
2151}
2152
2153static int
2154PySSL_set_owner(PySSLSocket *self, PyObject *value, void *c)
2155{
Serhiy Storchaka48842712016-04-06 09:45:48 +03002156 Py_XSETREF(self->owner, PyWeakref_NewRef(value, NULL));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002157 if (self->owner == NULL)
2158 return -1;
2159 return 0;
2160}
2161
2162PyDoc_STRVAR(PySSL_get_owner_doc,
2163"The Python-level owner of this object.\
2164Passed as \"self\" in servername callback.");
2165
Christian Heimesc7f70692019-05-31 11:44:05 +02002166static int
2167PySSL_traverse(PySSLSocket *self, visitproc visit, void *arg)
2168{
2169 Py_VISIT(self->exc_type);
2170 Py_VISIT(self->exc_value);
2171 Py_VISIT(self->exc_tb);
2172 return 0;
2173}
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002174
Christian Heimesc7f70692019-05-31 11:44:05 +02002175static int
2176PySSL_clear(PySSLSocket *self)
2177{
2178 Py_CLEAR(self->exc_type);
2179 Py_CLEAR(self->exc_value);
2180 Py_CLEAR(self->exc_tb);
2181 return 0;
2182}
2183
2184static void
2185PySSL_dealloc(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002186{
Christian Heimes5c36da72020-11-20 09:40:12 +01002187 PyTypeObject *tp = Py_TYPE(self);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002188 if (self->ssl)
2189 SSL_free(self->ssl);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002190 Py_XDECREF(self->Socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002191 Py_XDECREF(self->ctx);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002192 Py_XDECREF(self->server_hostname);
2193 Py_XDECREF(self->owner);
Victor Stinner32bd68c2020-12-01 10:37:39 +01002194 PyObject_Free(self);
Christian Heimes5c36da72020-11-20 09:40:12 +01002195 Py_DECREF(tp);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002196}
2197
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002198/* If the socket has a timeout, do a select()/poll() on the socket.
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002199 The argument writing indicates the direction.
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00002200 Returns one of the possibilities in the timeout_state enum (above).
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002201 */
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00002202
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002203static int
Victor Stinner14690702015-04-06 22:46:13 +02002204PySSL_select(PySocketSockObject *s, int writing, _PyTime_t timeout)
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002205{
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002206 int rc;
2207#ifdef HAVE_POLL
2208 struct pollfd pollfd;
2209 _PyTime_t ms;
2210#else
2211 int nfds;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002212 fd_set fds;
2213 struct timeval tv;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002214#endif
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002215
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002216 /* Nothing to do unless we're in timeout mode (not non-blocking) */
Victor Stinner14690702015-04-06 22:46:13 +02002217 if ((s == NULL) || (timeout == 0))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002218 return SOCKET_IS_NONBLOCKING;
Victor Stinner14690702015-04-06 22:46:13 +02002219 else if (timeout < 0) {
2220 if (s->sock_timeout > 0)
2221 return SOCKET_HAS_TIMED_OUT;
2222 else
2223 return SOCKET_IS_BLOCKING;
2224 }
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002225
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002226 /* Guard against closed socket */
Victor Stinner524714e2016-07-22 17:43:59 +02002227 if (s->sock_fd == INVALID_SOCKET)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002228 return SOCKET_HAS_BEEN_CLOSED;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002229
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002230 /* Prefer poll, if available, since you can poll() any fd
2231 * which can't be done with select(). */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002232#ifdef HAVE_POLL
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002233 pollfd.fd = s->sock_fd;
2234 pollfd.events = writing ? POLLOUT : POLLIN;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002235
Victor Stinner14690702015-04-06 22:46:13 +02002236 /* timeout is in seconds, poll() uses milliseconds */
2237 ms = (int)_PyTime_AsMilliseconds(timeout, _PyTime_ROUND_CEILING);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002238 assert(ms <= INT_MAX);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002239
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002240 PySSL_BEGIN_ALLOW_THREADS
2241 rc = poll(&pollfd, 1, (int)ms);
2242 PySSL_END_ALLOW_THREADS
2243#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002244 /* Guard against socket too large for select*/
Charles-François Nataliaa26b272011-08-28 17:51:43 +02002245 if (!_PyIsSelectable_fd(s->sock_fd))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002246 return SOCKET_TOO_LARGE_FOR_SELECT;
Neal Norwitz082b2df2006-02-07 07:04:46 +00002247
Victor Stinner14690702015-04-06 22:46:13 +02002248 _PyTime_AsTimeval_noraise(timeout, &tv, _PyTime_ROUND_CEILING);
Victor Stinnere2452312015-03-28 03:00:46 +01002249
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002250 FD_ZERO(&fds);
2251 FD_SET(s->sock_fd, &fds);
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002252
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002253 /* Wait until the socket becomes ready */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002254 PySSL_BEGIN_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002255 nfds = Py_SAFE_DOWNCAST(s->sock_fd+1, SOCKET_T, int);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002256 if (writing)
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002257 rc = select(nfds, NULL, &fds, NULL, &tv);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002258 else
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002259 rc = select(nfds, &fds, NULL, NULL, &tv);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002260 PySSL_END_ALLOW_THREADS
Bill Janssen6e027db2007-11-15 22:23:56 +00002261#endif
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002262
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002263 /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
2264 (when we are able to write or when there's something to read) */
2265 return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002266}
2267
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002268/*[clinic input]
2269_ssl._SSLSocket.write
2270 b: Py_buffer
2271 /
2272
2273Writes the bytes-like object b into the SSL object.
2274
2275Returns the number of bytes written.
2276[clinic start generated code]*/
2277
2278static PyObject *
2279_ssl__SSLSocket_write_impl(PySSLSocket *self, Py_buffer *b)
2280/*[clinic end generated code: output=aa7a6be5527358d8 input=77262d994fe5100a]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002281{
Christian Heimes89d15502021-04-19 06:55:30 +02002282 size_t count = 0;
2283 int retval;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002284 int sockstate;
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002285 _PySSLError err;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002286 int nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002287 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002288 _PyTime_t timeout, deadline = 0;
2289 int has_timeout;
Bill Janssen54cc54c2007-12-14 22:08:56 +00002290
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002291 if (sock != NULL) {
2292 if (((PyObject*)sock) == Py_None) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02002293 _setSSLError(get_state_sock(self),
2294 "Underlying socket connection gone",
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002295 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2296 return NULL;
2297 }
2298 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002299 }
2300
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002301 if (sock != NULL) {
2302 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002303 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002304 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2305 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
2306 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002307
Victor Stinner14690702015-04-06 22:46:13 +02002308 timeout = GET_SOCKET_TIMEOUT(sock);
2309 has_timeout = (timeout > 0);
2310 if (has_timeout)
2311 deadline = _PyTime_GetMonotonicClock() + timeout;
2312
2313 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002314 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Christian Heimes03c8ddd2020-11-20 09:26:07 +01002315 PyErr_SetString(PyExc_TimeoutError,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002316 "The write operation timed out");
2317 goto error;
2318 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02002319 PyErr_SetString(get_state_sock(self)->PySSLErrorObject,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002320 "Underlying socket has been closed.");
2321 goto error;
2322 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02002323 PyErr_SetString(get_state_sock(self)->PySSLErrorObject,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002324 "Underlying socket too large for select().");
2325 goto error;
2326 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002327
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002328 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002329 PySSL_BEGIN_ALLOW_THREADS
Christian Heimes89d15502021-04-19 06:55:30 +02002330 retval = SSL_write_ex(self->ssl, b->buf, (int)b->len, &count);
2331 err = _PySSL_errno(retval == 0, self->ssl, retval);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002332 PySSL_END_ALLOW_THREADS
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002333 self->err = err;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002334
2335 if (PyErr_CheckSignals())
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002336 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002337
Victor Stinner14690702015-04-06 22:46:13 +02002338 if (has_timeout)
2339 timeout = deadline - _PyTime_GetMonotonicClock();
2340
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002341 if (err.ssl == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +02002342 sockstate = PySSL_select(sock, 0, timeout);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002343 } else if (err.ssl == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +02002344 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002345 } else {
2346 sockstate = SOCKET_OPERATION_OK;
2347 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002348
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002349 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Christian Heimes03c8ddd2020-11-20 09:26:07 +01002350 PyErr_SetString(PyExc_TimeoutError,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002351 "The write operation timed out");
2352 goto error;
2353 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02002354 PyErr_SetString(get_state_sock(self)->PySSLErrorObject,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002355 "Underlying socket has been closed.");
2356 goto error;
2357 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
2358 break;
2359 }
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002360 } while (err.ssl == SSL_ERROR_WANT_READ ||
2361 err.ssl == SSL_ERROR_WANT_WRITE);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002362
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002363 Py_XDECREF(sock);
Christian Heimes89d15502021-04-19 06:55:30 +02002364 if (retval == 0)
2365 return PySSL_SetError(self, retval, __FILE__, __LINE__);
Christian Heimesc7f70692019-05-31 11:44:05 +02002366 if (PySSL_ChainExceptions(self) < 0)
2367 return NULL;
Christian Heimes89d15502021-04-19 06:55:30 +02002368 return PyLong_FromSize_t(count);
Antoine Pitrou7d7aede2009-11-25 18:55:32 +00002369error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002370 Py_XDECREF(sock);
Christian Heimesc7f70692019-05-31 11:44:05 +02002371 PySSL_ChainExceptions(self);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002372 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002373}
2374
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002375/*[clinic input]
2376_ssl._SSLSocket.pending
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002377
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002378Returns the number of already decrypted bytes available for read, pending on the connection.
2379[clinic start generated code]*/
2380
2381static PyObject *
2382_ssl__SSLSocket_pending_impl(PySSLSocket *self)
2383/*[clinic end generated code: output=983d9fecdc308a83 input=2b77487d6dfd597f]*/
Bill Janssen6e027db2007-11-15 22:23:56 +00002384{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002385 int count = 0;
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002386 _PySSLError err;
Bill Janssen6e027db2007-11-15 22:23:56 +00002387
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002388 PySSL_BEGIN_ALLOW_THREADS
2389 count = SSL_pending(self->ssl);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002390 err = _PySSL_errno(count < 0, self->ssl, count);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002391 PySSL_END_ALLOW_THREADS
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002392 self->err = err;
2393
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002394 if (count < 0)
2395 return PySSL_SetError(self, count, __FILE__, __LINE__);
2396 else
2397 return PyLong_FromLong(count);
Bill Janssen6e027db2007-11-15 22:23:56 +00002398}
2399
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002400/*[clinic input]
2401_ssl._SSLSocket.read
2402 size as len: int
2403 [
Larry Hastingsdbfdc382015-05-04 06:59:46 -07002404 buffer: Py_buffer(accept={rwbuffer})
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002405 ]
2406 /
Bill Janssen6e027db2007-11-15 22:23:56 +00002407
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002408Read up to size bytes from the SSL socket.
2409[clinic start generated code]*/
2410
2411static PyObject *
2412_ssl__SSLSocket_read_impl(PySSLSocket *self, int len, int group_right_1,
2413 Py_buffer *buffer)
Larry Hastingsdbfdc382015-05-04 06:59:46 -07002414/*[clinic end generated code: output=00097776cec2a0af input=ff157eb918d0905b]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002415{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002416 PyObject *dest = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002417 char *mem;
Christian Heimes89d15502021-04-19 06:55:30 +02002418 size_t count = 0;
2419 int retval;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002420 int sockstate;
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002421 _PySSLError err;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002422 int nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002423 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002424 _PyTime_t timeout, deadline = 0;
2425 int has_timeout;
Bill Janssen54cc54c2007-12-14 22:08:56 +00002426
Martin Panter5503d472016-03-27 05:35:19 +00002427 if (!group_right_1 && len < 0) {
2428 PyErr_SetString(PyExc_ValueError, "size should not be negative");
2429 return NULL;
2430 }
2431
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002432 if (sock != NULL) {
2433 if (((PyObject*)sock) == Py_None) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02002434 _setSSLError(get_state_sock(self),
2435 "Underlying socket connection gone",
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002436 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2437 return NULL;
2438 }
2439 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002440 }
2441
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002442 if (!group_right_1) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002443 dest = PyBytes_FromStringAndSize(NULL, len);
2444 if (dest == NULL)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002445 goto error;
Martin Panterbed7f1a2016-07-11 00:17:13 +00002446 if (len == 0) {
2447 Py_XDECREF(sock);
2448 return dest;
2449 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002450 mem = PyBytes_AS_STRING(dest);
2451 }
2452 else {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002453 mem = buffer->buf;
2454 if (len <= 0 || len > buffer->len) {
2455 len = (int) buffer->len;
2456 if (buffer->len != len) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002457 PyErr_SetString(PyExc_OverflowError,
2458 "maximum length can't fit in a C 'int'");
2459 goto error;
2460 }
Martin Panterbed7f1a2016-07-11 00:17:13 +00002461 if (len == 0) {
2462 count = 0;
2463 goto done;
2464 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002465 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002466 }
2467
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002468 if (sock != NULL) {
2469 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002470 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002471 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2472 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
2473 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002474
Victor Stinner14690702015-04-06 22:46:13 +02002475 timeout = GET_SOCKET_TIMEOUT(sock);
2476 has_timeout = (timeout > 0);
2477 if (has_timeout)
2478 deadline = _PyTime_GetMonotonicClock() + timeout;
2479
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002480 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002481 PySSL_BEGIN_ALLOW_THREADS
Christian Heimes89d15502021-04-19 06:55:30 +02002482 retval = SSL_read_ex(self->ssl, mem, len, &count);
2483 err = _PySSL_errno(retval == 0, self->ssl, retval);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002484 PySSL_END_ALLOW_THREADS
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002485 self->err = err;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002486
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002487 if (PyErr_CheckSignals())
2488 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002489
Victor Stinner14690702015-04-06 22:46:13 +02002490 if (has_timeout)
2491 timeout = deadline - _PyTime_GetMonotonicClock();
2492
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002493 if (err.ssl == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +02002494 sockstate = PySSL_select(sock, 0, timeout);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002495 } else if (err.ssl == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +02002496 sockstate = PySSL_select(sock, 1, timeout);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002497 } else if (err.ssl == SSL_ERROR_ZERO_RETURN &&
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002498 SSL_get_shutdown(self->ssl) == SSL_RECEIVED_SHUTDOWN)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002499 {
2500 count = 0;
2501 goto done;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002502 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002503 else
2504 sockstate = SOCKET_OPERATION_OK;
2505
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002506 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Christian Heimes03c8ddd2020-11-20 09:26:07 +01002507 PyErr_SetString(PyExc_TimeoutError,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002508 "The read operation timed out");
2509 goto error;
2510 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
2511 break;
2512 }
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002513 } while (err.ssl == SSL_ERROR_WANT_READ ||
2514 err.ssl == SSL_ERROR_WANT_WRITE);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002515
Christian Heimes89d15502021-04-19 06:55:30 +02002516 if (retval == 0) {
2517 PySSL_SetError(self, retval, __FILE__, __LINE__);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002518 goto error;
2519 }
Christian Heimesc7f70692019-05-31 11:44:05 +02002520 if (self->exc_type != NULL)
2521 goto error;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002522
2523done:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002524 Py_XDECREF(sock);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002525 if (!group_right_1) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002526 _PyBytes_Resize(&dest, count);
2527 return dest;
2528 }
2529 else {
Christian Heimes89d15502021-04-19 06:55:30 +02002530 return PyLong_FromSize_t(count);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002531 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002532
2533error:
Christian Heimesc7f70692019-05-31 11:44:05 +02002534 PySSL_ChainExceptions(self);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002535 Py_XDECREF(sock);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002536 if (!group_right_1)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002537 Py_XDECREF(dest);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002538 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002539}
2540
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002541/*[clinic input]
2542_ssl._SSLSocket.shutdown
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002543
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002544Does the SSL shutdown handshake with the remote end.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002545[clinic start generated code]*/
2546
2547static PyObject *
2548_ssl__SSLSocket_shutdown_impl(PySSLSocket *self)
Christian Heimes141c5e82018-02-24 21:10:57 +01002549/*[clinic end generated code: output=ca1aa7ed9d25ca42 input=11d39e69b0a2bf4a]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00002550{
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002551 _PySSLError err;
2552 int sockstate, nonblocking, ret;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002553 int zeros = 0;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002554 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002555 _PyTime_t timeout, deadline = 0;
2556 int has_timeout;
Bill Janssen40a0f662008-08-12 16:56:25 +00002557
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002558 if (sock != NULL) {
2559 /* Guard against closed socket */
Victor Stinner524714e2016-07-22 17:43:59 +02002560 if ((((PyObject*)sock) == Py_None) || (sock->sock_fd == INVALID_SOCKET)) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02002561 _setSSLError(get_state_sock(self),
2562 "Underlying socket connection gone",
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002563 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2564 return NULL;
2565 }
2566 Py_INCREF(sock);
2567
2568 /* Just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002569 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002570 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2571 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002572 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002573
Victor Stinner14690702015-04-06 22:46:13 +02002574 timeout = GET_SOCKET_TIMEOUT(sock);
2575 has_timeout = (timeout > 0);
2576 if (has_timeout)
2577 deadline = _PyTime_GetMonotonicClock() + timeout;
2578
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002579 while (1) {
2580 PySSL_BEGIN_ALLOW_THREADS
2581 /* Disable read-ahead so that unwrap can work correctly.
2582 * Otherwise OpenSSL might read in too much data,
2583 * eating clear text data that happens to be
2584 * transmitted after the SSL shutdown.
Ezio Melotti85a86292013-08-17 16:57:41 +03002585 * Should be safe to call repeatedly every time this
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002586 * function is used and the shutdown_seen_zero != 0
2587 * condition is met.
2588 */
2589 if (self->shutdown_seen_zero)
2590 SSL_set_read_ahead(self->ssl, 0);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002591 ret = SSL_shutdown(self->ssl);
2592 err = _PySSL_errno(ret < 0, self->ssl, ret);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002593 PySSL_END_ALLOW_THREADS
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002594 self->err = err;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002595
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002596 /* If err == 1, a secure shutdown with SSL_shutdown() is complete */
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002597 if (ret > 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002598 break;
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002599 if (ret == 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002600 /* Don't loop endlessly; instead preserve legacy
2601 behaviour of trying SSL_shutdown() only twice.
2602 This looks necessary for OpenSSL < 0.9.8m */
2603 if (++zeros > 1)
2604 break;
2605 /* Shutdown was sent, now try receiving */
2606 self->shutdown_seen_zero = 1;
2607 continue;
Bill Janssen40a0f662008-08-12 16:56:25 +00002608 }
2609
Victor Stinner14690702015-04-06 22:46:13 +02002610 if (has_timeout)
2611 timeout = deadline - _PyTime_GetMonotonicClock();
2612
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002613 /* Possibly retry shutdown until timeout or failure */
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002614 if (err.ssl == SSL_ERROR_WANT_READ)
Victor Stinner14690702015-04-06 22:46:13 +02002615 sockstate = PySSL_select(sock, 0, timeout);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002616 else if (err.ssl == SSL_ERROR_WANT_WRITE)
Victor Stinner14690702015-04-06 22:46:13 +02002617 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002618 else
2619 break;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002620
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002621 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002622 if (err.ssl == SSL_ERROR_WANT_READ)
Christian Heimes03c8ddd2020-11-20 09:26:07 +01002623 PyErr_SetString(PyExc_TimeoutError,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002624 "The read operation timed out");
2625 else
Christian Heimes03c8ddd2020-11-20 09:26:07 +01002626 PyErr_SetString(PyExc_TimeoutError,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002627 "The write operation timed out");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002628 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002629 }
2630 else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02002631 PyErr_SetString(get_state_sock(self)->PySSLErrorObject,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002632 "Underlying socket too large for select().");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002633 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002634 }
2635 else if (sockstate != SOCKET_OPERATION_OK)
2636 /* Retain the SSL error code */
2637 break;
2638 }
Nathaniel J. Smithc0da5822018-09-21 21:44:12 -07002639 if (ret < 0) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002640 Py_XDECREF(sock);
Christian Heimesc7f70692019-05-31 11:44:05 +02002641 PySSL_SetError(self, ret, __FILE__, __LINE__);
2642 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002643 }
Christian Heimesc7f70692019-05-31 11:44:05 +02002644 if (self->exc_type != NULL)
2645 goto error;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002646 if (sock)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002647 /* It's already INCREF'ed */
2648 return (PyObject *) sock;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002649 else
2650 Py_RETURN_NONE;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002651
2652error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002653 Py_XDECREF(sock);
Christian Heimesc7f70692019-05-31 11:44:05 +02002654 PySSL_ChainExceptions(self);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002655 return NULL;
Bill Janssen40a0f662008-08-12 16:56:25 +00002656}
2657
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002658/*[clinic input]
Christian Heimes141c5e82018-02-24 21:10:57 +01002659_ssl._SSLSocket.get_channel_binding
2660 cb_type: str = "tls-unique"
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002661
Christian Heimes141c5e82018-02-24 21:10:57 +01002662Get channel binding data for current connection.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002663
Christian Heimes141c5e82018-02-24 21:10:57 +01002664Raise ValueError if the requested `cb_type` is not supported. Return bytes
2665of the data or None if the data is not available (e.g. before the handshake).
2666Only 'tls-unique' channel binding data from RFC 5929 is supported.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002667[clinic start generated code]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00002668
Antoine Pitroud6494802011-07-21 01:11:30 +02002669static PyObject *
Christian Heimes141c5e82018-02-24 21:10:57 +01002670_ssl__SSLSocket_get_channel_binding_impl(PySSLSocket *self,
2671 const char *cb_type)
2672/*[clinic end generated code: output=34bac9acb6a61d31 input=08b7e43b99c17d41]*/
Antoine Pitroud6494802011-07-21 01:11:30 +02002673{
Antoine Pitroud6494802011-07-21 01:11:30 +02002674 char buf[PySSL_CB_MAXLEN];
Victor Stinner9ee02032013-06-23 15:08:23 +02002675 size_t len;
Antoine Pitroud6494802011-07-21 01:11:30 +02002676
Christian Heimes141c5e82018-02-24 21:10:57 +01002677 if (strcmp(cb_type, "tls-unique") == 0) {
2678 if (SSL_session_reused(self->ssl) ^ !self->socket_type) {
2679 /* if session is resumed XOR we are the client */
2680 len = SSL_get_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2681 }
2682 else {
2683 /* if a new session XOR we are the server */
2684 len = SSL_get_peer_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2685 }
Antoine Pitroud6494802011-07-21 01:11:30 +02002686 }
2687 else {
Christian Heimes141c5e82018-02-24 21:10:57 +01002688 PyErr_Format(
2689 PyExc_ValueError,
2690 "'%s' channel binding type not implemented",
2691 cb_type
2692 );
2693 return NULL;
Antoine Pitroud6494802011-07-21 01:11:30 +02002694 }
2695
2696 /* It cannot be negative in current OpenSSL version as of July 2011 */
Antoine Pitroud6494802011-07-21 01:11:30 +02002697 if (len == 0)
2698 Py_RETURN_NONE;
2699
Christian Heimes141c5e82018-02-24 21:10:57 +01002700 return PyBytes_FromStringAndSize(buf, len);
Antoine Pitroud6494802011-07-21 01:11:30 +02002701}
2702
Christian Heimes9fb051f2018-09-23 08:32:31 +02002703/*[clinic input]
2704_ssl._SSLSocket.verify_client_post_handshake
2705
2706Initiate TLS 1.3 post-handshake authentication
2707[clinic start generated code]*/
2708
2709static PyObject *
2710_ssl__SSLSocket_verify_client_post_handshake_impl(PySSLSocket *self)
2711/*[clinic end generated code: output=532147f3b1341425 input=6bfa874810a3d889]*/
2712{
2713#ifdef TLS1_3_VERSION
2714 int err = SSL_verify_client_post_handshake(self->ssl);
2715 if (err == 0)
Christian Heimes7f1305e2021-04-17 20:06:38 +02002716 return _setSSLError(get_state_sock(self), NULL, 0, __FILE__, __LINE__);
Christian Heimes9fb051f2018-09-23 08:32:31 +02002717 else
2718 Py_RETURN_NONE;
2719#else
2720 PyErr_SetString(PyExc_NotImplementedError,
2721 "Post-handshake auth is not supported by your "
2722 "OpenSSL version.");
2723 return NULL;
2724#endif
2725}
2726
Christian Heimes99a65702016-09-10 23:44:53 +02002727static SSL_SESSION*
2728_ssl_session_dup(SSL_SESSION *session) {
2729 SSL_SESSION *newsession = NULL;
2730 int slen;
2731 unsigned char *senc = NULL, *p;
2732 const unsigned char *const_p;
2733
2734 if (session == NULL) {
2735 PyErr_SetString(PyExc_ValueError, "Invalid session");
2736 goto error;
2737 }
2738
2739 /* get length */
2740 slen = i2d_SSL_SESSION(session, NULL);
2741 if (slen == 0 || slen > 0xFF00) {
2742 PyErr_SetString(PyExc_ValueError, "i2d() failed.");
2743 goto error;
2744 }
2745 if ((senc = PyMem_Malloc(slen)) == NULL) {
2746 PyErr_NoMemory();
2747 goto error;
2748 }
2749 p = senc;
2750 if (!i2d_SSL_SESSION(session, &p)) {
2751 PyErr_SetString(PyExc_ValueError, "i2d() failed.");
2752 goto error;
2753 }
2754 const_p = senc;
2755 newsession = d2i_SSL_SESSION(NULL, &const_p, slen);
2756 if (session == NULL) {
2757 goto error;
2758 }
2759 PyMem_Free(senc);
2760 return newsession;
2761 error:
2762 if (senc != NULL) {
2763 PyMem_Free(senc);
2764 }
2765 return NULL;
2766}
Christian Heimes99a65702016-09-10 23:44:53 +02002767
2768static PyObject *
2769PySSL_get_session(PySSLSocket *self, void *closure) {
2770 /* get_session can return sessions from a server-side connection,
2771 * it does not check for handshake done or client socket. */
2772 PySSLSession *pysess;
2773 SSL_SESSION *session;
2774
Christian Heimes99a65702016-09-10 23:44:53 +02002775 /* duplicate session as workaround for session bug in OpenSSL 1.1.0,
2776 * https://github.com/openssl/openssl/issues/1550 */
2777 session = SSL_get0_session(self->ssl); /* borrowed reference */
2778 if (session == NULL) {
2779 Py_RETURN_NONE;
2780 }
2781 if ((session = _ssl_session_dup(session)) == NULL) {
2782 return NULL;
2783 }
Christian Heimes99a65702016-09-10 23:44:53 +02002784 session = SSL_get1_session(self->ssl);
2785 if (session == NULL) {
2786 Py_RETURN_NONE;
2787 }
Christian Heimes7f1305e2021-04-17 20:06:38 +02002788 pysess = PyObject_GC_New(PySSLSession, self->ctx->state->PySSLSession_Type);
Christian Heimes99a65702016-09-10 23:44:53 +02002789 if (pysess == NULL) {
2790 SSL_SESSION_free(session);
2791 return NULL;
2792 }
2793
2794 assert(self->ctx);
2795 pysess->ctx = self->ctx;
2796 Py_INCREF(pysess->ctx);
2797 pysess->session = session;
Christian Heimesa5d07652016-09-24 10:48:05 +02002798 PyObject_GC_Track(pysess);
Christian Heimes99a65702016-09-10 23:44:53 +02002799 return (PyObject *)pysess;
2800}
2801
2802static int PySSL_set_session(PySSLSocket *self, PyObject *value,
2803 void *closure)
2804 {
2805 PySSLSession *pysess;
Christian Heimes99a65702016-09-10 23:44:53 +02002806 SSL_SESSION *session;
Christian Heimes99a65702016-09-10 23:44:53 +02002807 int result;
2808
Christian Heimes7f1305e2021-04-17 20:06:38 +02002809 if (!Py_IS_TYPE(value, get_state_sock(self)->PySSLSession_Type)) {
Ned Deily4531ec72018-06-11 20:26:28 -04002810 PyErr_SetString(PyExc_TypeError, "Value is not a SSLSession.");
Christian Heimes99a65702016-09-10 23:44:53 +02002811 return -1;
2812 }
2813 pysess = (PySSLSession *)value;
2814
2815 if (self->ctx->ctx != pysess->ctx->ctx) {
2816 PyErr_SetString(PyExc_ValueError,
2817 "Session refers to a different SSLContext.");
2818 return -1;
2819 }
2820 if (self->socket_type != PY_SSL_CLIENT) {
2821 PyErr_SetString(PyExc_ValueError,
2822 "Cannot set session for server-side SSLSocket.");
2823 return -1;
2824 }
Christian Heimes66dc33b2017-05-23 16:02:02 -07002825 if (SSL_is_init_finished(self->ssl)) {
Christian Heimes99a65702016-09-10 23:44:53 +02002826 PyErr_SetString(PyExc_ValueError,
2827 "Cannot set session after handshake.");
2828 return -1;
2829 }
Christian Heimes99a65702016-09-10 23:44:53 +02002830 /* duplicate session */
2831 if ((session = _ssl_session_dup(pysess->session)) == NULL) {
2832 return -1;
2833 }
2834 result = SSL_set_session(self->ssl, session);
2835 /* free duplicate, SSL_set_session() bumps ref count */
2836 SSL_SESSION_free(session);
Christian Heimes99a65702016-09-10 23:44:53 +02002837 if (result == 0) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02002838 _setSSLError(get_state_sock(self), NULL, 0, __FILE__, __LINE__);
Christian Heimes99a65702016-09-10 23:44:53 +02002839 return -1;
2840 }
2841 return 0;
2842}
2843
2844PyDoc_STRVAR(PySSL_set_session_doc,
2845"_setter_session(session)\n\
2846\
2847Get / set SSLSession.");
2848
2849static PyObject *
2850PySSL_get_session_reused(PySSLSocket *self, void *closure) {
2851 if (SSL_session_reused(self->ssl)) {
2852 Py_RETURN_TRUE;
2853 } else {
2854 Py_RETURN_FALSE;
2855 }
2856}
2857
2858PyDoc_STRVAR(PySSL_get_session_reused_doc,
2859"Was the client session reused during handshake?");
2860
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002861static PyGetSetDef ssl_getsetlist[] = {
2862 {"context", (getter) PySSL_get_context,
2863 (setter) PySSL_set_context, PySSL_set_context_doc},
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002864 {"server_side", (getter) PySSL_get_server_side, NULL,
2865 PySSL_get_server_side_doc},
2866 {"server_hostname", (getter) PySSL_get_server_hostname, NULL,
2867 PySSL_get_server_hostname_doc},
2868 {"owner", (getter) PySSL_get_owner, (setter) PySSL_set_owner,
2869 PySSL_get_owner_doc},
Christian Heimes99a65702016-09-10 23:44:53 +02002870 {"session", (getter) PySSL_get_session,
2871 (setter) PySSL_set_session, PySSL_set_session_doc},
2872 {"session_reused", (getter) PySSL_get_session_reused, NULL,
2873 PySSL_get_session_reused_doc},
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002874 {NULL}, /* sentinel */
2875};
2876
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002877static PyMethodDef PySSLMethods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002878 _SSL__SSLSOCKET_DO_HANDSHAKE_METHODDEF
2879 _SSL__SSLSOCKET_WRITE_METHODDEF
2880 _SSL__SSLSOCKET_READ_METHODDEF
2881 _SSL__SSLSOCKET_PENDING_METHODDEF
Christian Heimes141c5e82018-02-24 21:10:57 +01002882 _SSL__SSLSOCKET_GETPEERCERT_METHODDEF
2883 _SSL__SSLSOCKET_GET_CHANNEL_BINDING_METHODDEF
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002884 _SSL__SSLSOCKET_CIPHER_METHODDEF
2885 _SSL__SSLSOCKET_SHARED_CIPHERS_METHODDEF
2886 _SSL__SSLSOCKET_VERSION_METHODDEF
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002887 _SSL__SSLSOCKET_SELECTED_ALPN_PROTOCOL_METHODDEF
2888 _SSL__SSLSOCKET_COMPRESSION_METHODDEF
2889 _SSL__SSLSOCKET_SHUTDOWN_METHODDEF
Christian Heimes9fb051f2018-09-23 08:32:31 +02002890 _SSL__SSLSOCKET_VERIFY_CLIENT_POST_HANDSHAKE_METHODDEF
Christian Heimes666991f2021-04-26 15:01:40 +02002891 _SSL__SSLSOCKET_GET_UNVERIFIED_CHAIN_METHODDEF
2892 _SSL__SSLSOCKET_GET_VERIFIED_CHAIN_METHODDEF
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002893 {NULL, NULL}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002894};
2895
Christian Heimes5c36da72020-11-20 09:40:12 +01002896static PyType_Slot PySSLSocket_slots[] = {
2897 {Py_tp_methods, PySSLMethods},
2898 {Py_tp_getset, ssl_getsetlist},
2899 {Py_tp_dealloc, PySSL_dealloc},
2900 {Py_tp_traverse, PySSL_traverse},
2901 {Py_tp_clear, PySSL_clear},
2902 {0, 0},
2903};
2904
2905static PyType_Spec PySSLSocket_spec = {
2906 "_ssl._SSLSocket",
2907 sizeof(PySSLSocket),
2908 0,
Christian Heimes91554e42021-05-02 09:47:45 +02002909 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_IMMUTABLETYPE,
Christian Heimes5c36da72020-11-20 09:40:12 +01002910 PySSLSocket_slots,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002911};
2912
Antoine Pitrou152efa22010-05-16 18:19:27 +00002913/*
2914 * _SSLContext objects
2915 */
2916
Christian Heimes5fe668c2016-09-12 00:01:11 +02002917static int
Christian Heimes9fb051f2018-09-23 08:32:31 +02002918_set_verify_mode(PySSLContext *self, enum py_ssl_cert_requirements n)
Christian Heimes5fe668c2016-09-12 00:01:11 +02002919{
2920 int mode;
2921 int (*verify_cb)(int, X509_STORE_CTX *) = NULL;
2922
2923 switch(n) {
2924 case PY_SSL_CERT_NONE:
2925 mode = SSL_VERIFY_NONE;
2926 break;
2927 case PY_SSL_CERT_OPTIONAL:
2928 mode = SSL_VERIFY_PEER;
2929 break;
2930 case PY_SSL_CERT_REQUIRED:
2931 mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
2932 break;
2933 default:
2934 PyErr_SetString(PyExc_ValueError,
2935 "invalid value for verify_mode");
2936 return -1;
2937 }
Christian Heimesf0f59302019-07-01 08:29:17 +02002938
2939 /* bpo-37428: newPySSLSocket() sets SSL_VERIFY_POST_HANDSHAKE flag for
2940 * server sockets and SSL_set_post_handshake_auth() for client. */
2941
Christian Heimes5fe668c2016-09-12 00:01:11 +02002942 /* keep current verify cb */
Christian Heimes9fb051f2018-09-23 08:32:31 +02002943 verify_cb = SSL_CTX_get_verify_callback(self->ctx);
2944 SSL_CTX_set_verify(self->ctx, mode, verify_cb);
Christian Heimes5fe668c2016-09-12 00:01:11 +02002945 return 0;
2946}
2947
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002948/*[clinic input]
2949@classmethod
2950_ssl._SSLContext.__new__
2951 protocol as proto_version: int
2952 /
2953[clinic start generated code]*/
2954
Antoine Pitrou152efa22010-05-16 18:19:27 +00002955static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002956_ssl__SSLContext_impl(PyTypeObject *type, int proto_version)
2957/*[clinic end generated code: output=2cf0d7a0741b6bd1 input=8d58a805b95fc534]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00002958{
Antoine Pitrou152efa22010-05-16 18:19:27 +00002959 PySSLContext *self;
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01002960 long options;
Christian Heimes2875c602021-04-19 07:27:10 +02002961 const SSL_METHOD *method = NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002962 SSL_CTX *ctx = NULL;
Christian Heimes61d478c2018-01-27 15:51:38 +01002963 X509_VERIFY_PARAM *params;
Christian Heimes358cfd42016-09-10 22:43:48 +02002964 int result;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002965
Christian Heimes7f1305e2021-04-17 20:06:38 +02002966 /* slower approach, walk MRO and get borrowed reference to module.
2967 * _PyType_GetModuleByDef is required for SSLContext subclasses */
2968 PyObject *module = _PyType_GetModuleByDef(type, &_sslmodule_def);
2969 if (module == NULL) {
2970 PyErr_SetString(PyExc_RuntimeError,
2971 "Cannot find internal module state");
2972 return NULL;
2973 }
2974
Christian Heimes6e8cda92020-05-16 03:33:05 +02002975 switch(proto_version) {
2976#if defined(SSL3_VERSION) && !defined(OPENSSL_NO_SSL3)
2977 case PY_SSL_VERSION_SSL3:
Christian Heimes2875c602021-04-19 07:27:10 +02002978 PY_SSL_DEPRECATED("PROTOCOL_SSLv3", 2, NULL);
2979 method = SSLv3_method();
Christian Heimes6e8cda92020-05-16 03:33:05 +02002980 break;
Benjamin Petersone32467c2014-12-05 21:59:35 -05002981#endif
Christian Heimesa871f692020-06-01 08:58:14 +02002982#if (defined(TLS1_VERSION) && \
2983 !defined(OPENSSL_NO_TLS1) && \
2984 !defined(OPENSSL_NO_TLS1_METHOD))
Christian Heimes6e8cda92020-05-16 03:33:05 +02002985 case PY_SSL_VERSION_TLS1:
Christian Heimes2875c602021-04-19 07:27:10 +02002986 PY_SSL_DEPRECATED("PROTOCOL_TLSv1", 2, NULL);
2987 method = TLSv1_method();
Christian Heimes6e8cda92020-05-16 03:33:05 +02002988 break;
Victor Stinner3de49192011-05-09 00:42:58 +02002989#endif
Christian Heimesa871f692020-06-01 08:58:14 +02002990#if (defined(TLS1_1_VERSION) && \
2991 !defined(OPENSSL_NO_TLS1_1) && \
2992 !defined(OPENSSL_NO_TLS1_1_METHOD))
Christian Heimes6e8cda92020-05-16 03:33:05 +02002993 case PY_SSL_VERSION_TLS1_1:
Christian Heimes2875c602021-04-19 07:27:10 +02002994 PY_SSL_DEPRECATED("PROTOCOL_TLSv1_1", 2, NULL);
2995 method = TLSv1_1_method();
Christian Heimes6e8cda92020-05-16 03:33:05 +02002996 break;
2997#endif
Christian Heimesa871f692020-06-01 08:58:14 +02002998#if (defined(TLS1_2_VERSION) && \
2999 !defined(OPENSSL_NO_TLS1_2) && \
3000 !defined(OPENSSL_NO_TLS1_2_METHOD))
Christian Heimes6e8cda92020-05-16 03:33:05 +02003001 case PY_SSL_VERSION_TLS1_2:
Christian Heimes2875c602021-04-19 07:27:10 +02003002 PY_SSL_DEPRECATED("PROTOCOL_TLSv1_2", 2, NULL);
3003 method = TLSv1_2_method();
Christian Heimes6e8cda92020-05-16 03:33:05 +02003004 break;
3005#endif
3006 case PY_SSL_VERSION_TLS:
Christian Heimes2875c602021-04-19 07:27:10 +02003007 PY_SSL_DEPRECATED("PROTOCOL_TLS", 2, NULL);
3008 method = TLS_method();
Christian Heimes6e8cda92020-05-16 03:33:05 +02003009 break;
3010 case PY_SSL_VERSION_TLS_CLIENT:
Christian Heimes2875c602021-04-19 07:27:10 +02003011 method = TLS_client_method();
Christian Heimes6e8cda92020-05-16 03:33:05 +02003012 break;
3013 case PY_SSL_VERSION_TLS_SERVER:
Christian Heimes2875c602021-04-19 07:27:10 +02003014 method = TLS_server_method();
Christian Heimes6e8cda92020-05-16 03:33:05 +02003015 break;
3016 default:
Christian Heimes2875c602021-04-19 07:27:10 +02003017 method = NULL;
Christian Heimes6e8cda92020-05-16 03:33:05 +02003018 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003019
Christian Heimes2875c602021-04-19 07:27:10 +02003020 if (method == NULL) {
3021 PyErr_Format(PyExc_ValueError,
3022 "invalid or unsupported protocol version %i",
3023 proto_version);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003024 return NULL;
3025 }
Christian Heimes2875c602021-04-19 07:27:10 +02003026
3027 PySSL_BEGIN_ALLOW_THREADS
3028 ctx = SSL_CTX_new(method);
3029 PySSL_END_ALLOW_THREADS
3030
Antoine Pitrou152efa22010-05-16 18:19:27 +00003031 if (ctx == NULL) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02003032 _setSSLError(get_ssl_state(module), NULL, 0, __FILE__, __LINE__);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003033 return NULL;
3034 }
3035
3036 assert(type != NULL && type->tp_alloc != NULL);
3037 self = (PySSLContext *) type->tp_alloc(type, 0);
3038 if (self == NULL) {
3039 SSL_CTX_free(ctx);
3040 return NULL;
3041 }
3042 self->ctx = ctx;
Christian Heimes61d478c2018-01-27 15:51:38 +01003043 self->hostflags = X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS;
Christian Heimes11a14932018-02-24 02:35:08 +01003044 self->protocol = proto_version;
Christian Heimesc7f70692019-05-31 11:44:05 +02003045 self->msg_cb = NULL;
Christian Heimesc7f70692019-05-31 11:44:05 +02003046 self->keylog_filename = NULL;
3047 self->keylog_bio = NULL;
Benjamin Petersoncca27322015-01-23 16:35:37 -05003048 self->alpn_protocols = NULL;
Christian Heimes11a14932018-02-24 02:35:08 +01003049 self->set_sni_cb = NULL;
Christian Heimes7f1305e2021-04-17 20:06:38 +02003050 self->state = get_ssl_state(module);
3051
Christian Heimes1aa9a752013-12-02 02:41:19 +01003052 /* Don't check host name by default */
Christian Heimes5fe668c2016-09-12 00:01:11 +02003053 if (proto_version == PY_SSL_VERSION_TLS_CLIENT) {
3054 self->check_hostname = 1;
Christian Heimes9fb051f2018-09-23 08:32:31 +02003055 if (_set_verify_mode(self, PY_SSL_CERT_REQUIRED) == -1) {
Christian Heimes5fe668c2016-09-12 00:01:11 +02003056 Py_DECREF(self);
3057 return NULL;
3058 }
3059 } else {
3060 self->check_hostname = 0;
Christian Heimes9fb051f2018-09-23 08:32:31 +02003061 if (_set_verify_mode(self, PY_SSL_CERT_NONE) == -1) {
Christian Heimes5fe668c2016-09-12 00:01:11 +02003062 Py_DECREF(self);
3063 return NULL;
3064 }
3065 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003066 /* Defaults */
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01003067 options = SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
3068 if (proto_version != PY_SSL_VERSION_SSL2)
3069 options |= SSL_OP_NO_SSLv2;
Benjamin Petersona9dcdab2015-11-11 22:38:41 -08003070 if (proto_version != PY_SSL_VERSION_SSL3)
3071 options |= SSL_OP_NO_SSLv3;
Christian Heimes358cfd42016-09-10 22:43:48 +02003072 /* Minimal security flags for server and client side context.
3073 * Client sockets ignore server-side parameters. */
3074#ifdef SSL_OP_NO_COMPRESSION
3075 options |= SSL_OP_NO_COMPRESSION;
3076#endif
3077#ifdef SSL_OP_CIPHER_SERVER_PREFERENCE
3078 options |= SSL_OP_CIPHER_SERVER_PREFERENCE;
3079#endif
3080#ifdef SSL_OP_SINGLE_DH_USE
3081 options |= SSL_OP_SINGLE_DH_USE;
3082#endif
3083#ifdef SSL_OP_SINGLE_ECDH_USE
3084 options |= SSL_OP_SINGLE_ECDH_USE;
3085#endif
Christian Heimes6f37ebc2021-04-09 17:59:21 +02003086#ifdef SSL_OP_IGNORE_UNEXPECTED_EOF
3087 /* Make OpenSSL 3.0.0 behave like 1.1.1 */
3088 options |= SSL_OP_IGNORE_UNEXPECTED_EOF;
3089#endif
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01003090 SSL_CTX_set_options(self->ctx, options);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003091
Semen Zhydenko1295e112017-10-15 21:28:31 +02003092 /* A bare minimum cipher list without completely broken cipher suites.
Christian Heimes358cfd42016-09-10 22:43:48 +02003093 * It's far from perfect but gives users a better head start. */
3094 if (proto_version != PY_SSL_VERSION_SSL2) {
Christian Heimes892d66e2018-01-29 14:10:18 +01003095#if PY_SSL_DEFAULT_CIPHERS == 2
3096 /* stick to OpenSSL's default settings */
3097 result = 1;
3098#else
3099 result = SSL_CTX_set_cipher_list(ctx, PY_SSL_DEFAULT_CIPHER_STRING);
3100#endif
Christian Heimes358cfd42016-09-10 22:43:48 +02003101 } else {
3102 /* SSLv2 needs MD5 */
3103 result = SSL_CTX_set_cipher_list(ctx, "HIGH:!aNULL:!eNULL");
3104 }
3105 if (result == 0) {
3106 Py_DECREF(self);
3107 ERR_clear_error();
Christian Heimes7f1305e2021-04-17 20:06:38 +02003108 PyErr_SetString(get_state_ctx(self)->PySSLErrorObject,
Christian Heimes358cfd42016-09-10 22:43:48 +02003109 "No cipher can be selected.");
Christian Heimese9832522021-05-01 20:53:10 +02003110 goto error;
Christian Heimes358cfd42016-09-10 22:43:48 +02003111 }
Christian Heimese9832522021-05-01 20:53:10 +02003112#ifdef PY_SSL_MIN_PROTOCOL
3113 switch(proto_version) {
3114 case PY_SSL_VERSION_TLS:
3115 case PY_SSL_VERSION_TLS_CLIENT:
3116 case PY_SSL_VERSION_TLS_SERVER:
3117 result = SSL_CTX_set_min_proto_version(ctx, PY_SSL_MIN_PROTOCOL);
3118 if (result == 0) {
3119 PyErr_Format(PyExc_ValueError,
3120 "Failed to set minimum protocol 0x%x",
3121 PY_SSL_MIN_PROTOCOL);
3122 goto error;
3123 }
3124 break;
3125 default:
3126 break;
3127 }
3128#endif
Christian Heimes358cfd42016-09-10 22:43:48 +02003129
Benjamin Peterson3b1a8b32016-01-07 21:37:37 -08003130 /* Set SSL_MODE_RELEASE_BUFFERS. This potentially greatly reduces memory
Christian Heimes39258d32021-04-17 11:36:35 +02003131 usage for no cost at all. */
3132 SSL_CTX_set_mode(self->ctx, SSL_MODE_RELEASE_BUFFERS);
Antoine Pitrou0bebbc32014-03-22 18:13:50 +01003133
Antoine Pitroufc113ee2010-10-13 12:46:13 +00003134#define SID_CTX "Python"
3135 SSL_CTX_set_session_id_context(self->ctx, (const unsigned char *) SID_CTX,
3136 sizeof(SID_CTX));
3137#undef SID_CTX
3138
Christian Heimes61d478c2018-01-27 15:51:38 +01003139 params = SSL_CTX_get0_param(self->ctx);
Christian Heimes61d478c2018-01-27 15:51:38 +01003140 /* Improve trust chain building when cross-signed intermediate
3141 certificates are present. See https://bugs.python.org/issue23476. */
3142 X509_VERIFY_PARAM_set_flags(params, X509_V_FLAG_TRUSTED_FIRST);
Christian Heimes61d478c2018-01-27 15:51:38 +01003143 X509_VERIFY_PARAM_set_hostflags(params, self->hostflags);
Benjamin Petersonfdb19712015-03-04 22:11:12 -05003144
Christian Heimes9fb051f2018-09-23 08:32:31 +02003145#ifdef TLS1_3_VERSION
3146 self->post_handshake_auth = 0;
3147 SSL_CTX_set_post_handshake_auth(self->ctx, self->post_handshake_auth);
3148#endif
3149
Antoine Pitrou152efa22010-05-16 18:19:27 +00003150 return (PyObject *)self;
Christian Heimese9832522021-05-01 20:53:10 +02003151 error:
3152 Py_XDECREF(self);
3153 ERR_clear_error();
3154 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003155}
3156
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003157static int
3158context_traverse(PySSLContext *self, visitproc visit, void *arg)
3159{
Christian Heimes11a14932018-02-24 02:35:08 +01003160 Py_VISIT(self->set_sni_cb);
Christian Heimesc7f70692019-05-31 11:44:05 +02003161 Py_VISIT(self->msg_cb);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003162 return 0;
3163}
3164
3165static int
3166context_clear(PySSLContext *self)
3167{
Christian Heimes11a14932018-02-24 02:35:08 +01003168 Py_CLEAR(self->set_sni_cb);
Christian Heimesc7f70692019-05-31 11:44:05 +02003169 Py_CLEAR(self->msg_cb);
Christian Heimesc7f70692019-05-31 11:44:05 +02003170 Py_CLEAR(self->keylog_filename);
3171 if (self->keylog_bio != NULL) {
3172 PySSL_BEGIN_ALLOW_THREADS
3173 BIO_free_all(self->keylog_bio);
3174 PySSL_END_ALLOW_THREADS
3175 self->keylog_bio = NULL;
3176 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003177 return 0;
3178}
3179
Antoine Pitrou152efa22010-05-16 18:19:27 +00003180static void
3181context_dealloc(PySSLContext *self)
3182{
Christian Heimes5c36da72020-11-20 09:40:12 +01003183 PyTypeObject *tp = Py_TYPE(self);
INADA Naokia6296d32017-08-24 14:55:17 +09003184 /* bpo-31095: UnTrack is needed before calling any callbacks */
3185 PyObject_GC_UnTrack(self);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003186 context_clear(self);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003187 SSL_CTX_free(self->ctx);
Christian Heimes39258d32021-04-17 11:36:35 +02003188 PyMem_FREE(self->alpn_protocols);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003189 Py_TYPE(self)->tp_free(self);
Christian Heimes5c36da72020-11-20 09:40:12 +01003190 Py_DECREF(tp);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003191}
3192
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003193/*[clinic input]
3194_ssl._SSLContext.set_ciphers
3195 cipherlist: str
3196 /
3197[clinic start generated code]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003198
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003199static PyObject *
3200_ssl__SSLContext_set_ciphers_impl(PySSLContext *self, const char *cipherlist)
3201/*[clinic end generated code: output=3a3162f3557c0f3f input=a7ac931b9f3ca7fc]*/
3202{
3203 int ret = SSL_CTX_set_cipher_list(self->ctx, cipherlist);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003204 if (ret == 0) {
Antoine Pitrou65ec8ae2010-05-16 19:56:32 +00003205 /* Clearing the error queue is necessary on some OpenSSL versions,
3206 otherwise the error will be reported again when another SSL call
3207 is done. */
3208 ERR_clear_error();
Christian Heimes7f1305e2021-04-17 20:06:38 +02003209 PyErr_SetString(get_state_ctx(self)->PySSLErrorObject,
Antoine Pitrou152efa22010-05-16 18:19:27 +00003210 "No cipher can be selected.");
3211 return NULL;
3212 }
3213 Py_RETURN_NONE;
3214}
3215
Christian Heimes25bfcd52016-09-06 00:04:45 +02003216/*[clinic input]
3217_ssl._SSLContext.get_ciphers
3218[clinic start generated code]*/
3219
3220static PyObject *
3221_ssl__SSLContext_get_ciphers_impl(PySSLContext *self)
3222/*[clinic end generated code: output=a56e4d68a406dfc4 input=a2aadc9af89b79c5]*/
3223{
3224 SSL *ssl = NULL;
3225 STACK_OF(SSL_CIPHER) *sk = NULL;
Christian Heimes99a65702016-09-10 23:44:53 +02003226 const SSL_CIPHER *cipher;
Christian Heimes25bfcd52016-09-06 00:04:45 +02003227 int i=0;
3228 PyObject *result = NULL, *dct;
3229
3230 ssl = SSL_new(self->ctx);
3231 if (ssl == NULL) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02003232 _setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
Christian Heimes25bfcd52016-09-06 00:04:45 +02003233 goto exit;
3234 }
3235 sk = SSL_get_ciphers(ssl);
3236
3237 result = PyList_New(sk_SSL_CIPHER_num(sk));
3238 if (result == NULL) {
3239 goto exit;
3240 }
3241
3242 for (i = 0; i < sk_SSL_CIPHER_num(sk); i++) {
3243 cipher = sk_SSL_CIPHER_value(sk, i);
3244 dct = cipher_to_dict(cipher);
3245 if (dct == NULL) {
3246 Py_CLEAR(result);
3247 goto exit;
3248 }
3249 PyList_SET_ITEM(result, i, dct);
3250 }
3251
3252 exit:
3253 if (ssl != NULL)
3254 SSL_free(ssl);
3255 return result;
3256
3257}
Christian Heimes25bfcd52016-09-06 00:04:45 +02003258
3259
Benjamin Petersoncca27322015-01-23 16:35:37 -05003260static int
Benjamin Peterson88615022015-01-23 17:30:26 -05003261do_protocol_selection(int alpn, unsigned char **out, unsigned char *outlen,
3262 const unsigned char *server_protocols, unsigned int server_protocols_len,
3263 const unsigned char *client_protocols, unsigned int client_protocols_len)
Benjamin Petersoncca27322015-01-23 16:35:37 -05003264{
Benjamin Peterson88615022015-01-23 17:30:26 -05003265 int ret;
3266 if (client_protocols == NULL) {
3267 client_protocols = (unsigned char *)"";
3268 client_protocols_len = 0;
3269 }
3270 if (server_protocols == NULL) {
3271 server_protocols = (unsigned char *)"";
3272 server_protocols_len = 0;
Benjamin Petersoncca27322015-01-23 16:35:37 -05003273 }
3274
Benjamin Peterson88615022015-01-23 17:30:26 -05003275 ret = SSL_select_next_proto(out, outlen,
3276 server_protocols, server_protocols_len,
3277 client_protocols, client_protocols_len);
3278 if (alpn && ret != OPENSSL_NPN_NEGOTIATED)
3279 return SSL_TLSEXT_ERR_NOACK;
Benjamin Petersoncca27322015-01-23 16:35:37 -05003280
3281 return SSL_TLSEXT_ERR_OK;
3282}
3283
Benjamin Petersoncca27322015-01-23 16:35:37 -05003284static int
3285_selectALPN_cb(SSL *s,
3286 const unsigned char **out, unsigned char *outlen,
3287 const unsigned char *client_protocols, unsigned int client_protocols_len,
3288 void *args)
3289{
3290 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Peterson88615022015-01-23 17:30:26 -05003291 return do_protocol_selection(1, (unsigned char **)out, outlen,
3292 ctx->alpn_protocols, ctx->alpn_protocols_len,
3293 client_protocols, client_protocols_len);
Benjamin Petersoncca27322015-01-23 16:35:37 -05003294}
Benjamin Petersoncca27322015-01-23 16:35:37 -05003295
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003296/*[clinic input]
3297_ssl._SSLContext._set_alpn_protocols
3298 protos: Py_buffer
3299 /
3300[clinic start generated code]*/
3301
Benjamin Petersoncca27322015-01-23 16:35:37 -05003302static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003303_ssl__SSLContext__set_alpn_protocols_impl(PySSLContext *self,
3304 Py_buffer *protos)
3305/*[clinic end generated code: output=87599a7f76651a9b input=9bba964595d519be]*/
Benjamin Petersoncca27322015-01-23 16:35:37 -05003306{
Victor Stinner5a615592017-09-14 01:10:30 -07003307 if ((size_t)protos->len > UINT_MAX) {
Segev Finer5cff6372017-07-27 01:19:17 +03003308 PyErr_Format(PyExc_OverflowError,
Serhiy Storchakad53fe5f2019-03-13 22:59:55 +02003309 "protocols longer than %u bytes", UINT_MAX);
Segev Finer5cff6372017-07-27 01:19:17 +03003310 return NULL;
3311 }
3312
Victor Stinner00d7abd2020-12-01 09:56:42 +01003313 PyMem_Free(self->alpn_protocols);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003314 self->alpn_protocols = PyMem_Malloc(protos->len);
Benjamin Petersoncca27322015-01-23 16:35:37 -05003315 if (!self->alpn_protocols)
3316 return PyErr_NoMemory();
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003317 memcpy(self->alpn_protocols, protos->buf, protos->len);
Segev Finer5cff6372017-07-27 01:19:17 +03003318 self->alpn_protocols_len = (unsigned int)protos->len;
Benjamin Petersoncca27322015-01-23 16:35:37 -05003319
3320 if (SSL_CTX_set_alpn_protos(self->ctx, self->alpn_protocols, self->alpn_protocols_len))
3321 return PyErr_NoMemory();
3322 SSL_CTX_set_alpn_select_cb(self->ctx, _selectALPN_cb, self);
3323
Benjamin Petersoncca27322015-01-23 16:35:37 -05003324 Py_RETURN_NONE;
Benjamin Petersoncca27322015-01-23 16:35:37 -05003325}
3326
Antoine Pitrou152efa22010-05-16 18:19:27 +00003327static PyObject *
3328get_verify_mode(PySSLContext *self, void *c)
3329{
Christian Heimes9fb051f2018-09-23 08:32:31 +02003330 /* ignore SSL_VERIFY_CLIENT_ONCE and SSL_VERIFY_POST_HANDSHAKE */
3331 int mask = (SSL_VERIFY_NONE | SSL_VERIFY_PEER |
3332 SSL_VERIFY_FAIL_IF_NO_PEER_CERT);
3333 switch (SSL_CTX_get_verify_mode(self->ctx) & mask) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003334 case SSL_VERIFY_NONE:
3335 return PyLong_FromLong(PY_SSL_CERT_NONE);
3336 case SSL_VERIFY_PEER:
3337 return PyLong_FromLong(PY_SSL_CERT_OPTIONAL);
3338 case SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT:
3339 return PyLong_FromLong(PY_SSL_CERT_REQUIRED);
3340 }
Christian Heimes7f1305e2021-04-17 20:06:38 +02003341 PyErr_SetString(get_state_ctx(self)->PySSLErrorObject,
Antoine Pitrou152efa22010-05-16 18:19:27 +00003342 "invalid return value from SSL_CTX_get_verify_mode");
3343 return NULL;
3344}
3345
3346static int
3347set_verify_mode(PySSLContext *self, PyObject *arg, void *c)
3348{
Christian Heimes5fe668c2016-09-12 00:01:11 +02003349 int n;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003350 if (!PyArg_Parse(arg, "i", &n))
3351 return -1;
Christian Heimes5fe668c2016-09-12 00:01:11 +02003352 if (n == PY_SSL_CERT_NONE && self->check_hostname) {
Christian Heimes1aa9a752013-12-02 02:41:19 +01003353 PyErr_SetString(PyExc_ValueError,
3354 "Cannot set verify_mode to CERT_NONE when "
3355 "check_hostname is enabled.");
3356 return -1;
3357 }
Christian Heimes9fb051f2018-09-23 08:32:31 +02003358 return _set_verify_mode(self, n);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003359}
3360
3361static PyObject *
Christian Heimes22587792013-11-21 23:56:13 +01003362get_verify_flags(PySSLContext *self, void *c)
3363{
Christian Heimes598894f2016-09-05 23:19:05 +02003364 X509_VERIFY_PARAM *param;
Christian Heimes22587792013-11-21 23:56:13 +01003365 unsigned long flags;
3366
Christian Heimes61d478c2018-01-27 15:51:38 +01003367 param = SSL_CTX_get0_param(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02003368 flags = X509_VERIFY_PARAM_get_flags(param);
Christian Heimes22587792013-11-21 23:56:13 +01003369 return PyLong_FromUnsignedLong(flags);
3370}
3371
3372static int
3373set_verify_flags(PySSLContext *self, PyObject *arg, void *c)
3374{
Christian Heimes598894f2016-09-05 23:19:05 +02003375 X509_VERIFY_PARAM *param;
Christian Heimes22587792013-11-21 23:56:13 +01003376 unsigned long new_flags, flags, set, clear;
3377
3378 if (!PyArg_Parse(arg, "k", &new_flags))
3379 return -1;
Christian Heimes61d478c2018-01-27 15:51:38 +01003380 param = SSL_CTX_get0_param(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02003381 flags = X509_VERIFY_PARAM_get_flags(param);
Christian Heimes22587792013-11-21 23:56:13 +01003382 clear = flags & ~new_flags;
3383 set = ~flags & new_flags;
3384 if (clear) {
Christian Heimes598894f2016-09-05 23:19:05 +02003385 if (!X509_VERIFY_PARAM_clear_flags(param, clear)) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02003386 _setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
Christian Heimes22587792013-11-21 23:56:13 +01003387 return -1;
3388 }
3389 }
3390 if (set) {
Christian Heimes598894f2016-09-05 23:19:05 +02003391 if (!X509_VERIFY_PARAM_set_flags(param, set)) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02003392 _setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
Christian Heimes22587792013-11-21 23:56:13 +01003393 return -1;
3394 }
3395 }
3396 return 0;
3397}
3398
Christian Heimes698dde12018-02-27 11:54:43 +01003399/* Getter and setter for protocol version */
Christian Heimes698dde12018-02-27 11:54:43 +01003400static int
3401set_min_max_proto_version(PySSLContext *self, PyObject *arg, int what)
3402{
3403 long v;
3404 int result;
3405
3406 if (!PyArg_Parse(arg, "l", &v))
3407 return -1;
3408 if (v > INT_MAX) {
3409 PyErr_SetString(PyExc_OverflowError, "Option is too long");
3410 return -1;
3411 }
3412
3413 switch(self->protocol) {
3414 case PY_SSL_VERSION_TLS_CLIENT: /* fall through */
3415 case PY_SSL_VERSION_TLS_SERVER: /* fall through */
3416 case PY_SSL_VERSION_TLS:
3417 break;
3418 default:
3419 PyErr_SetString(
3420 PyExc_ValueError,
3421 "The context's protocol doesn't support modification of "
3422 "highest and lowest version."
3423 );
3424 return -1;
3425 }
3426
Christian Heimes2875c602021-04-19 07:27:10 +02003427 /* check for deprecations and supported values */
3428 switch(v) {
3429 case PY_PROTO_SSLv3:
3430 PY_SSL_DEPRECATED("TLSVersion.SSLv3", 2, -1);
3431 break;
3432 case PY_PROTO_TLSv1:
3433 PY_SSL_DEPRECATED("TLSVersion.TLSv1", 2, -1);
3434 break;
3435 case PY_PROTO_TLSv1_1:
3436 PY_SSL_DEPRECATED("TLSVersion.TLSv1_1", 2, -1);
3437 break;
3438 case PY_PROTO_MINIMUM_SUPPORTED:
3439 case PY_PROTO_MAXIMUM_SUPPORTED:
3440 case PY_PROTO_TLSv1_2:
3441 case PY_PROTO_TLSv1_3:
3442 /* ok */
3443 break;
3444 default:
3445 PyErr_Format(PyExc_ValueError,
3446 "Unsupported TLS/SSL version 0x%x", v);
3447 return -1;
3448 }
3449
Christian Heimes698dde12018-02-27 11:54:43 +01003450 if (what == 0) {
3451 switch(v) {
3452 case PY_PROTO_MINIMUM_SUPPORTED:
3453 v = 0;
3454 break;
3455 case PY_PROTO_MAXIMUM_SUPPORTED:
3456 /* Emulate max for set_min_proto_version */
3457 v = PY_PROTO_MAXIMUM_AVAILABLE;
3458 break;
3459 default:
3460 break;
3461 }
3462 result = SSL_CTX_set_min_proto_version(self->ctx, v);
3463 }
3464 else {
3465 switch(v) {
3466 case PY_PROTO_MAXIMUM_SUPPORTED:
3467 v = 0;
3468 break;
3469 case PY_PROTO_MINIMUM_SUPPORTED:
3470 /* Emulate max for set_min_proto_version */
3471 v = PY_PROTO_MINIMUM_AVAILABLE;
3472 break;
3473 default:
3474 break;
3475 }
3476 result = SSL_CTX_set_max_proto_version(self->ctx, v);
3477 }
3478 if (result == 0) {
3479 PyErr_Format(PyExc_ValueError,
3480 "Unsupported protocol version 0x%x", v);
3481 return -1;
3482 }
3483 return 0;
3484}
3485
3486static PyObject *
3487get_minimum_version(PySSLContext *self, void *c)
3488{
3489 int v = SSL_CTX_ctrl(self->ctx, SSL_CTRL_GET_MIN_PROTO_VERSION, 0, NULL);
3490 if (v == 0) {
3491 v = PY_PROTO_MINIMUM_SUPPORTED;
3492 }
3493 return PyLong_FromLong(v);
3494}
3495
3496static int
3497set_minimum_version(PySSLContext *self, PyObject *arg, void *c)
3498{
3499 return set_min_max_proto_version(self, arg, 0);
3500}
3501
3502static PyObject *
3503get_maximum_version(PySSLContext *self, void *c)
3504{
3505 int v = SSL_CTX_ctrl(self->ctx, SSL_CTRL_GET_MAX_PROTO_VERSION, 0, NULL);
3506 if (v == 0) {
3507 v = PY_PROTO_MAXIMUM_SUPPORTED;
3508 }
3509 return PyLong_FromLong(v);
3510}
3511
3512static int
3513set_maximum_version(PySSLContext *self, PyObject *arg, void *c)
3514{
3515 return set_min_max_proto_version(self, arg, 1);
3516}
Christian Heimes698dde12018-02-27 11:54:43 +01003517
Christian Heimes39258d32021-04-17 11:36:35 +02003518#ifdef TLS1_3_VERSION
Christian Heimes78c7d522019-06-03 21:00:10 +02003519static PyObject *
3520get_num_tickets(PySSLContext *self, void *c)
3521{
Victor Stinner76611c72019-07-09 13:30:52 +02003522 return PyLong_FromSize_t(SSL_CTX_get_num_tickets(self->ctx));
Christian Heimes78c7d522019-06-03 21:00:10 +02003523}
3524
3525static int
3526set_num_tickets(PySSLContext *self, PyObject *arg, void *c)
3527{
3528 long num;
3529 if (!PyArg_Parse(arg, "l", &num))
3530 return -1;
3531 if (num < 0) {
3532 PyErr_SetString(PyExc_ValueError, "value must be non-negative");
3533 return -1;
3534 }
3535 if (self->protocol != PY_SSL_VERSION_TLS_SERVER) {
3536 PyErr_SetString(PyExc_ValueError,
3537 "SSLContext is not a server context.");
3538 return -1;
3539 }
3540 if (SSL_CTX_set_num_tickets(self->ctx, num) != 1) {
3541 PyErr_SetString(PyExc_ValueError, "failed to set num tickets.");
3542 return -1;
3543 }
3544 return 0;
3545}
3546
3547PyDoc_STRVAR(PySSLContext_num_tickets_doc,
3548"Control the number of TLSv1.3 session tickets");
Christian Heimes39258d32021-04-17 11:36:35 +02003549#endif /* TLS1_3_VERSION */
Christian Heimes78c7d522019-06-03 21:00:10 +02003550
matthewhughes9348e836bb2020-07-17 09:59:15 +01003551static PyObject *
3552get_security_level(PySSLContext *self, void *c)
3553{
3554 return PyLong_FromLong(SSL_CTX_get_security_level(self->ctx));
3555}
3556PyDoc_STRVAR(PySSLContext_security_level_doc, "The current security level");
matthewhughes9348e836bb2020-07-17 09:59:15 +01003557
Christian Heimes22587792013-11-21 23:56:13 +01003558static PyObject *
Antoine Pitroub5218772010-05-21 09:56:06 +00003559get_options(PySSLContext *self, void *c)
3560{
3561 return PyLong_FromLong(SSL_CTX_get_options(self->ctx));
3562}
3563
3564static int
3565set_options(PySSLContext *self, PyObject *arg, void *c)
3566{
3567 long new_opts, opts, set, clear;
Christian Heimes2875c602021-04-19 07:27:10 +02003568 long opt_no = (
3569 SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1 |
3570 SSL_OP_NO_TLSv1_1 | SSL_OP_NO_TLSv1_2 | SSL_OP_NO_TLSv1_2
3571 );
3572
Antoine Pitroub5218772010-05-21 09:56:06 +00003573 if (!PyArg_Parse(arg, "l", &new_opts))
3574 return -1;
3575 opts = SSL_CTX_get_options(self->ctx);
3576 clear = opts & ~new_opts;
3577 set = ~opts & new_opts;
Christian Heimes2875c602021-04-19 07:27:10 +02003578
3579 if ((set & opt_no) != 0) {
3580 if (_ssl_deprecated("Setting OP_NO_SSL* or SSL_NO_TLS* options is "
3581 "deprecated", 2) < 0) {
3582 return -1;
3583 }
3584 }
Antoine Pitroub5218772010-05-21 09:56:06 +00003585 if (clear) {
Antoine Pitroub5218772010-05-21 09:56:06 +00003586 SSL_CTX_clear_options(self->ctx, clear);
Antoine Pitroub5218772010-05-21 09:56:06 +00003587 }
3588 if (set)
3589 SSL_CTX_set_options(self->ctx, set);
3590 return 0;
3591}
3592
Christian Heimes1aa9a752013-12-02 02:41:19 +01003593static PyObject *
Christian Heimes61d478c2018-01-27 15:51:38 +01003594get_host_flags(PySSLContext *self, void *c)
3595{
3596 return PyLong_FromUnsignedLong(self->hostflags);
3597}
3598
3599static int
3600set_host_flags(PySSLContext *self, PyObject *arg, void *c)
3601{
3602 X509_VERIFY_PARAM *param;
3603 unsigned int new_flags = 0;
3604
3605 if (!PyArg_Parse(arg, "I", &new_flags))
3606 return -1;
3607
3608 param = SSL_CTX_get0_param(self->ctx);
3609 self->hostflags = new_flags;
3610 X509_VERIFY_PARAM_set_hostflags(param, new_flags);
3611 return 0;
3612}
3613
3614static PyObject *
Christian Heimes1aa9a752013-12-02 02:41:19 +01003615get_check_hostname(PySSLContext *self, void *c)
3616{
3617 return PyBool_FromLong(self->check_hostname);
3618}
3619
3620static int
3621set_check_hostname(PySSLContext *self, PyObject *arg, void *c)
3622{
3623 int check_hostname;
3624 if (!PyArg_Parse(arg, "p", &check_hostname))
3625 return -1;
3626 if (check_hostname &&
3627 SSL_CTX_get_verify_mode(self->ctx) == SSL_VERIFY_NONE) {
Christian Heimese82c0342017-09-15 20:29:57 +02003628 /* check_hostname = True sets verify_mode = CERT_REQUIRED */
Christian Heimes9fb051f2018-09-23 08:32:31 +02003629 if (_set_verify_mode(self, PY_SSL_CERT_REQUIRED) == -1) {
Christian Heimese82c0342017-09-15 20:29:57 +02003630 return -1;
3631 }
Christian Heimes1aa9a752013-12-02 02:41:19 +01003632 }
3633 self->check_hostname = check_hostname;
3634 return 0;
3635}
3636
Christian Heimes11a14932018-02-24 02:35:08 +01003637static PyObject *
Christian Heimes9fb051f2018-09-23 08:32:31 +02003638get_post_handshake_auth(PySSLContext *self, void *c) {
3639#if TLS1_3_VERSION
3640 return PyBool_FromLong(self->post_handshake_auth);
3641#else
3642 Py_RETURN_NONE;
3643#endif
3644}
3645
3646#if TLS1_3_VERSION
3647static int
3648set_post_handshake_auth(PySSLContext *self, PyObject *arg, void *c) {
Zackery Spytz842acaa2018-12-17 07:52:45 -07003649 if (arg == NULL) {
3650 PyErr_SetString(PyExc_AttributeError, "cannot delete attribute");
3651 return -1;
3652 }
Christian Heimes9fb051f2018-09-23 08:32:31 +02003653 int pha = PyObject_IsTrue(arg);
3654
3655 if (pha == -1) {
3656 return -1;
3657 }
3658 self->post_handshake_auth = pha;
3659
Christian Heimesf0f59302019-07-01 08:29:17 +02003660 /* bpo-37428: newPySSLSocket() sets SSL_VERIFY_POST_HANDSHAKE flag for
3661 * server sockets and SSL_set_post_handshake_auth() for client. */
Christian Heimes9fb051f2018-09-23 08:32:31 +02003662
3663 return 0;
3664}
3665#endif
3666
3667static PyObject *
Christian Heimes11a14932018-02-24 02:35:08 +01003668get_protocol(PySSLContext *self, void *c) {
3669 return PyLong_FromLong(self->protocol);
3670}
Christian Heimes1aa9a752013-12-02 02:41:19 +01003671
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003672typedef struct {
3673 PyThreadState *thread_state;
3674 PyObject *callable;
3675 char *password;
Victor Stinner9ee02032013-06-23 15:08:23 +02003676 int size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003677 int error;
3678} _PySSLPasswordInfo;
3679
3680static int
3681_pwinfo_set(_PySSLPasswordInfo *pw_info, PyObject* password,
3682 const char *bad_type_error)
3683{
3684 /* Set the password and size fields of a _PySSLPasswordInfo struct
3685 from a unicode, bytes, or byte array object.
3686 The password field will be dynamically allocated and must be freed
3687 by the caller */
3688 PyObject *password_bytes = NULL;
3689 const char *data = NULL;
3690 Py_ssize_t size;
3691
3692 if (PyUnicode_Check(password)) {
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03003693 password_bytes = PyUnicode_AsUTF8String(password);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003694 if (!password_bytes) {
3695 goto error;
3696 }
3697 data = PyBytes_AS_STRING(password_bytes);
3698 size = PyBytes_GET_SIZE(password_bytes);
3699 } else if (PyBytes_Check(password)) {
3700 data = PyBytes_AS_STRING(password);
3701 size = PyBytes_GET_SIZE(password);
3702 } else if (PyByteArray_Check(password)) {
3703 data = PyByteArray_AS_STRING(password);
3704 size = PyByteArray_GET_SIZE(password);
3705 } else {
3706 PyErr_SetString(PyExc_TypeError, bad_type_error);
3707 goto error;
3708 }
3709
Victor Stinner9ee02032013-06-23 15:08:23 +02003710 if (size > (Py_ssize_t)INT_MAX) {
3711 PyErr_Format(PyExc_ValueError,
3712 "password cannot be longer than %d bytes", INT_MAX);
3713 goto error;
3714 }
3715
Victor Stinner11ebff22013-07-07 17:07:52 +02003716 PyMem_Free(pw_info->password);
3717 pw_info->password = PyMem_Malloc(size);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003718 if (!pw_info->password) {
3719 PyErr_SetString(PyExc_MemoryError,
3720 "unable to allocate password buffer");
3721 goto error;
3722 }
3723 memcpy(pw_info->password, data, size);
Victor Stinner9ee02032013-06-23 15:08:23 +02003724 pw_info->size = (int)size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003725
3726 Py_XDECREF(password_bytes);
3727 return 1;
3728
3729error:
3730 Py_XDECREF(password_bytes);
3731 return 0;
3732}
3733
3734static int
3735_password_callback(char *buf, int size, int rwflag, void *userdata)
3736{
3737 _PySSLPasswordInfo *pw_info = (_PySSLPasswordInfo*) userdata;
3738 PyObject *fn_ret = NULL;
3739
3740 PySSL_END_ALLOW_THREADS_S(pw_info->thread_state);
3741
Christian Heimesd3b73f32021-04-09 15:23:38 +02003742 if (pw_info->error) {
3743 /* already failed previously. OpenSSL 3.0.0-alpha14 invokes the
3744 * callback multiple times which can lead to fatal Python error in
3745 * exception check. */
3746 goto error;
3747 }
3748
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003749 if (pw_info->callable) {
Victor Stinnerf17c3de2016-12-06 18:46:19 +01003750 fn_ret = _PyObject_CallNoArg(pw_info->callable);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003751 if (!fn_ret) {
3752 /* TODO: It would be nice to move _ctypes_add_traceback() into the
3753 core python API, so we could use it to add a frame here */
3754 goto error;
3755 }
3756
3757 if (!_pwinfo_set(pw_info, fn_ret,
3758 "password callback must return a string")) {
3759 goto error;
3760 }
3761 Py_CLEAR(fn_ret);
3762 }
3763
3764 if (pw_info->size > size) {
3765 PyErr_Format(PyExc_ValueError,
3766 "password cannot be longer than %d bytes", size);
3767 goto error;
3768 }
3769
3770 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
3771 memcpy(buf, pw_info->password, pw_info->size);
3772 return pw_info->size;
3773
3774error:
3775 Py_XDECREF(fn_ret);
3776 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
3777 pw_info->error = 1;
3778 return -1;
3779}
3780
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003781/*[clinic input]
3782_ssl._SSLContext.load_cert_chain
3783 certfile: object
Serhiy Storchaka279f4462019-09-14 12:24:05 +03003784 keyfile: object = None
3785 password: object = None
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003786
3787[clinic start generated code]*/
3788
Antoine Pitroub5218772010-05-21 09:56:06 +00003789static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003790_ssl__SSLContext_load_cert_chain_impl(PySSLContext *self, PyObject *certfile,
3791 PyObject *keyfile, PyObject *password)
Serhiy Storchaka279f4462019-09-14 12:24:05 +03003792/*[clinic end generated code: output=9480bc1c380e2095 input=30bc7e967ea01a58]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003793{
Antoine Pitrou152efa22010-05-16 18:19:27 +00003794 PyObject *certfile_bytes = NULL, *keyfile_bytes = NULL;
Christian Heimes598894f2016-09-05 23:19:05 +02003795 pem_password_cb *orig_passwd_cb = SSL_CTX_get_default_passwd_cb(self->ctx);
3796 void *orig_passwd_userdata = SSL_CTX_get_default_passwd_cb_userdata(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003797 _PySSLPasswordInfo pw_info = { NULL, NULL, NULL, 0, 0 };
Antoine Pitrou152efa22010-05-16 18:19:27 +00003798 int r;
3799
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003800 errno = 0;
Antoine Pitrou67e8e562010-09-01 20:55:41 +00003801 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00003802 if (keyfile == Py_None)
3803 keyfile = NULL;
3804 if (!PyUnicode_FSConverter(certfile, &certfile_bytes)) {
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03003805 if (PyErr_ExceptionMatches(PyExc_TypeError)) {
3806 PyErr_SetString(PyExc_TypeError,
3807 "certfile should be a valid filesystem path");
3808 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003809 return NULL;
3810 }
3811 if (keyfile && !PyUnicode_FSConverter(keyfile, &keyfile_bytes)) {
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03003812 if (PyErr_ExceptionMatches(PyExc_TypeError)) {
3813 PyErr_SetString(PyExc_TypeError,
3814 "keyfile should be a valid filesystem path");
3815 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003816 goto error;
3817 }
Serhiy Storchaka279f4462019-09-14 12:24:05 +03003818 if (password != Py_None) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003819 if (PyCallable_Check(password)) {
3820 pw_info.callable = password;
3821 } else if (!_pwinfo_set(&pw_info, password,
3822 "password should be a string or callable")) {
3823 goto error;
3824 }
3825 SSL_CTX_set_default_passwd_cb(self->ctx, _password_callback);
3826 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, &pw_info);
3827 }
3828 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003829 r = SSL_CTX_use_certificate_chain_file(self->ctx,
3830 PyBytes_AS_STRING(certfile_bytes));
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003831 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003832 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003833 if (pw_info.error) {
3834 ERR_clear_error();
3835 /* the password callback has already set the error information */
3836 }
3837 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00003838 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03003839 PyErr_SetFromErrno(PyExc_OSError);
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003840 }
3841 else {
Christian Heimes7f1305e2021-04-17 20:06:38 +02003842 _setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003843 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003844 goto error;
3845 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003846 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou9c254862011-04-03 18:15:34 +02003847 r = SSL_CTX_use_PrivateKey_file(self->ctx,
Antoine Pitrou152efa22010-05-16 18:19:27 +00003848 PyBytes_AS_STRING(keyfile ? keyfile_bytes : certfile_bytes),
3849 SSL_FILETYPE_PEM);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003850 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
3851 Py_CLEAR(keyfile_bytes);
3852 Py_CLEAR(certfile_bytes);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003853 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003854 if (pw_info.error) {
3855 ERR_clear_error();
3856 /* the password callback has already set the error information */
3857 }
3858 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00003859 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03003860 PyErr_SetFromErrno(PyExc_OSError);
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003861 }
3862 else {
Christian Heimes7f1305e2021-04-17 20:06:38 +02003863 _setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003864 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003865 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003866 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003867 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003868 r = SSL_CTX_check_private_key(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003869 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003870 if (r != 1) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02003871 _setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
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 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
3875 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02003876 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003877 Py_RETURN_NONE;
3878
3879error:
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003880 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
3881 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02003882 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003883 Py_XDECREF(keyfile_bytes);
3884 Py_XDECREF(certfile_bytes);
3885 return NULL;
3886}
3887
Christian Heimesefff7062013-11-21 03:35:02 +01003888/* internal helper function, returns -1 on error
3889 */
3890static int
Serhiy Storchaka8f87eef2020-04-12 14:58:27 +03003891_add_ca_certs(PySSLContext *self, const void *data, Py_ssize_t len,
Christian Heimesefff7062013-11-21 03:35:02 +01003892 int filetype)
3893{
3894 BIO *biobuf = NULL;
3895 X509_STORE *store;
Christian Heimesb9ad88b2021-04-23 13:51:40 +02003896 int retval = -1, err, loaded = 0;
Christian Heimesefff7062013-11-21 03:35:02 +01003897
3898 assert(filetype == SSL_FILETYPE_ASN1 || filetype == SSL_FILETYPE_PEM);
3899
3900 if (len <= 0) {
3901 PyErr_SetString(PyExc_ValueError,
3902 "Empty certificate data");
3903 return -1;
3904 } else if (len > INT_MAX) {
3905 PyErr_SetString(PyExc_OverflowError,
3906 "Certificate data is too long.");
3907 return -1;
3908 }
3909
Christian Heimes1dbf61f2013-11-22 00:34:18 +01003910 biobuf = BIO_new_mem_buf(data, (int)len);
Christian Heimesefff7062013-11-21 03:35:02 +01003911 if (biobuf == NULL) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02003912 _setSSLError(get_state_ctx(self), "Can't allocate buffer", 0, __FILE__, __LINE__);
Christian Heimesefff7062013-11-21 03:35:02 +01003913 return -1;
3914 }
3915
3916 store = SSL_CTX_get_cert_store(self->ctx);
3917 assert(store != NULL);
3918
3919 while (1) {
3920 X509 *cert = NULL;
3921 int r;
3922
3923 if (filetype == SSL_FILETYPE_ASN1) {
3924 cert = d2i_X509_bio(biobuf, NULL);
3925 } else {
3926 cert = PEM_read_bio_X509(biobuf, NULL,
Christian Heimes598894f2016-09-05 23:19:05 +02003927 SSL_CTX_get_default_passwd_cb(self->ctx),
3928 SSL_CTX_get_default_passwd_cb_userdata(self->ctx)
3929 );
Christian Heimesefff7062013-11-21 03:35:02 +01003930 }
3931 if (cert == NULL) {
3932 break;
3933 }
3934 r = X509_STORE_add_cert(store, cert);
3935 X509_free(cert);
3936 if (!r) {
3937 err = ERR_peek_last_error();
3938 if ((ERR_GET_LIB(err) == ERR_LIB_X509) &&
3939 (ERR_GET_REASON(err) == X509_R_CERT_ALREADY_IN_HASH_TABLE)) {
3940 /* cert already in hash table, not an error */
3941 ERR_clear_error();
3942 } else {
3943 break;
3944 }
3945 }
3946 loaded++;
3947 }
3948
3949 err = ERR_peek_last_error();
Christian Heimesb9ad88b2021-04-23 13:51:40 +02003950 if (loaded == 0) {
3951 const char *msg = NULL;
3952 if (filetype == SSL_FILETYPE_PEM) {
3953 msg = "no start line: cadata does not contain a certificate";
3954 } else {
3955 msg = "not enough data: cadata does not contain a certificate";
3956 }
3957 _setSSLError(get_state_ctx(self), msg, 0, __FILE__, __LINE__);
3958 retval = -1;
3959 } else if ((filetype == SSL_FILETYPE_ASN1) &&
3960 (ERR_GET_LIB(err) == ERR_LIB_ASN1) &&
3961 (ERR_GET_REASON(err) == ASN1_R_HEADER_TOO_LONG)) {
Christian Heimesefff7062013-11-21 03:35:02 +01003962 /* EOF ASN1 file, not an error */
3963 ERR_clear_error();
3964 retval = 0;
3965 } else if ((filetype == SSL_FILETYPE_PEM) &&
Christian Heimesefff7062013-11-21 03:35:02 +01003966 (ERR_GET_LIB(err) == ERR_LIB_PEM) &&
3967 (ERR_GET_REASON(err) == PEM_R_NO_START_LINE)) {
3968 /* EOF PEM file, not an error */
3969 ERR_clear_error();
3970 retval = 0;
Christian Heimesb9ad88b2021-04-23 13:51:40 +02003971 } else if (err != 0) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02003972 _setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
Christian Heimesefff7062013-11-21 03:35:02 +01003973 retval = -1;
Christian Heimesb9ad88b2021-04-23 13:51:40 +02003974 } else {
3975 retval = 0;
Christian Heimesefff7062013-11-21 03:35:02 +01003976 }
3977
3978 BIO_free(biobuf);
3979 return retval;
3980}
3981
3982
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003983/*[clinic input]
3984_ssl._SSLContext.load_verify_locations
Serhiy Storchaka279f4462019-09-14 12:24:05 +03003985 cafile: object = None
3986 capath: object = None
3987 cadata: object = None
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003988
3989[clinic start generated code]*/
3990
Antoine Pitrou152efa22010-05-16 18:19:27 +00003991static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003992_ssl__SSLContext_load_verify_locations_impl(PySSLContext *self,
3993 PyObject *cafile,
3994 PyObject *capath,
3995 PyObject *cadata)
Serhiy Storchaka279f4462019-09-14 12:24:05 +03003996/*[clinic end generated code: output=454c7e41230ca551 input=42ecfe258233e194]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003997{
Antoine Pitrou152efa22010-05-16 18:19:27 +00003998 PyObject *cafile_bytes = NULL, *capath_bytes = NULL;
3999 const char *cafile_buf = NULL, *capath_buf = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01004000 int r = 0, ok = 1;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004001
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00004002 errno = 0;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004003 if (cafile == Py_None)
4004 cafile = NULL;
4005 if (capath == Py_None)
4006 capath = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01004007 if (cadata == Py_None)
4008 cadata = NULL;
4009
4010 if (cafile == NULL && capath == NULL && cadata == NULL) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00004011 PyErr_SetString(PyExc_TypeError,
Christian Heimesefff7062013-11-21 03:35:02 +01004012 "cafile, capath and cadata cannot be all omitted");
4013 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004014 }
4015 if (cafile && !PyUnicode_FSConverter(cafile, &cafile_bytes)) {
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03004016 if (PyErr_ExceptionMatches(PyExc_TypeError)) {
4017 PyErr_SetString(PyExc_TypeError,
4018 "cafile should be a valid filesystem path");
4019 }
Christian Heimesefff7062013-11-21 03:35:02 +01004020 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004021 }
4022 if (capath && !PyUnicode_FSConverter(capath, &capath_bytes)) {
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03004023 if (PyErr_ExceptionMatches(PyExc_TypeError)) {
4024 PyErr_SetString(PyExc_TypeError,
4025 "capath 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 }
Christian Heimesefff7062013-11-21 03:35:02 +01004029
4030 /* validata cadata type and load cadata */
4031 if (cadata) {
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03004032 if (PyUnicode_Check(cadata)) {
4033 PyObject *cadata_ascii = PyUnicode_AsASCIIString(cadata);
4034 if (cadata_ascii == NULL) {
4035 if (PyErr_ExceptionMatches(PyExc_UnicodeEncodeError)) {
4036 goto invalid_cadata;
4037 }
4038 goto error;
4039 }
4040 r = _add_ca_certs(self,
4041 PyBytes_AS_STRING(cadata_ascii),
4042 PyBytes_GET_SIZE(cadata_ascii),
4043 SSL_FILETYPE_PEM);
4044 Py_DECREF(cadata_ascii);
4045 if (r == -1) {
4046 goto error;
4047 }
4048 }
4049 else if (PyObject_CheckBuffer(cadata)) {
4050 Py_buffer buf;
4051 if (PyObject_GetBuffer(cadata, &buf, PyBUF_SIMPLE)) {
4052 goto error;
4053 }
Christian Heimesefff7062013-11-21 03:35:02 +01004054 if (!PyBuffer_IsContiguous(&buf, 'C') || buf.ndim > 1) {
4055 PyBuffer_Release(&buf);
4056 PyErr_SetString(PyExc_TypeError,
4057 "cadata should be a contiguous buffer with "
4058 "a single dimension");
4059 goto error;
4060 }
4061 r = _add_ca_certs(self, buf.buf, buf.len, SSL_FILETYPE_ASN1);
4062 PyBuffer_Release(&buf);
4063 if (r == -1) {
4064 goto error;
4065 }
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03004066 }
4067 else {
4068 invalid_cadata:
4069 PyErr_SetString(PyExc_TypeError,
4070 "cadata should be an ASCII string or a "
4071 "bytes-like object");
4072 goto error;
Christian Heimesefff7062013-11-21 03:35:02 +01004073 }
4074 }
4075
4076 /* load cafile or capath */
4077 if (cafile || capath) {
4078 if (cafile)
4079 cafile_buf = PyBytes_AS_STRING(cafile_bytes);
4080 if (capath)
4081 capath_buf = PyBytes_AS_STRING(capath_bytes);
4082 PySSL_BEGIN_ALLOW_THREADS
4083 r = SSL_CTX_load_verify_locations(self->ctx, cafile_buf, capath_buf);
4084 PySSL_END_ALLOW_THREADS
4085 if (r != 1) {
Christian Heimesefff7062013-11-21 03:35:02 +01004086 if (errno != 0) {
4087 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03004088 PyErr_SetFromErrno(PyExc_OSError);
Christian Heimesefff7062013-11-21 03:35:02 +01004089 }
4090 else {
Christian Heimes7f1305e2021-04-17 20:06:38 +02004091 _setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
Christian Heimesefff7062013-11-21 03:35:02 +01004092 }
4093 goto error;
4094 }
4095 }
4096 goto end;
4097
4098 error:
4099 ok = 0;
4100 end:
Antoine Pitrou152efa22010-05-16 18:19:27 +00004101 Py_XDECREF(cafile_bytes);
4102 Py_XDECREF(capath_bytes);
Christian Heimesefff7062013-11-21 03:35:02 +01004103 if (ok) {
4104 Py_RETURN_NONE;
4105 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00004106 return NULL;
4107 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00004108}
4109
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004110/*[clinic input]
4111_ssl._SSLContext.load_dh_params
4112 path as filepath: object
4113 /
4114
4115[clinic start generated code]*/
4116
Antoine Pitrou152efa22010-05-16 18:19:27 +00004117static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004118_ssl__SSLContext_load_dh_params(PySSLContext *self, PyObject *filepath)
4119/*[clinic end generated code: output=1c8e57a38e055af0 input=c8871f3c796ae1d6]*/
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004120{
4121 FILE *f;
4122 DH *dh;
4123
Victor Stinnerdaf45552013-08-28 00:53:59 +02004124 f = _Py_fopen_obj(filepath, "rb");
Victor Stinnere42ccd22015-03-18 01:39:23 +01004125 if (f == NULL)
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004126 return NULL;
Victor Stinnere42ccd22015-03-18 01:39:23 +01004127
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004128 errno = 0;
4129 PySSL_BEGIN_ALLOW_THREADS
4130 dh = PEM_read_DHparams(f, NULL, NULL, NULL);
Antoine Pitrou457a2292013-01-12 21:43:45 +01004131 fclose(f);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004132 PySSL_END_ALLOW_THREADS
4133 if (dh == NULL) {
4134 if (errno != 0) {
4135 ERR_clear_error();
4136 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
4137 }
4138 else {
Christian Heimes7f1305e2021-04-17 20:06:38 +02004139 _setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004140 }
4141 return NULL;
4142 }
Zackery Spytzaebc0492020-07-07 22:21:58 -06004143 if (!SSL_CTX_set_tmp_dh(self->ctx, dh)) {
4144 DH_free(dh);
Christian Heimes7f1305e2021-04-17 20:06:38 +02004145 return _setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
Zackery Spytzaebc0492020-07-07 22:21:58 -06004146 }
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004147 DH_free(dh);
4148 Py_RETURN_NONE;
4149}
4150
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004151/*[clinic input]
4152_ssl._SSLContext._wrap_socket
Christian Heimes7f1305e2021-04-17 20:06:38 +02004153 sock: object(subclass_of="get_state_ctx(self)->Sock_Type")
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004154 server_side: int
4155 server_hostname as hostname_obj: object = None
Christian Heimes141c5e82018-02-24 21:10:57 +01004156 *
4157 owner: object = None
4158 session: object = None
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004159
4160[clinic start generated code]*/
4161
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004162static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004163_ssl__SSLContext__wrap_socket_impl(PySSLContext *self, PyObject *sock,
Christian Heimes141c5e82018-02-24 21:10:57 +01004164 int server_side, PyObject *hostname_obj,
4165 PyObject *owner, PyObject *session)
Christian Heimes7f1305e2021-04-17 20:06:38 +02004166/*[clinic end generated code: output=f103f238633940b4 input=f5916eadbc6eae81]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004167{
Antoine Pitroud5323212010-10-22 18:19:07 +00004168 char *hostname = NULL;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004169 PyObject *res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004170
Antoine Pitroud5323212010-10-22 18:19:07 +00004171 /* server_hostname is either None (or absent), or to be encoded
Christian Heimesd02ac252018-03-25 12:36:13 +02004172 as IDN A-label (ASCII str) without NULL bytes. */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004173 if (hostname_obj != Py_None) {
Christian Heimes11a14932018-02-24 02:35:08 +01004174 if (!PyArg_Parse(hostname_obj, "es", "ascii", &hostname))
Antoine Pitroud5323212010-10-22 18:19:07 +00004175 return NULL;
Antoine Pitroud5323212010-10-22 18:19:07 +00004176 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00004177
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004178 res = (PyObject *) newPySSLSocket(self, (PySocketSockObject *)sock,
4179 server_side, hostname,
Christian Heimes141c5e82018-02-24 21:10:57 +01004180 owner, session,
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004181 NULL, NULL);
Antoine Pitroud5323212010-10-22 18:19:07 +00004182 if (hostname != NULL)
4183 PyMem_Free(hostname);
4184 return res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004185}
4186
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004187/*[clinic input]
4188_ssl._SSLContext._wrap_bio
Christian Heimes7f1305e2021-04-17 20:06:38 +02004189 incoming: object(subclass_of="get_state_ctx(self)->PySSLMemoryBIO_Type", type="PySSLMemoryBIO *")
4190 outgoing: object(subclass_of="get_state_ctx(self)->PySSLMemoryBIO_Type", type="PySSLMemoryBIO *")
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004191 server_side: int
4192 server_hostname as hostname_obj: object = None
Christian Heimes141c5e82018-02-24 21:10:57 +01004193 *
4194 owner: object = None
4195 session: object = None
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004196
4197[clinic start generated code]*/
4198
Antoine Pitroub0182c82010-10-12 20:09:02 +00004199static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004200_ssl__SSLContext__wrap_bio_impl(PySSLContext *self, PySSLMemoryBIO *incoming,
4201 PySSLMemoryBIO *outgoing, int server_side,
Christian Heimes141c5e82018-02-24 21:10:57 +01004202 PyObject *hostname_obj, PyObject *owner,
4203 PyObject *session)
Christian Heimes7f1305e2021-04-17 20:06:38 +02004204/*[clinic end generated code: output=5c5d6d9b41f99332 input=331edeec9c738382]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004205{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004206 char *hostname = NULL;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004207 PyObject *res;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004208
4209 /* server_hostname is either None (or absent), or to be encoded
Christian Heimesd02ac252018-03-25 12:36:13 +02004210 as IDN A-label (ASCII str) without NULL bytes. */
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004211 if (hostname_obj != Py_None) {
Christian Heimes11a14932018-02-24 02:35:08 +01004212 if (!PyArg_Parse(hostname_obj, "es", "ascii", &hostname))
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004213 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004214 }
4215
4216 res = (PyObject *) newPySSLSocket(self, NULL, server_side, hostname,
Christian Heimes141c5e82018-02-24 21:10:57 +01004217 owner, session,
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004218 incoming, outgoing);
4219
4220 PyMem_Free(hostname);
4221 return res;
4222}
4223
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004224/*[clinic input]
4225_ssl._SSLContext.session_stats
4226[clinic start generated code]*/
4227
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004228static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004229_ssl__SSLContext_session_stats_impl(PySSLContext *self)
4230/*[clinic end generated code: output=0d96411c42893bfb input=7e0a81fb11102c8b]*/
Antoine Pitroub0182c82010-10-12 20:09:02 +00004231{
4232 int r;
4233 PyObject *value, *stats = PyDict_New();
4234 if (!stats)
4235 return NULL;
4236
4237#define ADD_STATS(SSL_NAME, KEY_NAME) \
4238 value = PyLong_FromLong(SSL_CTX_sess_ ## SSL_NAME (self->ctx)); \
4239 if (value == NULL) \
4240 goto error; \
4241 r = PyDict_SetItemString(stats, KEY_NAME, value); \
4242 Py_DECREF(value); \
4243 if (r < 0) \
4244 goto error;
4245
4246 ADD_STATS(number, "number");
4247 ADD_STATS(connect, "connect");
4248 ADD_STATS(connect_good, "connect_good");
4249 ADD_STATS(connect_renegotiate, "connect_renegotiate");
4250 ADD_STATS(accept, "accept");
4251 ADD_STATS(accept_good, "accept_good");
4252 ADD_STATS(accept_renegotiate, "accept_renegotiate");
4253 ADD_STATS(accept, "accept");
4254 ADD_STATS(hits, "hits");
4255 ADD_STATS(misses, "misses");
4256 ADD_STATS(timeouts, "timeouts");
4257 ADD_STATS(cache_full, "cache_full");
4258
4259#undef ADD_STATS
4260
4261 return stats;
4262
4263error:
4264 Py_DECREF(stats);
4265 return NULL;
4266}
4267
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004268/*[clinic input]
4269_ssl._SSLContext.set_default_verify_paths
4270[clinic start generated code]*/
4271
Antoine Pitrou664c2d12010-11-17 20:29:42 +00004272static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004273_ssl__SSLContext_set_default_verify_paths_impl(PySSLContext *self)
4274/*[clinic end generated code: output=0bee74e6e09deaaa input=35f3408021463d74]*/
Antoine Pitrou664c2d12010-11-17 20:29:42 +00004275{
4276 if (!SSL_CTX_set_default_verify_paths(self->ctx)) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02004277 _setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
Antoine Pitrou664c2d12010-11-17 20:29:42 +00004278 return NULL;
4279 }
4280 Py_RETURN_NONE;
4281}
4282
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004283/*[clinic input]
4284_ssl._SSLContext.set_ecdh_curve
4285 name: object
4286 /
4287
4288[clinic start generated code]*/
4289
Antoine Pitrou923df6f2011-12-19 17:16:51 +01004290static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004291_ssl__SSLContext_set_ecdh_curve(PySSLContext *self, PyObject *name)
4292/*[clinic end generated code: output=23022c196e40d7d2 input=c2bafb6f6e34726b]*/
Antoine Pitrou923df6f2011-12-19 17:16:51 +01004293{
4294 PyObject *name_bytes;
4295 int nid;
4296 EC_KEY *key;
4297
4298 if (!PyUnicode_FSConverter(name, &name_bytes))
4299 return NULL;
4300 assert(PyBytes_Check(name_bytes));
4301 nid = OBJ_sn2nid(PyBytes_AS_STRING(name_bytes));
4302 Py_DECREF(name_bytes);
4303 if (nid == 0) {
4304 PyErr_Format(PyExc_ValueError,
4305 "unknown elliptic curve name %R", name);
4306 return NULL;
4307 }
4308 key = EC_KEY_new_by_curve_name(nid);
4309 if (key == NULL) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02004310 _setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
Antoine Pitrou923df6f2011-12-19 17:16:51 +01004311 return NULL;
4312 }
4313 SSL_CTX_set_tmp_ecdh(self->ctx, key);
4314 EC_KEY_free(key);
4315 Py_RETURN_NONE;
4316}
4317
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004318static int
4319_servername_callback(SSL *s, int *al, void *args)
4320{
4321 int ret;
Christian Heimes7f1305e2021-04-17 20:06:38 +02004322 PySSLContext *sslctx = (PySSLContext *) args;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004323 PySSLSocket *ssl;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004324 PyObject *result;
4325 /* The high-level ssl.SSLSocket object */
4326 PyObject *ssl_socket;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004327 const char *servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
Stefan Krah20d60802013-01-17 17:07:17 +01004328 PyGILState_STATE gstate = PyGILState_Ensure();
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004329
Christian Heimes7f1305e2021-04-17 20:06:38 +02004330 if (sslctx->set_sni_cb == NULL) {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004331 /* remove race condition in this the call back while if removing the
4332 * callback is in progress */
4333 PyGILState_Release(gstate);
Antoine Pitrou5dd12a52013-01-06 15:25:36 +01004334 return SSL_TLSEXT_ERR_OK;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004335 }
4336
4337 ssl = SSL_get_app_data(s);
Christian Heimes7f1305e2021-04-17 20:06:38 +02004338 assert(Py_IS_TYPE(ssl, get_state_ctx(sslctx)->PySSLSocket_Type));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004339
Serhiy Storchakaf51d7152015-11-02 14:40:41 +02004340 /* The servername callback expects an argument that represents the current
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004341 * SSL connection and that has a .context attribute that can be changed to
4342 * identify the requested hostname. Since the official API is the Python
4343 * level API we want to pass the callback a Python level object rather than
4344 * a _ssl.SSLSocket instance. If there's an "owner" (typically an
4345 * SSLObject) that will be passed. Otherwise if there's a socket then that
4346 * will be passed. If both do not exist only then the C-level object is
4347 * passed. */
4348 if (ssl->owner)
4349 ssl_socket = PyWeakref_GetObject(ssl->owner);
4350 else if (ssl->Socket)
4351 ssl_socket = PyWeakref_GetObject(ssl->Socket);
4352 else
4353 ssl_socket = (PyObject *) ssl;
4354
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004355 Py_INCREF(ssl_socket);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004356 if (ssl_socket == Py_None)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004357 goto error;
Victor Stinner7e001512013-06-25 00:44:31 +02004358
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004359 if (servername == NULL) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02004360 result = PyObject_CallFunctionObjArgs(sslctx->set_sni_cb, ssl_socket,
4361 Py_None, sslctx, NULL);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004362 }
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004363 else {
Christian Heimes11a14932018-02-24 02:35:08 +01004364 PyObject *servername_bytes;
4365 PyObject *servername_str;
4366
4367 servername_bytes = PyBytes_FromString(servername);
4368 if (servername_bytes == NULL) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02004369 PyErr_WriteUnraisable((PyObject *) sslctx);
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004370 goto error;
4371 }
Christian Heimes11a14932018-02-24 02:35:08 +01004372 /* server_hostname was encoded to an A-label by our caller; put it
4373 * back into a str object, but still as an A-label (bpo-28414)
4374 */
4375 servername_str = PyUnicode_FromEncodedObject(servername_bytes, "ascii", NULL);
Christian Heimes11a14932018-02-24 02:35:08 +01004376 if (servername_str == NULL) {
4377 PyErr_WriteUnraisable(servername_bytes);
Zackery Spytzee96f322020-07-09 04:00:21 -06004378 Py_DECREF(servername_bytes);
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004379 goto error;
4380 }
Zackery Spytzee96f322020-07-09 04:00:21 -06004381 Py_DECREF(servername_bytes);
Christian Heimes11a14932018-02-24 02:35:08 +01004382 result = PyObject_CallFunctionObjArgs(
Christian Heimes7f1305e2021-04-17 20:06:38 +02004383 sslctx->set_sni_cb, ssl_socket, servername_str,
4384 sslctx, NULL);
Christian Heimes11a14932018-02-24 02:35:08 +01004385 Py_DECREF(servername_str);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004386 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004387 Py_DECREF(ssl_socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004388
4389 if (result == NULL) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02004390 PyErr_WriteUnraisable(sslctx->set_sni_cb);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004391 *al = SSL_AD_HANDSHAKE_FAILURE;
4392 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
4393 }
4394 else {
Christian Heimes11a14932018-02-24 02:35:08 +01004395 /* Result may be None, a SSLContext or an integer
4396 * None and SSLContext are OK, integer or other values are an error.
4397 */
4398 if (result == Py_None) {
4399 ret = SSL_TLSEXT_ERR_OK;
4400 } else {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004401 *al = (int) PyLong_AsLong(result);
4402 if (PyErr_Occurred()) {
4403 PyErr_WriteUnraisable(result);
4404 *al = SSL_AD_INTERNAL_ERROR;
4405 }
4406 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
4407 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004408 Py_DECREF(result);
4409 }
4410
4411 PyGILState_Release(gstate);
4412 return ret;
4413
4414error:
4415 Py_DECREF(ssl_socket);
4416 *al = SSL_AD_INTERNAL_ERROR;
4417 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
4418 PyGILState_Release(gstate);
4419 return ret;
4420}
4421
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004422static PyObject *
Christian Heimes11a14932018-02-24 02:35:08 +01004423get_sni_callback(PySSLContext *self, void *c)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004424{
Christian Heimes11a14932018-02-24 02:35:08 +01004425 PyObject *cb = self->set_sni_cb;
4426 if (cb == NULL) {
4427 Py_RETURN_NONE;
4428 }
4429 Py_INCREF(cb);
4430 return cb;
4431}
4432
4433static int
4434set_sni_callback(PySSLContext *self, PyObject *arg, void *c)
4435{
4436 if (self->protocol == PY_SSL_VERSION_TLS_CLIENT) {
4437 PyErr_SetString(PyExc_ValueError,
4438 "sni_callback cannot be set on TLS_CLIENT context");
4439 return -1;
4440 }
Christian Heimes11a14932018-02-24 02:35:08 +01004441 Py_CLEAR(self->set_sni_cb);
4442 if (arg == Py_None) {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004443 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
4444 }
4445 else {
Christian Heimes11a14932018-02-24 02:35:08 +01004446 if (!PyCallable_Check(arg)) {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004447 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
4448 PyErr_SetString(PyExc_TypeError,
4449 "not a callable object");
Christian Heimes11a14932018-02-24 02:35:08 +01004450 return -1;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004451 }
Christian Heimes11a14932018-02-24 02:35:08 +01004452 Py_INCREF(arg);
4453 self->set_sni_cb = arg;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004454 SSL_CTX_set_tlsext_servername_callback(self->ctx, _servername_callback);
4455 SSL_CTX_set_tlsext_servername_arg(self->ctx, self);
4456 }
Christian Heimes11a14932018-02-24 02:35:08 +01004457 return 0;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004458}
4459
Christian Heimes11a14932018-02-24 02:35:08 +01004460PyDoc_STRVAR(PySSLContext_sni_callback_doc,
4461"Set a callback that will be called when a server name is provided by the SSL/TLS client in the SNI extension.\n\
4462\n\
4463If the argument is None then the callback is disabled. The method is called\n\
4464with the SSLSocket, the server name as a string, and the SSLContext object.\n\
4465See RFC 6066 for details of the SNI extension.");
4466
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004467/*[clinic input]
4468_ssl._SSLContext.cert_store_stats
4469
4470Returns quantities of loaded X.509 certificates.
4471
4472X.509 certificates with a CA extension and certificate revocation lists
4473inside the context's cert store.
4474
4475NOTE: Certificates in a capath directory aren't loaded unless they have
4476been used at least once.
4477[clinic start generated code]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004478
4479static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004480_ssl__SSLContext_cert_store_stats_impl(PySSLContext *self)
4481/*[clinic end generated code: output=5f356f4d9cca874d input=eb40dd0f6d0e40cf]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004482{
4483 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02004484 STACK_OF(X509_OBJECT) *objs;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004485 X509_OBJECT *obj;
Christian Heimes598894f2016-09-05 23:19:05 +02004486 int x509 = 0, crl = 0, ca = 0, i;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004487
4488 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02004489 objs = X509_STORE_get0_objects(store);
4490 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
4491 obj = sk_X509_OBJECT_value(objs, i);
4492 switch (X509_OBJECT_get_type(obj)) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004493 case X509_LU_X509:
4494 x509++;
Christian Heimes598894f2016-09-05 23:19:05 +02004495 if (X509_check_ca(X509_OBJECT_get0_X509(obj))) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004496 ca++;
4497 }
4498 break;
4499 case X509_LU_CRL:
4500 crl++;
4501 break;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004502 default:
4503 /* Ignore X509_LU_FAIL, X509_LU_RETRY, X509_LU_PKEY.
4504 * As far as I can tell they are internal states and never
4505 * stored in a cert store */
4506 break;
4507 }
4508 }
4509 return Py_BuildValue("{sisisi}", "x509", x509, "crl", crl,
4510 "x509_ca", ca);
4511}
4512
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004513/*[clinic input]
4514_ssl._SSLContext.get_ca_certs
4515 binary_form: bool = False
4516
4517Returns a list of dicts with information of loaded CA certs.
4518
4519If the optional argument is True, returns a DER-encoded copy of the CA
4520certificate.
4521
4522NOTE: Certificates in a capath directory aren't loaded unless they have
4523been used at least once.
4524[clinic start generated code]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004525
4526static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004527_ssl__SSLContext_get_ca_certs_impl(PySSLContext *self, int binary_form)
4528/*[clinic end generated code: output=0d58f148f37e2938 input=6887b5a09b7f9076]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004529{
4530 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02004531 STACK_OF(X509_OBJECT) *objs;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004532 PyObject *ci = NULL, *rlist = NULL;
4533 int i;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004534
4535 if ((rlist = PyList_New(0)) == NULL) {
4536 return NULL;
4537 }
4538
4539 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02004540 objs = X509_STORE_get0_objects(store);
4541 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004542 X509_OBJECT *obj;
4543 X509 *cert;
4544
Christian Heimes598894f2016-09-05 23:19:05 +02004545 obj = sk_X509_OBJECT_value(objs, i);
4546 if (X509_OBJECT_get_type(obj) != X509_LU_X509) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004547 /* not a x509 cert */
4548 continue;
4549 }
4550 /* CA for any purpose */
Christian Heimes598894f2016-09-05 23:19:05 +02004551 cert = X509_OBJECT_get0_X509(obj);
Christian Heimes9a5395a2013-06-17 15:44:12 +02004552 if (!X509_check_ca(cert)) {
4553 continue;
4554 }
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004555 if (binary_form) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02004556 ci = _certificate_to_der(get_state_ctx(self), cert);
Christian Heimes9a5395a2013-06-17 15:44:12 +02004557 } else {
Christian Heimes7f1305e2021-04-17 20:06:38 +02004558 ci = _decode_certificate(get_state_ctx(self), cert);
Christian Heimes9a5395a2013-06-17 15:44:12 +02004559 }
4560 if (ci == NULL) {
4561 goto error;
4562 }
4563 if (PyList_Append(rlist, ci) == -1) {
4564 goto error;
4565 }
4566 Py_CLEAR(ci);
4567 }
4568 return rlist;
4569
4570 error:
4571 Py_XDECREF(ci);
4572 Py_XDECREF(rlist);
4573 return NULL;
4574}
4575
4576
Antoine Pitrou152efa22010-05-16 18:19:27 +00004577static PyGetSetDef context_getsetlist[] = {
Christian Heimes1aa9a752013-12-02 02:41:19 +01004578 {"check_hostname", (getter) get_check_hostname,
4579 (setter) set_check_hostname, NULL},
Christian Heimes61d478c2018-01-27 15:51:38 +01004580 {"_host_flags", (getter) get_host_flags,
4581 (setter) set_host_flags, NULL},
Christian Heimes698dde12018-02-27 11:54:43 +01004582 {"minimum_version", (getter) get_minimum_version,
4583 (setter) set_minimum_version, NULL},
4584 {"maximum_version", (getter) get_maximum_version,
4585 (setter) set_maximum_version, NULL},
Christian Heimesc7f70692019-05-31 11:44:05 +02004586 {"keylog_filename", (getter) _PySSLContext_get_keylog_filename,
4587 (setter) _PySSLContext_set_keylog_filename, NULL},
Christian Heimesc7f70692019-05-31 11:44:05 +02004588 {"_msg_callback", (getter) _PySSLContext_get_msg_callback,
4589 (setter) _PySSLContext_set_msg_callback, NULL},
Christian Heimes11a14932018-02-24 02:35:08 +01004590 {"sni_callback", (getter) get_sni_callback,
Christian Heimes698dde12018-02-27 11:54:43 +01004591 (setter) set_sni_callback, PySSLContext_sni_callback_doc},
Christian Heimes39258d32021-04-17 11:36:35 +02004592#ifdef TLS1_3_VERSION
Christian Heimes78c7d522019-06-03 21:00:10 +02004593 {"num_tickets", (getter) get_num_tickets,
4594 (setter) set_num_tickets, PySSLContext_num_tickets_doc},
4595#endif
Antoine Pitroub5218772010-05-21 09:56:06 +00004596 {"options", (getter) get_options,
4597 (setter) set_options, NULL},
Christian Heimes9fb051f2018-09-23 08:32:31 +02004598 {"post_handshake_auth", (getter) get_post_handshake_auth,
4599#ifdef TLS1_3_VERSION
4600 (setter) set_post_handshake_auth,
4601#else
4602 NULL,
4603#endif
4604 NULL},
Christian Heimes11a14932018-02-24 02:35:08 +01004605 {"protocol", (getter) get_protocol,
4606 NULL, NULL},
Christian Heimes22587792013-11-21 23:56:13 +01004607 {"verify_flags", (getter) get_verify_flags,
4608 (setter) set_verify_flags, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00004609 {"verify_mode", (getter) get_verify_mode,
4610 (setter) set_verify_mode, NULL},
matthewhughes9348e836bb2020-07-17 09:59:15 +01004611 {"security_level", (getter) get_security_level,
4612 NULL, PySSLContext_security_level_doc},
Antoine Pitrou152efa22010-05-16 18:19:27 +00004613 {NULL}, /* sentinel */
4614};
4615
4616static struct PyMethodDef context_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004617 _SSL__SSLCONTEXT__WRAP_SOCKET_METHODDEF
4618 _SSL__SSLCONTEXT__WRAP_BIO_METHODDEF
4619 _SSL__SSLCONTEXT_SET_CIPHERS_METHODDEF
4620 _SSL__SSLCONTEXT__SET_ALPN_PROTOCOLS_METHODDEF
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004621 _SSL__SSLCONTEXT_LOAD_CERT_CHAIN_METHODDEF
4622 _SSL__SSLCONTEXT_LOAD_DH_PARAMS_METHODDEF
4623 _SSL__SSLCONTEXT_LOAD_VERIFY_LOCATIONS_METHODDEF
4624 _SSL__SSLCONTEXT_SESSION_STATS_METHODDEF
4625 _SSL__SSLCONTEXT_SET_DEFAULT_VERIFY_PATHS_METHODDEF
4626 _SSL__SSLCONTEXT_SET_ECDH_CURVE_METHODDEF
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004627 _SSL__SSLCONTEXT_CERT_STORE_STATS_METHODDEF
4628 _SSL__SSLCONTEXT_GET_CA_CERTS_METHODDEF
Christian Heimes25bfcd52016-09-06 00:04:45 +02004629 _SSL__SSLCONTEXT_GET_CIPHERS_METHODDEF
Antoine Pitrou152efa22010-05-16 18:19:27 +00004630 {NULL, NULL} /* sentinel */
4631};
4632
Christian Heimes5c36da72020-11-20 09:40:12 +01004633static PyType_Slot PySSLContext_slots[] = {
4634 {Py_tp_methods, context_methods},
4635 {Py_tp_getset, context_getsetlist},
4636 {Py_tp_new, _ssl__SSLContext},
4637 {Py_tp_dealloc, context_dealloc},
4638 {Py_tp_traverse, context_traverse},
4639 {Py_tp_clear, context_clear},
4640 {0, 0},
4641};
4642
4643static PyType_Spec PySSLContext_spec = {
4644 "_ssl._SSLContext",
4645 sizeof(PySSLContext),
4646 0,
Christian Heimes91554e42021-05-02 09:47:45 +02004647 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_IMMUTABLETYPE,
Christian Heimes5c36da72020-11-20 09:40:12 +01004648 PySSLContext_slots,
Antoine Pitrou152efa22010-05-16 18:19:27 +00004649};
4650
4651
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004652/*
4653 * MemoryBIO objects
4654 */
4655
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004656/*[clinic input]
4657@classmethod
4658_ssl.MemoryBIO.__new__
4659
4660[clinic start generated code]*/
4661
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004662static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004663_ssl_MemoryBIO_impl(PyTypeObject *type)
4664/*[clinic end generated code: output=8820a58db78330ac input=26d22e4909ecb1b5]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004665{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004666 BIO *bio;
4667 PySSLMemoryBIO *self;
4668
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004669 bio = BIO_new(BIO_s_mem());
4670 if (bio == NULL) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02004671 PyErr_SetString(PyExc_MemoryError, "failed to allocate BIO");
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004672 return NULL;
4673 }
4674 /* Since our BIO is non-blocking an empty read() does not indicate EOF,
4675 * just that no data is currently available. The SSL routines should retry
4676 * the read, which we can achieve by calling BIO_set_retry_read(). */
4677 BIO_set_retry_read(bio);
4678 BIO_set_mem_eof_return(bio, -1);
4679
4680 assert(type != NULL && type->tp_alloc != NULL);
4681 self = (PySSLMemoryBIO *) type->tp_alloc(type, 0);
4682 if (self == NULL) {
4683 BIO_free(bio);
4684 return NULL;
4685 }
4686 self->bio = bio;
4687 self->eof_written = 0;
4688
4689 return (PyObject *) self;
4690}
4691
4692static void
4693memory_bio_dealloc(PySSLMemoryBIO *self)
4694{
Christian Heimes5c36da72020-11-20 09:40:12 +01004695 PyTypeObject *tp = Py_TYPE(self);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004696 BIO_free(self->bio);
4697 Py_TYPE(self)->tp_free(self);
Christian Heimes5c36da72020-11-20 09:40:12 +01004698 Py_DECREF(tp);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004699}
4700
4701static PyObject *
4702memory_bio_get_pending(PySSLMemoryBIO *self, void *c)
4703{
Segev Finer5cff6372017-07-27 01:19:17 +03004704 return PyLong_FromSize_t(BIO_ctrl_pending(self->bio));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004705}
4706
4707PyDoc_STRVAR(PySSL_memory_bio_pending_doc,
4708"The number of bytes pending in the memory BIO.");
4709
4710static PyObject *
4711memory_bio_get_eof(PySSLMemoryBIO *self, void *c)
4712{
4713 return PyBool_FromLong((BIO_ctrl_pending(self->bio) == 0)
4714 && self->eof_written);
4715}
4716
4717PyDoc_STRVAR(PySSL_memory_bio_eof_doc,
4718"Whether the memory BIO is at EOF.");
4719
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004720/*[clinic input]
4721_ssl.MemoryBIO.read
4722 size as len: int = -1
4723 /
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004724
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004725Read up to size bytes from the memory BIO.
4726
4727If size is not specified, read the entire buffer.
4728If the return value is an empty bytes instance, this means either
4729EOF or that no data is available. Use the "eof" property to
4730distinguish between the two.
4731[clinic start generated code]*/
4732
4733static PyObject *
4734_ssl_MemoryBIO_read_impl(PySSLMemoryBIO *self, int len)
4735/*[clinic end generated code: output=a657aa1e79cd01b3 input=574d7be06a902366]*/
4736{
4737 int avail, nbytes;
4738 PyObject *result;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004739
Segev Finer5cff6372017-07-27 01:19:17 +03004740 avail = (int)Py_MIN(BIO_ctrl_pending(self->bio), INT_MAX);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004741 if ((len < 0) || (len > avail))
4742 len = avail;
4743
4744 result = PyBytes_FromStringAndSize(NULL, len);
4745 if ((result == NULL) || (len == 0))
4746 return result;
4747
4748 nbytes = BIO_read(self->bio, PyBytes_AS_STRING(result), len);
Zackery Spytz365ad2e2018-10-06 11:41:45 -06004749 if (nbytes < 0) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02004750 _sslmodulestate *state = get_state_mbio(self);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004751 Py_DECREF(result);
Christian Heimes7f1305e2021-04-17 20:06:38 +02004752 _setSSLError(state, NULL, 0, __FILE__, __LINE__);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004753 return NULL;
4754 }
4755
Zackery Spytz365ad2e2018-10-06 11:41:45 -06004756 /* There should never be any short reads but check anyway. */
4757 if (nbytes < len) {
4758 _PyBytes_Resize(&result, nbytes);
4759 }
4760
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004761 return result;
4762}
4763
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004764/*[clinic input]
4765_ssl.MemoryBIO.write
4766 b: Py_buffer
4767 /
4768
4769Writes the bytes b into the memory BIO.
4770
4771Returns the number of bytes written.
4772[clinic start generated code]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004773
4774static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004775_ssl_MemoryBIO_write_impl(PySSLMemoryBIO *self, Py_buffer *b)
4776/*[clinic end generated code: output=156ec59110d75935 input=e45757b3e17c4808]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004777{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004778 int nbytes;
4779
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004780 if (b->len > INT_MAX) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004781 PyErr_Format(PyExc_OverflowError,
4782 "string longer than %d bytes", INT_MAX);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004783 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004784 }
4785
4786 if (self->eof_written) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02004787 PyObject *module = PyType_GetModule(Py_TYPE(self));
4788 if (module == NULL)
4789 return NULL;
4790 PyErr_SetString(get_ssl_state(module)->PySSLErrorObject,
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004791 "cannot write() after write_eof()");
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004792 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004793 }
4794
Segev Finer5cff6372017-07-27 01:19:17 +03004795 nbytes = BIO_write(self->bio, b->buf, (int)b->len);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004796 if (nbytes < 0) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02004797 _sslmodulestate *state = get_state_mbio(self);
4798 _setSSLError(state, NULL, 0, __FILE__, __LINE__);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004799 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004800 }
4801
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004802 return PyLong_FromLong(nbytes);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004803}
4804
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004805/*[clinic input]
4806_ssl.MemoryBIO.write_eof
4807
4808Write an EOF marker to the memory BIO.
4809
4810When all data has been read, the "eof" property will be True.
4811[clinic start generated code]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004812
4813static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004814_ssl_MemoryBIO_write_eof_impl(PySSLMemoryBIO *self)
4815/*[clinic end generated code: output=d4106276ccd1ed34 input=56a945f1d29e8bd6]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004816{
4817 self->eof_written = 1;
4818 /* After an EOF is written, a zero return from read() should be a real EOF
4819 * i.e. it should not be retried. Clear the SHOULD_RETRY flag. */
4820 BIO_clear_retry_flags(self->bio);
4821 BIO_set_mem_eof_return(self->bio, 0);
4822
4823 Py_RETURN_NONE;
4824}
4825
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004826static PyGetSetDef memory_bio_getsetlist[] = {
4827 {"pending", (getter) memory_bio_get_pending, NULL,
4828 PySSL_memory_bio_pending_doc},
4829 {"eof", (getter) memory_bio_get_eof, NULL,
4830 PySSL_memory_bio_eof_doc},
4831 {NULL}, /* sentinel */
4832};
4833
4834static struct PyMethodDef memory_bio_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004835 _SSL_MEMORYBIO_READ_METHODDEF
4836 _SSL_MEMORYBIO_WRITE_METHODDEF
4837 _SSL_MEMORYBIO_WRITE_EOF_METHODDEF
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004838 {NULL, NULL} /* sentinel */
4839};
4840
Christian Heimes5c36da72020-11-20 09:40:12 +01004841static PyType_Slot PySSLMemoryBIO_slots[] = {
4842 {Py_tp_methods, memory_bio_methods},
4843 {Py_tp_getset, memory_bio_getsetlist},
4844 {Py_tp_new, _ssl_MemoryBIO},
4845 {Py_tp_dealloc, memory_bio_dealloc},
4846 {0, 0},
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004847};
4848
Christian Heimes5c36da72020-11-20 09:40:12 +01004849static PyType_Spec PySSLMemoryBIO_spec = {
4850 "_ssl.MemoryBIO",
4851 sizeof(PySSLMemoryBIO),
4852 0,
Christian Heimes91554e42021-05-02 09:47:45 +02004853 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_IMMUTABLETYPE,
Christian Heimes5c36da72020-11-20 09:40:12 +01004854 PySSLMemoryBIO_slots,
4855};
Antoine Pitrou152efa22010-05-16 18:19:27 +00004856
Christian Heimes99a65702016-09-10 23:44:53 +02004857/*
4858 * SSL Session object
4859 */
4860
4861static void
4862PySSLSession_dealloc(PySSLSession *self)
4863{
Christian Heimes5c36da72020-11-20 09:40:12 +01004864 PyTypeObject *tp = Py_TYPE(self);
INADA Naokia6296d32017-08-24 14:55:17 +09004865 /* bpo-31095: UnTrack is needed before calling any callbacks */
Christian Heimesa5d07652016-09-24 10:48:05 +02004866 PyObject_GC_UnTrack(self);
Christian Heimes99a65702016-09-10 23:44:53 +02004867 Py_XDECREF(self->ctx);
4868 if (self->session != NULL) {
4869 SSL_SESSION_free(self->session);
4870 }
Christian Heimesa5d07652016-09-24 10:48:05 +02004871 PyObject_GC_Del(self);
Christian Heimes5c36da72020-11-20 09:40:12 +01004872 Py_DECREF(tp);
Christian Heimes99a65702016-09-10 23:44:53 +02004873}
4874
4875static PyObject *
4876PySSLSession_richcompare(PyObject *left, PyObject *right, int op)
4877{
4878 int result;
Christian Heimes7f1305e2021-04-17 20:06:38 +02004879 PyTypeObject *sesstype = ((PySSLSession*)left)->ctx->state->PySSLSession_Type;
Christian Heimes99a65702016-09-10 23:44:53 +02004880
4881 if (left == NULL || right == NULL) {
4882 PyErr_BadInternalCall();
4883 return NULL;
4884 }
4885
Christian Heimes7f1305e2021-04-17 20:06:38 +02004886 if (!Py_IS_TYPE(left, sesstype) || !Py_IS_TYPE(right, sesstype)) {
Christian Heimes99a65702016-09-10 23:44:53 +02004887 Py_RETURN_NOTIMPLEMENTED;
4888 }
4889
4890 if (left == right) {
4891 result = 0;
4892 } else {
4893 const unsigned char *left_id, *right_id;
4894 unsigned int left_len, right_len;
4895 left_id = SSL_SESSION_get_id(((PySSLSession *)left)->session,
4896 &left_len);
4897 right_id = SSL_SESSION_get_id(((PySSLSession *)right)->session,
4898 &right_len);
4899 if (left_len == right_len) {
4900 result = memcmp(left_id, right_id, left_len);
4901 } else {
4902 result = 1;
4903 }
4904 }
4905
4906 switch (op) {
4907 case Py_EQ:
4908 if (result == 0) {
4909 Py_RETURN_TRUE;
4910 } else {
4911 Py_RETURN_FALSE;
4912 }
4913 break;
4914 case Py_NE:
4915 if (result != 0) {
4916 Py_RETURN_TRUE;
4917 } else {
4918 Py_RETURN_FALSE;
4919 }
4920 break;
4921 case Py_LT:
4922 case Py_LE:
4923 case Py_GT:
4924 case Py_GE:
4925 Py_RETURN_NOTIMPLEMENTED;
4926 break;
4927 default:
4928 PyErr_BadArgument();
4929 return NULL;
4930 }
4931}
4932
4933static int
4934PySSLSession_traverse(PySSLSession *self, visitproc visit, void *arg)
4935{
4936 Py_VISIT(self->ctx);
4937 return 0;
4938}
4939
4940static int
4941PySSLSession_clear(PySSLSession *self)
4942{
4943 Py_CLEAR(self->ctx);
4944 return 0;
4945}
4946
4947
4948static PyObject *
4949PySSLSession_get_time(PySSLSession *self, void *closure) {
4950 return PyLong_FromLong(SSL_SESSION_get_time(self->session));
4951}
4952
4953PyDoc_STRVAR(PySSLSession_get_time_doc,
4954"Session creation time (seconds since epoch).");
4955
4956
4957static PyObject *
4958PySSLSession_get_timeout(PySSLSession *self, void *closure) {
4959 return PyLong_FromLong(SSL_SESSION_get_timeout(self->session));
4960}
4961
4962PyDoc_STRVAR(PySSLSession_get_timeout_doc,
4963"Session timeout (delta in seconds).");
4964
4965
4966static PyObject *
4967PySSLSession_get_ticket_lifetime_hint(PySSLSession *self, void *closure) {
4968 unsigned long hint = SSL_SESSION_get_ticket_lifetime_hint(self->session);
4969 return PyLong_FromUnsignedLong(hint);
4970}
4971
4972PyDoc_STRVAR(PySSLSession_get_ticket_lifetime_hint_doc,
4973"Ticket life time hint.");
4974
4975
4976static PyObject *
4977PySSLSession_get_session_id(PySSLSession *self, void *closure) {
4978 const unsigned char *id;
4979 unsigned int len;
4980 id = SSL_SESSION_get_id(self->session, &len);
4981 return PyBytes_FromStringAndSize((const char *)id, len);
4982}
4983
4984PyDoc_STRVAR(PySSLSession_get_session_id_doc,
4985"Session id");
4986
4987
4988static PyObject *
4989PySSLSession_get_has_ticket(PySSLSession *self, void *closure) {
4990 if (SSL_SESSION_has_ticket(self->session)) {
4991 Py_RETURN_TRUE;
4992 } else {
4993 Py_RETURN_FALSE;
4994 }
4995}
4996
4997PyDoc_STRVAR(PySSLSession_get_has_ticket_doc,
4998"Does the session contain a ticket?");
4999
5000
5001static PyGetSetDef PySSLSession_getsetlist[] = {
5002 {"has_ticket", (getter) PySSLSession_get_has_ticket, NULL,
5003 PySSLSession_get_has_ticket_doc},
5004 {"id", (getter) PySSLSession_get_session_id, NULL,
5005 PySSLSession_get_session_id_doc},
5006 {"ticket_lifetime_hint", (getter) PySSLSession_get_ticket_lifetime_hint,
5007 NULL, PySSLSession_get_ticket_lifetime_hint_doc},
5008 {"time", (getter) PySSLSession_get_time, NULL,
5009 PySSLSession_get_time_doc},
5010 {"timeout", (getter) PySSLSession_get_timeout, NULL,
5011 PySSLSession_get_timeout_doc},
5012 {NULL}, /* sentinel */
5013};
5014
Christian Heimes5c36da72020-11-20 09:40:12 +01005015static PyType_Slot PySSLSession_slots[] = {
5016 {Py_tp_getset,PySSLSession_getsetlist},
5017 {Py_tp_richcompare, PySSLSession_richcompare},
5018 {Py_tp_dealloc, PySSLSession_dealloc},
5019 {Py_tp_traverse, PySSLSession_traverse},
5020 {Py_tp_clear, PySSLSession_clear},
5021 {0, 0},
5022};
5023
5024static PyType_Spec PySSLSession_spec = {
5025 "_ssl.SSLSession",
5026 sizeof(PySSLSession),
5027 0,
Christian Heimes91554e42021-05-02 09:47:45 +02005028 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_IMMUTABLETYPE,
Christian Heimes5c36da72020-11-20 09:40:12 +01005029 PySSLSession_slots,
Christian Heimes99a65702016-09-10 23:44:53 +02005030};
5031
5032
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005033/* helper routines for seeding the SSL PRNG */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005034/*[clinic input]
5035_ssl.RAND_add
Larry Hastingsdbfdc382015-05-04 06:59:46 -07005036 string as view: Py_buffer(accept={str, buffer})
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005037 entropy: double
5038 /
5039
5040Mix string into the OpenSSL PRNG state.
5041
5042entropy (a float) is a lower bound on the entropy contained in
Chandan Kumar63c2c8a2017-06-09 15:13:58 +05305043string. See RFC 4086.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005044[clinic start generated code]*/
5045
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005046static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005047_ssl_RAND_add_impl(PyObject *module, Py_buffer *view, double entropy)
Serhiy Storchaka5f31d5c2017-06-10 13:13:51 +03005048/*[clinic end generated code: output=e6dd48df9c9024e9 input=5c33017422828f5c]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005049{
Serhiy Storchaka8490f5a2015-03-20 09:00:36 +02005050 const char *buf;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02005051 Py_ssize_t len, written;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005052
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005053 buf = (const char *)view->buf;
5054 len = view->len;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02005055 do {
5056 written = Py_MIN(len, INT_MAX);
5057 RAND_add(buf, (int)written, entropy);
5058 buf += written;
5059 len -= written;
5060 } while (len);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02005061 Py_RETURN_NONE;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005062}
5063
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005064static PyObject *
Christian Heimes7f1305e2021-04-17 20:06:38 +02005065PySSL_RAND(PyObject *module, int len, int pseudo)
Victor Stinner99c8b162011-05-24 12:05:19 +02005066{
5067 int ok;
5068 PyObject *bytes;
5069 unsigned long err;
5070 const char *errstr;
5071 PyObject *v;
5072
Victor Stinner1e81a392013-12-19 16:47:04 +01005073 if (len < 0) {
5074 PyErr_SetString(PyExc_ValueError, "num must be positive");
5075 return NULL;
5076 }
5077
Victor Stinner99c8b162011-05-24 12:05:19 +02005078 bytes = PyBytes_FromStringAndSize(NULL, len);
5079 if (bytes == NULL)
5080 return NULL;
5081 if (pseudo) {
Christian Heimesa871f692020-06-01 08:58:14 +02005082 ok = RAND_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
Victor Stinner99c8b162011-05-24 12:05:19 +02005083 if (ok == 0 || ok == 1)
5084 return Py_BuildValue("NO", bytes, ok == 1 ? Py_True : Py_False);
5085 }
5086 else {
5087 ok = RAND_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
5088 if (ok == 1)
5089 return bytes;
5090 }
5091 Py_DECREF(bytes);
5092
5093 err = ERR_get_error();
5094 errstr = ERR_reason_error_string(err);
5095 v = Py_BuildValue("(ks)", err, errstr);
5096 if (v != NULL) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02005097 PyErr_SetObject(get_ssl_state(module)->PySSLErrorObject, v);
Victor Stinner99c8b162011-05-24 12:05:19 +02005098 Py_DECREF(v);
5099 }
5100 return NULL;
5101}
5102
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005103/*[clinic input]
5104_ssl.RAND_bytes
5105 n: int
5106 /
5107
5108Generate n cryptographically strong pseudo-random bytes.
5109[clinic start generated code]*/
5110
Victor Stinner99c8b162011-05-24 12:05:19 +02005111static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005112_ssl_RAND_bytes_impl(PyObject *module, int n)
5113/*[clinic end generated code: output=977da635e4838bc7 input=678ddf2872dfebfc]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02005114{
Christian Heimes7f1305e2021-04-17 20:06:38 +02005115 return PySSL_RAND(module, n, 0);
Victor Stinner99c8b162011-05-24 12:05:19 +02005116}
5117
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005118/*[clinic input]
5119_ssl.RAND_pseudo_bytes
5120 n: int
5121 /
5122
5123Generate n pseudo-random bytes.
5124
5125Return a pair (bytes, is_cryptographic). is_cryptographic is True
5126if the bytes generated are cryptographically strong.
5127[clinic start generated code]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02005128
5129static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005130_ssl_RAND_pseudo_bytes_impl(PyObject *module, int n)
5131/*[clinic end generated code: output=b1509e937000e52d input=58312bd53f9bbdd0]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02005132{
Christian Heimes2875c602021-04-19 07:27:10 +02005133 PY_SSL_DEPRECATED("RAND_pseudo_bytes", 1, NULL);
Christian Heimes7f1305e2021-04-17 20:06:38 +02005134 return PySSL_RAND(module, n, 1);
Victor Stinner99c8b162011-05-24 12:05:19 +02005135}
5136
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005137/*[clinic input]
5138_ssl.RAND_status
5139
Zackery Spytz7d37b862021-04-23 10:07:37 -06005140Returns True if the OpenSSL PRNG has been seeded with enough data and False if not.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005141
5142It is necessary to seed the PRNG with RAND_add() on some platforms before
5143using the ssl() function.
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_status_impl(PyObject *module)
Zackery Spytz7d37b862021-04-23 10:07:37 -06005148/*[clinic end generated code: output=7e0aaa2d39fdc1ad input=d5ae5aea52f36e01]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005149{
Zackery Spytz7d37b862021-04-23 10:07:37 -06005150 return PyBool_FromLong(RAND_status());
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005151}
5152
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005153/*[clinic input]
5154_ssl.get_default_verify_paths
5155
5156Return search paths and environment vars that are used by SSLContext's set_default_verify_paths() to load default CAs.
5157
5158The values are 'cert_file_env', 'cert_file', 'cert_dir_env', 'cert_dir'.
5159[clinic start generated code]*/
Christian Heimes6d7ad132013-06-09 18:02:55 +02005160
5161static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005162_ssl_get_default_verify_paths_impl(PyObject *module)
5163/*[clinic end generated code: output=e5b62a466271928b input=5210c953d98c3eb5]*/
Christian Heimes6d7ad132013-06-09 18:02:55 +02005164{
5165 PyObject *ofile_env = NULL;
5166 PyObject *ofile = NULL;
5167 PyObject *odir_env = NULL;
5168 PyObject *odir = NULL;
5169
Benjamin Petersond113c962015-07-18 10:59:13 -07005170#define CONVERT(info, target) { \
Christian Heimes6d7ad132013-06-09 18:02:55 +02005171 const char *tmp = (info); \
5172 target = NULL; \
5173 if (!tmp) { Py_INCREF(Py_None); target = Py_None; } \
5174 else if ((target = PyUnicode_DecodeFSDefault(tmp)) == NULL) { \
5175 target = PyBytes_FromString(tmp); } \
5176 if (!target) goto error; \
Benjamin Peterson025a1fd2015-11-14 15:12:38 -08005177 }
Christian Heimes6d7ad132013-06-09 18:02:55 +02005178
Benjamin Petersond113c962015-07-18 10:59:13 -07005179 CONVERT(X509_get_default_cert_file_env(), ofile_env);
5180 CONVERT(X509_get_default_cert_file(), ofile);
5181 CONVERT(X509_get_default_cert_dir_env(), odir_env);
5182 CONVERT(X509_get_default_cert_dir(), odir);
5183#undef CONVERT
Christian Heimes6d7ad132013-06-09 18:02:55 +02005184
Christian Heimes200bb1b2013-06-14 15:14:29 +02005185 return Py_BuildValue("NNNN", ofile_env, ofile, odir_env, odir);
Christian Heimes6d7ad132013-06-09 18:02:55 +02005186
5187 error:
5188 Py_XDECREF(ofile_env);
5189 Py_XDECREF(ofile);
5190 Py_XDECREF(odir_env);
5191 Py_XDECREF(odir);
5192 return NULL;
5193}
5194
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005195static PyObject*
Christian Heimes7f1305e2021-04-17 20:06:38 +02005196asn1obj2py(_sslmodulestate *state, ASN1_OBJECT *obj)
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005197{
5198 int nid;
5199 const char *ln, *sn;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005200
5201 nid = OBJ_obj2nid(obj);
5202 if (nid == NID_undef) {
5203 PyErr_Format(PyExc_ValueError, "Unknown object");
5204 return NULL;
5205 }
5206 sn = OBJ_nid2sn(nid);
5207 ln = OBJ_nid2ln(nid);
Christian Heimes7f1305e2021-04-17 20:06:38 +02005208 return Py_BuildValue("issN", nid, sn, ln, _asn1obj2py(state, obj, 1));
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005209}
5210
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005211/*[clinic input]
5212_ssl.txt2obj
5213 txt: str
5214 name: bool = False
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005215
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005216Lookup NID, short name, long name and OID of an ASN1_OBJECT.
5217
5218By default objects are looked up by OID. With name=True short and
5219long name are also matched.
5220[clinic start generated code]*/
5221
5222static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005223_ssl_txt2obj_impl(PyObject *module, const char *txt, int name)
5224/*[clinic end generated code: output=c38e3991347079c1 input=1c1e7d0aa7c48602]*/
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005225{
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005226 PyObject *result = NULL;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005227 ASN1_OBJECT *obj;
5228
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005229 obj = OBJ_txt2obj(txt, name ? 0 : 1);
5230 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01005231 PyErr_Format(PyExc_ValueError, "unknown object '%.100s'", txt);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005232 return NULL;
5233 }
Christian Heimes7f1305e2021-04-17 20:06:38 +02005234 result = asn1obj2py(get_ssl_state(module), obj);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005235 ASN1_OBJECT_free(obj);
5236 return result;
5237}
5238
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005239/*[clinic input]
5240_ssl.nid2obj
5241 nid: int
5242 /
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005243
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005244Lookup NID, short name, long name and OID of an ASN1_OBJECT by NID.
5245[clinic start generated code]*/
5246
5247static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005248_ssl_nid2obj_impl(PyObject *module, int nid)
5249/*[clinic end generated code: output=4a98ab691cd4f84a input=51787a3bee7d8f98]*/
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005250{
5251 PyObject *result = NULL;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005252 ASN1_OBJECT *obj;
5253
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005254 if (nid < NID_undef) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01005255 PyErr_SetString(PyExc_ValueError, "NID must be positive.");
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005256 return NULL;
5257 }
5258 obj = OBJ_nid2obj(nid);
5259 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01005260 PyErr_Format(PyExc_ValueError, "unknown NID %i", nid);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005261 return NULL;
5262 }
Christian Heimes7f1305e2021-04-17 20:06:38 +02005263 result = asn1obj2py(get_ssl_state(module), obj);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005264 ASN1_OBJECT_free(obj);
5265 return result;
5266}
5267
Christian Heimes46bebee2013-06-09 19:03:31 +02005268#ifdef _MSC_VER
Christian Heimes44109d72013-11-22 01:51:30 +01005269
5270static PyObject*
5271certEncodingType(DWORD encodingType)
5272{
5273 static PyObject *x509_asn = NULL;
5274 static PyObject *pkcs_7_asn = NULL;
5275
5276 if (x509_asn == NULL) {
5277 x509_asn = PyUnicode_InternFromString("x509_asn");
5278 if (x509_asn == NULL)
5279 return NULL;
5280 }
5281 if (pkcs_7_asn == NULL) {
5282 pkcs_7_asn = PyUnicode_InternFromString("pkcs_7_asn");
5283 if (pkcs_7_asn == NULL)
5284 return NULL;
5285 }
5286 switch(encodingType) {
5287 case X509_ASN_ENCODING:
5288 Py_INCREF(x509_asn);
5289 return x509_asn;
5290 case PKCS_7_ASN_ENCODING:
5291 Py_INCREF(pkcs_7_asn);
5292 return pkcs_7_asn;
5293 default:
5294 return PyLong_FromLong(encodingType);
5295 }
5296}
5297
5298static PyObject*
5299parseKeyUsage(PCCERT_CONTEXT pCertCtx, DWORD flags)
5300{
5301 CERT_ENHKEY_USAGE *usage;
5302 DWORD size, error, i;
5303 PyObject *retval;
5304
5305 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, NULL, &size)) {
5306 error = GetLastError();
5307 if (error == CRYPT_E_NOT_FOUND) {
5308 Py_RETURN_TRUE;
5309 }
5310 return PyErr_SetFromWindowsErr(error);
5311 }
5312
5313 usage = (CERT_ENHKEY_USAGE*)PyMem_Malloc(size);
5314 if (usage == NULL) {
5315 return PyErr_NoMemory();
5316 }
5317
5318 /* Now get the actual enhanced usage property */
5319 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, usage, &size)) {
5320 PyMem_Free(usage);
5321 error = GetLastError();
5322 if (error == CRYPT_E_NOT_FOUND) {
5323 Py_RETURN_TRUE;
5324 }
5325 return PyErr_SetFromWindowsErr(error);
5326 }
Christian Heimes915cd3f2019-09-09 18:06:55 +02005327 retval = PyFrozenSet_New(NULL);
Christian Heimes44109d72013-11-22 01:51:30 +01005328 if (retval == NULL) {
5329 goto error;
5330 }
5331 for (i = 0; i < usage->cUsageIdentifier; ++i) {
5332 if (usage->rgpszUsageIdentifier[i]) {
5333 PyObject *oid;
5334 int err;
5335 oid = PyUnicode_FromString(usage->rgpszUsageIdentifier[i]);
5336 if (oid == NULL) {
5337 Py_CLEAR(retval);
5338 goto error;
5339 }
5340 err = PySet_Add(retval, oid);
5341 Py_DECREF(oid);
5342 if (err == -1) {
5343 Py_CLEAR(retval);
5344 goto error;
5345 }
5346 }
5347 }
5348 error:
5349 PyMem_Free(usage);
5350 return retval;
5351}
5352
kctherookied93fbbf2019-03-29 00:59:06 +07005353static HCERTSTORE
5354ssl_collect_certificates(const char *store_name)
5355{
5356/* this function collects the system certificate stores listed in
5357 * system_stores into a collection certificate store for being
5358 * enumerated. The store must be readable to be added to the
5359 * store collection.
5360 */
5361
5362 HCERTSTORE hCollectionStore = NULL, hSystemStore = NULL;
5363 static DWORD system_stores[] = {
5364 CERT_SYSTEM_STORE_LOCAL_MACHINE,
5365 CERT_SYSTEM_STORE_LOCAL_MACHINE_ENTERPRISE,
5366 CERT_SYSTEM_STORE_LOCAL_MACHINE_GROUP_POLICY,
5367 CERT_SYSTEM_STORE_CURRENT_USER,
5368 CERT_SYSTEM_STORE_CURRENT_USER_GROUP_POLICY,
5369 CERT_SYSTEM_STORE_SERVICES,
5370 CERT_SYSTEM_STORE_USERS};
5371 size_t i, storesAdded;
5372 BOOL result;
5373
5374 hCollectionStore = CertOpenStore(CERT_STORE_PROV_COLLECTION, 0,
5375 (HCRYPTPROV)NULL, 0, NULL);
5376 if (!hCollectionStore) {
5377 return NULL;
5378 }
5379 storesAdded = 0;
5380 for (i = 0; i < sizeof(system_stores) / sizeof(DWORD); i++) {
5381 hSystemStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0,
5382 (HCRYPTPROV)NULL,
5383 CERT_STORE_READONLY_FLAG |
5384 system_stores[i], store_name);
5385 if (hSystemStore) {
5386 result = CertAddStoreToCollection(hCollectionStore, hSystemStore,
5387 CERT_PHYSICAL_STORE_ADD_ENABLE_FLAG, 0);
5388 if (result) {
5389 ++storesAdded;
5390 }
neoneneed701292019-09-09 21:33:43 +09005391 CertCloseStore(hSystemStore, 0); /* flag must be 0 */
kctherookied93fbbf2019-03-29 00:59:06 +07005392 }
5393 }
5394 if (storesAdded == 0) {
5395 CertCloseStore(hCollectionStore, CERT_CLOSE_STORE_FORCE_FLAG);
5396 return NULL;
5397 }
5398
5399 return hCollectionStore;
5400}
5401
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005402/*[clinic input]
5403_ssl.enum_certificates
5404 store_name: str
5405
5406Retrieve certificates from Windows' cert store.
5407
5408store_name may be one of 'CA', 'ROOT' or 'MY'. The system may provide
5409more cert storages, too. The function returns a list of (bytes,
5410encoding_type, trust) tuples. The encoding_type flag can be interpreted
5411with X509_ASN_ENCODING or PKCS_7_ASN_ENCODING. The trust setting is either
5412a set of OIDs or the boolean True.
5413[clinic start generated code]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00005414
Christian Heimes46bebee2013-06-09 19:03:31 +02005415static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005416_ssl_enum_certificates_impl(PyObject *module, const char *store_name)
5417/*[clinic end generated code: output=5134dc8bb3a3c893 input=915f60d70461ea4e]*/
Christian Heimes46bebee2013-06-09 19:03:31 +02005418{
kctherookied93fbbf2019-03-29 00:59:06 +07005419 HCERTSTORE hCollectionStore = NULL;
Christian Heimes44109d72013-11-22 01:51:30 +01005420 PCCERT_CONTEXT pCertCtx = NULL;
5421 PyObject *keyusage = NULL, *cert = NULL, *enc = NULL, *tup = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02005422 PyObject *result = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02005423
Christian Heimes915cd3f2019-09-09 18:06:55 +02005424 result = PySet_New(NULL);
Christian Heimes44109d72013-11-22 01:51:30 +01005425 if (result == NULL) {
5426 return NULL;
5427 }
kctherookied93fbbf2019-03-29 00:59:06 +07005428 hCollectionStore = ssl_collect_certificates(store_name);
5429 if (hCollectionStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02005430 Py_DECREF(result);
5431 return PyErr_SetFromWindowsErr(GetLastError());
5432 }
5433
kctherookied93fbbf2019-03-29 00:59:06 +07005434 while (pCertCtx = CertEnumCertificatesInStore(hCollectionStore, pCertCtx)) {
Christian Heimes44109d72013-11-22 01:51:30 +01005435 cert = PyBytes_FromStringAndSize((const char*)pCertCtx->pbCertEncoded,
5436 pCertCtx->cbCertEncoded);
5437 if (!cert) {
5438 Py_CLEAR(result);
5439 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02005440 }
Christian Heimes44109d72013-11-22 01:51:30 +01005441 if ((enc = certEncodingType(pCertCtx->dwCertEncodingType)) == NULL) {
5442 Py_CLEAR(result);
5443 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02005444 }
Christian Heimes44109d72013-11-22 01:51:30 +01005445 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG);
5446 if (keyusage == Py_True) {
5447 Py_DECREF(keyusage);
5448 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_EXT_ONLY_ENHKEY_USAGE_FLAG);
Christian Heimes46bebee2013-06-09 19:03:31 +02005449 }
Christian Heimes44109d72013-11-22 01:51:30 +01005450 if (keyusage == NULL) {
5451 Py_CLEAR(result);
5452 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02005453 }
Christian Heimes44109d72013-11-22 01:51:30 +01005454 if ((tup = PyTuple_New(3)) == NULL) {
5455 Py_CLEAR(result);
5456 break;
5457 }
5458 PyTuple_SET_ITEM(tup, 0, cert);
5459 cert = NULL;
5460 PyTuple_SET_ITEM(tup, 1, enc);
5461 enc = NULL;
5462 PyTuple_SET_ITEM(tup, 2, keyusage);
5463 keyusage = NULL;
Christian Heimes915cd3f2019-09-09 18:06:55 +02005464 if (PySet_Add(result, tup) == -1) {
5465 Py_CLEAR(result);
5466 Py_CLEAR(tup);
5467 break;
Christian Heimes44109d72013-11-22 01:51:30 +01005468 }
5469 Py_CLEAR(tup);
5470 }
5471 if (pCertCtx) {
5472 /* loop ended with an error, need to clean up context manually */
5473 CertFreeCertificateContext(pCertCtx);
Christian Heimes46bebee2013-06-09 19:03:31 +02005474 }
5475
5476 /* In error cases cert, enc and tup may not be NULL */
5477 Py_XDECREF(cert);
5478 Py_XDECREF(enc);
Christian Heimes44109d72013-11-22 01:51:30 +01005479 Py_XDECREF(keyusage);
Christian Heimes46bebee2013-06-09 19:03:31 +02005480 Py_XDECREF(tup);
5481
kctherookied93fbbf2019-03-29 00:59:06 +07005482 /* CERT_CLOSE_STORE_FORCE_FLAG forces freeing of memory for all contexts
5483 associated with the store, in this case our collection store and the
5484 associated system stores. */
5485 if (!CertCloseStore(hCollectionStore, CERT_CLOSE_STORE_FORCE_FLAG)) {
Christian Heimes46bebee2013-06-09 19:03:31 +02005486 /* This error case might shadow another exception.*/
Christian Heimes44109d72013-11-22 01:51:30 +01005487 Py_XDECREF(result);
5488 return PyErr_SetFromWindowsErr(GetLastError());
5489 }
kctherookied93fbbf2019-03-29 00:59:06 +07005490
Christian Heimes915cd3f2019-09-09 18:06:55 +02005491 /* convert set to list */
5492 if (result == NULL) {
5493 return NULL;
5494 } else {
5495 PyObject *lst = PySequence_List(result);
5496 Py_DECREF(result);
5497 return lst;
5498 }
Christian Heimes44109d72013-11-22 01:51:30 +01005499}
5500
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005501/*[clinic input]
5502_ssl.enum_crls
5503 store_name: str
5504
5505Retrieve CRLs from Windows' cert store.
5506
5507store_name may be one of 'CA', 'ROOT' or 'MY'. The system may provide
5508more cert storages, too. The function returns a list of (bytes,
5509encoding_type) tuples. The encoding_type flag can be interpreted with
5510X509_ASN_ENCODING or PKCS_7_ASN_ENCODING.
5511[clinic start generated code]*/
Christian Heimes44109d72013-11-22 01:51:30 +01005512
5513static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005514_ssl_enum_crls_impl(PyObject *module, const char *store_name)
5515/*[clinic end generated code: output=bce467f60ccd03b6 input=a1f1d7629f1c5d3d]*/
Christian Heimes44109d72013-11-22 01:51:30 +01005516{
kctherookied93fbbf2019-03-29 00:59:06 +07005517 HCERTSTORE hCollectionStore = NULL;
Christian Heimes44109d72013-11-22 01:51:30 +01005518 PCCRL_CONTEXT pCrlCtx = NULL;
5519 PyObject *crl = NULL, *enc = NULL, *tup = NULL;
5520 PyObject *result = NULL;
5521
Christian Heimes915cd3f2019-09-09 18:06:55 +02005522 result = PySet_New(NULL);
Christian Heimes44109d72013-11-22 01:51:30 +01005523 if (result == NULL) {
5524 return NULL;
5525 }
kctherookied93fbbf2019-03-29 00:59:06 +07005526 hCollectionStore = ssl_collect_certificates(store_name);
5527 if (hCollectionStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02005528 Py_DECREF(result);
5529 return PyErr_SetFromWindowsErr(GetLastError());
5530 }
Christian Heimes44109d72013-11-22 01:51:30 +01005531
kctherookied93fbbf2019-03-29 00:59:06 +07005532 while (pCrlCtx = CertEnumCRLsInStore(hCollectionStore, pCrlCtx)) {
Christian Heimes44109d72013-11-22 01:51:30 +01005533 crl = PyBytes_FromStringAndSize((const char*)pCrlCtx->pbCrlEncoded,
5534 pCrlCtx->cbCrlEncoded);
5535 if (!crl) {
5536 Py_CLEAR(result);
5537 break;
5538 }
5539 if ((enc = certEncodingType(pCrlCtx->dwCertEncodingType)) == NULL) {
5540 Py_CLEAR(result);
5541 break;
5542 }
5543 if ((tup = PyTuple_New(2)) == NULL) {
5544 Py_CLEAR(result);
5545 break;
5546 }
5547 PyTuple_SET_ITEM(tup, 0, crl);
5548 crl = NULL;
5549 PyTuple_SET_ITEM(tup, 1, enc);
5550 enc = NULL;
5551
Christian Heimes915cd3f2019-09-09 18:06:55 +02005552 if (PySet_Add(result, tup) == -1) {
5553 Py_CLEAR(result);
5554 Py_CLEAR(tup);
5555 break;
Christian Heimes44109d72013-11-22 01:51:30 +01005556 }
5557 Py_CLEAR(tup);
Christian Heimes46bebee2013-06-09 19:03:31 +02005558 }
Christian Heimes44109d72013-11-22 01:51:30 +01005559 if (pCrlCtx) {
5560 /* loop ended with an error, need to clean up context manually */
5561 CertFreeCRLContext(pCrlCtx);
5562 }
5563
5564 /* In error cases cert, enc and tup may not be NULL */
5565 Py_XDECREF(crl);
5566 Py_XDECREF(enc);
5567 Py_XDECREF(tup);
5568
kctherookied93fbbf2019-03-29 00:59:06 +07005569 /* CERT_CLOSE_STORE_FORCE_FLAG forces freeing of memory for all contexts
5570 associated with the store, in this case our collection store and the
5571 associated system stores. */
5572 if (!CertCloseStore(hCollectionStore, CERT_CLOSE_STORE_FORCE_FLAG)) {
Christian Heimes44109d72013-11-22 01:51:30 +01005573 /* This error case might shadow another exception.*/
5574 Py_XDECREF(result);
5575 return PyErr_SetFromWindowsErr(GetLastError());
5576 }
Christian Heimes915cd3f2019-09-09 18:06:55 +02005577 /* convert set to list */
5578 if (result == NULL) {
5579 return NULL;
5580 } else {
5581 PyObject *lst = PySequence_List(result);
5582 Py_DECREF(result);
5583 return lst;
5584 }
Christian Heimes46bebee2013-06-09 19:03:31 +02005585}
Christian Heimes44109d72013-11-22 01:51:30 +01005586
5587#endif /* _MSC_VER */
Bill Janssen40a0f662008-08-12 16:56:25 +00005588
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005589/* List of functions exported by this module. */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005590static PyMethodDef PySSL_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005591 _SSL__TEST_DECODE_CERT_METHODDEF
5592 _SSL_RAND_ADD_METHODDEF
5593 _SSL_RAND_BYTES_METHODDEF
5594 _SSL_RAND_PSEUDO_BYTES_METHODDEF
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005595 _SSL_RAND_STATUS_METHODDEF
5596 _SSL_GET_DEFAULT_VERIFY_PATHS_METHODDEF
5597 _SSL_ENUM_CERTIFICATES_METHODDEF
5598 _SSL_ENUM_CRLS_METHODDEF
5599 _SSL_TXT2OBJ_METHODDEF
5600 _SSL_NID2OBJ_METHODDEF
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005601 {NULL, NULL} /* Sentinel */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005602};
5603
5604
Christian Heimes7f1305e2021-04-17 20:06:38 +02005605PyDoc_STRVAR(module_doc,
5606"Implementation module for SSL socket operations. See the socket module\n\
5607for documentation.");
Christian Heimes5c36da72020-11-20 09:40:12 +01005608
5609static int
5610sslmodule_init_exceptions(PyObject *module)
5611{
Christian Heimes7f1305e2021-04-17 20:06:38 +02005612 _sslmodulestate *state = get_ssl_state(module);
Christian Heimes5c36da72020-11-20 09:40:12 +01005613 PyObject *bases = NULL;
5614
Christian Heimes7f1305e2021-04-17 20:06:38 +02005615#define add_exception(exc, name, doc, base) \
5616do { \
5617 (exc) = PyErr_NewExceptionWithDoc("ssl." name, (doc), (base), NULL); \
5618 if ((state) == NULL) goto error; \
5619 if (PyModule_AddObjectRef(module, name, exc) < 0) goto error; \
Christian Heimes5c36da72020-11-20 09:40:12 +01005620} while(0)
5621
Christian Heimes7f1305e2021-04-17 20:06:38 +02005622 state->PySSLErrorObject = PyType_FromSpecWithBases(
5623 &sslerror_type_spec, PyExc_OSError);
5624 if (state->PySSLErrorObject == NULL) {
Christian Heimes5c36da72020-11-20 09:40:12 +01005625 goto error;
5626 }
Christian Heimes7f1305e2021-04-17 20:06:38 +02005627 if (PyModule_AddObjectRef(module, "SSLError", state->PySSLErrorObject) < 0) {
Christian Heimes5c36da72020-11-20 09:40:12 +01005628 goto error;
5629 }
5630
5631 /* ssl.CertificateError used to be a subclass of ValueError */
Christian Heimes7f1305e2021-04-17 20:06:38 +02005632 bases = PyTuple_Pack(2, state->PySSLErrorObject, PyExc_ValueError);
Christian Heimes5c36da72020-11-20 09:40:12 +01005633 if (bases == NULL) {
5634 goto error;
5635 }
5636 add_exception(
Christian Heimes7f1305e2021-04-17 20:06:38 +02005637 state->PySSLCertVerificationErrorObject,
Christian Heimes5c36da72020-11-20 09:40:12 +01005638 "SSLCertVerificationError",
5639 SSLCertVerificationError_doc,
5640 bases
5641 );
5642 Py_CLEAR(bases);
5643
5644 add_exception(
Christian Heimes7f1305e2021-04-17 20:06:38 +02005645 state->PySSLZeroReturnErrorObject,
Christian Heimes5c36da72020-11-20 09:40:12 +01005646 "SSLZeroReturnError",
5647 SSLZeroReturnError_doc,
Christian Heimes7f1305e2021-04-17 20:06:38 +02005648 state->PySSLErrorObject
Christian Heimes5c36da72020-11-20 09:40:12 +01005649 );
5650
5651 add_exception(
Christian Heimes7f1305e2021-04-17 20:06:38 +02005652 state->PySSLWantWriteErrorObject,
Christian Heimes5c36da72020-11-20 09:40:12 +01005653 "SSLWantWriteError",
5654 SSLWantWriteError_doc,
Christian Heimes7f1305e2021-04-17 20:06:38 +02005655 state->PySSLErrorObject
Christian Heimes5c36da72020-11-20 09:40:12 +01005656 );
5657
5658 add_exception(
Christian Heimes7f1305e2021-04-17 20:06:38 +02005659 state->PySSLWantReadErrorObject,
Christian Heimes5c36da72020-11-20 09:40:12 +01005660 "SSLWantReadError",
5661 SSLWantReadError_doc,
Christian Heimes7f1305e2021-04-17 20:06:38 +02005662 state->PySSLErrorObject
Christian Heimes5c36da72020-11-20 09:40:12 +01005663 );
5664
5665 add_exception(
Christian Heimes7f1305e2021-04-17 20:06:38 +02005666 state->PySSLSyscallErrorObject,
Christian Heimes5c36da72020-11-20 09:40:12 +01005667 "SSLSyscallError",
5668 SSLSyscallError_doc,
Christian Heimes7f1305e2021-04-17 20:06:38 +02005669 state->PySSLErrorObject
Christian Heimes5c36da72020-11-20 09:40:12 +01005670 );
5671
5672 add_exception(
Christian Heimes7f1305e2021-04-17 20:06:38 +02005673 state->PySSLEOFErrorObject,
Christian Heimes5c36da72020-11-20 09:40:12 +01005674 "SSLEOFError",
5675 SSLEOFError_doc,
Christian Heimes7f1305e2021-04-17 20:06:38 +02005676 state->PySSLErrorObject
Christian Heimes5c36da72020-11-20 09:40:12 +01005677 );
5678#undef add_exception
5679
5680 return 0;
5681 error:
5682 Py_XDECREF(bases);
5683 return -1;
5684}
5685
5686static int
5687sslmodule_init_socketapi(PyObject *module)
5688{
Christian Heimes7f1305e2021-04-17 20:06:38 +02005689 _sslmodulestate *state = get_ssl_state(module);
5690 PySocketModule_APIObject *sockmod = PySocketModule_ImportModuleAndAPI();
Christian Heimes5c36da72020-11-20 09:40:12 +01005691
Christian Heimes7f1305e2021-04-17 20:06:38 +02005692 if ((sockmod == NULL) || (sockmod->Sock_Type == NULL)) {
Christian Heimes5c36da72020-11-20 09:40:12 +01005693 return -1;
Christian Heimes5c36da72020-11-20 09:40:12 +01005694 }
Christian Heimes7f1305e2021-04-17 20:06:38 +02005695 state->Sock_Type = sockmod->Sock_Type;
5696 Py_INCREF(state->Sock_Type);
Christian Heimes5c36da72020-11-20 09:40:12 +01005697 return 0;
5698}
Christian Heimesc941e622017-09-05 15:47:11 +02005699
Christian Heimes5c36da72020-11-20 09:40:12 +01005700static int
5701sslmodule_init_constants(PyObject *m)
5702{
Christian Heimes7f1305e2021-04-17 20:06:38 +02005703
Christian Heimes892d66e2018-01-29 14:10:18 +01005704 PyModule_AddStringConstant(m, "_DEFAULT_CIPHERS",
5705 PY_SSL_DEFAULT_CIPHER_STRING);
5706
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005707 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
5708 PY_SSL_ERROR_ZERO_RETURN);
5709 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
5710 PY_SSL_ERROR_WANT_READ);
5711 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
5712 PY_SSL_ERROR_WANT_WRITE);
5713 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
5714 PY_SSL_ERROR_WANT_X509_LOOKUP);
5715 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
5716 PY_SSL_ERROR_SYSCALL);
5717 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
5718 PY_SSL_ERROR_SSL);
5719 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
5720 PY_SSL_ERROR_WANT_CONNECT);
5721 /* non ssl.h errorcodes */
5722 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
5723 PY_SSL_ERROR_EOF);
5724 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
5725 PY_SSL_ERROR_INVALID_ERROR_CODE);
5726 /* cert requirements */
5727 PyModule_AddIntConstant(m, "CERT_NONE",
5728 PY_SSL_CERT_NONE);
5729 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
5730 PY_SSL_CERT_OPTIONAL);
5731 PyModule_AddIntConstant(m, "CERT_REQUIRED",
5732 PY_SSL_CERT_REQUIRED);
Christian Heimes22587792013-11-21 23:56:13 +01005733 /* CRL verification for verification_flags */
5734 PyModule_AddIntConstant(m, "VERIFY_DEFAULT",
5735 0);
5736 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_LEAF",
5737 X509_V_FLAG_CRL_CHECK);
5738 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_CHAIN",
5739 X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
5740 PyModule_AddIntConstant(m, "VERIFY_X509_STRICT",
5741 X509_V_FLAG_X509_STRICT);
Chris Burre0b4aa02021-03-18 09:24:01 +01005742 PyModule_AddIntConstant(m, "VERIFY_ALLOW_PROXY_CERTS",
5743 X509_V_FLAG_ALLOW_PROXY_CERTS);
Benjamin Peterson990fcaa2015-03-04 22:49:41 -05005744 PyModule_AddIntConstant(m, "VERIFY_X509_TRUSTED_FIRST",
5745 X509_V_FLAG_TRUSTED_FIRST);
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00005746
l0x64d97522021-04-19 13:51:18 +02005747#ifdef X509_V_FLAG_PARTIAL_CHAIN
5748 PyModule_AddIntConstant(m, "VERIFY_X509_PARTIAL_CHAIN",
5749 X509_V_FLAG_PARTIAL_CHAIN);
5750#endif
5751
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01005752 /* Alert Descriptions from ssl.h */
5753 /* note RESERVED constants no longer intended for use have been removed */
5754 /* http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-6 */
5755
5756#define ADD_AD_CONSTANT(s) \
5757 PyModule_AddIntConstant(m, "ALERT_DESCRIPTION_"#s, \
5758 SSL_AD_##s)
5759
5760 ADD_AD_CONSTANT(CLOSE_NOTIFY);
5761 ADD_AD_CONSTANT(UNEXPECTED_MESSAGE);
5762 ADD_AD_CONSTANT(BAD_RECORD_MAC);
5763 ADD_AD_CONSTANT(RECORD_OVERFLOW);
5764 ADD_AD_CONSTANT(DECOMPRESSION_FAILURE);
5765 ADD_AD_CONSTANT(HANDSHAKE_FAILURE);
5766 ADD_AD_CONSTANT(BAD_CERTIFICATE);
5767 ADD_AD_CONSTANT(UNSUPPORTED_CERTIFICATE);
5768 ADD_AD_CONSTANT(CERTIFICATE_REVOKED);
5769 ADD_AD_CONSTANT(CERTIFICATE_EXPIRED);
5770 ADD_AD_CONSTANT(CERTIFICATE_UNKNOWN);
5771 ADD_AD_CONSTANT(ILLEGAL_PARAMETER);
5772 ADD_AD_CONSTANT(UNKNOWN_CA);
5773 ADD_AD_CONSTANT(ACCESS_DENIED);
5774 ADD_AD_CONSTANT(DECODE_ERROR);
5775 ADD_AD_CONSTANT(DECRYPT_ERROR);
5776 ADD_AD_CONSTANT(PROTOCOL_VERSION);
5777 ADD_AD_CONSTANT(INSUFFICIENT_SECURITY);
5778 ADD_AD_CONSTANT(INTERNAL_ERROR);
5779 ADD_AD_CONSTANT(USER_CANCELLED);
5780 ADD_AD_CONSTANT(NO_RENEGOTIATION);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01005781 /* Not all constants are in old OpenSSL versions */
Antoine Pitrou912fbff2013-03-30 16:29:32 +01005782#ifdef SSL_AD_UNSUPPORTED_EXTENSION
5783 ADD_AD_CONSTANT(UNSUPPORTED_EXTENSION);
5784#endif
5785#ifdef SSL_AD_CERTIFICATE_UNOBTAINABLE
5786 ADD_AD_CONSTANT(CERTIFICATE_UNOBTAINABLE);
5787#endif
5788#ifdef SSL_AD_UNRECOGNIZED_NAME
5789 ADD_AD_CONSTANT(UNRECOGNIZED_NAME);
5790#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01005791#ifdef SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE
5792 ADD_AD_CONSTANT(BAD_CERTIFICATE_STATUS_RESPONSE);
5793#endif
5794#ifdef SSL_AD_BAD_CERTIFICATE_HASH_VALUE
5795 ADD_AD_CONSTANT(BAD_CERTIFICATE_HASH_VALUE);
5796#endif
5797#ifdef SSL_AD_UNKNOWN_PSK_IDENTITY
5798 ADD_AD_CONSTANT(UNKNOWN_PSK_IDENTITY);
5799#endif
5800
5801#undef ADD_AD_CONSTANT
5802
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005803 /* protocol versions */
Victor Stinner3de49192011-05-09 00:42:58 +02005804#ifndef OPENSSL_NO_SSL2
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005805 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
5806 PY_SSL_VERSION_SSL2);
Victor Stinner3de49192011-05-09 00:42:58 +02005807#endif
Benjamin Petersone32467c2014-12-05 21:59:35 -05005808#ifndef OPENSSL_NO_SSL3
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005809 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
5810 PY_SSL_VERSION_SSL3);
Benjamin Petersone32467c2014-12-05 21:59:35 -05005811#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005812 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
Christian Heimes598894f2016-09-05 23:19:05 +02005813 PY_SSL_VERSION_TLS);
5814 PyModule_AddIntConstant(m, "PROTOCOL_TLS",
5815 PY_SSL_VERSION_TLS);
Christian Heimes5fe668c2016-09-12 00:01:11 +02005816 PyModule_AddIntConstant(m, "PROTOCOL_TLS_CLIENT",
5817 PY_SSL_VERSION_TLS_CLIENT);
5818 PyModule_AddIntConstant(m, "PROTOCOL_TLS_SERVER",
5819 PY_SSL_VERSION_TLS_SERVER);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005820 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
5821 PY_SSL_VERSION_TLS1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01005822 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_1",
5823 PY_SSL_VERSION_TLS1_1);
5824 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_2",
5825 PY_SSL_VERSION_TLS1_2);
Antoine Pitrou04f6a322010-04-05 21:40:07 +00005826
Antoine Pitroub5218772010-05-21 09:56:06 +00005827 /* protocol options */
Antoine Pitrou3f366312012-01-27 09:50:45 +01005828 PyModule_AddIntConstant(m, "OP_ALL",
5829 SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
Antoine Pitroub5218772010-05-21 09:56:06 +00005830 PyModule_AddIntConstant(m, "OP_NO_SSLv2", SSL_OP_NO_SSLv2);
5831 PyModule_AddIntConstant(m, "OP_NO_SSLv3", SSL_OP_NO_SSLv3);
5832 PyModule_AddIntConstant(m, "OP_NO_TLSv1", SSL_OP_NO_TLSv1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01005833 PyModule_AddIntConstant(m, "OP_NO_TLSv1_1", SSL_OP_NO_TLSv1_1);
5834 PyModule_AddIntConstant(m, "OP_NO_TLSv1_2", SSL_OP_NO_TLSv1_2);
Christian Heimescb5b68a2017-09-07 18:07:00 -07005835#ifdef SSL_OP_NO_TLSv1_3
5836 PyModule_AddIntConstant(m, "OP_NO_TLSv1_3", SSL_OP_NO_TLSv1_3);
5837#else
5838 PyModule_AddIntConstant(m, "OP_NO_TLSv1_3", 0);
5839#endif
Antoine Pitrou6db49442011-12-19 13:27:11 +01005840 PyModule_AddIntConstant(m, "OP_CIPHER_SERVER_PREFERENCE",
5841 SSL_OP_CIPHER_SERVER_PREFERENCE);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01005842 PyModule_AddIntConstant(m, "OP_SINGLE_DH_USE", SSL_OP_SINGLE_DH_USE);
Christian Heimes99a65702016-09-10 23:44:53 +02005843 PyModule_AddIntConstant(m, "OP_NO_TICKET", SSL_OP_NO_TICKET);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01005844#ifdef SSL_OP_SINGLE_ECDH_USE
Antoine Pitrou923df6f2011-12-19 17:16:51 +01005845 PyModule_AddIntConstant(m, "OP_SINGLE_ECDH_USE", SSL_OP_SINGLE_ECDH_USE);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01005846#endif
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01005847#ifdef SSL_OP_NO_COMPRESSION
5848 PyModule_AddIntConstant(m, "OP_NO_COMPRESSION",
5849 SSL_OP_NO_COMPRESSION);
5850#endif
Christian Heimes05d9fe32018-02-27 08:55:39 +01005851#ifdef SSL_OP_ENABLE_MIDDLEBOX_COMPAT
5852 PyModule_AddIntConstant(m, "OP_ENABLE_MIDDLEBOX_COMPAT",
5853 SSL_OP_ENABLE_MIDDLEBOX_COMPAT);
5854#endif
Christian Heimes67c48012018-05-15 16:25:40 -04005855#ifdef SSL_OP_NO_RENEGOTIATION
5856 PyModule_AddIntConstant(m, "OP_NO_RENEGOTIATION",
5857 SSL_OP_NO_RENEGOTIATION);
5858#endif
Christian Heimes6f37ebc2021-04-09 17:59:21 +02005859#ifdef SSL_OP_IGNORE_UNEXPECTED_EOF
5860 PyModule_AddIntConstant(m, "OP_IGNORE_UNEXPECTED_EOF",
5861 SSL_OP_IGNORE_UNEXPECTED_EOF);
5862#endif
Antoine Pitroub5218772010-05-21 09:56:06 +00005863
Christian Heimes61d478c2018-01-27 15:51:38 +01005864#ifdef X509_CHECK_FLAG_ALWAYS_CHECK_SUBJECT
5865 PyModule_AddIntConstant(m, "HOSTFLAG_ALWAYS_CHECK_SUBJECT",
5866 X509_CHECK_FLAG_ALWAYS_CHECK_SUBJECT);
5867#endif
5868#ifdef X509_CHECK_FLAG_NEVER_CHECK_SUBJECT
5869 PyModule_AddIntConstant(m, "HOSTFLAG_NEVER_CHECK_SUBJECT",
5870 X509_CHECK_FLAG_NEVER_CHECK_SUBJECT);
5871#endif
5872#ifdef X509_CHECK_FLAG_NO_WILDCARDS
5873 PyModule_AddIntConstant(m, "HOSTFLAG_NO_WILDCARDS",
5874 X509_CHECK_FLAG_NO_WILDCARDS);
5875#endif
5876#ifdef X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS
5877 PyModule_AddIntConstant(m, "HOSTFLAG_NO_PARTIAL_WILDCARDS",
5878 X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS);
5879#endif
5880#ifdef X509_CHECK_FLAG_MULTI_LABEL_WILDCARDS
5881 PyModule_AddIntConstant(m, "HOSTFLAG_MULTI_LABEL_WILDCARDS",
5882 X509_CHECK_FLAG_MULTI_LABEL_WILDCARDS);
5883#endif
5884#ifdef X509_CHECK_FLAG_SINGLE_LABEL_SUBDOMAINS
5885 PyModule_AddIntConstant(m, "HOSTFLAG_SINGLE_LABEL_SUBDOMAINS",
5886 X509_CHECK_FLAG_SINGLE_LABEL_SUBDOMAINS);
5887#endif
5888
Christian Heimes666991f2021-04-26 15:01:40 +02005889 /* file types */
5890 PyModule_AddIntConstant(m, "ENCODING_PEM", PY_SSL_ENCODING_PEM);
5891 PyModule_AddIntConstant(m, "ENCODING_DER", PY_SSL_ENCODING_DER);
5892
Christian Heimes698dde12018-02-27 11:54:43 +01005893 /* protocol versions */
5894 PyModule_AddIntConstant(m, "PROTO_MINIMUM_SUPPORTED",
5895 PY_PROTO_MINIMUM_SUPPORTED);
5896 PyModule_AddIntConstant(m, "PROTO_MAXIMUM_SUPPORTED",
5897 PY_PROTO_MAXIMUM_SUPPORTED);
5898 PyModule_AddIntConstant(m, "PROTO_SSLv3", PY_PROTO_SSLv3);
5899 PyModule_AddIntConstant(m, "PROTO_TLSv1", PY_PROTO_TLSv1);
5900 PyModule_AddIntConstant(m, "PROTO_TLSv1_1", PY_PROTO_TLSv1_1);
5901 PyModule_AddIntConstant(m, "PROTO_TLSv1_2", PY_PROTO_TLSv1_2);
5902 PyModule_AddIntConstant(m, "PROTO_TLSv1_3", PY_PROTO_TLSv1_3);
Antoine Pitroud5323212010-10-22 18:19:07 +00005903
Victor Stinnerb37672d2018-11-22 03:37:50 +01005904#define addbool(m, key, value) \
5905 do { \
5906 PyObject *bool_obj = (value) ? Py_True : Py_False; \
5907 Py_INCREF(bool_obj); \
5908 PyModule_AddObject((m), (key), bool_obj); \
5909 } while (0)
Christian Heimes698dde12018-02-27 11:54:43 +01005910
Christian Heimes698dde12018-02-27 11:54:43 +01005911 addbool(m, "HAS_SNI", 1);
Christian Heimes698dde12018-02-27 11:54:43 +01005912 addbool(m, "HAS_TLS_UNIQUE", 1);
Christian Heimes698dde12018-02-27 11:54:43 +01005913 addbool(m, "HAS_ECDH", 1);
Christian Heimes698dde12018-02-27 11:54:43 +01005914 addbool(m, "HAS_NPN", 0);
Christian Heimes698dde12018-02-27 11:54:43 +01005915 addbool(m, "HAS_ALPN", 1);
Christian Heimes698dde12018-02-27 11:54:43 +01005916
5917#if defined(SSL2_VERSION) && !defined(OPENSSL_NO_SSL2)
5918 addbool(m, "HAS_SSLv2", 1);
5919#else
5920 addbool(m, "HAS_SSLv2", 0);
5921#endif
5922
5923#if defined(SSL3_VERSION) && !defined(OPENSSL_NO_SSL3)
5924 addbool(m, "HAS_SSLv3", 1);
5925#else
5926 addbool(m, "HAS_SSLv3", 0);
5927#endif
5928
5929#if defined(TLS1_VERSION) && !defined(OPENSSL_NO_TLS1)
5930 addbool(m, "HAS_TLSv1", 1);
5931#else
5932 addbool(m, "HAS_TLSv1", 0);
5933#endif
5934
5935#if defined(TLS1_1_VERSION) && !defined(OPENSSL_NO_TLS1_1)
5936 addbool(m, "HAS_TLSv1_1", 1);
5937#else
5938 addbool(m, "HAS_TLSv1_1", 0);
5939#endif
5940
5941#if defined(TLS1_2_VERSION) && !defined(OPENSSL_NO_TLS1_2)
5942 addbool(m, "HAS_TLSv1_2", 1);
5943#else
5944 addbool(m, "HAS_TLSv1_2", 0);
5945#endif
Benjamin Petersoncca27322015-01-23 16:35:37 -05005946
Christian Heimescb5b68a2017-09-07 18:07:00 -07005947#if defined(TLS1_3_VERSION) && !defined(OPENSSL_NO_TLS1_3)
Christian Heimes698dde12018-02-27 11:54:43 +01005948 addbool(m, "HAS_TLSv1_3", 1);
Christian Heimescb5b68a2017-09-07 18:07:00 -07005949#else
Christian Heimes698dde12018-02-27 11:54:43 +01005950 addbool(m, "HAS_TLSv1_3", 0);
Christian Heimescb5b68a2017-09-07 18:07:00 -07005951#endif
Christian Heimescb5b68a2017-09-07 18:07:00 -07005952
Christian Heimes5c36da72020-11-20 09:40:12 +01005953 return 0;
5954}
5955
Christian Heimes7f1305e2021-04-17 20:06:38 +02005956static int
5957sslmodule_init_errorcodes(PyObject *module)
5958{
5959 _sslmodulestate *state = get_ssl_state(module);
Christian Heimes5c36da72020-11-20 09:40:12 +01005960
Christian Heimes7f1305e2021-04-17 20:06:38 +02005961 struct py_ssl_error_code *errcode;
5962 struct py_ssl_library_code *libcode;
Christian Heimes5c36da72020-11-20 09:40:12 +01005963
Christian Heimes7f1305e2021-04-17 20:06:38 +02005964 /* Mappings for error codes */
5965 state->err_codes_to_names = PyDict_New();
5966 if (state->err_codes_to_names == NULL)
5967 return -1;
5968 state->err_names_to_codes = PyDict_New();
5969 if (state->err_names_to_codes == NULL)
5970 return -1;
5971 state->lib_codes_to_names = PyDict_New();
5972 if (state->lib_codes_to_names == NULL)
5973 return -1;
5974
5975 errcode = error_codes;
5976 while (errcode->mnemonic != NULL) {
5977 PyObject *mnemo, *key;
5978 mnemo = PyUnicode_FromString(errcode->mnemonic);
5979 key = Py_BuildValue("ii", errcode->library, errcode->reason);
5980 if (mnemo == NULL || key == NULL)
5981 return -1;
5982 if (PyDict_SetItem(state->err_codes_to_names, key, mnemo))
5983 return -1;
5984 if (PyDict_SetItem(state->err_names_to_codes, mnemo, key))
5985 return -1;
5986 Py_DECREF(key);
5987 Py_DECREF(mnemo);
5988 errcode++;
5989 }
5990
5991 libcode = library_codes;
5992 while (libcode->library != NULL) {
5993 PyObject *mnemo, *key;
5994 key = PyLong_FromLong(libcode->code);
5995 mnemo = PyUnicode_FromString(libcode->library);
5996 if (key == NULL || mnemo == NULL)
5997 return -1;
5998 if (PyDict_SetItem(state->lib_codes_to_names, key, mnemo))
5999 return -1;
6000 Py_DECREF(key);
6001 Py_DECREF(mnemo);
6002 libcode++;
6003 }
6004
6005 if (PyModule_AddObjectRef(module, "err_codes_to_names", state->err_codes_to_names))
6006 return -1;
6007 if (PyModule_AddObjectRef(module, "err_names_to_codes", state->err_names_to_codes))
6008 return -1;
6009 if (PyModule_AddObjectRef(module, "lib_codes_to_names", state->lib_codes_to_names))
6010 return -1;
6011
6012 return 0;
6013}
6014
6015static void
6016parse_openssl_version(unsigned long libver,
6017 unsigned int *major, unsigned int *minor,
6018 unsigned int *fix, unsigned int *patch,
6019 unsigned int *status)
6020{
6021 *status = libver & 0xF;
6022 libver >>= 4;
6023 *patch = libver & 0xFF;
6024 libver >>= 8;
6025 *fix = libver & 0xFF;
6026 libver >>= 8;
6027 *minor = libver & 0xFF;
6028 libver >>= 8;
6029 *major = libver & 0xFF;
6030}
6031
6032static int
6033sslmodule_init_versioninfo(PyObject *m)
6034{
6035 PyObject *r;
6036 unsigned long libver;
6037 unsigned int major, minor, fix, patch, status;
6038
6039 /* OpenSSL version */
6040 /* SSLeay() gives us the version of the library linked against,
6041 which could be different from the headers version.
6042 */
6043 libver = OpenSSL_version_num();
6044 r = PyLong_FromUnsignedLong(libver);
6045 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r))
6046 return -1;
6047
6048 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
6049 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
6050 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r))
6051 return -1;
6052
6053 r = PyUnicode_FromString(OpenSSL_version(OPENSSL_VERSION));
6054 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r))
6055 return -1;
6056
6057 libver = OPENSSL_VERSION_NUMBER;
6058 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
6059 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
6060 if (r == NULL || PyModule_AddObject(m, "_OPENSSL_API_VERSION", r))
6061 return -1;
6062
6063 return 0;
6064}
6065
6066static int
6067sslmodule_init_types(PyObject *module)
6068{
6069 _sslmodulestate *state = get_ssl_state(module);
6070
6071 state->PySSLContext_Type = (PyTypeObject *)PyType_FromModuleAndSpec(
6072 module, &PySSLContext_spec, NULL
6073 );
6074 if (state->PySSLContext_Type == NULL)
6075 return -1;
6076
6077 state->PySSLSocket_Type = (PyTypeObject *)PyType_FromModuleAndSpec(
6078 module, &PySSLSocket_spec, NULL
6079 );
6080 if (state->PySSLSocket_Type == NULL)
6081 return -1;
6082
6083 state->PySSLMemoryBIO_Type = (PyTypeObject *)PyType_FromModuleAndSpec(
6084 module, &PySSLMemoryBIO_spec, NULL
6085 );
6086 if (state->PySSLMemoryBIO_Type == NULL)
6087 return -1;
6088
6089 state->PySSLSession_Type = (PyTypeObject *)PyType_FromModuleAndSpec(
6090 module, &PySSLSession_spec, NULL
6091 );
6092 if (state->PySSLSession_Type == NULL)
6093 return -1;
6094
Christian Heimes666991f2021-04-26 15:01:40 +02006095 state->PySSLCertificate_Type = (PyTypeObject *)PyType_FromModuleAndSpec(
6096 module, &PySSLCertificate_spec, NULL
6097 );
6098 if (state->PySSLCertificate_Type == NULL)
6099 return -1;
6100
Christian Heimes7f1305e2021-04-17 20:06:38 +02006101 if (PyModule_AddType(module, state->PySSLContext_Type))
6102 return -1;
6103 if (PyModule_AddType(module, state->PySSLSocket_Type))
6104 return -1;
6105 if (PyModule_AddType(module, state->PySSLMemoryBIO_Type))
6106 return -1;
6107 if (PyModule_AddType(module, state->PySSLSession_Type))
6108 return -1;
Christian Heimes666991f2021-04-26 15:01:40 +02006109 if (PyModule_AddType(module, state->PySSLCertificate_Type))
6110 return -1;
Christian Heimes7f1305e2021-04-17 20:06:38 +02006111 return 0;
6112}
6113
6114static PyModuleDef_Slot sslmodule_slots[] = {
6115 {Py_mod_exec, sslmodule_init_types},
6116 {Py_mod_exec, sslmodule_init_exceptions},
6117 {Py_mod_exec, sslmodule_init_socketapi},
6118 {Py_mod_exec, sslmodule_init_errorcodes},
6119 {Py_mod_exec, sslmodule_init_constants},
6120 {Py_mod_exec, sslmodule_init_versioninfo},
6121 {0, NULL}
6122};
6123
6124static int
6125sslmodule_traverse(PyObject *m, visitproc visit, void *arg)
6126{
6127 _sslmodulestate *state = get_ssl_state(m);
6128
6129 Py_VISIT(state->PySSLContext_Type);
6130 Py_VISIT(state->PySSLSocket_Type);
6131 Py_VISIT(state->PySSLMemoryBIO_Type);
6132 Py_VISIT(state->PySSLSession_Type);
Christian Heimes666991f2021-04-26 15:01:40 +02006133 Py_VISIT(state->PySSLCertificate_Type);
Christian Heimes7f1305e2021-04-17 20:06:38 +02006134 Py_VISIT(state->PySSLErrorObject);
6135 Py_VISIT(state->PySSLCertVerificationErrorObject);
6136 Py_VISIT(state->PySSLZeroReturnErrorObject);
6137 Py_VISIT(state->PySSLWantReadErrorObject);
6138 Py_VISIT(state->PySSLWantWriteErrorObject);
6139 Py_VISIT(state->PySSLSyscallErrorObject);
6140 Py_VISIT(state->PySSLEOFErrorObject);
6141 Py_VISIT(state->err_codes_to_names);
6142 Py_VISIT(state->err_names_to_codes);
6143 Py_VISIT(state->lib_codes_to_names);
6144 Py_VISIT(state->Sock_Type);
6145
6146 return 0;
6147}
6148
6149static int
6150sslmodule_clear(PyObject *m)
6151{
6152 _sslmodulestate *state = get_ssl_state(m);
6153
6154 Py_CLEAR(state->PySSLContext_Type);
6155 Py_CLEAR(state->PySSLSocket_Type);
6156 Py_CLEAR(state->PySSLMemoryBIO_Type);
6157 Py_CLEAR(state->PySSLSession_Type);
Christian Heimes666991f2021-04-26 15:01:40 +02006158 Py_CLEAR(state->PySSLCertificate_Type);
Christian Heimes7f1305e2021-04-17 20:06:38 +02006159 Py_CLEAR(state->PySSLErrorObject);
6160 Py_CLEAR(state->PySSLCertVerificationErrorObject);
6161 Py_CLEAR(state->PySSLZeroReturnErrorObject);
6162 Py_CLEAR(state->PySSLWantReadErrorObject);
6163 Py_CLEAR(state->PySSLWantWriteErrorObject);
6164 Py_CLEAR(state->PySSLSyscallErrorObject);
6165 Py_CLEAR(state->PySSLEOFErrorObject);
6166 Py_CLEAR(state->err_codes_to_names);
6167 Py_CLEAR(state->err_names_to_codes);
6168 Py_CLEAR(state->lib_codes_to_names);
6169 Py_CLEAR(state->Sock_Type);
6170
6171 return 0;
6172}
6173
6174static void
6175sslmodule_free(void *m)
6176{
6177 sslmodule_clear((PyObject *)m);
6178}
6179
6180static struct PyModuleDef _sslmodule_def = {
Christian Heimes5c36da72020-11-20 09:40:12 +01006181 PyModuleDef_HEAD_INIT,
Christian Heimes7f1305e2021-04-17 20:06:38 +02006182 .m_name = "_ssl",
6183 .m_doc = module_doc,
6184 .m_size = sizeof(_sslmodulestate),
6185 .m_methods = PySSL_methods,
6186 .m_slots = sslmodule_slots,
6187 .m_traverse = sslmodule_traverse,
6188 .m_clear = sslmodule_clear,
6189 .m_free = sslmodule_free
Christian Heimes5c36da72020-11-20 09:40:12 +01006190};
6191
6192PyMODINIT_FUNC
6193PyInit__ssl(void)
6194{
Christian Heimes7f1305e2021-04-17 20:06:38 +02006195 return PyModuleDef_Init(&_sslmodule_def);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00006196}