blob: 8daf04dd08bbb4bc123fd1baccaa6db2ea71549e [file] [log] [blame]
Thomas Woutersed03b412007-08-28 21:37:11 +00001/* SSL socket module
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002
3 SSL support based on patches by Brian E Gallew and Laszlo Kovacs.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004 Re-worked a bit by Bill Janssen to add server-side support and
Bill Janssen6e027db2007-11-15 22:23:56 +00005 certificate decoding. Chris Stawarz contributed some non-blocking
6 patches.
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00007
Thomas Wouters1b7f8912007-09-19 03:06:30 +00008 This module is imported by ssl.py. It should *not* be used
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00009 directly.
10
Thomas Wouters1b7f8912007-09-19 03:06:30 +000011 XXX should partial writes be enabled, SSL_MODE_ENABLE_PARTIAL_WRITE?
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +000012
13 XXX integrate several "shutdown modes" as suggested in
14 http://bugs.python.org/issue8108#msg102867 ?
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000015*/
16
Christian Heimesa4833882021-04-13 08:17:26 +020017/* Don't warn about deprecated functions, */
18#ifndef OPENSSL_API_COMPAT
19 // 0x10101000L == 1.1.1, 30000 == 3.0.0
20 #define OPENSSL_API_COMPAT 0x10101000L
21#endif
22#define OPENSSL_NO_DEPRECATED 1
23
Victor Stinner2e57b4e2014-07-01 16:37:17 +020024#define PY_SSIZE_T_CLEAN
25
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000026#include "Python.h"
Thomas Woutersed03b412007-08-28 21:37:11 +000027
Christian Heimes7f1305e2021-04-17 20:06:38 +020028/* Include symbols from _socket module */
29#include "socketmodule.h"
30
31#include "_ssl.h"
32
Steve Dower68d663c2017-07-17 11:15:48 +020033/* Redefined below for Windows debug builds after important #includes */
34#define _PySSL_FIX_ERRNO
Christian Heimesf77b4b22013-08-21 13:26:05 +020035
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +020036#define PySSL_BEGIN_ALLOW_THREADS_S(save) \
Christian Heimes39258d32021-04-17 11:36:35 +020037 do { (save) = PyEval_SaveThread(); } while(0)
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +020038#define PySSL_END_ALLOW_THREADS_S(save) \
Christian Heimes39258d32021-04-17 11:36:35 +020039 do { PyEval_RestoreThread(save); _PySSL_FIX_ERRNO; } while(0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +000040#define PySSL_BEGIN_ALLOW_THREADS { \
Antoine Pitroucbb82eb2010-05-05 15:57:33 +000041 PyThreadState *_save = NULL; \
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +020042 PySSL_BEGIN_ALLOW_THREADS_S(_save);
43#define PySSL_BLOCK_THREADS PySSL_END_ALLOW_THREADS_S(_save);
44#define PySSL_UNBLOCK_THREADS PySSL_BEGIN_ALLOW_THREADS_S(_save);
45#define PySSL_END_ALLOW_THREADS PySSL_END_ALLOW_THREADS_S(_save); }
Thomas Wouters1b7f8912007-09-19 03:06:30 +000046
Antoine Pitrou2463e5f2013-03-28 22:24:43 +010047
48#if defined(HAVE_POLL_H)
49#include <poll.h>
50#elif defined(HAVE_SYS_POLL_H)
51#include <sys/poll.h>
52#endif
53
54/* Include OpenSSL header files */
55#include "openssl/rsa.h"
56#include "openssl/crypto.h"
57#include "openssl/x509.h"
58#include "openssl/x509v3.h"
59#include "openssl/pem.h"
60#include "openssl/ssl.h"
61#include "openssl/err.h"
62#include "openssl/rand.h"
Antoine Pitroub1fdf472014-10-05 20:41:53 +020063#include "openssl/bio.h"
Alexandru Ardeleanb3a271f2018-09-17 14:53:31 +030064#include "openssl/dh.h"
Antoine Pitrou2463e5f2013-03-28 22:24:43 +010065
Christian Heimesc087a262020-05-15 20:55:25 +020066#ifndef OPENSSL_THREADS
67# error "OPENSSL_THREADS is not defined, Python requires thread-safe OpenSSL"
68#endif
69
Antoine Pitrou2463e5f2013-03-28 22:24:43 +010070
Antoine Pitrou2463e5f2013-03-28 22:24:43 +010071
72struct py_ssl_error_code {
73 const char *mnemonic;
74 int library, reason;
75};
Christian Heimes7f1305e2021-04-17 20:06:38 +020076
Antoine Pitrou2463e5f2013-03-28 22:24:43 +010077struct py_ssl_library_code {
78 const char *library;
79 int code;
80};
81
Steve Dower68d663c2017-07-17 11:15:48 +020082#if defined(MS_WINDOWS) && defined(Py_DEBUG)
83/* Debug builds on Windows rely on getting errno directly from OpenSSL.
84 * However, because it uses a different CRT, we need to transfer the
85 * value of errno from OpenSSL into our debug CRT.
86 *
87 * Don't be fooled - this is horribly ugly code. The only reasonable
88 * alternative is to do both debug and release builds of OpenSSL, which
89 * requires much uglier code to transform their automatically generated
90 * makefile. This is the lesser of all the evils.
91 */
92
93static void _PySSLFixErrno(void) {
94 HMODULE ucrtbase = GetModuleHandleW(L"ucrtbase.dll");
95 if (!ucrtbase) {
96 /* If ucrtbase.dll is not loaded but the SSL DLLs are, we likely
97 * have a catastrophic failure, but this function is not the
98 * place to raise it. */
99 return;
100 }
101
102 typedef int *(__stdcall *errno_func)(void);
103 errno_func ssl_errno = (errno_func)GetProcAddress(ucrtbase, "_errno");
104 if (ssl_errno) {
105 errno = *ssl_errno();
106 *ssl_errno() = 0;
107 } else {
108 errno = ENOTRECOVERABLE;
109 }
110}
111
112#undef _PySSL_FIX_ERRNO
113#define _PySSL_FIX_ERRNO _PySSLFixErrno()
114#endif
115
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100116/* Include generated data (error codes) */
Christian Heimes150af752021-04-09 17:02:00 +0200117#if (OPENSSL_VERSION_NUMBER >= 0x30000000L)
118#include "_ssl_data_300.h"
119#elif (OPENSSL_VERSION_NUMBER >= 0x10101000L) && !defined(LIBRESSL_VERSION_NUMBER)
120#include "_ssl_data_111.h"
121#else
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100122#include "_ssl_data.h"
Christian Heimes150af752021-04-09 17:02:00 +0200123#endif
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100124
Christian Heimes39258d32021-04-17 11:36:35 +0200125/* OpenSSL API 1.1.0+ does not include version methods */
Christian Heimes33091132021-04-20 18:10:10 +0200126#ifndef OPENSSL_NO_SSL3_METHOD
127extern const SSL_METHOD *SSLv3_method(void);
128#endif
Christian Heimesa871f692020-06-01 08:58:14 +0200129#ifndef OPENSSL_NO_TLS1_METHOD
Christian Heimesa4833882021-04-13 08:17:26 +0200130extern const SSL_METHOD *TLSv1_method(void);
Christian Heimesa871f692020-06-01 08:58:14 +0200131#endif
132#ifndef OPENSSL_NO_TLS1_1_METHOD
Christian Heimesa4833882021-04-13 08:17:26 +0200133extern const SSL_METHOD *TLSv1_1_method(void);
Christian Heimesa871f692020-06-01 08:58:14 +0200134#endif
135#ifndef OPENSSL_NO_TLS1_2_METHOD
Christian Heimesa4833882021-04-13 08:17:26 +0200136extern const SSL_METHOD *TLSv1_2_method(void);
Christian Heimesa871f692020-06-01 08:58:14 +0200137#endif
138
Victor Stinner524714e2016-07-22 17:43:59 +0200139#ifndef INVALID_SOCKET /* MS defines this */
140#define INVALID_SOCKET (-1)
141#endif
142
Christian Heimes39258d32021-04-17 11:36:35 +0200143/* OpenSSL 1.1 does not have SSL 2.0 */
Christian Heimes598894f2016-09-05 23:19:05 +0200144#define OPENSSL_NO_SSL2
Christian Heimes598894f2016-09-05 23:19:05 +0200145
Christian Heimes892d66e2018-01-29 14:10:18 +0100146/* Default cipher suites */
147#ifndef PY_SSL_DEFAULT_CIPHERS
148#define PY_SSL_DEFAULT_CIPHERS 1
149#endif
150
151#if PY_SSL_DEFAULT_CIPHERS == 0
152 #ifndef PY_SSL_DEFAULT_CIPHER_STRING
153 #error "Py_SSL_DEFAULT_CIPHERS 0 needs Py_SSL_DEFAULT_CIPHER_STRING"
154 #endif
Christian Heimese9832522021-05-01 20:53:10 +0200155 #ifndef PY_SSL_MIN_PROTOCOL
156 #define PY_SSL_MIN_PROTOCOL TLS1_2_VERSION
157 #endif
Christian Heimes892d66e2018-01-29 14:10:18 +0100158#elif PY_SSL_DEFAULT_CIPHERS == 1
Stéphane Wirtel07fbbfd2018-10-05 16:17:18 +0200159/* Python custom selection of sensible cipher suites
Christian Heimese9832522021-05-01 20:53:10 +0200160 * @SECLEVEL=2: security level 2 with 112 bits minimum security (e.g. 2048 bits RSA key)
161 * ECDH+*: enable ephemeral elliptic curve Diffie-Hellman
162 * DHE+*: fallback to ephemeral finite field Diffie-Hellman
163 * encryption order: AES AEAD (GCM), ChaCha AEAD, AES CBC
Christian Heimes892d66e2018-01-29 14:10:18 +0100164 * !aNULL:!eNULL: really no NULL ciphers
Christian Heimes892d66e2018-01-29 14:10:18 +0100165 * !aDSS: no authentication with discrete logarithm DSA algorithm
Christian Heimese9832522021-05-01 20:53:10 +0200166 * !SHA1: no weak SHA1 MAC
167 * !AESCCM: no CCM mode, it's uncommon and slow
168 *
169 * Based on Hynek's excellent blog post (update 2021-02-11)
170 * https://hynek.me/articles/hardening-your-web-servers-ssl-ciphers/
Christian Heimes892d66e2018-01-29 14:10:18 +0100171 */
Christian Heimese9832522021-05-01 20:53:10 +0200172 #define PY_SSL_DEFAULT_CIPHER_STRING "@SECLEVEL=2:ECDH+AESGCM:ECDH+CHACHA20:ECDH+AES:DHE+AES:!aNULL:!eNULL:!aDSS:!SHA1:!AESCCM"
173 #ifndef PY_SSL_MIN_PROTOCOL
174 #define PY_SSL_MIN_PROTOCOL TLS1_2_VERSION
175 #endif
Christian Heimes892d66e2018-01-29 14:10:18 +0100176#elif PY_SSL_DEFAULT_CIPHERS == 2
177/* Ignored in SSLContext constructor, only used to as _ssl.DEFAULT_CIPHER_STRING */
178 #define PY_SSL_DEFAULT_CIPHER_STRING SSL_DEFAULT_CIPHER_LIST
179#else
180 #error "Unsupported PY_SSL_DEFAULT_CIPHERS"
181#endif
182
Christian Heimes598894f2016-09-05 23:19:05 +0200183
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000184enum py_ssl_error {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000185 /* these mirror ssl.h */
186 PY_SSL_ERROR_NONE,
187 PY_SSL_ERROR_SSL,
188 PY_SSL_ERROR_WANT_READ,
189 PY_SSL_ERROR_WANT_WRITE,
190 PY_SSL_ERROR_WANT_X509_LOOKUP,
191 PY_SSL_ERROR_SYSCALL, /* look at error stack/return value/errno */
192 PY_SSL_ERROR_ZERO_RETURN,
193 PY_SSL_ERROR_WANT_CONNECT,
194 /* start of non ssl.h errorcodes */
195 PY_SSL_ERROR_EOF, /* special case of SSL_ERROR_SYSCALL */
196 PY_SSL_ERROR_NO_SOCKET, /* socket has been GC'd */
197 PY_SSL_ERROR_INVALID_ERROR_CODE
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000198};
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000199
Thomas Woutersed03b412007-08-28 21:37:11 +0000200enum py_ssl_server_or_client {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000201 PY_SSL_CLIENT,
202 PY_SSL_SERVER
Thomas Woutersed03b412007-08-28 21:37:11 +0000203};
204
205enum py_ssl_cert_requirements {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000206 PY_SSL_CERT_NONE,
207 PY_SSL_CERT_OPTIONAL,
208 PY_SSL_CERT_REQUIRED
Thomas Woutersed03b412007-08-28 21:37:11 +0000209};
210
211enum py_ssl_version {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000212 PY_SSL_VERSION_SSL2,
Victor Stinner3de49192011-05-09 00:42:58 +0200213 PY_SSL_VERSION_SSL3=1,
Christian Heimes5fe668c2016-09-12 00:01:11 +0200214 PY_SSL_VERSION_TLS, /* SSLv23 */
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100215 PY_SSL_VERSION_TLS1,
216 PY_SSL_VERSION_TLS1_1,
Christian Heimes5fe668c2016-09-12 00:01:11 +0200217 PY_SSL_VERSION_TLS1_2,
Christian Heimes5fe668c2016-09-12 00:01:11 +0200218 PY_SSL_VERSION_TLS_CLIENT=0x10,
219 PY_SSL_VERSION_TLS_SERVER,
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100220};
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200221
Christian Heimes698dde12018-02-27 11:54:43 +0100222enum py_proto_version {
223 PY_PROTO_MINIMUM_SUPPORTED = -2,
224 PY_PROTO_SSLv3 = SSL3_VERSION,
225 PY_PROTO_TLSv1 = TLS1_VERSION,
226 PY_PROTO_TLSv1_1 = TLS1_1_VERSION,
227 PY_PROTO_TLSv1_2 = TLS1_2_VERSION,
228#ifdef TLS1_3_VERSION
229 PY_PROTO_TLSv1_3 = TLS1_3_VERSION,
230#else
231 PY_PROTO_TLSv1_3 = 0x304,
232#endif
233 PY_PROTO_MAXIMUM_SUPPORTED = -1,
234
235/* OpenSSL has no dedicated API to set the minimum version to the maximum
236 * available version, and the other way around. We have to figure out the
237 * minimum and maximum available version on our own and hope for the best.
238 */
239#if defined(SSL3_VERSION) && !defined(OPENSSL_NO_SSL3)
240 PY_PROTO_MINIMUM_AVAILABLE = PY_PROTO_SSLv3,
241#elif defined(TLS1_VERSION) && !defined(OPENSSL_NO_TLS1)
242 PY_PROTO_MINIMUM_AVAILABLE = PY_PROTO_TLSv1,
243#elif defined(TLS1_1_VERSION) && !defined(OPENSSL_NO_TLS1_1)
244 PY_PROTO_MINIMUM_AVAILABLE = PY_PROTO_TLSv1_1,
245#elif defined(TLS1_2_VERSION) && !defined(OPENSSL_NO_TLS1_2)
246 PY_PROTO_MINIMUM_AVAILABLE = PY_PROTO_TLSv1_2,
247#elif defined(TLS1_3_VERSION) && !defined(OPENSSL_NO_TLS1_3)
248 PY_PROTO_MINIMUM_AVAILABLE = PY_PROTO_TLSv1_3,
249#else
250 #error "PY_PROTO_MINIMUM_AVAILABLE not found"
251#endif
252
253#if defined(TLS1_3_VERSION) && !defined(OPENSSL_NO_TLS1_3)
254 PY_PROTO_MAXIMUM_AVAILABLE = PY_PROTO_TLSv1_3,
255#elif defined(TLS1_2_VERSION) && !defined(OPENSSL_NO_TLS1_2)
256 PY_PROTO_MAXIMUM_AVAILABLE = PY_PROTO_TLSv1_2,
257#elif defined(TLS1_1_VERSION) && !defined(OPENSSL_NO_TLS1_1)
258 PY_PROTO_MAXIMUM_AVAILABLE = PY_PROTO_TLSv1_1,
259#elif defined(TLS1_VERSION) && !defined(OPENSSL_NO_TLS1)
260 PY_PROTO_MAXIMUM_AVAILABLE = PY_PROTO_TLSv1,
261#elif defined(SSL3_VERSION) && !defined(OPENSSL_NO_SSL3)
262 PY_PROTO_MAXIMUM_AVAILABLE = PY_PROTO_SSLv3,
263#else
264 #error "PY_PROTO_MAXIMUM_AVAILABLE not found"
265#endif
266};
267
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000268/* SSL socket object */
269
270#define X509_NAME_MAXLEN 256
271
Antoine Pitroub5218772010-05-21 09:56:06 +0000272
Antoine Pitroud6494802011-07-21 01:11:30 +0200273/* In case of 'tls-unique' it will be 12 bytes for TLS, 36 bytes for
274 * older SSL, but let's be safe */
275#define PySSL_CB_MAXLEN 128
276
Antoine Pitroua9bf2ac2012-02-17 18:47:54 +0100277
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000278typedef struct {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000279 PyObject_HEAD
Antoine Pitrou152efa22010-05-16 18:19:27 +0000280 SSL_CTX *ctx;
Benjamin Petersoncca27322015-01-23 16:35:37 -0500281 unsigned char *alpn_protocols;
Segev Finer5cff6372017-07-27 01:19:17 +0300282 unsigned int alpn_protocols_len;
Christian Heimes11a14932018-02-24 02:35:08 +0100283 PyObject *set_sni_cb;
Christian Heimes1aa9a752013-12-02 02:41:19 +0100284 int check_hostname;
Christian Heimes61d478c2018-01-27 15:51:38 +0100285 /* OpenSSL has no API to get hostflags from X509_VERIFY_PARAM* struct.
286 * We have to maintain our own copy. OpenSSL's hostflags default to 0.
287 */
288 unsigned int hostflags;
Christian Heimes11a14932018-02-24 02:35:08 +0100289 int protocol;
Christian Heimes9fb051f2018-09-23 08:32:31 +0200290#ifdef TLS1_3_VERSION
291 int post_handshake_auth;
292#endif
Christian Heimesc7f70692019-05-31 11:44:05 +0200293 PyObject *msg_cb;
Christian Heimesc7f70692019-05-31 11:44:05 +0200294 PyObject *keylog_filename;
295 BIO *keylog_bio;
Christian Heimes7f1305e2021-04-17 20:06:38 +0200296 /* Cached module state, also used in SSLSocket and SSLSession code. */
297 _sslmodulestate *state;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000298} PySSLContext;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000299
Antoine Pitrou152efa22010-05-16 18:19:27 +0000300typedef struct {
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700301 int ssl; /* last seen error from SSL */
302 int c; /* last seen error from libc */
303#ifdef MS_WINDOWS
304 int ws; /* last seen error from winsock */
305#endif
306} _PySSLError;
307
308typedef struct {
Antoine Pitrou152efa22010-05-16 18:19:27 +0000309 PyObject_HEAD
310 PyObject *Socket; /* weakref to socket on which we're layered */
311 SSL *ssl;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100312 PySSLContext *ctx; /* weakref to SSL context */
Antoine Pitrou20b85552013-09-29 19:50:53 +0200313 char shutdown_seen_zero;
Antoine Pitroud6494802011-07-21 01:11:30 +0200314 enum py_ssl_server_or_client socket_type;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200315 PyObject *owner; /* Python level "owner" passed to servername callback */
316 PyObject *server_hostname;
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700317 _PySSLError err; /* last seen error from various sources */
Christian Heimesc7f70692019-05-31 11:44:05 +0200318 /* Some SSL callbacks don't have error reporting. Callback wrappers
319 * store exception information on the socket. The handshake, read, write,
320 * and shutdown methods check for chained exceptions.
321 */
322 PyObject *exc_type;
323 PyObject *exc_value;
324 PyObject *exc_tb;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000325} PySSLSocket;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000326
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200327typedef struct {
328 PyObject_HEAD
329 BIO *bio;
330 int eof_written;
331} PySSLMemoryBIO;
332
Christian Heimes99a65702016-09-10 23:44:53 +0200333typedef struct {
334 PyObject_HEAD
335 SSL_SESSION *session;
336 PySSLContext *ctx;
337} PySSLSession;
338
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700339static inline _PySSLError _PySSL_errno(int failed, const SSL *ssl, int retcode)
340{
341 _PySSLError err = { 0 };
342 if (failed) {
Steve Dowere6eb48c2017-09-08 15:16:15 -0700343#ifdef MS_WINDOWS
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700344 err.ws = WSAGetLastError();
345 _PySSL_FIX_ERRNO;
Steve Dowere6eb48c2017-09-08 15:16:15 -0700346#endif
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700347 err.c = errno;
348 err.ssl = SSL_get_error(ssl, retcode);
349 }
350 return err;
351}
Steve Dowere6eb48c2017-09-08 15:16:15 -0700352
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +0300353/*[clinic input]
354module _ssl
Christian Heimes7f1305e2021-04-17 20:06:38 +0200355class _ssl._SSLContext "PySSLContext *" "get_state_type(type)->PySSLContext_Type"
356class _ssl._SSLSocket "PySSLSocket *" "get_state_type(type)->PySSLSocket_Type"
357class _ssl.MemoryBIO "PySSLMemoryBIO *" "get_state_type(type)->PySSLMemoryBIO_Type"
358class _ssl.SSLSession "PySSLSession *" "get_state_type(type)->PySSLSession_Type"
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +0300359[clinic start generated code]*/
Christian Heimes7f1305e2021-04-17 20:06:38 +0200360/*[clinic end generated code: output=da39a3ee5e6b4b0d input=d293bed8bae240fd]*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +0300361
362#include "clinic/_ssl.c.h"
363
Victor Stinner14690702015-04-06 22:46:13 +0200364static int PySSL_select(PySocketSockObject *s, int writing, _PyTime_t timeout);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000365
Christian Heimes141c5e82018-02-24 21:10:57 +0100366static int PySSL_set_owner(PySSLSocket *, PyObject *, void *);
367static int PySSL_set_session(PySSLSocket *, PyObject *, void *);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000368
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000369typedef enum {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000370 SOCKET_IS_NONBLOCKING,
371 SOCKET_IS_BLOCKING,
372 SOCKET_HAS_TIMED_OUT,
373 SOCKET_HAS_BEEN_CLOSED,
374 SOCKET_TOO_LARGE_FOR_SELECT,
375 SOCKET_OPERATION_OK
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000376} timeout_state;
377
Thomas Woutersed03b412007-08-28 21:37:11 +0000378/* Wrap error strings with filename and line # */
Thomas Woutersed03b412007-08-28 21:37:11 +0000379#define ERRSTR1(x,y,z) (x ":" y ": " z)
Victor Stinner45e8e2f2014-05-14 17:24:35 +0200380#define ERRSTR(x) ERRSTR1("_ssl.c", Py_STRINGIFY(__LINE__), x)
Thomas Woutersed03b412007-08-28 21:37:11 +0000381
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200382/* Get the socket from a PySSLSocket, if it has one */
383#define GET_SOCKET(obj) ((obj)->Socket ? \
384 (PySocketSockObject *) PyWeakref_GetObject((obj)->Socket) : NULL)
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200385
Victor Stinner14690702015-04-06 22:46:13 +0200386/* If sock is NULL, use a timeout of 0 second */
387#define GET_SOCKET_TIMEOUT(sock) \
388 ((sock != NULL) ? (sock)->sock_timeout : 0)
389
Christian Heimesc7f70692019-05-31 11:44:05 +0200390#include "_ssl/debughelpers.c"
391
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200392/*
393 * SSL errors.
394 */
395
396PyDoc_STRVAR(SSLError_doc,
397"An error occurred in the SSL implementation.");
398
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700399PyDoc_STRVAR(SSLCertVerificationError_doc,
400"A certificate could not be verified.");
401
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200402PyDoc_STRVAR(SSLZeroReturnError_doc,
403"SSL/TLS session closed cleanly.");
404
405PyDoc_STRVAR(SSLWantReadError_doc,
406"Non-blocking SSL socket needs to read more data\n"
407"before the requested operation can be completed.");
408
409PyDoc_STRVAR(SSLWantWriteError_doc,
410"Non-blocking SSL socket needs to write more data\n"
411"before the requested operation can be completed.");
412
413PyDoc_STRVAR(SSLSyscallError_doc,
414"System error when attempting SSL operation.");
415
416PyDoc_STRVAR(SSLEOFError_doc,
417"SSL/TLS connection terminated abruptly.");
418
419static PyObject *
420SSLError_str(PyOSErrorObject *self)
421{
422 if (self->strerror != NULL && PyUnicode_Check(self->strerror)) {
423 Py_INCREF(self->strerror);
424 return self->strerror;
425 }
426 else
427 return PyObject_Str(self->args);
428}
429
430static PyType_Slot sslerror_type_slots[] = {
Inada Naoki926b0cb2019-04-17 08:39:46 +0900431 {Py_tp_doc, (void*)SSLError_doc},
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200432 {Py_tp_str, SSLError_str},
433 {0, 0},
434};
435
436static PyType_Spec sslerror_type_spec = {
Miss Islington (bot)ea47a8a2021-05-27 09:25:22 -0700437 .name = "ssl.SSLError",
438 .basicsize = sizeof(PyOSErrorObject),
Miss Islington (bot)a7aa1052021-05-28 16:47:36 -0700439 .flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_IMMUTABLETYPE),
Miss Islington (bot)ea47a8a2021-05-27 09:25:22 -0700440 .slots = sslerror_type_slots
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200441};
442
443static void
Christian Heimes7f1305e2021-04-17 20:06:38 +0200444fill_and_set_sslerror(_sslmodulestate *state,
445 PySSLSocket *sslsock, PyObject *type, int ssl_errno,
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700446 const char *errstr, int lineno, unsigned long errcode)
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200447{
448 PyObject *err_value = NULL, *reason_obj = NULL, *lib_obj = NULL;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700449 PyObject *verify_obj = NULL, *verify_code_obj = NULL;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200450 PyObject *init_value, *msg, *key;
451 _Py_IDENTIFIER(reason);
452 _Py_IDENTIFIER(library);
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700453 _Py_IDENTIFIER(verify_message);
454 _Py_IDENTIFIER(verify_code);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200455
456 if (errcode != 0) {
457 int lib, reason;
458
459 lib = ERR_GET_LIB(errcode);
460 reason = ERR_GET_REASON(errcode);
461 key = Py_BuildValue("ii", lib, reason);
462 if (key == NULL)
463 goto fail;
Christian Heimes7f1305e2021-04-17 20:06:38 +0200464 reason_obj = PyDict_GetItemWithError(state->err_codes_to_names, key);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200465 Py_DECREF(key);
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +0300466 if (reason_obj == NULL && PyErr_Occurred()) {
467 goto fail;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200468 }
469 key = PyLong_FromLong(lib);
470 if (key == NULL)
471 goto fail;
Christian Heimes7f1305e2021-04-17 20:06:38 +0200472 lib_obj = PyDict_GetItemWithError(state->lib_codes_to_names, key);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200473 Py_DECREF(key);
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +0300474 if (lib_obj == NULL && PyErr_Occurred()) {
475 goto fail;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200476 }
477 if (errstr == NULL)
478 errstr = ERR_reason_error_string(errcode);
479 }
480 if (errstr == NULL)
481 errstr = "unknown error";
482
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700483 /* verify code for cert validation error */
Christian Heimes7f1305e2021-04-17 20:06:38 +0200484 if ((sslsock != NULL) && (type == state->PySSLCertVerificationErrorObject)) {
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700485 const char *verify_str = NULL;
486 long verify_code;
487
488 verify_code = SSL_get_verify_result(sslsock->ssl);
489 verify_code_obj = PyLong_FromLong(verify_code);
490 if (verify_code_obj == NULL) {
491 goto fail;
492 }
493
494 switch (verify_code) {
495 case X509_V_ERR_HOSTNAME_MISMATCH:
496 verify_obj = PyUnicode_FromFormat(
497 "Hostname mismatch, certificate is not valid for '%S'.",
498 sslsock->server_hostname
499 );
500 break;
501 case X509_V_ERR_IP_ADDRESS_MISMATCH:
502 verify_obj = PyUnicode_FromFormat(
503 "IP address mismatch, certificate is not valid for '%S'.",
504 sslsock->server_hostname
505 );
506 break;
507 default:
508 verify_str = X509_verify_cert_error_string(verify_code);
509 if (verify_str != NULL) {
510 verify_obj = PyUnicode_FromString(verify_str);
511 } else {
512 verify_obj = Py_None;
513 Py_INCREF(verify_obj);
514 }
515 break;
516 }
517 if (verify_obj == NULL) {
518 goto fail;
519 }
520 }
521
522 if (verify_obj && reason_obj && lib_obj)
523 msg = PyUnicode_FromFormat("[%S: %S] %s: %S (_ssl.c:%d)",
524 lib_obj, reason_obj, errstr, verify_obj,
525 lineno);
526 else if (reason_obj && lib_obj)
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200527 msg = PyUnicode_FromFormat("[%S: %S] %s (_ssl.c:%d)",
528 lib_obj, reason_obj, errstr, lineno);
529 else if (lib_obj)
530 msg = PyUnicode_FromFormat("[%S] %s (_ssl.c:%d)",
531 lib_obj, errstr, lineno);
532 else
533 msg = PyUnicode_FromFormat("%s (_ssl.c:%d)", errstr, lineno);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200534 if (msg == NULL)
535 goto fail;
Victor Stinnerba9be472013-10-31 15:00:24 +0100536
Paul Monsonfb7e7502019-05-15 15:38:55 -0700537 init_value = Py_BuildValue("iN", ERR_GET_REASON(ssl_errno), msg);
Victor Stinnerba9be472013-10-31 15:00:24 +0100538 if (init_value == NULL)
539 goto fail;
540
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200541 err_value = PyObject_CallObject(type, init_value);
542 Py_DECREF(init_value);
543 if (err_value == NULL)
544 goto fail;
Victor Stinnerba9be472013-10-31 15:00:24 +0100545
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200546 if (reason_obj == NULL)
547 reason_obj = Py_None;
548 if (_PyObject_SetAttrId(err_value, &PyId_reason, reason_obj))
549 goto fail;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700550
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200551 if (lib_obj == NULL)
552 lib_obj = Py_None;
553 if (_PyObject_SetAttrId(err_value, &PyId_library, lib_obj))
554 goto fail;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700555
Christian Heimes7f1305e2021-04-17 20:06:38 +0200556 if ((sslsock != NULL) && (type == state->PySSLCertVerificationErrorObject)) {
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700557 /* Only set verify code / message for SSLCertVerificationError */
558 if (_PyObject_SetAttrId(err_value, &PyId_verify_code,
559 verify_code_obj))
560 goto fail;
561 if (_PyObject_SetAttrId(err_value, &PyId_verify_message, verify_obj))
562 goto fail;
563 }
564
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200565 PyErr_SetObject(type, err_value);
566fail:
567 Py_XDECREF(err_value);
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700568 Py_XDECREF(verify_code_obj);
569 Py_XDECREF(verify_obj);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200570}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000571
Christian Heimesc7f70692019-05-31 11:44:05 +0200572static int
573PySSL_ChainExceptions(PySSLSocket *sslsock) {
574 if (sslsock->exc_type == NULL)
575 return 0;
576
577 _PyErr_ChainExceptions(sslsock->exc_type, sslsock->exc_value, sslsock->exc_tb);
578 sslsock->exc_type = NULL;
579 sslsock->exc_value = NULL;
580 sslsock->exc_tb = NULL;
581 return -1;
582}
583
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000584static PyObject *
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700585PySSL_SetError(PySSLSocket *sslsock, int ret, const char *filename, int lineno)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000586{
Christian Heimes7f1305e2021-04-17 20:06:38 +0200587 PyObject *type;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200588 char *errstr = NULL;
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700589 _PySSLError err;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000590 enum py_ssl_error p = PY_SSL_ERROR_NONE;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200591 unsigned long e = 0;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000592
Christian Heimes7f1305e2021-04-17 20:06:38 +0200593 assert(sslsock != NULL);
594
595 _sslmodulestate *state = get_state_sock(sslsock);
596 type = state->PySSLErrorObject;
597
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000598 assert(ret <= 0);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200599 e = ERR_peek_last_error();
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000600
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700601 if (sslsock->ssl != NULL) {
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700602 err = sslsock->err;
Thomas Woutersed03b412007-08-28 21:37:11 +0000603
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700604 switch (err.ssl) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000605 case SSL_ERROR_ZERO_RETURN:
Antoine Pitrou41032a62011-10-27 23:56:55 +0200606 errstr = "TLS/SSL connection has been closed (EOF)";
Christian Heimes7f1305e2021-04-17 20:06:38 +0200607 type = state->PySSLZeroReturnErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000608 p = PY_SSL_ERROR_ZERO_RETURN;
609 break;
610 case SSL_ERROR_WANT_READ:
611 errstr = "The operation did not complete (read)";
Christian Heimes7f1305e2021-04-17 20:06:38 +0200612 type = state->PySSLWantReadErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000613 p = PY_SSL_ERROR_WANT_READ;
614 break;
615 case SSL_ERROR_WANT_WRITE:
616 p = PY_SSL_ERROR_WANT_WRITE;
Christian Heimes7f1305e2021-04-17 20:06:38 +0200617 type = state->PySSLWantWriteErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000618 errstr = "The operation did not complete (write)";
619 break;
620 case SSL_ERROR_WANT_X509_LOOKUP:
621 p = PY_SSL_ERROR_WANT_X509_LOOKUP;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000622 errstr = "The operation did not complete (X509 lookup)";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000623 break;
624 case SSL_ERROR_WANT_CONNECT:
625 p = PY_SSL_ERROR_WANT_CONNECT;
626 errstr = "The operation did not complete (connect)";
627 break;
628 case SSL_ERROR_SYSCALL:
629 {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000630 if (e == 0) {
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700631 PySocketSockObject *s = GET_SOCKET(sslsock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000632 if (ret == 0 || (((PyObject *)s) == Py_None)) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000633 p = PY_SSL_ERROR_EOF;
Christian Heimes7f1305e2021-04-17 20:06:38 +0200634 type = state->PySSLEOFErrorObject;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000635 errstr = "EOF occurred in violation of protocol";
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200636 } else if (s && ret == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000637 /* underlying BIO reported an I/O error */
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000638 ERR_clear_error();
Steve Dowere6eb48c2017-09-08 15:16:15 -0700639#ifdef MS_WINDOWS
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700640 if (err.ws) {
641 return PyErr_SetFromWindowsErr(err.ws);
642 }
Steve Dowere6eb48c2017-09-08 15:16:15 -0700643#endif
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700644 if (err.c) {
645 errno = err.c;
Steve Dowere6eb48c2017-09-08 15:16:15 -0700646 return PyErr_SetFromErrno(PyExc_OSError);
647 }
Dima Tisnek495bd032020-08-16 02:01:19 +0900648 else {
649 p = PY_SSL_ERROR_EOF;
Christian Heimes7f1305e2021-04-17 20:06:38 +0200650 type = state->PySSLEOFErrorObject;
Dima Tisnek495bd032020-08-16 02:01:19 +0900651 errstr = "EOF occurred in violation of protocol";
652 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000653 } else { /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000654 p = PY_SSL_ERROR_SYSCALL;
Christian Heimes7f1305e2021-04-17 20:06:38 +0200655 type = state->PySSLSyscallErrorObject;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000656 errstr = "Some I/O error occurred";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000657 }
658 } else {
659 p = PY_SSL_ERROR_SYSCALL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000660 }
661 break;
662 }
663 case SSL_ERROR_SSL:
664 {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000665 p = PY_SSL_ERROR_SSL;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700666 if (e == 0) {
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200667 /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000668 errstr = "A failure in the SSL library occurred";
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700669 }
670 if (ERR_GET_LIB(e) == ERR_LIB_SSL &&
671 ERR_GET_REASON(e) == SSL_R_CERTIFICATE_VERIFY_FAILED) {
Christian Heimes7f1305e2021-04-17 20:06:38 +0200672 type = state->PySSLCertVerificationErrorObject;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700673 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000674 break;
675 }
676 default:
677 p = PY_SSL_ERROR_INVALID_ERROR_CODE;
678 errstr = "Invalid error code";
679 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000680 }
Christian Heimes7f1305e2021-04-17 20:06:38 +0200681 fill_and_set_sslerror(state, sslsock, type, p, errstr, lineno, e);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000682 ERR_clear_error();
Christian Heimesc7f70692019-05-31 11:44:05 +0200683 PySSL_ChainExceptions(sslsock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000684 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000685}
686
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000687static PyObject *
Christian Heimes7f1305e2021-04-17 20:06:38 +0200688_setSSLError (_sslmodulestate *state, const char *errstr, int errcode, const char *filename, int lineno)
689{
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200690 if (errstr == NULL)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000691 errcode = ERR_peek_last_error();
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200692 else
693 errcode = 0;
Christian Heimes7f1305e2021-04-17 20:06:38 +0200694 fill_and_set_sslerror(state, NULL, state->PySSLErrorObject, errcode, errstr, lineno, errcode);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000695 ERR_clear_error();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000696 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000697}
698
Christian Heimes2875c602021-04-19 07:27:10 +0200699static int
Miss Islington (bot)d7930fb2021-06-11 00:36:17 -0700700_ssl_deprecated(const char* msg, int stacklevel) {
701 return PyErr_WarnEx(
702 PyExc_DeprecationWarning, msg, stacklevel
Christian Heimes2875c602021-04-19 07:27:10 +0200703 );
704}
705
706#define PY_SSL_DEPRECATED(name, stacklevel, ret) \
707 if (_ssl_deprecated((name), (stacklevel)) == -1) return (ret)
708
Christian Heimes61d478c2018-01-27 15:51:38 +0100709/*
710 * SSL objects
711 */
712
713static int
714_ssl_configure_hostname(PySSLSocket *self, const char* server_hostname)
715{
716 int retval = -1;
717 ASN1_OCTET_STRING *ip;
718 PyObject *hostname;
719 size_t len;
720
721 assert(server_hostname);
722
723 /* Disable OpenSSL's special mode with leading dot in hostname:
724 * When name starts with a dot (e.g ".example.com"), it will be
725 * matched by a certificate valid for any sub-domain of name.
726 */
727 len = strlen(server_hostname);
728 if (len == 0 || *server_hostname == '.') {
729 PyErr_SetString(
730 PyExc_ValueError,
731 "server_hostname cannot be an empty string or start with a "
732 "leading dot.");
733 return retval;
734 }
735
736 /* inet_pton is not available on all platforms. */
737 ip = a2i_IPADDRESS(server_hostname);
738 if (ip == NULL) {
739 ERR_clear_error();
740 }
741
Christian Heimes11a14932018-02-24 02:35:08 +0100742 hostname = PyUnicode_Decode(server_hostname, len, "ascii", "strict");
Christian Heimes61d478c2018-01-27 15:51:38 +0100743 if (hostname == NULL) {
744 goto error;
745 }
746 self->server_hostname = hostname;
747
748 /* Only send SNI extension for non-IP hostnames */
749 if (ip == NULL) {
750 if (!SSL_set_tlsext_host_name(self->ssl, server_hostname)) {
Christian Heimes7f1305e2021-04-17 20:06:38 +0200751 _setSSLError(get_state_sock(self), NULL, 0, __FILE__, __LINE__);
Zackery Spytzc32f2972020-10-25 12:02:30 -0600752 goto error;
Christian Heimes61d478c2018-01-27 15:51:38 +0100753 }
754 }
755 if (self->ctx->check_hostname) {
756 X509_VERIFY_PARAM *param = SSL_get0_param(self->ssl);
757 if (ip == NULL) {
Christian Heimesd02ac252018-03-25 12:36:13 +0200758 if (!X509_VERIFY_PARAM_set1_host(param, server_hostname,
759 strlen(server_hostname))) {
Christian Heimes7f1305e2021-04-17 20:06:38 +0200760 _setSSLError(get_state_sock(self), NULL, 0, __FILE__, __LINE__);
Christian Heimes61d478c2018-01-27 15:51:38 +0100761 goto error;
762 }
763 } else {
Christian Heimesa871f692020-06-01 08:58:14 +0200764 if (!X509_VERIFY_PARAM_set1_ip(param, ASN1_STRING_get0_data(ip),
Christian Heimes61d478c2018-01-27 15:51:38 +0100765 ASN1_STRING_length(ip))) {
Christian Heimes7f1305e2021-04-17 20:06:38 +0200766 _setSSLError(get_state_sock(self), NULL, 0, __FILE__, __LINE__);
Christian Heimes61d478c2018-01-27 15:51:38 +0100767 goto error;
768 }
769 }
770 }
771 retval = 0;
772 error:
773 if (ip != NULL) {
774 ASN1_OCTET_STRING_free(ip);
775 }
776 return retval;
777}
778
Antoine Pitrou152efa22010-05-16 18:19:27 +0000779static PySSLSocket *
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100780newPySSLSocket(PySSLContext *sslctx, PySocketSockObject *sock,
Antoine Pitroud5323212010-10-22 18:19:07 +0000781 enum py_ssl_server_or_client socket_type,
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200782 char *server_hostname,
Christian Heimes141c5e82018-02-24 21:10:57 +0100783 PyObject *owner, PyObject *session,
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200784 PySSLMemoryBIO *inbio, PySSLMemoryBIO *outbio)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000785{
Antoine Pitrou152efa22010-05-16 18:19:27 +0000786 PySSLSocket *self;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100787 SSL_CTX *ctx = sslctx->ctx;
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700788 _PySSLError err = { 0 };
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000789
Miss Islington (bot)d7930fb2021-06-11 00:36:17 -0700790 if ((socket_type == PY_SSL_SERVER) &&
791 (sslctx->protocol == PY_SSL_VERSION_TLS_CLIENT)) {
792 _setSSLError(get_state_ctx(sslctx),
793 "Cannot create a server socket with a "
794 "PROTOCOL_TLS_CLIENT context", 0, __FILE__, __LINE__);
795 return NULL;
796 }
797 if ((socket_type == PY_SSL_CLIENT) &&
798 (sslctx->protocol == PY_SSL_VERSION_TLS_SERVER)) {
799 _setSSLError(get_state_ctx(sslctx),
800 "Cannot create a client socket with a "
801 "PROTOCOL_TLS_SERVER context", 0, __FILE__, __LINE__);
802 return NULL;
803 }
804
Miss Islington (bot)ea47a8a2021-05-27 09:25:22 -0700805 self = PyObject_GC_New(PySSLSocket,
806 get_state_ctx(sslctx)->PySSLSocket_Type);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000807 if (self == NULL)
808 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000809
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000810 self->ssl = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000811 self->Socket = NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100812 self->ctx = sslctx;
Nathaniel J. Smith65ece7c2017-06-07 23:30:43 -0700813 Py_INCREF(sslctx);
Antoine Pitrou860aee72013-09-29 19:52:45 +0200814 self->shutdown_seen_zero = 0;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200815 self->owner = NULL;
Benjamin Peterson81b9ecd2016-08-15 21:55:37 -0700816 self->server_hostname = NULL;
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700817 self->err = err;
Christian Heimesc7f70692019-05-31 11:44:05 +0200818 self->exc_type = NULL;
819 self->exc_value = NULL;
820 self->exc_tb = NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200821
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000822 /* Make sure the SSL error state is initialized */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000823 ERR_clear_error();
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000824
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000825 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitrou152efa22010-05-16 18:19:27 +0000826 self->ssl = SSL_new(ctx);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000827 PySSL_END_ALLOW_THREADS
Zackery Spytz4c49da02018-12-07 03:11:30 -0700828 if (self->ssl == NULL) {
829 Py_DECREF(self);
Christian Heimes7f1305e2021-04-17 20:06:38 +0200830 _setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
Zackery Spytz4c49da02018-12-07 03:11:30 -0700831 return NULL;
832 }
Christian Heimesb467d9a2021-04-17 10:07:19 +0200833 /* bpo43522 and OpenSSL < 1.1.1l: copy hostflags manually */
834#if !defined(LIBRESSL_VERSION_NUMBER) && OPENSSL_VERSION < 0x101010cf
835 X509_VERIFY_PARAM *ssl_params = SSL_get0_param(self->ssl);
836 X509_VERIFY_PARAM_set_hostflags(ssl_params, sslctx->hostflags);
837#endif
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200838 SSL_set_app_data(self->ssl, self);
839 if (sock) {
840 SSL_set_fd(self->ssl, Py_SAFE_DOWNCAST(sock->sock_fd, SOCKET_T, int));
841 } else {
842 /* BIOs are reference counted and SSL_set_bio borrows our reference.
843 * To prevent a double free in memory_bio_dealloc() we need to take an
844 * extra reference here. */
Christian Heimes598894f2016-09-05 23:19:05 +0200845 BIO_up_ref(inbio->bio);
846 BIO_up_ref(outbio->bio);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200847 SSL_set_bio(self->ssl, inbio->bio, outbio->bio);
848 }
Alex Gaynorf0422422018-05-14 11:51:45 -0400849 SSL_set_mode(self->ssl,
850 SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER | SSL_MODE_AUTO_RETRY);
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000851
Christian Heimesf0f59302019-07-01 08:29:17 +0200852#ifdef TLS1_3_VERSION
853 if (sslctx->post_handshake_auth == 1) {
854 if (socket_type == PY_SSL_SERVER) {
855 /* bpo-37428: OpenSSL does not ignore SSL_VERIFY_POST_HANDSHAKE.
856 * Set SSL_VERIFY_POST_HANDSHAKE flag only for server sockets and
857 * only in combination with SSL_VERIFY_PEER flag. */
858 int mode = SSL_get_verify_mode(self->ssl);
859 if (mode & SSL_VERIFY_PEER) {
860 int (*verify_cb)(int, X509_STORE_CTX *) = NULL;
861 verify_cb = SSL_get_verify_callback(self->ssl);
862 mode |= SSL_VERIFY_POST_HANDSHAKE;
863 SSL_set_verify(self->ssl, mode, verify_cb);
864 }
865 } else {
866 /* client socket */
867 SSL_set_post_handshake_auth(self->ssl, 1);
868 }
869 }
870#endif
871
Christian Heimes61d478c2018-01-27 15:51:38 +0100872 if (server_hostname != NULL) {
873 if (_ssl_configure_hostname(self, server_hostname) < 0) {
874 Py_DECREF(self);
875 return NULL;
876 }
877 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000878 /* If the socket is in non-blocking mode or timeout mode, set the BIO
879 * to non-blocking mode (blocking is the default)
880 */
Victor Stinnere2452312015-03-28 03:00:46 +0100881 if (sock && sock->sock_timeout >= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000882 BIO_set_nbio(SSL_get_rbio(self->ssl), 1);
883 BIO_set_nbio(SSL_get_wbio(self->ssl), 1);
884 }
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000885
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000886 PySSL_BEGIN_ALLOW_THREADS
887 if (socket_type == PY_SSL_CLIENT)
888 SSL_set_connect_state(self->ssl);
889 else
890 SSL_set_accept_state(self->ssl);
891 PySSL_END_ALLOW_THREADS
Martin v. Löwis09c35f72002-07-28 09:57:45 +0000892
Antoine Pitroud6494802011-07-21 01:11:30 +0200893 self->socket_type = socket_type;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200894 if (sock != NULL) {
895 self->Socket = PyWeakref_NewRef((PyObject *) sock, NULL);
896 if (self->Socket == NULL) {
897 Py_DECREF(self);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200898 return NULL;
899 }
Victor Stinnera9eb38f2013-10-31 16:35:38 +0100900 }
Christian Heimes141c5e82018-02-24 21:10:57 +0100901 if (owner && owner != Py_None) {
902 if (PySSL_set_owner(self, owner, NULL) == -1) {
903 Py_DECREF(self);
904 return NULL;
905 }
906 }
907 if (session && session != Py_None) {
908 if (PySSL_set_session(self, session, NULL) == -1) {
909 Py_DECREF(self);
910 return NULL;
911 }
912 }
Miss Islington (bot)ea47a8a2021-05-27 09:25:22 -0700913
914 PyObject_GC_Track(self);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000915 return self;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000916}
917
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000918/* SSL object methods */
919
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +0300920/*[clinic input]
921_ssl._SSLSocket.do_handshake
922[clinic start generated code]*/
923
924static PyObject *
925_ssl__SSLSocket_do_handshake_impl(PySSLSocket *self)
926/*[clinic end generated code: output=6c0898a8936548f6 input=d2d737de3df018c8]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000927{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000928 int ret;
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700929 _PySSLError err;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000930 int sockstate, nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200931 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +0200932 _PyTime_t timeout, deadline = 0;
933 int has_timeout;
Antoine Pitroud3f8ab82010-04-24 21:26:44 +0000934
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200935 if (sock) {
936 if (((PyObject*)sock) == Py_None) {
Christian Heimes7f1305e2021-04-17 20:06:38 +0200937 _setSSLError(get_state_sock(self),
938 "Underlying socket connection gone",
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200939 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
940 return NULL;
941 }
942 Py_INCREF(sock);
943
944 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +0100945 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200946 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
947 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000948 }
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000949
Victor Stinner14690702015-04-06 22:46:13 +0200950 timeout = GET_SOCKET_TIMEOUT(sock);
951 has_timeout = (timeout > 0);
952 if (has_timeout)
953 deadline = _PyTime_GetMonotonicClock() + timeout;
954
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000955 /* Actually negotiate SSL connection */
956 /* XXX If SSL_do_handshake() returns 0, it's also a failure. */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000957 do {
Bill Janssen6e027db2007-11-15 22:23:56 +0000958 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000959 ret = SSL_do_handshake(self->ssl);
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700960 err = _PySSL_errno(ret < 1, self->ssl, ret);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000961 PySSL_END_ALLOW_THREADS
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700962 self->err = err;
Victor Stinner4e3cfa42015-04-02 21:28:28 +0200963
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000964 if (PyErr_CheckSignals())
965 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +0200966
Victor Stinner14690702015-04-06 22:46:13 +0200967 if (has_timeout)
968 timeout = deadline - _PyTime_GetMonotonicClock();
969
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700970 if (err.ssl == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +0200971 sockstate = PySSL_select(sock, 0, timeout);
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700972 } else if (err.ssl == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +0200973 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000974 } else {
975 sockstate = SOCKET_OPERATION_OK;
976 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +0200977
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000978 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Christian Heimes03c8ddd2020-11-20 09:26:07 +0100979 PyErr_SetString(PyExc_TimeoutError,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000980 ERRSTR("The handshake operation timed out"));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000981 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000982 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
Christian Heimes7f1305e2021-04-17 20:06:38 +0200983 PyErr_SetString(get_state_sock(self)->PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000984 ERRSTR("Underlying socket has been closed."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000985 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000986 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
Christian Heimes7f1305e2021-04-17 20:06:38 +0200987 PyErr_SetString(get_state_sock(self)->PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000988 ERRSTR("Underlying socket too large for select()."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000989 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000990 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
991 break;
992 }
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700993 } while (err.ssl == SSL_ERROR_WANT_READ ||
994 err.ssl == SSL_ERROR_WANT_WRITE);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200995 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000996 if (ret < 1)
997 return PySSL_SetError(self, ret, __FILE__, __LINE__);
Christian Heimesc7f70692019-05-31 11:44:05 +0200998 if (PySSL_ChainExceptions(self) < 0)
999 return NULL;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001000 Py_RETURN_NONE;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001001error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001002 Py_XDECREF(sock);
Christian Heimesc7f70692019-05-31 11:44:05 +02001003 PySSL_ChainExceptions(self);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001004 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001005}
1006
Thomas Woutersed03b412007-08-28 21:37:11 +00001007static PyObject *
Christian Heimes7f1305e2021-04-17 20:06:38 +02001008_asn1obj2py(_sslmodulestate *state, const ASN1_OBJECT *name, int no_name)
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001009{
1010 char buf[X509_NAME_MAXLEN];
1011 char *namebuf = buf;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001012 int buflen;
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001013 PyObject *name_obj = NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001014
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001015 buflen = OBJ_obj2txt(namebuf, X509_NAME_MAXLEN, name, no_name);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001016 if (buflen < 0) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02001017 _setSSLError(state, NULL, 0, __FILE__, __LINE__);
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001018 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001019 }
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001020 /* initial buffer is too small for oid + terminating null byte */
1021 if (buflen > X509_NAME_MAXLEN - 1) {
1022 /* make OBJ_obj2txt() calculate the required buflen */
1023 buflen = OBJ_obj2txt(NULL, 0, name, no_name);
1024 /* allocate len + 1 for terminating NULL byte */
1025 namebuf = PyMem_Malloc(buflen + 1);
1026 if (namebuf == NULL) {
1027 PyErr_NoMemory();
1028 return NULL;
1029 }
1030 buflen = OBJ_obj2txt(namebuf, buflen + 1, name, no_name);
1031 if (buflen < 0) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02001032 _setSSLError(state, NULL, 0, __FILE__, __LINE__);
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001033 goto done;
1034 }
1035 }
1036 if (!buflen && no_name) {
1037 Py_INCREF(Py_None);
1038 name_obj = Py_None;
1039 }
1040 else {
1041 name_obj = PyUnicode_FromStringAndSize(namebuf, buflen);
1042 }
1043
1044 done:
1045 if (buf != namebuf) {
1046 PyMem_Free(namebuf);
1047 }
1048 return name_obj;
1049}
1050
1051static PyObject *
Christian Heimes7f1305e2021-04-17 20:06:38 +02001052_create_tuple_for_attribute(_sslmodulestate *state,
1053 ASN1_OBJECT *name, ASN1_STRING *value)
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001054{
1055 Py_ssize_t buflen;
1056 unsigned char *valuebuf = NULL;
1057 PyObject *attr;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001058
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001059 buflen = ASN1_STRING_to_UTF8(&valuebuf, value);
1060 if (buflen < 0) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02001061 _setSSLError(state, NULL, 0, __FILE__, __LINE__);
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001062 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001063 }
Christian Heimes7f1305e2021-04-17 20:06:38 +02001064 attr = Py_BuildValue("Ns#", _asn1obj2py(state, name, 0), valuebuf, buflen);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001065 OPENSSL_free(valuebuf);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001066 return attr;
Thomas Woutersed03b412007-08-28 21:37:11 +00001067}
1068
1069static PyObject *
Christian Heimes7f1305e2021-04-17 20:06:38 +02001070_create_tuple_for_X509_NAME (_sslmodulestate *state, X509_NAME *xname)
Thomas Woutersed03b412007-08-28 21:37:11 +00001071{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001072 PyObject *dn = NULL; /* tuple which represents the "distinguished name" */
1073 PyObject *rdn = NULL; /* tuple to hold a "relative distinguished name" */
1074 PyObject *rdnt;
1075 PyObject *attr = NULL; /* tuple to hold an attribute */
1076 int entry_count = X509_NAME_entry_count(xname);
1077 X509_NAME_ENTRY *entry;
1078 ASN1_OBJECT *name;
1079 ASN1_STRING *value;
1080 int index_counter;
1081 int rdn_level = -1;
1082 int retcode;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001083
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001084 dn = PyList_New(0);
1085 if (dn == NULL)
1086 return NULL;
1087 /* now create another tuple to hold the top-level RDN */
1088 rdn = PyList_New(0);
1089 if (rdn == NULL)
1090 goto fail0;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001091
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001092 for (index_counter = 0;
1093 index_counter < entry_count;
1094 index_counter++)
1095 {
1096 entry = X509_NAME_get_entry(xname, index_counter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001097
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001098 /* check to see if we've gotten to a new RDN */
1099 if (rdn_level >= 0) {
Christian Heimes598894f2016-09-05 23:19:05 +02001100 if (rdn_level != X509_NAME_ENTRY_set(entry)) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001101 /* yes, new RDN */
1102 /* add old RDN to DN */
1103 rdnt = PyList_AsTuple(rdn);
1104 Py_DECREF(rdn);
1105 if (rdnt == NULL)
1106 goto fail0;
1107 retcode = PyList_Append(dn, rdnt);
1108 Py_DECREF(rdnt);
1109 if (retcode < 0)
1110 goto fail0;
1111 /* create new RDN */
1112 rdn = PyList_New(0);
1113 if (rdn == NULL)
1114 goto fail0;
1115 }
1116 }
Christian Heimes598894f2016-09-05 23:19:05 +02001117 rdn_level = X509_NAME_ENTRY_set(entry);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001118
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001119 /* now add this attribute to the current RDN */
1120 name = X509_NAME_ENTRY_get_object(entry);
1121 value = X509_NAME_ENTRY_get_data(entry);
Christian Heimes7f1305e2021-04-17 20:06:38 +02001122 attr = _create_tuple_for_attribute(state, name, value);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001123 /*
1124 fprintf(stderr, "RDN level %d, attribute %s: %s\n",
1125 entry->set,
1126 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 0)),
1127 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 1)));
1128 */
1129 if (attr == NULL)
1130 goto fail1;
1131 retcode = PyList_Append(rdn, attr);
1132 Py_DECREF(attr);
1133 if (retcode < 0)
1134 goto fail1;
1135 }
1136 /* now, there's typically a dangling RDN */
Antoine Pitrou2f5a1632012-02-15 22:25:27 +01001137 if (rdn != NULL) {
1138 if (PyList_GET_SIZE(rdn) > 0) {
1139 rdnt = PyList_AsTuple(rdn);
1140 Py_DECREF(rdn);
1141 if (rdnt == NULL)
1142 goto fail0;
1143 retcode = PyList_Append(dn, rdnt);
1144 Py_DECREF(rdnt);
1145 if (retcode < 0)
1146 goto fail0;
1147 }
1148 else {
1149 Py_DECREF(rdn);
1150 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001151 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001152
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001153 /* convert list to tuple */
1154 rdnt = PyList_AsTuple(dn);
1155 Py_DECREF(dn);
1156 if (rdnt == NULL)
1157 return NULL;
1158 return rdnt;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001159
1160 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001161 Py_XDECREF(rdn);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001162
1163 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001164 Py_XDECREF(dn);
1165 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001166}
1167
1168static PyObject *
Christian Heimes7f1305e2021-04-17 20:06:38 +02001169_get_peer_alt_names (_sslmodulestate *state, X509 *certificate) {
Guido van Rossumf06628b2007-11-21 20:01:53 +00001170
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001171 /* this code follows the procedure outlined in
1172 OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print()
1173 function to extract the STACK_OF(GENERAL_NAME),
1174 then iterates through the stack to add the
1175 names. */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001176
Alex Gaynorb87c0df2017-06-06 07:53:11 -04001177 int j;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001178 PyObject *peer_alt_names = Py_None;
Christian Heimes60bf2fc2013-09-05 16:04:35 +02001179 PyObject *v = NULL, *t;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001180 GENERAL_NAMES *names = NULL;
1181 GENERAL_NAME *name;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001182 BIO *biobuf = NULL;
1183 char buf[2048];
1184 char *vptr;
1185 int len;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001186
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001187 if (certificate == NULL)
1188 return peer_alt_names;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001189
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001190 /* get a memory buffer */
1191 biobuf = BIO_new(BIO_s_mem());
Zackery Spytz4c49da02018-12-07 03:11:30 -07001192 if (biobuf == NULL) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02001193 PyErr_SetString(state->PySSLErrorObject, "failed to allocate BIO");
Zackery Spytz4c49da02018-12-07 03:11:30 -07001194 return NULL;
1195 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001196
Alex Gaynorb87c0df2017-06-06 07:53:11 -04001197 names = (GENERAL_NAMES *)X509_get_ext_d2i(
1198 certificate, NID_subject_alt_name, NULL, NULL);
1199 if (names != NULL) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001200 if (peer_alt_names == Py_None) {
1201 peer_alt_names = PyList_New(0);
1202 if (peer_alt_names == NULL)
1203 goto fail;
1204 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001205
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001206 for(j = 0; j < sk_GENERAL_NAME_num(names); j++) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001207 /* get a rendering of each name in the set of names */
Christian Heimes824f7f32013-08-17 00:54:47 +02001208 int gntype;
1209 ASN1_STRING *as = NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001210
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001211 name = sk_GENERAL_NAME_value(names, j);
Christian Heimes474afdd2013-08-17 17:18:56 +02001212 gntype = name->type;
Christian Heimes824f7f32013-08-17 00:54:47 +02001213 switch (gntype) {
1214 case GEN_DIRNAME:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001215 /* we special-case DirName as a tuple of
1216 tuples of attributes */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001217
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001218 t = PyTuple_New(2);
1219 if (t == NULL) {
1220 goto fail;
1221 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001222
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001223 v = PyUnicode_FromString("DirName");
1224 if (v == NULL) {
1225 Py_DECREF(t);
1226 goto fail;
1227 }
1228 PyTuple_SET_ITEM(t, 0, v);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001229
Christian Heimes7f1305e2021-04-17 20:06:38 +02001230 v = _create_tuple_for_X509_NAME(state, name->d.dirn);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001231 if (v == NULL) {
1232 Py_DECREF(t);
1233 goto fail;
1234 }
1235 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +02001236 break;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001237
Christian Heimes824f7f32013-08-17 00:54:47 +02001238 case GEN_EMAIL:
1239 case GEN_DNS:
1240 case GEN_URI:
1241 /* GENERAL_NAME_print() doesn't handle NULL bytes in ASN1_string
1242 correctly, CVE-2013-4238 */
1243 t = PyTuple_New(2);
1244 if (t == NULL)
1245 goto fail;
1246 switch (gntype) {
1247 case GEN_EMAIL:
1248 v = PyUnicode_FromString("email");
1249 as = name->d.rfc822Name;
1250 break;
1251 case GEN_DNS:
1252 v = PyUnicode_FromString("DNS");
1253 as = name->d.dNSName;
1254 break;
1255 case GEN_URI:
1256 v = PyUnicode_FromString("URI");
1257 as = name->d.uniformResourceIdentifier;
1258 break;
1259 }
1260 if (v == NULL) {
1261 Py_DECREF(t);
1262 goto fail;
1263 }
1264 PyTuple_SET_ITEM(t, 0, v);
Christian Heimesa871f692020-06-01 08:58:14 +02001265 v = PyUnicode_FromStringAndSize((char *)ASN1_STRING_get0_data(as),
Christian Heimes824f7f32013-08-17 00:54:47 +02001266 ASN1_STRING_length(as));
1267 if (v == NULL) {
1268 Py_DECREF(t);
1269 goto fail;
1270 }
1271 PyTuple_SET_ITEM(t, 1, v);
1272 break;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001273
Christian Heimes1c03abd2016-09-06 23:25:35 +02001274 case GEN_RID:
1275 t = PyTuple_New(2);
1276 if (t == NULL)
1277 goto fail;
1278
1279 v = PyUnicode_FromString("Registered ID");
1280 if (v == NULL) {
1281 Py_DECREF(t);
1282 goto fail;
1283 }
1284 PyTuple_SET_ITEM(t, 0, v);
1285
1286 len = i2t_ASN1_OBJECT(buf, sizeof(buf)-1, name->d.rid);
1287 if (len < 0) {
1288 Py_DECREF(t);
Christian Heimes7f1305e2021-04-17 20:06:38 +02001289 _setSSLError(state, NULL, 0, __FILE__, __LINE__);
Christian Heimes1c03abd2016-09-06 23:25:35 +02001290 goto fail;
1291 } else if (len >= (int)sizeof(buf)) {
1292 v = PyUnicode_FromString("<INVALID>");
1293 } else {
1294 v = PyUnicode_FromStringAndSize(buf, len);
1295 }
1296 if (v == NULL) {
1297 Py_DECREF(t);
1298 goto fail;
1299 }
1300 PyTuple_SET_ITEM(t, 1, v);
1301 break;
1302
Christian Heimes2b7de662019-12-07 17:59:36 +01001303 case GEN_IPADD:
1304 /* OpenSSL < 3.0.0 adds a trailing \n to IPv6. 3.0.0 removed
1305 * the trailing newline. Remove it in all versions
1306 */
1307 t = PyTuple_New(2);
1308 if (t == NULL)
1309 goto fail;
1310
1311 v = PyUnicode_FromString("IP Address");
1312 if (v == NULL) {
1313 Py_DECREF(t);
1314 goto fail;
1315 }
1316 PyTuple_SET_ITEM(t, 0, v);
1317
1318 if (name->d.ip->length == 4) {
1319 unsigned char *p = name->d.ip->data;
1320 v = PyUnicode_FromFormat(
1321 "%d.%d.%d.%d",
1322 p[0], p[1], p[2], p[3]
1323 );
1324 } else if (name->d.ip->length == 16) {
1325 /* PyUnicode_FromFormat() does not support %X */
1326 unsigned char *p = name->d.ip->data;
1327 len = sprintf(
1328 buf,
1329 "%X:%X:%X:%X:%X:%X:%X:%X",
1330 p[0] << 8 | p[1],
1331 p[2] << 8 | p[3],
1332 p[4] << 8 | p[5],
1333 p[6] << 8 | p[7],
1334 p[8] << 8 | p[9],
1335 p[10] << 8 | p[11],
1336 p[12] << 8 | p[13],
1337 p[14] << 8 | p[15]
1338 );
1339 v = PyUnicode_FromStringAndSize(buf, len);
1340 } else {
1341 v = PyUnicode_FromString("<invalid>");
1342 }
1343
1344 if (v == NULL) {
1345 Py_DECREF(t);
1346 goto fail;
1347 }
1348 PyTuple_SET_ITEM(t, 1, v);
1349 break;
1350
Christian Heimes824f7f32013-08-17 00:54:47 +02001351 default:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001352 /* for everything else, we use the OpenSSL print form */
Christian Heimes824f7f32013-08-17 00:54:47 +02001353 switch (gntype) {
1354 /* check for new general name type */
1355 case GEN_OTHERNAME:
1356 case GEN_X400:
1357 case GEN_EDIPARTY:
Christian Heimes824f7f32013-08-17 00:54:47 +02001358 case GEN_RID:
1359 break;
1360 default:
1361 if (PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
1362 "Unknown general name type %d",
1363 gntype) == -1) {
1364 goto fail;
1365 }
1366 break;
1367 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001368 (void) BIO_reset(biobuf);
1369 GENERAL_NAME_print(biobuf, name);
1370 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1371 if (len < 0) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02001372 _setSSLError(state, NULL, 0, __FILE__, __LINE__);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001373 goto fail;
1374 }
1375 vptr = strchr(buf, ':');
Christian Heimes1c03abd2016-09-06 23:25:35 +02001376 if (vptr == NULL) {
1377 PyErr_Format(PyExc_ValueError,
1378 "Invalid value %.200s",
1379 buf);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001380 goto fail;
Christian Heimes1c03abd2016-09-06 23:25:35 +02001381 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001382 t = PyTuple_New(2);
1383 if (t == NULL)
1384 goto fail;
1385 v = PyUnicode_FromStringAndSize(buf, (vptr - buf));
1386 if (v == NULL) {
1387 Py_DECREF(t);
1388 goto fail;
1389 }
1390 PyTuple_SET_ITEM(t, 0, v);
1391 v = PyUnicode_FromStringAndSize((vptr + 1),
1392 (len - (vptr - buf + 1)));
1393 if (v == NULL) {
1394 Py_DECREF(t);
1395 goto fail;
1396 }
1397 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +02001398 break;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001399 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001400
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001401 /* and add that rendering to the list */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001402
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001403 if (PyList_Append(peer_alt_names, t) < 0) {
1404 Py_DECREF(t);
1405 goto fail;
1406 }
1407 Py_DECREF(t);
1408 }
Antoine Pitrou116d6b92011-11-23 01:39:19 +01001409 sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001410 }
1411 BIO_free(biobuf);
1412 if (peer_alt_names != Py_None) {
1413 v = PyList_AsTuple(peer_alt_names);
1414 Py_DECREF(peer_alt_names);
1415 return v;
1416 } else {
1417 return peer_alt_names;
1418 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001419
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001420
1421 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001422 if (biobuf != NULL)
1423 BIO_free(biobuf);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001424
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001425 if (peer_alt_names != Py_None) {
1426 Py_XDECREF(peer_alt_names);
1427 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001428
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001429 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001430}
1431
1432static PyObject *
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001433_get_aia_uri(X509 *certificate, int nid) {
1434 PyObject *lst = NULL, *ostr = NULL;
1435 int i, result;
1436 AUTHORITY_INFO_ACCESS *info;
1437
1438 info = X509_get_ext_d2i(certificate, NID_info_access, NULL, NULL);
Benjamin Petersonf0c90382015-11-14 15:12:18 -08001439 if (info == NULL)
1440 return Py_None;
1441 if (sk_ACCESS_DESCRIPTION_num(info) == 0) {
1442 AUTHORITY_INFO_ACCESS_free(info);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001443 return Py_None;
1444 }
1445
1446 if ((lst = PyList_New(0)) == NULL) {
1447 goto fail;
1448 }
1449
1450 for (i = 0; i < sk_ACCESS_DESCRIPTION_num(info); i++) {
1451 ACCESS_DESCRIPTION *ad = sk_ACCESS_DESCRIPTION_value(info, i);
1452 ASN1_IA5STRING *uri;
1453
1454 if ((OBJ_obj2nid(ad->method) != nid) ||
1455 (ad->location->type != GEN_URI)) {
1456 continue;
1457 }
1458 uri = ad->location->d.uniformResourceIdentifier;
1459 ostr = PyUnicode_FromStringAndSize((char *)uri->data,
1460 uri->length);
1461 if (ostr == NULL) {
1462 goto fail;
1463 }
1464 result = PyList_Append(lst, ostr);
1465 Py_DECREF(ostr);
1466 if (result < 0) {
1467 goto fail;
1468 }
1469 }
1470 AUTHORITY_INFO_ACCESS_free(info);
1471
1472 /* convert to tuple or None */
1473 if (PyList_Size(lst) == 0) {
1474 Py_DECREF(lst);
1475 return Py_None;
1476 } else {
1477 PyObject *tup;
1478 tup = PyList_AsTuple(lst);
1479 Py_DECREF(lst);
1480 return tup;
1481 }
1482
1483 fail:
1484 AUTHORITY_INFO_ACCESS_free(info);
Christian Heimes18fc7be2013-11-21 23:57:49 +01001485 Py_XDECREF(lst);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001486 return NULL;
1487}
1488
1489static PyObject *
1490_get_crl_dp(X509 *certificate) {
1491 STACK_OF(DIST_POINT) *dps;
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001492 int i, j;
1493 PyObject *lst, *res = NULL;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001494
Christian Heimes598894f2016-09-05 23:19:05 +02001495 dps = X509_get_ext_d2i(certificate, NID_crl_distribution_points, NULL, NULL);
Christian Heimes949ec142013-11-21 16:26:51 +01001496
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001497 if (dps == NULL)
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001498 return Py_None;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001499
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001500 lst = PyList_New(0);
1501 if (lst == NULL)
1502 goto done;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001503
1504 for (i=0; i < sk_DIST_POINT_num(dps); i++) {
1505 DIST_POINT *dp;
1506 STACK_OF(GENERAL_NAME) *gns;
1507
1508 dp = sk_DIST_POINT_value(dps, i);
Christian Heimesa37f5242019-01-15 23:47:42 +01001509 if (dp->distpoint == NULL) {
1510 /* Ignore empty DP value, CVE-2019-5010 */
1511 continue;
1512 }
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001513 gns = dp->distpoint->name.fullname;
1514
1515 for (j=0; j < sk_GENERAL_NAME_num(gns); j++) {
1516 GENERAL_NAME *gn;
1517 ASN1_IA5STRING *uri;
1518 PyObject *ouri;
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001519 int err;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001520
1521 gn = sk_GENERAL_NAME_value(gns, j);
1522 if (gn->type != GEN_URI) {
1523 continue;
1524 }
1525 uri = gn->d.uniformResourceIdentifier;
1526 ouri = PyUnicode_FromStringAndSize((char *)uri->data,
1527 uri->length);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001528 if (ouri == NULL)
1529 goto done;
1530
1531 err = PyList_Append(lst, ouri);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001532 Py_DECREF(ouri);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001533 if (err < 0)
1534 goto done;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001535 }
1536 }
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001537
1538 /* Convert to tuple. */
1539 res = (PyList_GET_SIZE(lst) > 0) ? PyList_AsTuple(lst) : Py_None;
1540
1541 done:
1542 Py_XDECREF(lst);
Olivier Vielpeau2849cc32017-04-14 21:06:07 -04001543 CRL_DIST_POINTS_free(dps);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001544 return res;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001545}
1546
1547static PyObject *
Christian Heimes7f1305e2021-04-17 20:06:38 +02001548_decode_certificate(_sslmodulestate *state, X509 *certificate) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001549
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001550 PyObject *retval = NULL;
1551 BIO *biobuf = NULL;
1552 PyObject *peer;
1553 PyObject *peer_alt_names = NULL;
1554 PyObject *issuer;
1555 PyObject *version;
1556 PyObject *sn_obj;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001557 PyObject *obj;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001558 ASN1_INTEGER *serialNumber;
1559 char buf[2048];
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001560 int len, result;
Christian Heimesa871f692020-06-01 08:58:14 +02001561 const ASN1_TIME *notBefore, *notAfter;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001562 PyObject *pnotBefore, *pnotAfter;
Thomas Woutersed03b412007-08-28 21:37:11 +00001563
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001564 retval = PyDict_New();
1565 if (retval == NULL)
1566 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001567
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001568 peer = _create_tuple_for_X509_NAME(
Christian Heimes7f1305e2021-04-17 20:06:38 +02001569 state,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001570 X509_get_subject_name(certificate));
1571 if (peer == NULL)
1572 goto fail0;
1573 if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) {
1574 Py_DECREF(peer);
1575 goto fail0;
1576 }
1577 Py_DECREF(peer);
Thomas Woutersed03b412007-08-28 21:37:11 +00001578
Antoine Pitroufb046912010-11-09 20:21:19 +00001579 issuer = _create_tuple_for_X509_NAME(
Christian Heimes7f1305e2021-04-17 20:06:38 +02001580 state,
Antoine Pitroufb046912010-11-09 20:21:19 +00001581 X509_get_issuer_name(certificate));
1582 if (issuer == NULL)
1583 goto fail0;
1584 if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001585 Py_DECREF(issuer);
Antoine Pitroufb046912010-11-09 20:21:19 +00001586 goto fail0;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001587 }
Antoine Pitroufb046912010-11-09 20:21:19 +00001588 Py_DECREF(issuer);
1589
1590 version = PyLong_FromLong(X509_get_version(certificate) + 1);
Christian Heimes5962bef2013-07-26 15:51:18 +02001591 if (version == NULL)
1592 goto fail0;
Antoine Pitroufb046912010-11-09 20:21:19 +00001593 if (PyDict_SetItemString(retval, "version", version) < 0) {
1594 Py_DECREF(version);
1595 goto fail0;
1596 }
1597 Py_DECREF(version);
Guido van Rossumf06628b2007-11-21 20:01:53 +00001598
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001599 /* get a memory buffer */
1600 biobuf = BIO_new(BIO_s_mem());
Zackery Spytz4c49da02018-12-07 03:11:30 -07001601 if (biobuf == NULL) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02001602 PyErr_SetString(state->PySSLErrorObject, "failed to allocate BIO");
Zackery Spytz4c49da02018-12-07 03:11:30 -07001603 goto fail0;
1604 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001605
Antoine Pitroufb046912010-11-09 20:21:19 +00001606 (void) BIO_reset(biobuf);
1607 serialNumber = X509_get_serialNumber(certificate);
1608 /* should not exceed 20 octets, 160 bits, so buf is big enough */
1609 i2a_ASN1_INTEGER(biobuf, serialNumber);
1610 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1611 if (len < 0) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02001612 _setSSLError(state, NULL, 0, __FILE__, __LINE__);
Antoine Pitroufb046912010-11-09 20:21:19 +00001613 goto fail1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001614 }
Antoine Pitroufb046912010-11-09 20:21:19 +00001615 sn_obj = PyUnicode_FromStringAndSize(buf, len);
1616 if (sn_obj == NULL)
1617 goto fail1;
1618 if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) {
1619 Py_DECREF(sn_obj);
1620 goto fail1;
1621 }
1622 Py_DECREF(sn_obj);
1623
1624 (void) BIO_reset(biobuf);
Christian Heimesa871f692020-06-01 08:58:14 +02001625 notBefore = X509_get0_notBefore(certificate);
Antoine Pitroufb046912010-11-09 20:21:19 +00001626 ASN1_TIME_print(biobuf, notBefore);
1627 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1628 if (len < 0) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02001629 _setSSLError(state, NULL, 0, __FILE__, __LINE__);
Antoine Pitroufb046912010-11-09 20:21:19 +00001630 goto fail1;
1631 }
1632 pnotBefore = PyUnicode_FromStringAndSize(buf, len);
1633 if (pnotBefore == NULL)
1634 goto fail1;
1635 if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) {
1636 Py_DECREF(pnotBefore);
1637 goto fail1;
1638 }
1639 Py_DECREF(pnotBefore);
Thomas Woutersed03b412007-08-28 21:37:11 +00001640
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001641 (void) BIO_reset(biobuf);
Christian Heimesa871f692020-06-01 08:58:14 +02001642 notAfter = X509_get0_notAfter(certificate);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001643 ASN1_TIME_print(biobuf, notAfter);
1644 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1645 if (len < 0) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02001646 _setSSLError(state, NULL, 0, __FILE__, __LINE__);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001647 goto fail1;
1648 }
1649 pnotAfter = PyUnicode_FromStringAndSize(buf, len);
1650 if (pnotAfter == NULL)
1651 goto fail1;
1652 if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) {
1653 Py_DECREF(pnotAfter);
1654 goto fail1;
1655 }
1656 Py_DECREF(pnotAfter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001657
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001658 /* Now look for subjectAltName */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001659
Christian Heimes7f1305e2021-04-17 20:06:38 +02001660 peer_alt_names = _get_peer_alt_names(state, certificate);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001661 if (peer_alt_names == NULL)
1662 goto fail1;
1663 else if (peer_alt_names != Py_None) {
1664 if (PyDict_SetItemString(retval, "subjectAltName",
1665 peer_alt_names) < 0) {
1666 Py_DECREF(peer_alt_names);
1667 goto fail1;
1668 }
1669 Py_DECREF(peer_alt_names);
1670 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001671
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001672 /* Authority Information Access: OCSP URIs */
1673 obj = _get_aia_uri(certificate, NID_ad_OCSP);
1674 if (obj == NULL) {
1675 goto fail1;
1676 } else if (obj != Py_None) {
1677 result = PyDict_SetItemString(retval, "OCSP", obj);
1678 Py_DECREF(obj);
1679 if (result < 0) {
1680 goto fail1;
1681 }
1682 }
1683
1684 obj = _get_aia_uri(certificate, NID_ad_ca_issuers);
1685 if (obj == NULL) {
1686 goto fail1;
1687 } else if (obj != Py_None) {
1688 result = PyDict_SetItemString(retval, "caIssuers", obj);
1689 Py_DECREF(obj);
1690 if (result < 0) {
1691 goto fail1;
1692 }
1693 }
1694
1695 /* CDP (CRL distribution points) */
1696 obj = _get_crl_dp(certificate);
1697 if (obj == NULL) {
1698 goto fail1;
1699 } else if (obj != Py_None) {
1700 result = PyDict_SetItemString(retval, "crlDistributionPoints", obj);
1701 Py_DECREF(obj);
1702 if (result < 0) {
1703 goto fail1;
1704 }
1705 }
1706
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001707 BIO_free(biobuf);
1708 return retval;
Thomas Woutersed03b412007-08-28 21:37:11 +00001709
1710 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001711 if (biobuf != NULL)
1712 BIO_free(biobuf);
Thomas Woutersed03b412007-08-28 21:37:11 +00001713 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001714 Py_XDECREF(retval);
1715 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001716}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001717
Christian Heimes9a5395a2013-06-17 15:44:12 +02001718static PyObject *
Christian Heimes7f1305e2021-04-17 20:06:38 +02001719_certificate_to_der(_sslmodulestate *state, X509 *certificate)
Christian Heimes9a5395a2013-06-17 15:44:12 +02001720{
1721 unsigned char *bytes_buf = NULL;
1722 int len;
1723 PyObject *retval;
1724
1725 bytes_buf = NULL;
1726 len = i2d_X509(certificate, &bytes_buf);
1727 if (len < 0) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02001728 _setSSLError(state, NULL, 0, __FILE__, __LINE__);
Christian Heimes9a5395a2013-06-17 15:44:12 +02001729 return NULL;
1730 }
1731 /* this is actually an immutable bytes sequence */
1732 retval = PyBytes_FromStringAndSize((const char *) bytes_buf, len);
1733 OPENSSL_free(bytes_buf);
1734 return retval;
1735}
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001736
Christian Heimes666991f2021-04-26 15:01:40 +02001737#include "_ssl/misc.c"
1738#include "_ssl/cert.c"
1739
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001740/*[clinic input]
1741_ssl._test_decode_cert
1742 path: object(converter="PyUnicode_FSConverter")
1743 /
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001744
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001745[clinic start generated code]*/
1746
1747static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001748_ssl__test_decode_cert_impl(PyObject *module, PyObject *path)
1749/*[clinic end generated code: output=96becb9abb23c091 input=cdeaaf02d4346628]*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001750{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001751 PyObject *retval = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001752 X509 *x=NULL;
1753 BIO *cert;
Christian Heimes7f1305e2021-04-17 20:06:38 +02001754 _sslmodulestate *state = get_ssl_state(module);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001755
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001756 if ((cert=BIO_new(BIO_s_file())) == NULL) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02001757 PyErr_SetString(state->PySSLErrorObject,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001758 "Can't malloc memory to read file");
1759 goto fail0;
1760 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001761
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001762 if (BIO_read_filename(cert, PyBytes_AsString(path)) <= 0) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02001763 PyErr_SetString(state->PySSLErrorObject,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001764 "Can't open file");
1765 goto fail0;
1766 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001767
Alex Gaynor40dad952019-08-15 08:31:28 -04001768 x = PEM_read_bio_X509(cert, NULL, NULL, NULL);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001769 if (x == NULL) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02001770 PyErr_SetString(state->PySSLErrorObject,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001771 "Error decoding PEM-encoded file");
1772 goto fail0;
1773 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001774
Christian Heimes7f1305e2021-04-17 20:06:38 +02001775 retval = _decode_certificate(state, x);
Mark Dickinsonee55df52010-08-03 18:31:54 +00001776 X509_free(x);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001777
1778 fail0:
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001779 Py_DECREF(path);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001780 if (cert != NULL) BIO_free(cert);
1781 return retval;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001782}
1783
1784
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001785/*[clinic input]
Christian Heimes141c5e82018-02-24 21:10:57 +01001786_ssl._SSLSocket.getpeercert
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001787 der as binary_mode: bool = False
1788 /
1789
1790Returns the certificate for the peer.
1791
1792If no certificate was provided, returns None. If a certificate was
1793provided, but not validated, returns an empty dictionary. Otherwise
1794returns a dict containing information about the peer certificate.
1795
1796If the optional argument is True, returns a DER-encoded copy of the
1797peer certificate, or None if no certificate was provided. This will
1798return the certificate even if it wasn't validated.
1799[clinic start generated code]*/
1800
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001801static PyObject *
Christian Heimes141c5e82018-02-24 21:10:57 +01001802_ssl__SSLSocket_getpeercert_impl(PySSLSocket *self, int binary_mode)
1803/*[clinic end generated code: output=1f0ab66dfb693c88 input=c0fbe802e57629b7]*/
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001804{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001805 int verification;
Christian Heimes66dc33b2017-05-23 16:02:02 -07001806 X509 *peer_cert;
1807 PyObject *result;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001808
Christian Heimes66dc33b2017-05-23 16:02:02 -07001809 if (!SSL_is_init_finished(self->ssl)) {
Antoine Pitrou20b85552013-09-29 19:50:53 +02001810 PyErr_SetString(PyExc_ValueError,
1811 "handshake not done yet");
1812 return NULL;
1813 }
Christian Heimes66dc33b2017-05-23 16:02:02 -07001814 peer_cert = SSL_get_peer_certificate(self->ssl);
1815 if (peer_cert == NULL)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001816 Py_RETURN_NONE;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001817
Antoine Pitrou721738f2012-08-15 23:20:39 +02001818 if (binary_mode) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001819 /* return cert in DER-encoded format */
Christian Heimes7f1305e2021-04-17 20:06:38 +02001820 result = _certificate_to_der(get_state_sock(self), peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001821 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00001822 verification = SSL_CTX_get_verify_mode(SSL_get_SSL_CTX(self->ssl));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001823 if ((verification & SSL_VERIFY_PEER) == 0)
Christian Heimes66dc33b2017-05-23 16:02:02 -07001824 result = PyDict_New();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001825 else
Christian Heimes7f1305e2021-04-17 20:06:38 +02001826 result = _decode_certificate(get_state_sock(self), peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001827 }
Christian Heimes66dc33b2017-05-23 16:02:02 -07001828 X509_free(peer_cert);
1829 return result;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001830}
1831
Christian Heimes666991f2021-04-26 15:01:40 +02001832/*[clinic input]
1833_ssl._SSLSocket.get_verified_chain
1834
1835[clinic start generated code]*/
1836
1837static PyObject *
1838_ssl__SSLSocket_get_verified_chain_impl(PySSLSocket *self)
1839/*[clinic end generated code: output=802421163cdc3110 input=5fb0714f77e2bd51]*/
1840{
1841 /* borrowed reference */
1842 STACK_OF(X509) *chain = SSL_get0_verified_chain(self->ssl);
1843 if (chain == NULL) {
1844 Py_RETURN_NONE;
1845 }
1846 return _PySSL_CertificateFromX509Stack(self->ctx->state, chain, 1);
1847}
1848
1849/*[clinic input]
1850_ssl._SSLSocket.get_unverified_chain
1851
1852[clinic start generated code]*/
1853
1854static PyObject *
1855_ssl__SSLSocket_get_unverified_chain_impl(PySSLSocket *self)
1856/*[clinic end generated code: output=5acdae414e13f913 input=78c33c360c635cb5]*/
1857{
1858 PyObject *retval;
1859 /* borrowed reference */
1860 /* TODO: include SSL_get_peer_certificate() for server-side sockets */
1861 STACK_OF(X509) *chain = SSL_get_peer_cert_chain(self->ssl);
1862 if (chain == NULL) {
1863 Py_RETURN_NONE;
1864 }
1865 retval = _PySSL_CertificateFromX509Stack(self->ctx->state, chain, 1);
1866 if (retval == NULL) {
1867 return NULL;
1868 }
1869 /* OpenSSL does not include peer cert for server side connections */
1870 if (self->socket_type == PY_SSL_SERVER) {
1871 PyObject *peerobj = NULL;
1872 X509 *peer = SSL_get_peer_certificate(self->ssl);
1873
1874 if (peer == NULL) {
1875 peerobj = Py_None;
1876 Py_INCREF(peerobj);
1877 } else {
1878 /* consume X509 reference on success */
1879 peerobj = _PySSL_CertificateFromX509(self->ctx->state, peer, 0);
1880 if (peerobj == NULL) {
1881 X509_free(peer);
1882 Py_DECREF(retval);
1883 return NULL;
1884 }
1885 }
1886 int res = PyList_Insert(retval, 0, peerobj);
1887 Py_DECREF(peerobj);
1888 if (res < 0) {
1889 Py_DECREF(retval);
1890 return NULL;
1891 }
1892 }
1893 return retval;
1894}
1895
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001896static PyObject *
1897cipher_to_tuple(const SSL_CIPHER *cipher)
1898{
1899 const char *cipher_name, *cipher_protocol;
1900 PyObject *v, *retval = PyTuple_New(3);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001901 if (retval == NULL)
1902 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001903
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001904 cipher_name = SSL_CIPHER_get_name(cipher);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001905 if (cipher_name == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001906 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001907 PyTuple_SET_ITEM(retval, 0, Py_None);
1908 } else {
1909 v = PyUnicode_FromString(cipher_name);
1910 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001911 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001912 PyTuple_SET_ITEM(retval, 0, v);
1913 }
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001914
1915 cipher_protocol = SSL_CIPHER_get_version(cipher);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001916 if (cipher_protocol == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001917 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001918 PyTuple_SET_ITEM(retval, 1, Py_None);
1919 } else {
1920 v = PyUnicode_FromString(cipher_protocol);
1921 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001922 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001923 PyTuple_SET_ITEM(retval, 1, v);
1924 }
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001925
1926 v = PyLong_FromLong(SSL_CIPHER_get_bits(cipher, NULL));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001927 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001928 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001929 PyTuple_SET_ITEM(retval, 2, v);
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001930
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001931 return retval;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001932
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001933 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001934 Py_DECREF(retval);
1935 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001936}
1937
Christian Heimes25bfcd52016-09-06 00:04:45 +02001938static PyObject *
1939cipher_to_dict(const SSL_CIPHER *cipher)
1940{
1941 const char *cipher_name, *cipher_protocol;
1942
1943 unsigned long cipher_id;
1944 int alg_bits, strength_bits, len;
1945 char buf[512] = {0};
Christian Heimes25bfcd52016-09-06 00:04:45 +02001946 int aead, nid;
1947 const char *skcipher = NULL, *digest = NULL, *kx = NULL, *auth = NULL;
Christian Heimes25bfcd52016-09-06 00:04:45 +02001948
1949 /* can be NULL */
1950 cipher_name = SSL_CIPHER_get_name(cipher);
1951 cipher_protocol = SSL_CIPHER_get_version(cipher);
1952 cipher_id = SSL_CIPHER_get_id(cipher);
1953 SSL_CIPHER_description(cipher, buf, sizeof(buf) - 1);
Segev Finer5cff6372017-07-27 01:19:17 +03001954 /* Downcast to avoid a warning. Safe since buf is always 512 bytes */
1955 len = (int)strlen(buf);
Christian Heimes25bfcd52016-09-06 00:04:45 +02001956 if (len > 1 && buf[len-1] == '\n')
1957 buf[len-1] = '\0';
1958 strength_bits = SSL_CIPHER_get_bits(cipher, &alg_bits);
1959
Christian Heimes25bfcd52016-09-06 00:04:45 +02001960 aead = SSL_CIPHER_is_aead(cipher);
1961 nid = SSL_CIPHER_get_cipher_nid(cipher);
1962 skcipher = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1963 nid = SSL_CIPHER_get_digest_nid(cipher);
1964 digest = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1965 nid = SSL_CIPHER_get_kx_nid(cipher);
1966 kx = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1967 nid = SSL_CIPHER_get_auth_nid(cipher);
1968 auth = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
Christian Heimes25bfcd52016-09-06 00:04:45 +02001969
Victor Stinner410b9882016-09-12 12:00:23 +02001970 return Py_BuildValue(
Christian Heimes25bfcd52016-09-06 00:04:45 +02001971 "{sksssssssisi"
Christian Heimes25bfcd52016-09-06 00:04:45 +02001972 "sOssssssss"
Christian Heimes25bfcd52016-09-06 00:04:45 +02001973 "}",
1974 "id", cipher_id,
1975 "name", cipher_name,
1976 "protocol", cipher_protocol,
1977 "description", buf,
1978 "strength_bits", strength_bits,
1979 "alg_bits", alg_bits
Christian Heimes25bfcd52016-09-06 00:04:45 +02001980 ,"aead", aead ? Py_True : Py_False,
1981 "symmetric", skcipher,
1982 "digest", digest,
1983 "kea", kx,
1984 "auth", auth
Christian Heimes25bfcd52016-09-06 00:04:45 +02001985 );
Christian Heimes25bfcd52016-09-06 00:04:45 +02001986}
Christian Heimes25bfcd52016-09-06 00:04:45 +02001987
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001988/*[clinic input]
1989_ssl._SSLSocket.shared_ciphers
1990[clinic start generated code]*/
1991
1992static PyObject *
1993_ssl__SSLSocket_shared_ciphers_impl(PySSLSocket *self)
1994/*[clinic end generated code: output=3d174ead2e42c4fd input=0bfe149da8fe6306]*/
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001995{
1996 STACK_OF(SSL_CIPHER) *ciphers;
1997 int i;
1998 PyObject *res;
1999
Christian Heimes598894f2016-09-05 23:19:05 +02002000 ciphers = SSL_get_ciphers(self->ssl);
2001 if (!ciphers)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06002002 Py_RETURN_NONE;
Benjamin Peterson4cb17812015-01-07 11:14:26 -06002003 res = PyList_New(sk_SSL_CIPHER_num(ciphers));
2004 if (!res)
2005 return NULL;
2006 for (i = 0; i < sk_SSL_CIPHER_num(ciphers); i++) {
2007 PyObject *tup = cipher_to_tuple(sk_SSL_CIPHER_value(ciphers, i));
2008 if (!tup) {
2009 Py_DECREF(res);
2010 return NULL;
2011 }
2012 PyList_SET_ITEM(res, i, tup);
2013 }
2014 return res;
2015}
2016
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002017/*[clinic input]
2018_ssl._SSLSocket.cipher
2019[clinic start generated code]*/
2020
2021static PyObject *
2022_ssl__SSLSocket_cipher_impl(PySSLSocket *self)
2023/*[clinic end generated code: output=376417c16d0e5815 input=548fb0e27243796d]*/
Benjamin Peterson4cb17812015-01-07 11:14:26 -06002024{
2025 const SSL_CIPHER *current;
2026
2027 if (self->ssl == NULL)
2028 Py_RETURN_NONE;
2029 current = SSL_get_current_cipher(self->ssl);
2030 if (current == NULL)
2031 Py_RETURN_NONE;
2032 return cipher_to_tuple(current);
2033}
2034
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002035/*[clinic input]
2036_ssl._SSLSocket.version
2037[clinic start generated code]*/
2038
2039static PyObject *
2040_ssl__SSLSocket_version_impl(PySSLSocket *self)
2041/*[clinic end generated code: output=178aed33193b2cdb input=900186a503436fd6]*/
Antoine Pitrou47e40422014-09-04 21:00:10 +02002042{
2043 const char *version;
2044
2045 if (self->ssl == NULL)
2046 Py_RETURN_NONE;
Christian Heimes68771112017-09-05 21:55:40 -07002047 if (!SSL_is_init_finished(self->ssl)) {
2048 /* handshake not finished */
2049 Py_RETURN_NONE;
2050 }
Antoine Pitrou47e40422014-09-04 21:00:10 +02002051 version = SSL_get_version(self->ssl);
2052 if (!strcmp(version, "unknown"))
2053 Py_RETURN_NONE;
2054 return PyUnicode_FromString(version);
2055}
2056
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002057/*[clinic input]
2058_ssl._SSLSocket.selected_alpn_protocol
2059[clinic start generated code]*/
2060
2061static PyObject *
2062_ssl__SSLSocket_selected_alpn_protocol_impl(PySSLSocket *self)
2063/*[clinic end generated code: output=ec33688b303d250f input=442de30e35bc2913]*/
2064{
Benjamin Petersoncca27322015-01-23 16:35:37 -05002065 const unsigned char *out;
2066 unsigned int outlen;
2067
2068 SSL_get0_alpn_selected(self->ssl, &out, &outlen);
2069
2070 if (out == NULL)
2071 Py_RETURN_NONE;
2072 return PyUnicode_FromStringAndSize((char *)out, outlen);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002073}
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002074
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002075/*[clinic input]
2076_ssl._SSLSocket.compression
2077[clinic start generated code]*/
2078
2079static PyObject *
2080_ssl__SSLSocket_compression_impl(PySSLSocket *self)
2081/*[clinic end generated code: output=bd16cb1bb4646ae7 input=5d059d0a2bbc32c8]*/
2082{
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01002083#ifdef OPENSSL_NO_COMP
2084 Py_RETURN_NONE;
2085#else
2086 const COMP_METHOD *comp_method;
2087 const char *short_name;
2088
2089 if (self->ssl == NULL)
2090 Py_RETURN_NONE;
2091 comp_method = SSL_get_current_compression(self->ssl);
Christian Heimes598894f2016-09-05 23:19:05 +02002092 if (comp_method == NULL || COMP_get_type(comp_method) == NID_undef)
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01002093 Py_RETURN_NONE;
Christian Heimes281e5f82016-09-06 01:10:39 +02002094 short_name = OBJ_nid2sn(COMP_get_type(comp_method));
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01002095 if (short_name == NULL)
2096 Py_RETURN_NONE;
2097 return PyUnicode_DecodeFSDefault(short_name);
2098#endif
2099}
2100
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002101static PySSLContext *PySSL_get_context(PySSLSocket *self, void *closure) {
2102 Py_INCREF(self->ctx);
2103 return self->ctx;
2104}
2105
2106static int PySSL_set_context(PySSLSocket *self, PyObject *value,
2107 void *closure) {
2108
Christian Heimes7f1305e2021-04-17 20:06:38 +02002109 if (PyObject_TypeCheck(value, self->ctx->state->PySSLContext_Type)) {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002110 Py_INCREF(value);
Serhiy Storchaka57a01d32016-04-10 18:05:40 +03002111 Py_SETREF(self->ctx, (PySSLContext *)value);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002112 SSL_set_SSL_CTX(self->ssl, self->ctx->ctx);
Christian Heimes77cde502021-03-21 16:13:09 +01002113 /* Set SSL* internal msg_callback to state of new context's state */
2114 SSL_set_msg_callback(
2115 self->ssl,
2116 self->ctx->msg_cb ? _PySSL_msg_callback : NULL
2117 );
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002118 } else {
Ned Deily4531ec72018-06-11 20:26:28 -04002119 PyErr_SetString(PyExc_TypeError, "The value must be a SSLContext");
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002120 return -1;
2121 }
2122
2123 return 0;
2124}
2125
2126PyDoc_STRVAR(PySSL_set_context_doc,
2127"_setter_context(ctx)\n\
2128\
2129This changes the context associated with the SSLSocket. This is typically\n\
Christian Heimes11a14932018-02-24 02:35:08 +01002130used from within a callback function set by the sni_callback\n\
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002131on the SSLContext to change the certificate information associated with the\n\
2132SSLSocket before the cryptographic exchange handshake messages\n");
2133
2134
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002135static PyObject *
2136PySSL_get_server_side(PySSLSocket *self, void *c)
2137{
2138 return PyBool_FromLong(self->socket_type == PY_SSL_SERVER);
2139}
2140
2141PyDoc_STRVAR(PySSL_get_server_side_doc,
2142"Whether this is a server-side socket.");
2143
2144static PyObject *
2145PySSL_get_server_hostname(PySSLSocket *self, void *c)
2146{
2147 if (self->server_hostname == NULL)
2148 Py_RETURN_NONE;
2149 Py_INCREF(self->server_hostname);
2150 return self->server_hostname;
2151}
2152
2153PyDoc_STRVAR(PySSL_get_server_hostname_doc,
2154"The currently set server hostname (for SNI).");
2155
2156static PyObject *
2157PySSL_get_owner(PySSLSocket *self, void *c)
2158{
2159 PyObject *owner;
2160
2161 if (self->owner == NULL)
2162 Py_RETURN_NONE;
2163
2164 owner = PyWeakref_GetObject(self->owner);
2165 Py_INCREF(owner);
2166 return owner;
2167}
2168
2169static int
2170PySSL_set_owner(PySSLSocket *self, PyObject *value, void *c)
2171{
Serhiy Storchaka48842712016-04-06 09:45:48 +03002172 Py_XSETREF(self->owner, PyWeakref_NewRef(value, NULL));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002173 if (self->owner == NULL)
2174 return -1;
2175 return 0;
2176}
2177
2178PyDoc_STRVAR(PySSL_get_owner_doc,
2179"The Python-level owner of this object.\
2180Passed as \"self\" in servername callback.");
2181
Christian Heimesc7f70692019-05-31 11:44:05 +02002182static int
2183PySSL_traverse(PySSLSocket *self, visitproc visit, void *arg)
2184{
2185 Py_VISIT(self->exc_type);
2186 Py_VISIT(self->exc_value);
2187 Py_VISIT(self->exc_tb);
Miss Islington (bot)ea47a8a2021-05-27 09:25:22 -07002188 Py_VISIT(Py_TYPE(self));
Christian Heimesc7f70692019-05-31 11:44:05 +02002189 return 0;
2190}
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002191
Christian Heimesc7f70692019-05-31 11:44:05 +02002192static int
2193PySSL_clear(PySSLSocket *self)
2194{
2195 Py_CLEAR(self->exc_type);
2196 Py_CLEAR(self->exc_value);
2197 Py_CLEAR(self->exc_tb);
2198 return 0;
2199}
2200
2201static void
2202PySSL_dealloc(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002203{
Christian Heimes5c36da72020-11-20 09:40:12 +01002204 PyTypeObject *tp = Py_TYPE(self);
Miss Islington (bot)ea47a8a2021-05-27 09:25:22 -07002205 PyObject_GC_UnTrack(self);
2206 if (self->ssl) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002207 SSL_free(self->ssl);
Miss Islington (bot)ea47a8a2021-05-27 09:25:22 -07002208 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002209 Py_XDECREF(self->Socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002210 Py_XDECREF(self->ctx);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002211 Py_XDECREF(self->server_hostname);
2212 Py_XDECREF(self->owner);
Miss Islington (bot)ea47a8a2021-05-27 09:25:22 -07002213 PyObject_GC_Del(self);
Christian Heimes5c36da72020-11-20 09:40:12 +01002214 Py_DECREF(tp);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002215}
2216
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002217/* If the socket has a timeout, do a select()/poll() on the socket.
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002218 The argument writing indicates the direction.
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00002219 Returns one of the possibilities in the timeout_state enum (above).
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002220 */
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00002221
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002222static int
Victor Stinner14690702015-04-06 22:46:13 +02002223PySSL_select(PySocketSockObject *s, int writing, _PyTime_t timeout)
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002224{
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002225 int rc;
2226#ifdef HAVE_POLL
2227 struct pollfd pollfd;
2228 _PyTime_t ms;
2229#else
2230 int nfds;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002231 fd_set fds;
2232 struct timeval tv;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002233#endif
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002234
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002235 /* Nothing to do unless we're in timeout mode (not non-blocking) */
Victor Stinner14690702015-04-06 22:46:13 +02002236 if ((s == NULL) || (timeout == 0))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002237 return SOCKET_IS_NONBLOCKING;
Victor Stinner14690702015-04-06 22:46:13 +02002238 else if (timeout < 0) {
2239 if (s->sock_timeout > 0)
2240 return SOCKET_HAS_TIMED_OUT;
2241 else
2242 return SOCKET_IS_BLOCKING;
2243 }
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002244
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002245 /* Guard against closed socket */
Victor Stinner524714e2016-07-22 17:43:59 +02002246 if (s->sock_fd == INVALID_SOCKET)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002247 return SOCKET_HAS_BEEN_CLOSED;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002248
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002249 /* Prefer poll, if available, since you can poll() any fd
2250 * which can't be done with select(). */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002251#ifdef HAVE_POLL
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002252 pollfd.fd = s->sock_fd;
2253 pollfd.events = writing ? POLLOUT : POLLIN;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002254
Victor Stinner14690702015-04-06 22:46:13 +02002255 /* timeout is in seconds, poll() uses milliseconds */
2256 ms = (int)_PyTime_AsMilliseconds(timeout, _PyTime_ROUND_CEILING);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002257 assert(ms <= INT_MAX);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002258
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002259 PySSL_BEGIN_ALLOW_THREADS
2260 rc = poll(&pollfd, 1, (int)ms);
2261 PySSL_END_ALLOW_THREADS
2262#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002263 /* Guard against socket too large for select*/
Charles-François Nataliaa26b272011-08-28 17:51:43 +02002264 if (!_PyIsSelectable_fd(s->sock_fd))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002265 return SOCKET_TOO_LARGE_FOR_SELECT;
Neal Norwitz082b2df2006-02-07 07:04:46 +00002266
Victor Stinner14690702015-04-06 22:46:13 +02002267 _PyTime_AsTimeval_noraise(timeout, &tv, _PyTime_ROUND_CEILING);
Victor Stinnere2452312015-03-28 03:00:46 +01002268
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002269 FD_ZERO(&fds);
2270 FD_SET(s->sock_fd, &fds);
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002271
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002272 /* Wait until the socket becomes ready */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002273 PySSL_BEGIN_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002274 nfds = Py_SAFE_DOWNCAST(s->sock_fd+1, SOCKET_T, int);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002275 if (writing)
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002276 rc = select(nfds, NULL, &fds, NULL, &tv);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002277 else
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002278 rc = select(nfds, &fds, NULL, NULL, &tv);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002279 PySSL_END_ALLOW_THREADS
Bill Janssen6e027db2007-11-15 22:23:56 +00002280#endif
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002281
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002282 /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
2283 (when we are able to write or when there's something to read) */
2284 return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002285}
2286
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002287/*[clinic input]
2288_ssl._SSLSocket.write
2289 b: Py_buffer
2290 /
2291
2292Writes the bytes-like object b into the SSL object.
2293
2294Returns the number of bytes written.
2295[clinic start generated code]*/
2296
2297static PyObject *
2298_ssl__SSLSocket_write_impl(PySSLSocket *self, Py_buffer *b)
2299/*[clinic end generated code: output=aa7a6be5527358d8 input=77262d994fe5100a]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002300{
Christian Heimes89d15502021-04-19 06:55:30 +02002301 size_t count = 0;
2302 int retval;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002303 int sockstate;
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002304 _PySSLError err;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002305 int nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002306 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002307 _PyTime_t timeout, deadline = 0;
2308 int has_timeout;
Bill Janssen54cc54c2007-12-14 22:08:56 +00002309
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002310 if (sock != NULL) {
2311 if (((PyObject*)sock) == Py_None) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02002312 _setSSLError(get_state_sock(self),
2313 "Underlying socket connection gone",
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002314 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2315 return NULL;
2316 }
2317 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002318 }
2319
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002320 if (sock != NULL) {
2321 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002322 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002323 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2324 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
2325 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002326
Victor Stinner14690702015-04-06 22:46:13 +02002327 timeout = GET_SOCKET_TIMEOUT(sock);
2328 has_timeout = (timeout > 0);
2329 if (has_timeout)
2330 deadline = _PyTime_GetMonotonicClock() + timeout;
2331
2332 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002333 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Christian Heimes03c8ddd2020-11-20 09:26:07 +01002334 PyErr_SetString(PyExc_TimeoutError,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002335 "The write operation timed out");
2336 goto error;
2337 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02002338 PyErr_SetString(get_state_sock(self)->PySSLErrorObject,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002339 "Underlying socket has been closed.");
2340 goto error;
2341 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02002342 PyErr_SetString(get_state_sock(self)->PySSLErrorObject,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002343 "Underlying socket too large for select().");
2344 goto error;
2345 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002346
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002347 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002348 PySSL_BEGIN_ALLOW_THREADS
Christian Heimes89d15502021-04-19 06:55:30 +02002349 retval = SSL_write_ex(self->ssl, b->buf, (int)b->len, &count);
2350 err = _PySSL_errno(retval == 0, self->ssl, retval);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002351 PySSL_END_ALLOW_THREADS
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002352 self->err = err;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002353
2354 if (PyErr_CheckSignals())
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002355 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002356
Victor Stinner14690702015-04-06 22:46:13 +02002357 if (has_timeout)
2358 timeout = deadline - _PyTime_GetMonotonicClock();
2359
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002360 if (err.ssl == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +02002361 sockstate = PySSL_select(sock, 0, timeout);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002362 } else if (err.ssl == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +02002363 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002364 } else {
2365 sockstate = SOCKET_OPERATION_OK;
2366 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002367
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002368 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Christian Heimes03c8ddd2020-11-20 09:26:07 +01002369 PyErr_SetString(PyExc_TimeoutError,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002370 "The write operation timed out");
2371 goto error;
2372 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02002373 PyErr_SetString(get_state_sock(self)->PySSLErrorObject,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002374 "Underlying socket has been closed.");
2375 goto error;
2376 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
2377 break;
2378 }
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002379 } while (err.ssl == SSL_ERROR_WANT_READ ||
2380 err.ssl == SSL_ERROR_WANT_WRITE);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002381
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002382 Py_XDECREF(sock);
Christian Heimes89d15502021-04-19 06:55:30 +02002383 if (retval == 0)
2384 return PySSL_SetError(self, retval, __FILE__, __LINE__);
Christian Heimesc7f70692019-05-31 11:44:05 +02002385 if (PySSL_ChainExceptions(self) < 0)
2386 return NULL;
Christian Heimes89d15502021-04-19 06:55:30 +02002387 return PyLong_FromSize_t(count);
Antoine Pitrou7d7aede2009-11-25 18:55:32 +00002388error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002389 Py_XDECREF(sock);
Christian Heimesc7f70692019-05-31 11:44:05 +02002390 PySSL_ChainExceptions(self);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002391 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002392}
2393
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002394/*[clinic input]
2395_ssl._SSLSocket.pending
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002396
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002397Returns the number of already decrypted bytes available for read, pending on the connection.
2398[clinic start generated code]*/
2399
2400static PyObject *
2401_ssl__SSLSocket_pending_impl(PySSLSocket *self)
2402/*[clinic end generated code: output=983d9fecdc308a83 input=2b77487d6dfd597f]*/
Bill Janssen6e027db2007-11-15 22:23:56 +00002403{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002404 int count = 0;
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002405 _PySSLError err;
Bill Janssen6e027db2007-11-15 22:23:56 +00002406
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002407 PySSL_BEGIN_ALLOW_THREADS
2408 count = SSL_pending(self->ssl);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002409 err = _PySSL_errno(count < 0, self->ssl, count);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002410 PySSL_END_ALLOW_THREADS
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002411 self->err = err;
2412
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002413 if (count < 0)
2414 return PySSL_SetError(self, count, __FILE__, __LINE__);
2415 else
2416 return PyLong_FromLong(count);
Bill Janssen6e027db2007-11-15 22:23:56 +00002417}
2418
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002419/*[clinic input]
2420_ssl._SSLSocket.read
2421 size as len: int
2422 [
Larry Hastingsdbfdc382015-05-04 06:59:46 -07002423 buffer: Py_buffer(accept={rwbuffer})
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002424 ]
2425 /
Bill Janssen6e027db2007-11-15 22:23:56 +00002426
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002427Read up to size bytes from the SSL socket.
2428[clinic start generated code]*/
2429
2430static PyObject *
2431_ssl__SSLSocket_read_impl(PySSLSocket *self, int len, int group_right_1,
2432 Py_buffer *buffer)
Larry Hastingsdbfdc382015-05-04 06:59:46 -07002433/*[clinic end generated code: output=00097776cec2a0af input=ff157eb918d0905b]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002434{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002435 PyObject *dest = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002436 char *mem;
Christian Heimes89d15502021-04-19 06:55:30 +02002437 size_t count = 0;
2438 int retval;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002439 int sockstate;
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002440 _PySSLError err;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002441 int nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002442 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002443 _PyTime_t timeout, deadline = 0;
2444 int has_timeout;
Bill Janssen54cc54c2007-12-14 22:08:56 +00002445
Martin Panter5503d472016-03-27 05:35:19 +00002446 if (!group_right_1 && len < 0) {
2447 PyErr_SetString(PyExc_ValueError, "size should not be negative");
2448 return NULL;
2449 }
2450
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002451 if (sock != NULL) {
2452 if (((PyObject*)sock) == Py_None) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02002453 _setSSLError(get_state_sock(self),
2454 "Underlying socket connection gone",
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002455 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2456 return NULL;
2457 }
2458 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002459 }
2460
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002461 if (!group_right_1) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002462 dest = PyBytes_FromStringAndSize(NULL, len);
2463 if (dest == NULL)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002464 goto error;
Martin Panterbed7f1a2016-07-11 00:17:13 +00002465 if (len == 0) {
2466 Py_XDECREF(sock);
2467 return dest;
2468 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002469 mem = PyBytes_AS_STRING(dest);
2470 }
2471 else {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002472 mem = buffer->buf;
2473 if (len <= 0 || len > buffer->len) {
2474 len = (int) buffer->len;
2475 if (buffer->len != len) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002476 PyErr_SetString(PyExc_OverflowError,
2477 "maximum length can't fit in a C 'int'");
2478 goto error;
2479 }
Martin Panterbed7f1a2016-07-11 00:17:13 +00002480 if (len == 0) {
2481 count = 0;
2482 goto done;
2483 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002484 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002485 }
2486
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002487 if (sock != NULL) {
2488 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002489 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002490 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2491 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
2492 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002493
Victor Stinner14690702015-04-06 22:46:13 +02002494 timeout = GET_SOCKET_TIMEOUT(sock);
2495 has_timeout = (timeout > 0);
2496 if (has_timeout)
2497 deadline = _PyTime_GetMonotonicClock() + timeout;
2498
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002499 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002500 PySSL_BEGIN_ALLOW_THREADS
Christian Heimes89d15502021-04-19 06:55:30 +02002501 retval = SSL_read_ex(self->ssl, mem, len, &count);
2502 err = _PySSL_errno(retval == 0, self->ssl, retval);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002503 PySSL_END_ALLOW_THREADS
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002504 self->err = err;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002505
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002506 if (PyErr_CheckSignals())
2507 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002508
Victor Stinner14690702015-04-06 22:46:13 +02002509 if (has_timeout)
2510 timeout = deadline - _PyTime_GetMonotonicClock();
2511
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002512 if (err.ssl == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +02002513 sockstate = PySSL_select(sock, 0, timeout);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002514 } else if (err.ssl == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +02002515 sockstate = PySSL_select(sock, 1, timeout);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002516 } else if (err.ssl == SSL_ERROR_ZERO_RETURN &&
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002517 SSL_get_shutdown(self->ssl) == SSL_RECEIVED_SHUTDOWN)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002518 {
2519 count = 0;
2520 goto done;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002521 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002522 else
2523 sockstate = SOCKET_OPERATION_OK;
2524
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002525 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Christian Heimes03c8ddd2020-11-20 09:26:07 +01002526 PyErr_SetString(PyExc_TimeoutError,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002527 "The read operation timed out");
2528 goto error;
2529 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
2530 break;
2531 }
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002532 } while (err.ssl == SSL_ERROR_WANT_READ ||
2533 err.ssl == SSL_ERROR_WANT_WRITE);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002534
Christian Heimes89d15502021-04-19 06:55:30 +02002535 if (retval == 0) {
2536 PySSL_SetError(self, retval, __FILE__, __LINE__);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002537 goto error;
2538 }
Christian Heimesc7f70692019-05-31 11:44:05 +02002539 if (self->exc_type != NULL)
2540 goto error;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002541
2542done:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002543 Py_XDECREF(sock);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002544 if (!group_right_1) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002545 _PyBytes_Resize(&dest, count);
2546 return dest;
2547 }
2548 else {
Christian Heimes89d15502021-04-19 06:55:30 +02002549 return PyLong_FromSize_t(count);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002550 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002551
2552error:
Christian Heimesc7f70692019-05-31 11:44:05 +02002553 PySSL_ChainExceptions(self);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002554 Py_XDECREF(sock);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002555 if (!group_right_1)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002556 Py_XDECREF(dest);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002557 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002558}
2559
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002560/*[clinic input]
2561_ssl._SSLSocket.shutdown
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002562
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002563Does the SSL shutdown handshake with the remote end.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002564[clinic start generated code]*/
2565
2566static PyObject *
2567_ssl__SSLSocket_shutdown_impl(PySSLSocket *self)
Christian Heimes141c5e82018-02-24 21:10:57 +01002568/*[clinic end generated code: output=ca1aa7ed9d25ca42 input=11d39e69b0a2bf4a]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00002569{
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002570 _PySSLError err;
2571 int sockstate, nonblocking, ret;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002572 int zeros = 0;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002573 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002574 _PyTime_t timeout, deadline = 0;
2575 int has_timeout;
Bill Janssen40a0f662008-08-12 16:56:25 +00002576
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002577 if (sock != NULL) {
2578 /* Guard against closed socket */
Victor Stinner524714e2016-07-22 17:43:59 +02002579 if ((((PyObject*)sock) == Py_None) || (sock->sock_fd == INVALID_SOCKET)) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02002580 _setSSLError(get_state_sock(self),
2581 "Underlying socket connection gone",
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002582 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2583 return NULL;
2584 }
2585 Py_INCREF(sock);
2586
2587 /* Just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002588 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002589 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2590 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002591 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002592
Victor Stinner14690702015-04-06 22:46:13 +02002593 timeout = GET_SOCKET_TIMEOUT(sock);
2594 has_timeout = (timeout > 0);
2595 if (has_timeout)
2596 deadline = _PyTime_GetMonotonicClock() + timeout;
2597
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002598 while (1) {
2599 PySSL_BEGIN_ALLOW_THREADS
2600 /* Disable read-ahead so that unwrap can work correctly.
2601 * Otherwise OpenSSL might read in too much data,
2602 * eating clear text data that happens to be
2603 * transmitted after the SSL shutdown.
Ezio Melotti85a86292013-08-17 16:57:41 +03002604 * Should be safe to call repeatedly every time this
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002605 * function is used and the shutdown_seen_zero != 0
2606 * condition is met.
2607 */
2608 if (self->shutdown_seen_zero)
2609 SSL_set_read_ahead(self->ssl, 0);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002610 ret = SSL_shutdown(self->ssl);
2611 err = _PySSL_errno(ret < 0, self->ssl, ret);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002612 PySSL_END_ALLOW_THREADS
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002613 self->err = err;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002614
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002615 /* If err == 1, a secure shutdown with SSL_shutdown() is complete */
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002616 if (ret > 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002617 break;
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002618 if (ret == 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002619 /* Don't loop endlessly; instead preserve legacy
2620 behaviour of trying SSL_shutdown() only twice.
2621 This looks necessary for OpenSSL < 0.9.8m */
2622 if (++zeros > 1)
2623 break;
2624 /* Shutdown was sent, now try receiving */
2625 self->shutdown_seen_zero = 1;
2626 continue;
Bill Janssen40a0f662008-08-12 16:56:25 +00002627 }
2628
Victor Stinner14690702015-04-06 22:46:13 +02002629 if (has_timeout)
2630 timeout = deadline - _PyTime_GetMonotonicClock();
2631
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002632 /* Possibly retry shutdown until timeout or failure */
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002633 if (err.ssl == SSL_ERROR_WANT_READ)
Victor Stinner14690702015-04-06 22:46:13 +02002634 sockstate = PySSL_select(sock, 0, timeout);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002635 else if (err.ssl == SSL_ERROR_WANT_WRITE)
Victor Stinner14690702015-04-06 22:46:13 +02002636 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002637 else
2638 break;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002639
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002640 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002641 if (err.ssl == SSL_ERROR_WANT_READ)
Christian Heimes03c8ddd2020-11-20 09:26:07 +01002642 PyErr_SetString(PyExc_TimeoutError,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002643 "The read operation timed out");
2644 else
Christian Heimes03c8ddd2020-11-20 09:26:07 +01002645 PyErr_SetString(PyExc_TimeoutError,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002646 "The write operation timed out");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002647 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002648 }
2649 else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02002650 PyErr_SetString(get_state_sock(self)->PySSLErrorObject,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002651 "Underlying socket too large for select().");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002652 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002653 }
2654 else if (sockstate != SOCKET_OPERATION_OK)
2655 /* Retain the SSL error code */
2656 break;
2657 }
Nathaniel J. Smithc0da5822018-09-21 21:44:12 -07002658 if (ret < 0) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002659 Py_XDECREF(sock);
Christian Heimesc7f70692019-05-31 11:44:05 +02002660 PySSL_SetError(self, ret, __FILE__, __LINE__);
2661 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002662 }
Christian Heimesc7f70692019-05-31 11:44:05 +02002663 if (self->exc_type != NULL)
2664 goto error;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002665 if (sock)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002666 /* It's already INCREF'ed */
2667 return (PyObject *) sock;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002668 else
2669 Py_RETURN_NONE;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002670
2671error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002672 Py_XDECREF(sock);
Christian Heimesc7f70692019-05-31 11:44:05 +02002673 PySSL_ChainExceptions(self);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002674 return NULL;
Bill Janssen40a0f662008-08-12 16:56:25 +00002675}
2676
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002677/*[clinic input]
Christian Heimes141c5e82018-02-24 21:10:57 +01002678_ssl._SSLSocket.get_channel_binding
2679 cb_type: str = "tls-unique"
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002680
Christian Heimes141c5e82018-02-24 21:10:57 +01002681Get channel binding data for current connection.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002682
Christian Heimes141c5e82018-02-24 21:10:57 +01002683Raise ValueError if the requested `cb_type` is not supported. Return bytes
2684of the data or None if the data is not available (e.g. before the handshake).
2685Only 'tls-unique' channel binding data from RFC 5929 is supported.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002686[clinic start generated code]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00002687
Antoine Pitroud6494802011-07-21 01:11:30 +02002688static PyObject *
Christian Heimes141c5e82018-02-24 21:10:57 +01002689_ssl__SSLSocket_get_channel_binding_impl(PySSLSocket *self,
2690 const char *cb_type)
2691/*[clinic end generated code: output=34bac9acb6a61d31 input=08b7e43b99c17d41]*/
Antoine Pitroud6494802011-07-21 01:11:30 +02002692{
Antoine Pitroud6494802011-07-21 01:11:30 +02002693 char buf[PySSL_CB_MAXLEN];
Victor Stinner9ee02032013-06-23 15:08:23 +02002694 size_t len;
Antoine Pitroud6494802011-07-21 01:11:30 +02002695
Christian Heimes141c5e82018-02-24 21:10:57 +01002696 if (strcmp(cb_type, "tls-unique") == 0) {
2697 if (SSL_session_reused(self->ssl) ^ !self->socket_type) {
2698 /* if session is resumed XOR we are the client */
2699 len = SSL_get_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2700 }
2701 else {
2702 /* if a new session XOR we are the server */
2703 len = SSL_get_peer_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2704 }
Antoine Pitroud6494802011-07-21 01:11:30 +02002705 }
2706 else {
Christian Heimes141c5e82018-02-24 21:10:57 +01002707 PyErr_Format(
2708 PyExc_ValueError,
2709 "'%s' channel binding type not implemented",
2710 cb_type
2711 );
2712 return NULL;
Antoine Pitroud6494802011-07-21 01:11:30 +02002713 }
2714
2715 /* It cannot be negative in current OpenSSL version as of July 2011 */
Antoine Pitroud6494802011-07-21 01:11:30 +02002716 if (len == 0)
2717 Py_RETURN_NONE;
2718
Christian Heimes141c5e82018-02-24 21:10:57 +01002719 return PyBytes_FromStringAndSize(buf, len);
Antoine Pitroud6494802011-07-21 01:11:30 +02002720}
2721
Christian Heimes9fb051f2018-09-23 08:32:31 +02002722/*[clinic input]
2723_ssl._SSLSocket.verify_client_post_handshake
2724
2725Initiate TLS 1.3 post-handshake authentication
2726[clinic start generated code]*/
2727
2728static PyObject *
2729_ssl__SSLSocket_verify_client_post_handshake_impl(PySSLSocket *self)
2730/*[clinic end generated code: output=532147f3b1341425 input=6bfa874810a3d889]*/
2731{
2732#ifdef TLS1_3_VERSION
2733 int err = SSL_verify_client_post_handshake(self->ssl);
2734 if (err == 0)
Christian Heimes7f1305e2021-04-17 20:06:38 +02002735 return _setSSLError(get_state_sock(self), NULL, 0, __FILE__, __LINE__);
Christian Heimes9fb051f2018-09-23 08:32:31 +02002736 else
2737 Py_RETURN_NONE;
2738#else
2739 PyErr_SetString(PyExc_NotImplementedError,
2740 "Post-handshake auth is not supported by your "
2741 "OpenSSL version.");
2742 return NULL;
2743#endif
2744}
2745
Christian Heimes99a65702016-09-10 23:44:53 +02002746static SSL_SESSION*
2747_ssl_session_dup(SSL_SESSION *session) {
2748 SSL_SESSION *newsession = NULL;
2749 int slen;
2750 unsigned char *senc = NULL, *p;
2751 const unsigned char *const_p;
2752
2753 if (session == NULL) {
2754 PyErr_SetString(PyExc_ValueError, "Invalid session");
2755 goto error;
2756 }
2757
2758 /* get length */
2759 slen = i2d_SSL_SESSION(session, NULL);
2760 if (slen == 0 || slen > 0xFF00) {
2761 PyErr_SetString(PyExc_ValueError, "i2d() failed.");
2762 goto error;
2763 }
2764 if ((senc = PyMem_Malloc(slen)) == NULL) {
2765 PyErr_NoMemory();
2766 goto error;
2767 }
2768 p = senc;
2769 if (!i2d_SSL_SESSION(session, &p)) {
2770 PyErr_SetString(PyExc_ValueError, "i2d() failed.");
2771 goto error;
2772 }
2773 const_p = senc;
2774 newsession = d2i_SSL_SESSION(NULL, &const_p, slen);
2775 if (session == NULL) {
2776 goto error;
2777 }
2778 PyMem_Free(senc);
2779 return newsession;
2780 error:
2781 if (senc != NULL) {
2782 PyMem_Free(senc);
2783 }
2784 return NULL;
2785}
Christian Heimes99a65702016-09-10 23:44:53 +02002786
2787static PyObject *
2788PySSL_get_session(PySSLSocket *self, void *closure) {
2789 /* get_session can return sessions from a server-side connection,
2790 * it does not check for handshake done or client socket. */
2791 PySSLSession *pysess;
2792 SSL_SESSION *session;
2793
Christian Heimes99a65702016-09-10 23:44:53 +02002794 /* duplicate session as workaround for session bug in OpenSSL 1.1.0,
2795 * https://github.com/openssl/openssl/issues/1550 */
2796 session = SSL_get0_session(self->ssl); /* borrowed reference */
2797 if (session == NULL) {
2798 Py_RETURN_NONE;
2799 }
2800 if ((session = _ssl_session_dup(session)) == NULL) {
2801 return NULL;
2802 }
Christian Heimes99a65702016-09-10 23:44:53 +02002803 session = SSL_get1_session(self->ssl);
2804 if (session == NULL) {
2805 Py_RETURN_NONE;
2806 }
Christian Heimes7f1305e2021-04-17 20:06:38 +02002807 pysess = PyObject_GC_New(PySSLSession, self->ctx->state->PySSLSession_Type);
Christian Heimes99a65702016-09-10 23:44:53 +02002808 if (pysess == NULL) {
2809 SSL_SESSION_free(session);
2810 return NULL;
2811 }
2812
2813 assert(self->ctx);
2814 pysess->ctx = self->ctx;
2815 Py_INCREF(pysess->ctx);
2816 pysess->session = session;
Christian Heimesa5d07652016-09-24 10:48:05 +02002817 PyObject_GC_Track(pysess);
Christian Heimes99a65702016-09-10 23:44:53 +02002818 return (PyObject *)pysess;
2819}
2820
2821static int PySSL_set_session(PySSLSocket *self, PyObject *value,
2822 void *closure)
2823 {
2824 PySSLSession *pysess;
Christian Heimes99a65702016-09-10 23:44:53 +02002825 SSL_SESSION *session;
Christian Heimes99a65702016-09-10 23:44:53 +02002826 int result;
2827
Christian Heimes7f1305e2021-04-17 20:06:38 +02002828 if (!Py_IS_TYPE(value, get_state_sock(self)->PySSLSession_Type)) {
Ned Deily4531ec72018-06-11 20:26:28 -04002829 PyErr_SetString(PyExc_TypeError, "Value is not a SSLSession.");
Christian Heimes99a65702016-09-10 23:44:53 +02002830 return -1;
2831 }
2832 pysess = (PySSLSession *)value;
2833
2834 if (self->ctx->ctx != pysess->ctx->ctx) {
2835 PyErr_SetString(PyExc_ValueError,
2836 "Session refers to a different SSLContext.");
2837 return -1;
2838 }
2839 if (self->socket_type != PY_SSL_CLIENT) {
2840 PyErr_SetString(PyExc_ValueError,
2841 "Cannot set session for server-side SSLSocket.");
2842 return -1;
2843 }
Christian Heimes66dc33b2017-05-23 16:02:02 -07002844 if (SSL_is_init_finished(self->ssl)) {
Christian Heimes99a65702016-09-10 23:44:53 +02002845 PyErr_SetString(PyExc_ValueError,
2846 "Cannot set session after handshake.");
2847 return -1;
2848 }
Christian Heimes99a65702016-09-10 23:44:53 +02002849 /* duplicate session */
2850 if ((session = _ssl_session_dup(pysess->session)) == NULL) {
2851 return -1;
2852 }
2853 result = SSL_set_session(self->ssl, session);
2854 /* free duplicate, SSL_set_session() bumps ref count */
2855 SSL_SESSION_free(session);
Christian Heimes99a65702016-09-10 23:44:53 +02002856 if (result == 0) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02002857 _setSSLError(get_state_sock(self), NULL, 0, __FILE__, __LINE__);
Christian Heimes99a65702016-09-10 23:44:53 +02002858 return -1;
2859 }
2860 return 0;
2861}
2862
2863PyDoc_STRVAR(PySSL_set_session_doc,
2864"_setter_session(session)\n\
2865\
2866Get / set SSLSession.");
2867
2868static PyObject *
2869PySSL_get_session_reused(PySSLSocket *self, void *closure) {
2870 if (SSL_session_reused(self->ssl)) {
2871 Py_RETURN_TRUE;
2872 } else {
2873 Py_RETURN_FALSE;
2874 }
2875}
2876
2877PyDoc_STRVAR(PySSL_get_session_reused_doc,
2878"Was the client session reused during handshake?");
2879
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002880static PyGetSetDef ssl_getsetlist[] = {
2881 {"context", (getter) PySSL_get_context,
2882 (setter) PySSL_set_context, PySSL_set_context_doc},
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002883 {"server_side", (getter) PySSL_get_server_side, NULL,
2884 PySSL_get_server_side_doc},
2885 {"server_hostname", (getter) PySSL_get_server_hostname, NULL,
2886 PySSL_get_server_hostname_doc},
2887 {"owner", (getter) PySSL_get_owner, (setter) PySSL_set_owner,
2888 PySSL_get_owner_doc},
Christian Heimes99a65702016-09-10 23:44:53 +02002889 {"session", (getter) PySSL_get_session,
2890 (setter) PySSL_set_session, PySSL_set_session_doc},
2891 {"session_reused", (getter) PySSL_get_session_reused, NULL,
2892 PySSL_get_session_reused_doc},
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002893 {NULL}, /* sentinel */
2894};
2895
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002896static PyMethodDef PySSLMethods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002897 _SSL__SSLSOCKET_DO_HANDSHAKE_METHODDEF
2898 _SSL__SSLSOCKET_WRITE_METHODDEF
2899 _SSL__SSLSOCKET_READ_METHODDEF
2900 _SSL__SSLSOCKET_PENDING_METHODDEF
Christian Heimes141c5e82018-02-24 21:10:57 +01002901 _SSL__SSLSOCKET_GETPEERCERT_METHODDEF
2902 _SSL__SSLSOCKET_GET_CHANNEL_BINDING_METHODDEF
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002903 _SSL__SSLSOCKET_CIPHER_METHODDEF
2904 _SSL__SSLSOCKET_SHARED_CIPHERS_METHODDEF
2905 _SSL__SSLSOCKET_VERSION_METHODDEF
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002906 _SSL__SSLSOCKET_SELECTED_ALPN_PROTOCOL_METHODDEF
2907 _SSL__SSLSOCKET_COMPRESSION_METHODDEF
2908 _SSL__SSLSOCKET_SHUTDOWN_METHODDEF
Christian Heimes9fb051f2018-09-23 08:32:31 +02002909 _SSL__SSLSOCKET_VERIFY_CLIENT_POST_HANDSHAKE_METHODDEF
Christian Heimes666991f2021-04-26 15:01:40 +02002910 _SSL__SSLSOCKET_GET_UNVERIFIED_CHAIN_METHODDEF
2911 _SSL__SSLSOCKET_GET_VERIFIED_CHAIN_METHODDEF
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002912 {NULL, NULL}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002913};
2914
Christian Heimes5c36da72020-11-20 09:40:12 +01002915static PyType_Slot PySSLSocket_slots[] = {
2916 {Py_tp_methods, PySSLMethods},
2917 {Py_tp_getset, ssl_getsetlist},
2918 {Py_tp_dealloc, PySSL_dealloc},
2919 {Py_tp_traverse, PySSL_traverse},
2920 {Py_tp_clear, PySSL_clear},
2921 {0, 0},
2922};
2923
2924static PyType_Spec PySSLSocket_spec = {
Miss Islington (bot)ea47a8a2021-05-27 09:25:22 -07002925 .name = "_ssl._SSLSocket",
2926 .basicsize = sizeof(PySSLSocket),
2927 .flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_IMMUTABLETYPE |
2928 Py_TPFLAGS_HAVE_GC),
2929 .slots = PySSLSocket_slots,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002930};
2931
Antoine Pitrou152efa22010-05-16 18:19:27 +00002932/*
2933 * _SSLContext objects
2934 */
2935
Christian Heimes5fe668c2016-09-12 00:01:11 +02002936static int
Christian Heimes9fb051f2018-09-23 08:32:31 +02002937_set_verify_mode(PySSLContext *self, enum py_ssl_cert_requirements n)
Christian Heimes5fe668c2016-09-12 00:01:11 +02002938{
2939 int mode;
2940 int (*verify_cb)(int, X509_STORE_CTX *) = NULL;
2941
2942 switch(n) {
2943 case PY_SSL_CERT_NONE:
2944 mode = SSL_VERIFY_NONE;
2945 break;
2946 case PY_SSL_CERT_OPTIONAL:
2947 mode = SSL_VERIFY_PEER;
2948 break;
2949 case PY_SSL_CERT_REQUIRED:
2950 mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
2951 break;
2952 default:
2953 PyErr_SetString(PyExc_ValueError,
2954 "invalid value for verify_mode");
2955 return -1;
2956 }
Christian Heimesf0f59302019-07-01 08:29:17 +02002957
2958 /* bpo-37428: newPySSLSocket() sets SSL_VERIFY_POST_HANDSHAKE flag for
2959 * server sockets and SSL_set_post_handshake_auth() for client. */
2960
Christian Heimes5fe668c2016-09-12 00:01:11 +02002961 /* keep current verify cb */
Christian Heimes9fb051f2018-09-23 08:32:31 +02002962 verify_cb = SSL_CTX_get_verify_callback(self->ctx);
2963 SSL_CTX_set_verify(self->ctx, mode, verify_cb);
Christian Heimes5fe668c2016-09-12 00:01:11 +02002964 return 0;
2965}
2966
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002967/*[clinic input]
2968@classmethod
2969_ssl._SSLContext.__new__
2970 protocol as proto_version: int
2971 /
2972[clinic start generated code]*/
2973
Antoine Pitrou152efa22010-05-16 18:19:27 +00002974static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002975_ssl__SSLContext_impl(PyTypeObject *type, int proto_version)
2976/*[clinic end generated code: output=2cf0d7a0741b6bd1 input=8d58a805b95fc534]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00002977{
Antoine Pitrou152efa22010-05-16 18:19:27 +00002978 PySSLContext *self;
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01002979 long options;
Christian Heimes2875c602021-04-19 07:27:10 +02002980 const SSL_METHOD *method = NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002981 SSL_CTX *ctx = NULL;
Christian Heimes61d478c2018-01-27 15:51:38 +01002982 X509_VERIFY_PARAM *params;
Christian Heimes358cfd42016-09-10 22:43:48 +02002983 int result;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002984
Christian Heimes7f1305e2021-04-17 20:06:38 +02002985 /* slower approach, walk MRO and get borrowed reference to module.
2986 * _PyType_GetModuleByDef is required for SSLContext subclasses */
2987 PyObject *module = _PyType_GetModuleByDef(type, &_sslmodule_def);
2988 if (module == NULL) {
2989 PyErr_SetString(PyExc_RuntimeError,
2990 "Cannot find internal module state");
2991 return NULL;
2992 }
2993
Christian Heimes6e8cda92020-05-16 03:33:05 +02002994 switch(proto_version) {
2995#if defined(SSL3_VERSION) && !defined(OPENSSL_NO_SSL3)
2996 case PY_SSL_VERSION_SSL3:
Miss Islington (bot)d7930fb2021-06-11 00:36:17 -07002997 PY_SSL_DEPRECATED("ssl.PROTOCOL_SSLv3 is deprecated", 2, NULL);
Christian Heimes2875c602021-04-19 07:27:10 +02002998 method = SSLv3_method();
Christian Heimes6e8cda92020-05-16 03:33:05 +02002999 break;
Benjamin Petersone32467c2014-12-05 21:59:35 -05003000#endif
Christian Heimesa871f692020-06-01 08:58:14 +02003001#if (defined(TLS1_VERSION) && \
3002 !defined(OPENSSL_NO_TLS1) && \
3003 !defined(OPENSSL_NO_TLS1_METHOD))
Christian Heimes6e8cda92020-05-16 03:33:05 +02003004 case PY_SSL_VERSION_TLS1:
Miss Islington (bot)d7930fb2021-06-11 00:36:17 -07003005 PY_SSL_DEPRECATED("ssl.PROTOCOL_TLSv1 is deprecated", 2, NULL);
Christian Heimes2875c602021-04-19 07:27:10 +02003006 method = TLSv1_method();
Christian Heimes6e8cda92020-05-16 03:33:05 +02003007 break;
Victor Stinner3de49192011-05-09 00:42:58 +02003008#endif
Christian Heimesa871f692020-06-01 08:58:14 +02003009#if (defined(TLS1_1_VERSION) && \
3010 !defined(OPENSSL_NO_TLS1_1) && \
3011 !defined(OPENSSL_NO_TLS1_1_METHOD))
Christian Heimes6e8cda92020-05-16 03:33:05 +02003012 case PY_SSL_VERSION_TLS1_1:
Miss Islington (bot)d7930fb2021-06-11 00:36:17 -07003013 PY_SSL_DEPRECATED("ssl.PROTOCOL_TLSv1_1 is deprecated", 2, NULL);
Christian Heimes2875c602021-04-19 07:27:10 +02003014 method = TLSv1_1_method();
Christian Heimes6e8cda92020-05-16 03:33:05 +02003015 break;
3016#endif
Christian Heimesa871f692020-06-01 08:58:14 +02003017#if (defined(TLS1_2_VERSION) && \
3018 !defined(OPENSSL_NO_TLS1_2) && \
3019 !defined(OPENSSL_NO_TLS1_2_METHOD))
Christian Heimes6e8cda92020-05-16 03:33:05 +02003020 case PY_SSL_VERSION_TLS1_2:
Miss Islington (bot)d7930fb2021-06-11 00:36:17 -07003021 PY_SSL_DEPRECATED("ssl.PROTOCOL_TLSv1_2 is deprecated", 2, NULL);
Christian Heimes2875c602021-04-19 07:27:10 +02003022 method = TLSv1_2_method();
Christian Heimes6e8cda92020-05-16 03:33:05 +02003023 break;
3024#endif
3025 case PY_SSL_VERSION_TLS:
Miss Islington (bot)d7930fb2021-06-11 00:36:17 -07003026 PY_SSL_DEPRECATED("ssl.PROTOCOL_TLS is deprecated", 2, NULL);
Christian Heimes2875c602021-04-19 07:27:10 +02003027 method = TLS_method();
Christian Heimes6e8cda92020-05-16 03:33:05 +02003028 break;
3029 case PY_SSL_VERSION_TLS_CLIENT:
Christian Heimes2875c602021-04-19 07:27:10 +02003030 method = TLS_client_method();
Christian Heimes6e8cda92020-05-16 03:33:05 +02003031 break;
3032 case PY_SSL_VERSION_TLS_SERVER:
Christian Heimes2875c602021-04-19 07:27:10 +02003033 method = TLS_server_method();
Christian Heimes6e8cda92020-05-16 03:33:05 +02003034 break;
3035 default:
Christian Heimes2875c602021-04-19 07:27:10 +02003036 method = NULL;
Christian Heimes6e8cda92020-05-16 03:33:05 +02003037 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003038
Christian Heimes2875c602021-04-19 07:27:10 +02003039 if (method == NULL) {
3040 PyErr_Format(PyExc_ValueError,
3041 "invalid or unsupported protocol version %i",
3042 proto_version);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003043 return NULL;
3044 }
Christian Heimes2875c602021-04-19 07:27:10 +02003045
3046 PySSL_BEGIN_ALLOW_THREADS
3047 ctx = SSL_CTX_new(method);
3048 PySSL_END_ALLOW_THREADS
3049
Antoine Pitrou152efa22010-05-16 18:19:27 +00003050 if (ctx == NULL) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02003051 _setSSLError(get_ssl_state(module), NULL, 0, __FILE__, __LINE__);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003052 return NULL;
3053 }
3054
3055 assert(type != NULL && type->tp_alloc != NULL);
3056 self = (PySSLContext *) type->tp_alloc(type, 0);
3057 if (self == NULL) {
3058 SSL_CTX_free(ctx);
3059 return NULL;
3060 }
3061 self->ctx = ctx;
Christian Heimes61d478c2018-01-27 15:51:38 +01003062 self->hostflags = X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS;
Christian Heimes11a14932018-02-24 02:35:08 +01003063 self->protocol = proto_version;
Christian Heimesc7f70692019-05-31 11:44:05 +02003064 self->msg_cb = NULL;
Christian Heimesc7f70692019-05-31 11:44:05 +02003065 self->keylog_filename = NULL;
3066 self->keylog_bio = NULL;
Benjamin Petersoncca27322015-01-23 16:35:37 -05003067 self->alpn_protocols = NULL;
Christian Heimes11a14932018-02-24 02:35:08 +01003068 self->set_sni_cb = NULL;
Christian Heimes7f1305e2021-04-17 20:06:38 +02003069 self->state = get_ssl_state(module);
3070
Christian Heimes1aa9a752013-12-02 02:41:19 +01003071 /* Don't check host name by default */
Christian Heimes5fe668c2016-09-12 00:01:11 +02003072 if (proto_version == PY_SSL_VERSION_TLS_CLIENT) {
3073 self->check_hostname = 1;
Christian Heimes9fb051f2018-09-23 08:32:31 +02003074 if (_set_verify_mode(self, PY_SSL_CERT_REQUIRED) == -1) {
Christian Heimes5fe668c2016-09-12 00:01:11 +02003075 Py_DECREF(self);
3076 return NULL;
3077 }
3078 } else {
3079 self->check_hostname = 0;
Christian Heimes9fb051f2018-09-23 08:32:31 +02003080 if (_set_verify_mode(self, PY_SSL_CERT_NONE) == -1) {
Christian Heimes5fe668c2016-09-12 00:01:11 +02003081 Py_DECREF(self);
3082 return NULL;
3083 }
3084 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003085 /* Defaults */
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01003086 options = SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
3087 if (proto_version != PY_SSL_VERSION_SSL2)
3088 options |= SSL_OP_NO_SSLv2;
Benjamin Petersona9dcdab2015-11-11 22:38:41 -08003089 if (proto_version != PY_SSL_VERSION_SSL3)
3090 options |= SSL_OP_NO_SSLv3;
Christian Heimes358cfd42016-09-10 22:43:48 +02003091 /* Minimal security flags for server and client side context.
3092 * Client sockets ignore server-side parameters. */
3093#ifdef SSL_OP_NO_COMPRESSION
3094 options |= SSL_OP_NO_COMPRESSION;
3095#endif
3096#ifdef SSL_OP_CIPHER_SERVER_PREFERENCE
3097 options |= SSL_OP_CIPHER_SERVER_PREFERENCE;
3098#endif
3099#ifdef SSL_OP_SINGLE_DH_USE
3100 options |= SSL_OP_SINGLE_DH_USE;
3101#endif
3102#ifdef SSL_OP_SINGLE_ECDH_USE
3103 options |= SSL_OP_SINGLE_ECDH_USE;
3104#endif
Christian Heimes6f37ebc2021-04-09 17:59:21 +02003105#ifdef SSL_OP_IGNORE_UNEXPECTED_EOF
3106 /* Make OpenSSL 3.0.0 behave like 1.1.1 */
3107 options |= SSL_OP_IGNORE_UNEXPECTED_EOF;
3108#endif
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01003109 SSL_CTX_set_options(self->ctx, options);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003110
Semen Zhydenko1295e112017-10-15 21:28:31 +02003111 /* A bare minimum cipher list without completely broken cipher suites.
Christian Heimes358cfd42016-09-10 22:43:48 +02003112 * It's far from perfect but gives users a better head start. */
3113 if (proto_version != PY_SSL_VERSION_SSL2) {
Christian Heimes892d66e2018-01-29 14:10:18 +01003114#if PY_SSL_DEFAULT_CIPHERS == 2
3115 /* stick to OpenSSL's default settings */
3116 result = 1;
3117#else
3118 result = SSL_CTX_set_cipher_list(ctx, PY_SSL_DEFAULT_CIPHER_STRING);
3119#endif
Christian Heimes358cfd42016-09-10 22:43:48 +02003120 } else {
3121 /* SSLv2 needs MD5 */
3122 result = SSL_CTX_set_cipher_list(ctx, "HIGH:!aNULL:!eNULL");
3123 }
3124 if (result == 0) {
3125 Py_DECREF(self);
3126 ERR_clear_error();
Christian Heimes7f1305e2021-04-17 20:06:38 +02003127 PyErr_SetString(get_state_ctx(self)->PySSLErrorObject,
Christian Heimes358cfd42016-09-10 22:43:48 +02003128 "No cipher can be selected.");
Christian Heimese9832522021-05-01 20:53:10 +02003129 goto error;
Christian Heimes358cfd42016-09-10 22:43:48 +02003130 }
Christian Heimese9832522021-05-01 20:53:10 +02003131#ifdef PY_SSL_MIN_PROTOCOL
3132 switch(proto_version) {
3133 case PY_SSL_VERSION_TLS:
3134 case PY_SSL_VERSION_TLS_CLIENT:
3135 case PY_SSL_VERSION_TLS_SERVER:
3136 result = SSL_CTX_set_min_proto_version(ctx, PY_SSL_MIN_PROTOCOL);
3137 if (result == 0) {
3138 PyErr_Format(PyExc_ValueError,
3139 "Failed to set minimum protocol 0x%x",
3140 PY_SSL_MIN_PROTOCOL);
3141 goto error;
3142 }
3143 break;
3144 default:
3145 break;
3146 }
3147#endif
Christian Heimes358cfd42016-09-10 22:43:48 +02003148
Benjamin Peterson3b1a8b32016-01-07 21:37:37 -08003149 /* Set SSL_MODE_RELEASE_BUFFERS. This potentially greatly reduces memory
Christian Heimes39258d32021-04-17 11:36:35 +02003150 usage for no cost at all. */
3151 SSL_CTX_set_mode(self->ctx, SSL_MODE_RELEASE_BUFFERS);
Antoine Pitrou0bebbc32014-03-22 18:13:50 +01003152
Antoine Pitroufc113ee2010-10-13 12:46:13 +00003153#define SID_CTX "Python"
3154 SSL_CTX_set_session_id_context(self->ctx, (const unsigned char *) SID_CTX,
3155 sizeof(SID_CTX));
3156#undef SID_CTX
3157
Christian Heimes61d478c2018-01-27 15:51:38 +01003158 params = SSL_CTX_get0_param(self->ctx);
Christian Heimes61d478c2018-01-27 15:51:38 +01003159 /* Improve trust chain building when cross-signed intermediate
3160 certificates are present. See https://bugs.python.org/issue23476. */
3161 X509_VERIFY_PARAM_set_flags(params, X509_V_FLAG_TRUSTED_FIRST);
Christian Heimes61d478c2018-01-27 15:51:38 +01003162 X509_VERIFY_PARAM_set_hostflags(params, self->hostflags);
Benjamin Petersonfdb19712015-03-04 22:11:12 -05003163
Christian Heimes9fb051f2018-09-23 08:32:31 +02003164#ifdef TLS1_3_VERSION
3165 self->post_handshake_auth = 0;
3166 SSL_CTX_set_post_handshake_auth(self->ctx, self->post_handshake_auth);
3167#endif
3168
Antoine Pitrou152efa22010-05-16 18:19:27 +00003169 return (PyObject *)self;
Christian Heimese9832522021-05-01 20:53:10 +02003170 error:
3171 Py_XDECREF(self);
3172 ERR_clear_error();
3173 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003174}
3175
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003176static int
3177context_traverse(PySSLContext *self, visitproc visit, void *arg)
3178{
Christian Heimes11a14932018-02-24 02:35:08 +01003179 Py_VISIT(self->set_sni_cb);
Christian Heimesc7f70692019-05-31 11:44:05 +02003180 Py_VISIT(self->msg_cb);
Miss Islington (bot)ea47a8a2021-05-27 09:25:22 -07003181 Py_VISIT(Py_TYPE(self));
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003182 return 0;
3183}
3184
3185static int
3186context_clear(PySSLContext *self)
3187{
Christian Heimes11a14932018-02-24 02:35:08 +01003188 Py_CLEAR(self->set_sni_cb);
Christian Heimesc7f70692019-05-31 11:44:05 +02003189 Py_CLEAR(self->msg_cb);
Christian Heimesc7f70692019-05-31 11:44:05 +02003190 Py_CLEAR(self->keylog_filename);
3191 if (self->keylog_bio != NULL) {
3192 PySSL_BEGIN_ALLOW_THREADS
3193 BIO_free_all(self->keylog_bio);
3194 PySSL_END_ALLOW_THREADS
3195 self->keylog_bio = NULL;
3196 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003197 return 0;
3198}
3199
Antoine Pitrou152efa22010-05-16 18:19:27 +00003200static void
3201context_dealloc(PySSLContext *self)
3202{
Christian Heimes5c36da72020-11-20 09:40:12 +01003203 PyTypeObject *tp = Py_TYPE(self);
INADA Naokia6296d32017-08-24 14:55:17 +09003204 /* bpo-31095: UnTrack is needed before calling any callbacks */
3205 PyObject_GC_UnTrack(self);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003206 context_clear(self);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003207 SSL_CTX_free(self->ctx);
Christian Heimes39258d32021-04-17 11:36:35 +02003208 PyMem_FREE(self->alpn_protocols);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003209 Py_TYPE(self)->tp_free(self);
Christian Heimes5c36da72020-11-20 09:40:12 +01003210 Py_DECREF(tp);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003211}
3212
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003213/*[clinic input]
3214_ssl._SSLContext.set_ciphers
3215 cipherlist: str
3216 /
3217[clinic start generated code]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003218
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003219static PyObject *
3220_ssl__SSLContext_set_ciphers_impl(PySSLContext *self, const char *cipherlist)
3221/*[clinic end generated code: output=3a3162f3557c0f3f input=a7ac931b9f3ca7fc]*/
3222{
3223 int ret = SSL_CTX_set_cipher_list(self->ctx, cipherlist);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003224 if (ret == 0) {
Antoine Pitrou65ec8ae2010-05-16 19:56:32 +00003225 /* Clearing the error queue is necessary on some OpenSSL versions,
3226 otherwise the error will be reported again when another SSL call
3227 is done. */
3228 ERR_clear_error();
Christian Heimes7f1305e2021-04-17 20:06:38 +02003229 PyErr_SetString(get_state_ctx(self)->PySSLErrorObject,
Antoine Pitrou152efa22010-05-16 18:19:27 +00003230 "No cipher can be selected.");
3231 return NULL;
3232 }
3233 Py_RETURN_NONE;
3234}
3235
Christian Heimes25bfcd52016-09-06 00:04:45 +02003236/*[clinic input]
3237_ssl._SSLContext.get_ciphers
3238[clinic start generated code]*/
3239
3240static PyObject *
3241_ssl__SSLContext_get_ciphers_impl(PySSLContext *self)
3242/*[clinic end generated code: output=a56e4d68a406dfc4 input=a2aadc9af89b79c5]*/
3243{
3244 SSL *ssl = NULL;
3245 STACK_OF(SSL_CIPHER) *sk = NULL;
Christian Heimes99a65702016-09-10 23:44:53 +02003246 const SSL_CIPHER *cipher;
Christian Heimes25bfcd52016-09-06 00:04:45 +02003247 int i=0;
3248 PyObject *result = NULL, *dct;
3249
3250 ssl = SSL_new(self->ctx);
3251 if (ssl == NULL) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02003252 _setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
Christian Heimes25bfcd52016-09-06 00:04:45 +02003253 goto exit;
3254 }
3255 sk = SSL_get_ciphers(ssl);
3256
3257 result = PyList_New(sk_SSL_CIPHER_num(sk));
3258 if (result == NULL) {
3259 goto exit;
3260 }
3261
3262 for (i = 0; i < sk_SSL_CIPHER_num(sk); i++) {
3263 cipher = sk_SSL_CIPHER_value(sk, i);
3264 dct = cipher_to_dict(cipher);
3265 if (dct == NULL) {
3266 Py_CLEAR(result);
3267 goto exit;
3268 }
3269 PyList_SET_ITEM(result, i, dct);
3270 }
3271
3272 exit:
3273 if (ssl != NULL)
3274 SSL_free(ssl);
3275 return result;
3276
3277}
Christian Heimes25bfcd52016-09-06 00:04:45 +02003278
3279
Benjamin Petersoncca27322015-01-23 16:35:37 -05003280static int
Benjamin Peterson88615022015-01-23 17:30:26 -05003281do_protocol_selection(int alpn, unsigned char **out, unsigned char *outlen,
3282 const unsigned char *server_protocols, unsigned int server_protocols_len,
3283 const unsigned char *client_protocols, unsigned int client_protocols_len)
Benjamin Petersoncca27322015-01-23 16:35:37 -05003284{
Benjamin Peterson88615022015-01-23 17:30:26 -05003285 int ret;
3286 if (client_protocols == NULL) {
3287 client_protocols = (unsigned char *)"";
3288 client_protocols_len = 0;
3289 }
3290 if (server_protocols == NULL) {
3291 server_protocols = (unsigned char *)"";
3292 server_protocols_len = 0;
Benjamin Petersoncca27322015-01-23 16:35:37 -05003293 }
3294
Benjamin Peterson88615022015-01-23 17:30:26 -05003295 ret = SSL_select_next_proto(out, outlen,
3296 server_protocols, server_protocols_len,
3297 client_protocols, client_protocols_len);
3298 if (alpn && ret != OPENSSL_NPN_NEGOTIATED)
3299 return SSL_TLSEXT_ERR_NOACK;
Benjamin Petersoncca27322015-01-23 16:35:37 -05003300
3301 return SSL_TLSEXT_ERR_OK;
3302}
3303
Benjamin Petersoncca27322015-01-23 16:35:37 -05003304static int
3305_selectALPN_cb(SSL *s,
3306 const unsigned char **out, unsigned char *outlen,
3307 const unsigned char *client_protocols, unsigned int client_protocols_len,
3308 void *args)
3309{
3310 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Peterson88615022015-01-23 17:30:26 -05003311 return do_protocol_selection(1, (unsigned char **)out, outlen,
3312 ctx->alpn_protocols, ctx->alpn_protocols_len,
3313 client_protocols, client_protocols_len);
Benjamin Petersoncca27322015-01-23 16:35:37 -05003314}
Benjamin Petersoncca27322015-01-23 16:35:37 -05003315
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003316/*[clinic input]
3317_ssl._SSLContext._set_alpn_protocols
3318 protos: Py_buffer
3319 /
3320[clinic start generated code]*/
3321
Benjamin Petersoncca27322015-01-23 16:35:37 -05003322static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003323_ssl__SSLContext__set_alpn_protocols_impl(PySSLContext *self,
3324 Py_buffer *protos)
3325/*[clinic end generated code: output=87599a7f76651a9b input=9bba964595d519be]*/
Benjamin Petersoncca27322015-01-23 16:35:37 -05003326{
Victor Stinner5a615592017-09-14 01:10:30 -07003327 if ((size_t)protos->len > UINT_MAX) {
Segev Finer5cff6372017-07-27 01:19:17 +03003328 PyErr_Format(PyExc_OverflowError,
Serhiy Storchakad53fe5f2019-03-13 22:59:55 +02003329 "protocols longer than %u bytes", UINT_MAX);
Segev Finer5cff6372017-07-27 01:19:17 +03003330 return NULL;
3331 }
3332
Victor Stinner00d7abd2020-12-01 09:56:42 +01003333 PyMem_Free(self->alpn_protocols);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003334 self->alpn_protocols = PyMem_Malloc(protos->len);
Benjamin Petersoncca27322015-01-23 16:35:37 -05003335 if (!self->alpn_protocols)
3336 return PyErr_NoMemory();
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003337 memcpy(self->alpn_protocols, protos->buf, protos->len);
Segev Finer5cff6372017-07-27 01:19:17 +03003338 self->alpn_protocols_len = (unsigned int)protos->len;
Benjamin Petersoncca27322015-01-23 16:35:37 -05003339
3340 if (SSL_CTX_set_alpn_protos(self->ctx, self->alpn_protocols, self->alpn_protocols_len))
3341 return PyErr_NoMemory();
3342 SSL_CTX_set_alpn_select_cb(self->ctx, _selectALPN_cb, self);
3343
Benjamin Petersoncca27322015-01-23 16:35:37 -05003344 Py_RETURN_NONE;
Benjamin Petersoncca27322015-01-23 16:35:37 -05003345}
3346
Antoine Pitrou152efa22010-05-16 18:19:27 +00003347static PyObject *
3348get_verify_mode(PySSLContext *self, void *c)
3349{
Christian Heimes9fb051f2018-09-23 08:32:31 +02003350 /* ignore SSL_VERIFY_CLIENT_ONCE and SSL_VERIFY_POST_HANDSHAKE */
3351 int mask = (SSL_VERIFY_NONE | SSL_VERIFY_PEER |
3352 SSL_VERIFY_FAIL_IF_NO_PEER_CERT);
3353 switch (SSL_CTX_get_verify_mode(self->ctx) & mask) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003354 case SSL_VERIFY_NONE:
3355 return PyLong_FromLong(PY_SSL_CERT_NONE);
3356 case SSL_VERIFY_PEER:
3357 return PyLong_FromLong(PY_SSL_CERT_OPTIONAL);
3358 case SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT:
3359 return PyLong_FromLong(PY_SSL_CERT_REQUIRED);
3360 }
Christian Heimes7f1305e2021-04-17 20:06:38 +02003361 PyErr_SetString(get_state_ctx(self)->PySSLErrorObject,
Antoine Pitrou152efa22010-05-16 18:19:27 +00003362 "invalid return value from SSL_CTX_get_verify_mode");
3363 return NULL;
3364}
3365
3366static int
3367set_verify_mode(PySSLContext *self, PyObject *arg, void *c)
3368{
Christian Heimes5fe668c2016-09-12 00:01:11 +02003369 int n;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003370 if (!PyArg_Parse(arg, "i", &n))
3371 return -1;
Christian Heimes5fe668c2016-09-12 00:01:11 +02003372 if (n == PY_SSL_CERT_NONE && self->check_hostname) {
Christian Heimes1aa9a752013-12-02 02:41:19 +01003373 PyErr_SetString(PyExc_ValueError,
3374 "Cannot set verify_mode to CERT_NONE when "
3375 "check_hostname is enabled.");
3376 return -1;
3377 }
Christian Heimes9fb051f2018-09-23 08:32:31 +02003378 return _set_verify_mode(self, n);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003379}
3380
3381static PyObject *
Christian Heimes22587792013-11-21 23:56:13 +01003382get_verify_flags(PySSLContext *self, void *c)
3383{
Christian Heimes598894f2016-09-05 23:19:05 +02003384 X509_VERIFY_PARAM *param;
Christian Heimes22587792013-11-21 23:56:13 +01003385 unsigned long flags;
3386
Christian Heimes61d478c2018-01-27 15:51:38 +01003387 param = SSL_CTX_get0_param(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02003388 flags = X509_VERIFY_PARAM_get_flags(param);
Christian Heimes22587792013-11-21 23:56:13 +01003389 return PyLong_FromUnsignedLong(flags);
3390}
3391
3392static int
3393set_verify_flags(PySSLContext *self, PyObject *arg, void *c)
3394{
Christian Heimes598894f2016-09-05 23:19:05 +02003395 X509_VERIFY_PARAM *param;
Christian Heimes22587792013-11-21 23:56:13 +01003396 unsigned long new_flags, flags, set, clear;
3397
3398 if (!PyArg_Parse(arg, "k", &new_flags))
3399 return -1;
Christian Heimes61d478c2018-01-27 15:51:38 +01003400 param = SSL_CTX_get0_param(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02003401 flags = X509_VERIFY_PARAM_get_flags(param);
Christian Heimes22587792013-11-21 23:56:13 +01003402 clear = flags & ~new_flags;
3403 set = ~flags & new_flags;
3404 if (clear) {
Christian Heimes598894f2016-09-05 23:19:05 +02003405 if (!X509_VERIFY_PARAM_clear_flags(param, clear)) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02003406 _setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
Christian Heimes22587792013-11-21 23:56:13 +01003407 return -1;
3408 }
3409 }
3410 if (set) {
Christian Heimes598894f2016-09-05 23:19:05 +02003411 if (!X509_VERIFY_PARAM_set_flags(param, set)) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02003412 _setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
Christian Heimes22587792013-11-21 23:56:13 +01003413 return -1;
3414 }
3415 }
3416 return 0;
3417}
3418
Christian Heimes698dde12018-02-27 11:54:43 +01003419/* Getter and setter for protocol version */
Christian Heimes698dde12018-02-27 11:54:43 +01003420static int
3421set_min_max_proto_version(PySSLContext *self, PyObject *arg, int what)
3422{
3423 long v;
3424 int result;
3425
3426 if (!PyArg_Parse(arg, "l", &v))
3427 return -1;
3428 if (v > INT_MAX) {
3429 PyErr_SetString(PyExc_OverflowError, "Option is too long");
3430 return -1;
3431 }
3432
3433 switch(self->protocol) {
3434 case PY_SSL_VERSION_TLS_CLIENT: /* fall through */
3435 case PY_SSL_VERSION_TLS_SERVER: /* fall through */
3436 case PY_SSL_VERSION_TLS:
3437 break;
3438 default:
3439 PyErr_SetString(
3440 PyExc_ValueError,
3441 "The context's protocol doesn't support modification of "
3442 "highest and lowest version."
3443 );
3444 return -1;
3445 }
3446
Christian Heimes2875c602021-04-19 07:27:10 +02003447 /* check for deprecations and supported values */
3448 switch(v) {
3449 case PY_PROTO_SSLv3:
Miss Islington (bot)d7930fb2021-06-11 00:36:17 -07003450 PY_SSL_DEPRECATED("ssl.TLSVersion.SSLv3 is deprecated", 2, -1);
Christian Heimes2875c602021-04-19 07:27:10 +02003451 break;
3452 case PY_PROTO_TLSv1:
Miss Islington (bot)d7930fb2021-06-11 00:36:17 -07003453 PY_SSL_DEPRECATED("ssl.TLSVersion.TLSv1 is deprecated", 2, -1);
Christian Heimes2875c602021-04-19 07:27:10 +02003454 break;
3455 case PY_PROTO_TLSv1_1:
Miss Islington (bot)d7930fb2021-06-11 00:36:17 -07003456 PY_SSL_DEPRECATED("ssl.TLSVersion.TLSv1_1 is deprecated", 2, -1);
Christian Heimes2875c602021-04-19 07:27:10 +02003457 break;
3458 case PY_PROTO_MINIMUM_SUPPORTED:
3459 case PY_PROTO_MAXIMUM_SUPPORTED:
3460 case PY_PROTO_TLSv1_2:
3461 case PY_PROTO_TLSv1_3:
3462 /* ok */
3463 break;
3464 default:
3465 PyErr_Format(PyExc_ValueError,
3466 "Unsupported TLS/SSL version 0x%x", v);
3467 return -1;
3468 }
3469
Christian Heimes698dde12018-02-27 11:54:43 +01003470 if (what == 0) {
3471 switch(v) {
3472 case PY_PROTO_MINIMUM_SUPPORTED:
3473 v = 0;
3474 break;
3475 case PY_PROTO_MAXIMUM_SUPPORTED:
3476 /* Emulate max for set_min_proto_version */
3477 v = PY_PROTO_MAXIMUM_AVAILABLE;
3478 break;
3479 default:
3480 break;
3481 }
3482 result = SSL_CTX_set_min_proto_version(self->ctx, v);
3483 }
3484 else {
3485 switch(v) {
3486 case PY_PROTO_MAXIMUM_SUPPORTED:
3487 v = 0;
3488 break;
3489 case PY_PROTO_MINIMUM_SUPPORTED:
3490 /* Emulate max for set_min_proto_version */
3491 v = PY_PROTO_MINIMUM_AVAILABLE;
3492 break;
3493 default:
3494 break;
3495 }
3496 result = SSL_CTX_set_max_proto_version(self->ctx, v);
3497 }
3498 if (result == 0) {
3499 PyErr_Format(PyExc_ValueError,
3500 "Unsupported protocol version 0x%x", v);
3501 return -1;
3502 }
3503 return 0;
3504}
3505
3506static PyObject *
3507get_minimum_version(PySSLContext *self, void *c)
3508{
3509 int v = SSL_CTX_ctrl(self->ctx, SSL_CTRL_GET_MIN_PROTO_VERSION, 0, NULL);
3510 if (v == 0) {
3511 v = PY_PROTO_MINIMUM_SUPPORTED;
3512 }
3513 return PyLong_FromLong(v);
3514}
3515
3516static int
3517set_minimum_version(PySSLContext *self, PyObject *arg, void *c)
3518{
3519 return set_min_max_proto_version(self, arg, 0);
3520}
3521
3522static PyObject *
3523get_maximum_version(PySSLContext *self, void *c)
3524{
3525 int v = SSL_CTX_ctrl(self->ctx, SSL_CTRL_GET_MAX_PROTO_VERSION, 0, NULL);
3526 if (v == 0) {
3527 v = PY_PROTO_MAXIMUM_SUPPORTED;
3528 }
3529 return PyLong_FromLong(v);
3530}
3531
3532static int
3533set_maximum_version(PySSLContext *self, PyObject *arg, void *c)
3534{
3535 return set_min_max_proto_version(self, arg, 1);
3536}
Christian Heimes698dde12018-02-27 11:54:43 +01003537
Christian Heimes39258d32021-04-17 11:36:35 +02003538#ifdef TLS1_3_VERSION
Christian Heimes78c7d522019-06-03 21:00:10 +02003539static PyObject *
3540get_num_tickets(PySSLContext *self, void *c)
3541{
Victor Stinner76611c72019-07-09 13:30:52 +02003542 return PyLong_FromSize_t(SSL_CTX_get_num_tickets(self->ctx));
Christian Heimes78c7d522019-06-03 21:00:10 +02003543}
3544
3545static int
3546set_num_tickets(PySSLContext *self, PyObject *arg, void *c)
3547{
3548 long num;
3549 if (!PyArg_Parse(arg, "l", &num))
3550 return -1;
3551 if (num < 0) {
3552 PyErr_SetString(PyExc_ValueError, "value must be non-negative");
3553 return -1;
3554 }
3555 if (self->protocol != PY_SSL_VERSION_TLS_SERVER) {
3556 PyErr_SetString(PyExc_ValueError,
3557 "SSLContext is not a server context.");
3558 return -1;
3559 }
3560 if (SSL_CTX_set_num_tickets(self->ctx, num) != 1) {
3561 PyErr_SetString(PyExc_ValueError, "failed to set num tickets.");
3562 return -1;
3563 }
3564 return 0;
3565}
3566
3567PyDoc_STRVAR(PySSLContext_num_tickets_doc,
3568"Control the number of TLSv1.3 session tickets");
Christian Heimes39258d32021-04-17 11:36:35 +02003569#endif /* TLS1_3_VERSION */
Christian Heimes78c7d522019-06-03 21:00:10 +02003570
matthewhughes9348e836bb2020-07-17 09:59:15 +01003571static PyObject *
3572get_security_level(PySSLContext *self, void *c)
3573{
3574 return PyLong_FromLong(SSL_CTX_get_security_level(self->ctx));
3575}
3576PyDoc_STRVAR(PySSLContext_security_level_doc, "The current security level");
matthewhughes9348e836bb2020-07-17 09:59:15 +01003577
Christian Heimes22587792013-11-21 23:56:13 +01003578static PyObject *
Antoine Pitroub5218772010-05-21 09:56:06 +00003579get_options(PySSLContext *self, void *c)
3580{
3581 return PyLong_FromLong(SSL_CTX_get_options(self->ctx));
3582}
3583
3584static int
3585set_options(PySSLContext *self, PyObject *arg, void *c)
3586{
3587 long new_opts, opts, set, clear;
Christian Heimes2875c602021-04-19 07:27:10 +02003588 long opt_no = (
3589 SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1 |
3590 SSL_OP_NO_TLSv1_1 | SSL_OP_NO_TLSv1_2 | SSL_OP_NO_TLSv1_2
3591 );
3592
Antoine Pitroub5218772010-05-21 09:56:06 +00003593 if (!PyArg_Parse(arg, "l", &new_opts))
3594 return -1;
3595 opts = SSL_CTX_get_options(self->ctx);
3596 clear = opts & ~new_opts;
3597 set = ~opts & new_opts;
Christian Heimes2875c602021-04-19 07:27:10 +02003598
3599 if ((set & opt_no) != 0) {
Miss Islington (bot)d7930fb2021-06-11 00:36:17 -07003600 if (_ssl_deprecated("ssl.OP_NO_SSL*/ssl.SSL_NO_TLS* options are "
Christian Heimes2875c602021-04-19 07:27:10 +02003601 "deprecated", 2) < 0) {
3602 return -1;
3603 }
3604 }
Antoine Pitroub5218772010-05-21 09:56:06 +00003605 if (clear) {
Antoine Pitroub5218772010-05-21 09:56:06 +00003606 SSL_CTX_clear_options(self->ctx, clear);
Antoine Pitroub5218772010-05-21 09:56:06 +00003607 }
3608 if (set)
3609 SSL_CTX_set_options(self->ctx, set);
3610 return 0;
3611}
3612
Christian Heimes1aa9a752013-12-02 02:41:19 +01003613static PyObject *
Christian Heimes61d478c2018-01-27 15:51:38 +01003614get_host_flags(PySSLContext *self, void *c)
3615{
3616 return PyLong_FromUnsignedLong(self->hostflags);
3617}
3618
3619static int
3620set_host_flags(PySSLContext *self, PyObject *arg, void *c)
3621{
3622 X509_VERIFY_PARAM *param;
3623 unsigned int new_flags = 0;
3624
3625 if (!PyArg_Parse(arg, "I", &new_flags))
3626 return -1;
3627
3628 param = SSL_CTX_get0_param(self->ctx);
3629 self->hostflags = new_flags;
3630 X509_VERIFY_PARAM_set_hostflags(param, new_flags);
3631 return 0;
3632}
3633
3634static PyObject *
Christian Heimes1aa9a752013-12-02 02:41:19 +01003635get_check_hostname(PySSLContext *self, void *c)
3636{
3637 return PyBool_FromLong(self->check_hostname);
3638}
3639
3640static int
3641set_check_hostname(PySSLContext *self, PyObject *arg, void *c)
3642{
3643 int check_hostname;
3644 if (!PyArg_Parse(arg, "p", &check_hostname))
3645 return -1;
3646 if (check_hostname &&
3647 SSL_CTX_get_verify_mode(self->ctx) == SSL_VERIFY_NONE) {
Christian Heimese82c0342017-09-15 20:29:57 +02003648 /* check_hostname = True sets verify_mode = CERT_REQUIRED */
Christian Heimes9fb051f2018-09-23 08:32:31 +02003649 if (_set_verify_mode(self, PY_SSL_CERT_REQUIRED) == -1) {
Christian Heimese82c0342017-09-15 20:29:57 +02003650 return -1;
3651 }
Christian Heimes1aa9a752013-12-02 02:41:19 +01003652 }
3653 self->check_hostname = check_hostname;
3654 return 0;
3655}
3656
Christian Heimes11a14932018-02-24 02:35:08 +01003657static PyObject *
Christian Heimes9fb051f2018-09-23 08:32:31 +02003658get_post_handshake_auth(PySSLContext *self, void *c) {
3659#if TLS1_3_VERSION
3660 return PyBool_FromLong(self->post_handshake_auth);
3661#else
3662 Py_RETURN_NONE;
3663#endif
3664}
3665
3666#if TLS1_3_VERSION
3667static int
3668set_post_handshake_auth(PySSLContext *self, PyObject *arg, void *c) {
Zackery Spytz842acaa2018-12-17 07:52:45 -07003669 if (arg == NULL) {
3670 PyErr_SetString(PyExc_AttributeError, "cannot delete attribute");
3671 return -1;
3672 }
Christian Heimes9fb051f2018-09-23 08:32:31 +02003673 int pha = PyObject_IsTrue(arg);
3674
3675 if (pha == -1) {
3676 return -1;
3677 }
3678 self->post_handshake_auth = pha;
3679
Christian Heimesf0f59302019-07-01 08:29:17 +02003680 /* bpo-37428: newPySSLSocket() sets SSL_VERIFY_POST_HANDSHAKE flag for
3681 * server sockets and SSL_set_post_handshake_auth() for client. */
Christian Heimes9fb051f2018-09-23 08:32:31 +02003682
3683 return 0;
3684}
3685#endif
3686
3687static PyObject *
Christian Heimes11a14932018-02-24 02:35:08 +01003688get_protocol(PySSLContext *self, void *c) {
3689 return PyLong_FromLong(self->protocol);
3690}
Christian Heimes1aa9a752013-12-02 02:41:19 +01003691
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003692typedef struct {
3693 PyThreadState *thread_state;
3694 PyObject *callable;
3695 char *password;
Victor Stinner9ee02032013-06-23 15:08:23 +02003696 int size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003697 int error;
3698} _PySSLPasswordInfo;
3699
3700static int
3701_pwinfo_set(_PySSLPasswordInfo *pw_info, PyObject* password,
3702 const char *bad_type_error)
3703{
3704 /* Set the password and size fields of a _PySSLPasswordInfo struct
3705 from a unicode, bytes, or byte array object.
3706 The password field will be dynamically allocated and must be freed
3707 by the caller */
3708 PyObject *password_bytes = NULL;
3709 const char *data = NULL;
3710 Py_ssize_t size;
3711
3712 if (PyUnicode_Check(password)) {
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03003713 password_bytes = PyUnicode_AsUTF8String(password);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003714 if (!password_bytes) {
3715 goto error;
3716 }
3717 data = PyBytes_AS_STRING(password_bytes);
3718 size = PyBytes_GET_SIZE(password_bytes);
3719 } else if (PyBytes_Check(password)) {
3720 data = PyBytes_AS_STRING(password);
3721 size = PyBytes_GET_SIZE(password);
3722 } else if (PyByteArray_Check(password)) {
3723 data = PyByteArray_AS_STRING(password);
3724 size = PyByteArray_GET_SIZE(password);
3725 } else {
3726 PyErr_SetString(PyExc_TypeError, bad_type_error);
3727 goto error;
3728 }
3729
Victor Stinner9ee02032013-06-23 15:08:23 +02003730 if (size > (Py_ssize_t)INT_MAX) {
3731 PyErr_Format(PyExc_ValueError,
3732 "password cannot be longer than %d bytes", INT_MAX);
3733 goto error;
3734 }
3735
Victor Stinner11ebff22013-07-07 17:07:52 +02003736 PyMem_Free(pw_info->password);
3737 pw_info->password = PyMem_Malloc(size);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003738 if (!pw_info->password) {
3739 PyErr_SetString(PyExc_MemoryError,
3740 "unable to allocate password buffer");
3741 goto error;
3742 }
3743 memcpy(pw_info->password, data, size);
Victor Stinner9ee02032013-06-23 15:08:23 +02003744 pw_info->size = (int)size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003745
3746 Py_XDECREF(password_bytes);
3747 return 1;
3748
3749error:
3750 Py_XDECREF(password_bytes);
3751 return 0;
3752}
3753
3754static int
3755_password_callback(char *buf, int size, int rwflag, void *userdata)
3756{
3757 _PySSLPasswordInfo *pw_info = (_PySSLPasswordInfo*) userdata;
3758 PyObject *fn_ret = NULL;
3759
3760 PySSL_END_ALLOW_THREADS_S(pw_info->thread_state);
3761
Christian Heimesd3b73f32021-04-09 15:23:38 +02003762 if (pw_info->error) {
3763 /* already failed previously. OpenSSL 3.0.0-alpha14 invokes the
3764 * callback multiple times which can lead to fatal Python error in
3765 * exception check. */
3766 goto error;
3767 }
3768
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003769 if (pw_info->callable) {
Victor Stinnerf17c3de2016-12-06 18:46:19 +01003770 fn_ret = _PyObject_CallNoArg(pw_info->callable);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003771 if (!fn_ret) {
3772 /* TODO: It would be nice to move _ctypes_add_traceback() into the
3773 core python API, so we could use it to add a frame here */
3774 goto error;
3775 }
3776
3777 if (!_pwinfo_set(pw_info, fn_ret,
3778 "password callback must return a string")) {
3779 goto error;
3780 }
3781 Py_CLEAR(fn_ret);
3782 }
3783
3784 if (pw_info->size > size) {
3785 PyErr_Format(PyExc_ValueError,
3786 "password cannot be longer than %d bytes", size);
3787 goto error;
3788 }
3789
3790 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
3791 memcpy(buf, pw_info->password, pw_info->size);
3792 return pw_info->size;
3793
3794error:
3795 Py_XDECREF(fn_ret);
3796 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
3797 pw_info->error = 1;
3798 return -1;
3799}
3800
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003801/*[clinic input]
3802_ssl._SSLContext.load_cert_chain
3803 certfile: object
Serhiy Storchaka279f4462019-09-14 12:24:05 +03003804 keyfile: object = None
3805 password: object = None
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003806
3807[clinic start generated code]*/
3808
Antoine Pitroub5218772010-05-21 09:56:06 +00003809static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003810_ssl__SSLContext_load_cert_chain_impl(PySSLContext *self, PyObject *certfile,
3811 PyObject *keyfile, PyObject *password)
Serhiy Storchaka279f4462019-09-14 12:24:05 +03003812/*[clinic end generated code: output=9480bc1c380e2095 input=30bc7e967ea01a58]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003813{
Antoine Pitrou152efa22010-05-16 18:19:27 +00003814 PyObject *certfile_bytes = NULL, *keyfile_bytes = NULL;
Christian Heimes598894f2016-09-05 23:19:05 +02003815 pem_password_cb *orig_passwd_cb = SSL_CTX_get_default_passwd_cb(self->ctx);
3816 void *orig_passwd_userdata = SSL_CTX_get_default_passwd_cb_userdata(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003817 _PySSLPasswordInfo pw_info = { NULL, NULL, NULL, 0, 0 };
Antoine Pitrou152efa22010-05-16 18:19:27 +00003818 int r;
3819
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003820 errno = 0;
Antoine Pitrou67e8e562010-09-01 20:55:41 +00003821 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00003822 if (keyfile == Py_None)
3823 keyfile = NULL;
3824 if (!PyUnicode_FSConverter(certfile, &certfile_bytes)) {
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03003825 if (PyErr_ExceptionMatches(PyExc_TypeError)) {
3826 PyErr_SetString(PyExc_TypeError,
3827 "certfile should be a valid filesystem path");
3828 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003829 return NULL;
3830 }
3831 if (keyfile && !PyUnicode_FSConverter(keyfile, &keyfile_bytes)) {
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03003832 if (PyErr_ExceptionMatches(PyExc_TypeError)) {
3833 PyErr_SetString(PyExc_TypeError,
3834 "keyfile should be a valid filesystem path");
3835 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003836 goto error;
3837 }
Serhiy Storchaka279f4462019-09-14 12:24:05 +03003838 if (password != Py_None) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003839 if (PyCallable_Check(password)) {
3840 pw_info.callable = password;
3841 } else if (!_pwinfo_set(&pw_info, password,
3842 "password should be a string or callable")) {
3843 goto error;
3844 }
3845 SSL_CTX_set_default_passwd_cb(self->ctx, _password_callback);
3846 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, &pw_info);
3847 }
3848 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003849 r = SSL_CTX_use_certificate_chain_file(self->ctx,
3850 PyBytes_AS_STRING(certfile_bytes));
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003851 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003852 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003853 if (pw_info.error) {
3854 ERR_clear_error();
3855 /* the password callback has already set the error information */
3856 }
3857 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00003858 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03003859 PyErr_SetFromErrno(PyExc_OSError);
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003860 }
3861 else {
Christian Heimes7f1305e2021-04-17 20:06:38 +02003862 _setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003863 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003864 goto error;
3865 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003866 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou9c254862011-04-03 18:15:34 +02003867 r = SSL_CTX_use_PrivateKey_file(self->ctx,
Antoine Pitrou152efa22010-05-16 18:19:27 +00003868 PyBytes_AS_STRING(keyfile ? keyfile_bytes : certfile_bytes),
3869 SSL_FILETYPE_PEM);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003870 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
3871 Py_CLEAR(keyfile_bytes);
3872 Py_CLEAR(certfile_bytes);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003873 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003874 if (pw_info.error) {
3875 ERR_clear_error();
3876 /* the password callback has already set the error information */
3877 }
3878 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00003879 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03003880 PyErr_SetFromErrno(PyExc_OSError);
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003881 }
3882 else {
Christian Heimes7f1305e2021-04-17 20:06:38 +02003883 _setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003884 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003885 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003886 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003887 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003888 r = SSL_CTX_check_private_key(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003889 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003890 if (r != 1) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02003891 _setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003892 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003893 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003894 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
3895 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02003896 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003897 Py_RETURN_NONE;
3898
3899error:
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003900 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
3901 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02003902 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003903 Py_XDECREF(keyfile_bytes);
3904 Py_XDECREF(certfile_bytes);
3905 return NULL;
3906}
3907
Christian Heimesefff7062013-11-21 03:35:02 +01003908/* internal helper function, returns -1 on error
3909 */
3910static int
Serhiy Storchaka8f87eef2020-04-12 14:58:27 +03003911_add_ca_certs(PySSLContext *self, const void *data, Py_ssize_t len,
Christian Heimesefff7062013-11-21 03:35:02 +01003912 int filetype)
3913{
3914 BIO *biobuf = NULL;
3915 X509_STORE *store;
Christian Heimesb9ad88b2021-04-23 13:51:40 +02003916 int retval = -1, err, loaded = 0;
Christian Heimesefff7062013-11-21 03:35:02 +01003917
3918 assert(filetype == SSL_FILETYPE_ASN1 || filetype == SSL_FILETYPE_PEM);
3919
3920 if (len <= 0) {
3921 PyErr_SetString(PyExc_ValueError,
3922 "Empty certificate data");
3923 return -1;
3924 } else if (len > INT_MAX) {
3925 PyErr_SetString(PyExc_OverflowError,
3926 "Certificate data is too long.");
3927 return -1;
3928 }
3929
Christian Heimes1dbf61f2013-11-22 00:34:18 +01003930 biobuf = BIO_new_mem_buf(data, (int)len);
Christian Heimesefff7062013-11-21 03:35:02 +01003931 if (biobuf == NULL) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02003932 _setSSLError(get_state_ctx(self), "Can't allocate buffer", 0, __FILE__, __LINE__);
Christian Heimesefff7062013-11-21 03:35:02 +01003933 return -1;
3934 }
3935
3936 store = SSL_CTX_get_cert_store(self->ctx);
3937 assert(store != NULL);
3938
3939 while (1) {
3940 X509 *cert = NULL;
3941 int r;
3942
3943 if (filetype == SSL_FILETYPE_ASN1) {
3944 cert = d2i_X509_bio(biobuf, NULL);
3945 } else {
3946 cert = PEM_read_bio_X509(biobuf, NULL,
Christian Heimes598894f2016-09-05 23:19:05 +02003947 SSL_CTX_get_default_passwd_cb(self->ctx),
3948 SSL_CTX_get_default_passwd_cb_userdata(self->ctx)
3949 );
Christian Heimesefff7062013-11-21 03:35:02 +01003950 }
3951 if (cert == NULL) {
3952 break;
3953 }
3954 r = X509_STORE_add_cert(store, cert);
3955 X509_free(cert);
3956 if (!r) {
3957 err = ERR_peek_last_error();
3958 if ((ERR_GET_LIB(err) == ERR_LIB_X509) &&
3959 (ERR_GET_REASON(err) == X509_R_CERT_ALREADY_IN_HASH_TABLE)) {
3960 /* cert already in hash table, not an error */
3961 ERR_clear_error();
3962 } else {
3963 break;
3964 }
3965 }
3966 loaded++;
3967 }
3968
3969 err = ERR_peek_last_error();
Christian Heimesb9ad88b2021-04-23 13:51:40 +02003970 if (loaded == 0) {
3971 const char *msg = NULL;
3972 if (filetype == SSL_FILETYPE_PEM) {
3973 msg = "no start line: cadata does not contain a certificate";
3974 } else {
3975 msg = "not enough data: cadata does not contain a certificate";
3976 }
3977 _setSSLError(get_state_ctx(self), msg, 0, __FILE__, __LINE__);
3978 retval = -1;
3979 } else if ((filetype == SSL_FILETYPE_ASN1) &&
3980 (ERR_GET_LIB(err) == ERR_LIB_ASN1) &&
3981 (ERR_GET_REASON(err) == ASN1_R_HEADER_TOO_LONG)) {
Christian Heimesefff7062013-11-21 03:35:02 +01003982 /* EOF ASN1 file, not an error */
3983 ERR_clear_error();
3984 retval = 0;
3985 } else if ((filetype == SSL_FILETYPE_PEM) &&
Christian Heimesefff7062013-11-21 03:35:02 +01003986 (ERR_GET_LIB(err) == ERR_LIB_PEM) &&
3987 (ERR_GET_REASON(err) == PEM_R_NO_START_LINE)) {
3988 /* EOF PEM file, not an error */
3989 ERR_clear_error();
3990 retval = 0;
Christian Heimesb9ad88b2021-04-23 13:51:40 +02003991 } else if (err != 0) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02003992 _setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
Christian Heimesefff7062013-11-21 03:35:02 +01003993 retval = -1;
Christian Heimesb9ad88b2021-04-23 13:51:40 +02003994 } else {
3995 retval = 0;
Christian Heimesefff7062013-11-21 03:35:02 +01003996 }
3997
3998 BIO_free(biobuf);
3999 return retval;
4000}
4001
4002
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004003/*[clinic input]
4004_ssl._SSLContext.load_verify_locations
Serhiy Storchaka279f4462019-09-14 12:24:05 +03004005 cafile: object = None
4006 capath: object = None
4007 cadata: object = None
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004008
4009[clinic start generated code]*/
4010
Antoine Pitrou152efa22010-05-16 18:19:27 +00004011static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004012_ssl__SSLContext_load_verify_locations_impl(PySSLContext *self,
4013 PyObject *cafile,
4014 PyObject *capath,
4015 PyObject *cadata)
Serhiy Storchaka279f4462019-09-14 12:24:05 +03004016/*[clinic end generated code: output=454c7e41230ca551 input=42ecfe258233e194]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004017{
Antoine Pitrou152efa22010-05-16 18:19:27 +00004018 PyObject *cafile_bytes = NULL, *capath_bytes = NULL;
4019 const char *cafile_buf = NULL, *capath_buf = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01004020 int r = 0, ok = 1;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004021
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00004022 errno = 0;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004023 if (cafile == Py_None)
4024 cafile = NULL;
4025 if (capath == Py_None)
4026 capath = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01004027 if (cadata == Py_None)
4028 cadata = NULL;
4029
4030 if (cafile == NULL && capath == NULL && cadata == NULL) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00004031 PyErr_SetString(PyExc_TypeError,
Christian Heimesefff7062013-11-21 03:35:02 +01004032 "cafile, capath and cadata cannot be all omitted");
4033 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004034 }
4035 if (cafile && !PyUnicode_FSConverter(cafile, &cafile_bytes)) {
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03004036 if (PyErr_ExceptionMatches(PyExc_TypeError)) {
4037 PyErr_SetString(PyExc_TypeError,
4038 "cafile should be a valid filesystem path");
4039 }
Christian Heimesefff7062013-11-21 03:35:02 +01004040 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004041 }
4042 if (capath && !PyUnicode_FSConverter(capath, &capath_bytes)) {
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03004043 if (PyErr_ExceptionMatches(PyExc_TypeError)) {
4044 PyErr_SetString(PyExc_TypeError,
4045 "capath should be a valid filesystem path");
4046 }
Christian Heimesefff7062013-11-21 03:35:02 +01004047 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004048 }
Christian Heimesefff7062013-11-21 03:35:02 +01004049
4050 /* validata cadata type and load cadata */
4051 if (cadata) {
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03004052 if (PyUnicode_Check(cadata)) {
4053 PyObject *cadata_ascii = PyUnicode_AsASCIIString(cadata);
4054 if (cadata_ascii == NULL) {
4055 if (PyErr_ExceptionMatches(PyExc_UnicodeEncodeError)) {
4056 goto invalid_cadata;
4057 }
4058 goto error;
4059 }
4060 r = _add_ca_certs(self,
4061 PyBytes_AS_STRING(cadata_ascii),
4062 PyBytes_GET_SIZE(cadata_ascii),
4063 SSL_FILETYPE_PEM);
4064 Py_DECREF(cadata_ascii);
4065 if (r == -1) {
4066 goto error;
4067 }
4068 }
4069 else if (PyObject_CheckBuffer(cadata)) {
4070 Py_buffer buf;
4071 if (PyObject_GetBuffer(cadata, &buf, PyBUF_SIMPLE)) {
4072 goto error;
4073 }
Christian Heimesefff7062013-11-21 03:35:02 +01004074 if (!PyBuffer_IsContiguous(&buf, 'C') || buf.ndim > 1) {
4075 PyBuffer_Release(&buf);
4076 PyErr_SetString(PyExc_TypeError,
4077 "cadata should be a contiguous buffer with "
4078 "a single dimension");
4079 goto error;
4080 }
4081 r = _add_ca_certs(self, buf.buf, buf.len, SSL_FILETYPE_ASN1);
4082 PyBuffer_Release(&buf);
4083 if (r == -1) {
4084 goto error;
4085 }
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03004086 }
4087 else {
4088 invalid_cadata:
4089 PyErr_SetString(PyExc_TypeError,
4090 "cadata should be an ASCII string or a "
4091 "bytes-like object");
4092 goto error;
Christian Heimesefff7062013-11-21 03:35:02 +01004093 }
4094 }
4095
4096 /* load cafile or capath */
4097 if (cafile || capath) {
4098 if (cafile)
4099 cafile_buf = PyBytes_AS_STRING(cafile_bytes);
4100 if (capath)
4101 capath_buf = PyBytes_AS_STRING(capath_bytes);
4102 PySSL_BEGIN_ALLOW_THREADS
4103 r = SSL_CTX_load_verify_locations(self->ctx, cafile_buf, capath_buf);
4104 PySSL_END_ALLOW_THREADS
4105 if (r != 1) {
Christian Heimesefff7062013-11-21 03:35:02 +01004106 if (errno != 0) {
4107 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03004108 PyErr_SetFromErrno(PyExc_OSError);
Christian Heimesefff7062013-11-21 03:35:02 +01004109 }
4110 else {
Christian Heimes7f1305e2021-04-17 20:06:38 +02004111 _setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
Christian Heimesefff7062013-11-21 03:35:02 +01004112 }
4113 goto error;
4114 }
4115 }
4116 goto end;
4117
4118 error:
4119 ok = 0;
4120 end:
Antoine Pitrou152efa22010-05-16 18:19:27 +00004121 Py_XDECREF(cafile_bytes);
4122 Py_XDECREF(capath_bytes);
Christian Heimesefff7062013-11-21 03:35:02 +01004123 if (ok) {
4124 Py_RETURN_NONE;
4125 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00004126 return NULL;
4127 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00004128}
4129
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004130/*[clinic input]
4131_ssl._SSLContext.load_dh_params
4132 path as filepath: object
4133 /
4134
4135[clinic start generated code]*/
4136
Antoine Pitrou152efa22010-05-16 18:19:27 +00004137static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004138_ssl__SSLContext_load_dh_params(PySSLContext *self, PyObject *filepath)
4139/*[clinic end generated code: output=1c8e57a38e055af0 input=c8871f3c796ae1d6]*/
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004140{
4141 FILE *f;
4142 DH *dh;
4143
Victor Stinnerdaf45552013-08-28 00:53:59 +02004144 f = _Py_fopen_obj(filepath, "rb");
Victor Stinnere42ccd22015-03-18 01:39:23 +01004145 if (f == NULL)
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004146 return NULL;
Victor Stinnere42ccd22015-03-18 01:39:23 +01004147
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004148 errno = 0;
4149 PySSL_BEGIN_ALLOW_THREADS
4150 dh = PEM_read_DHparams(f, NULL, NULL, NULL);
Antoine Pitrou457a2292013-01-12 21:43:45 +01004151 fclose(f);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004152 PySSL_END_ALLOW_THREADS
4153 if (dh == NULL) {
4154 if (errno != 0) {
4155 ERR_clear_error();
4156 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
4157 }
4158 else {
Christian Heimes7f1305e2021-04-17 20:06:38 +02004159 _setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004160 }
4161 return NULL;
4162 }
Zackery Spytzaebc0492020-07-07 22:21:58 -06004163 if (!SSL_CTX_set_tmp_dh(self->ctx, dh)) {
4164 DH_free(dh);
Christian Heimes7f1305e2021-04-17 20:06:38 +02004165 return _setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
Zackery Spytzaebc0492020-07-07 22:21:58 -06004166 }
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004167 DH_free(dh);
4168 Py_RETURN_NONE;
4169}
4170
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004171/*[clinic input]
4172_ssl._SSLContext._wrap_socket
Christian Heimes7f1305e2021-04-17 20:06:38 +02004173 sock: object(subclass_of="get_state_ctx(self)->Sock_Type")
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004174 server_side: int
4175 server_hostname as hostname_obj: object = None
Christian Heimes141c5e82018-02-24 21:10:57 +01004176 *
4177 owner: object = None
4178 session: object = None
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004179
4180[clinic start generated code]*/
4181
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004182static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004183_ssl__SSLContext__wrap_socket_impl(PySSLContext *self, PyObject *sock,
Christian Heimes141c5e82018-02-24 21:10:57 +01004184 int server_side, PyObject *hostname_obj,
4185 PyObject *owner, PyObject *session)
Christian Heimes7f1305e2021-04-17 20:06:38 +02004186/*[clinic end generated code: output=f103f238633940b4 input=f5916eadbc6eae81]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004187{
Antoine Pitroud5323212010-10-22 18:19:07 +00004188 char *hostname = NULL;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004189 PyObject *res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004190
Antoine Pitroud5323212010-10-22 18:19:07 +00004191 /* server_hostname is either None (or absent), or to be encoded
Christian Heimesd02ac252018-03-25 12:36:13 +02004192 as IDN A-label (ASCII str) without NULL bytes. */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004193 if (hostname_obj != Py_None) {
Christian Heimes11a14932018-02-24 02:35:08 +01004194 if (!PyArg_Parse(hostname_obj, "es", "ascii", &hostname))
Antoine Pitroud5323212010-10-22 18:19:07 +00004195 return NULL;
Antoine Pitroud5323212010-10-22 18:19:07 +00004196 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00004197
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004198 res = (PyObject *) newPySSLSocket(self, (PySocketSockObject *)sock,
4199 server_side, hostname,
Christian Heimes141c5e82018-02-24 21:10:57 +01004200 owner, session,
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004201 NULL, NULL);
Antoine Pitroud5323212010-10-22 18:19:07 +00004202 if (hostname != NULL)
4203 PyMem_Free(hostname);
4204 return res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004205}
4206
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004207/*[clinic input]
4208_ssl._SSLContext._wrap_bio
Christian Heimes7f1305e2021-04-17 20:06:38 +02004209 incoming: object(subclass_of="get_state_ctx(self)->PySSLMemoryBIO_Type", type="PySSLMemoryBIO *")
4210 outgoing: object(subclass_of="get_state_ctx(self)->PySSLMemoryBIO_Type", type="PySSLMemoryBIO *")
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004211 server_side: int
4212 server_hostname as hostname_obj: object = None
Christian Heimes141c5e82018-02-24 21:10:57 +01004213 *
4214 owner: object = None
4215 session: object = None
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004216
4217[clinic start generated code]*/
4218
Antoine Pitroub0182c82010-10-12 20:09:02 +00004219static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004220_ssl__SSLContext__wrap_bio_impl(PySSLContext *self, PySSLMemoryBIO *incoming,
4221 PySSLMemoryBIO *outgoing, int server_side,
Christian Heimes141c5e82018-02-24 21:10:57 +01004222 PyObject *hostname_obj, PyObject *owner,
4223 PyObject *session)
Christian Heimes7f1305e2021-04-17 20:06:38 +02004224/*[clinic end generated code: output=5c5d6d9b41f99332 input=331edeec9c738382]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004225{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004226 char *hostname = NULL;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004227 PyObject *res;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004228
4229 /* server_hostname is either None (or absent), or to be encoded
Christian Heimesd02ac252018-03-25 12:36:13 +02004230 as IDN A-label (ASCII str) without NULL bytes. */
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004231 if (hostname_obj != Py_None) {
Christian Heimes11a14932018-02-24 02:35:08 +01004232 if (!PyArg_Parse(hostname_obj, "es", "ascii", &hostname))
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004233 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004234 }
4235
4236 res = (PyObject *) newPySSLSocket(self, NULL, server_side, hostname,
Christian Heimes141c5e82018-02-24 21:10:57 +01004237 owner, session,
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004238 incoming, outgoing);
4239
4240 PyMem_Free(hostname);
4241 return res;
4242}
4243
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004244/*[clinic input]
4245_ssl._SSLContext.session_stats
4246[clinic start generated code]*/
4247
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004248static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004249_ssl__SSLContext_session_stats_impl(PySSLContext *self)
4250/*[clinic end generated code: output=0d96411c42893bfb input=7e0a81fb11102c8b]*/
Antoine Pitroub0182c82010-10-12 20:09:02 +00004251{
4252 int r;
4253 PyObject *value, *stats = PyDict_New();
4254 if (!stats)
4255 return NULL;
4256
4257#define ADD_STATS(SSL_NAME, KEY_NAME) \
4258 value = PyLong_FromLong(SSL_CTX_sess_ ## SSL_NAME (self->ctx)); \
4259 if (value == NULL) \
4260 goto error; \
4261 r = PyDict_SetItemString(stats, KEY_NAME, value); \
4262 Py_DECREF(value); \
4263 if (r < 0) \
4264 goto error;
4265
4266 ADD_STATS(number, "number");
4267 ADD_STATS(connect, "connect");
4268 ADD_STATS(connect_good, "connect_good");
4269 ADD_STATS(connect_renegotiate, "connect_renegotiate");
4270 ADD_STATS(accept, "accept");
4271 ADD_STATS(accept_good, "accept_good");
4272 ADD_STATS(accept_renegotiate, "accept_renegotiate");
4273 ADD_STATS(accept, "accept");
4274 ADD_STATS(hits, "hits");
4275 ADD_STATS(misses, "misses");
4276 ADD_STATS(timeouts, "timeouts");
4277 ADD_STATS(cache_full, "cache_full");
4278
4279#undef ADD_STATS
4280
4281 return stats;
4282
4283error:
4284 Py_DECREF(stats);
4285 return NULL;
4286}
4287
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004288/*[clinic input]
4289_ssl._SSLContext.set_default_verify_paths
4290[clinic start generated code]*/
4291
Antoine Pitrou664c2d12010-11-17 20:29:42 +00004292static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004293_ssl__SSLContext_set_default_verify_paths_impl(PySSLContext *self)
4294/*[clinic end generated code: output=0bee74e6e09deaaa input=35f3408021463d74]*/
Antoine Pitrou664c2d12010-11-17 20:29:42 +00004295{
4296 if (!SSL_CTX_set_default_verify_paths(self->ctx)) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02004297 _setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
Antoine Pitrou664c2d12010-11-17 20:29:42 +00004298 return NULL;
4299 }
4300 Py_RETURN_NONE;
4301}
4302
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004303/*[clinic input]
4304_ssl._SSLContext.set_ecdh_curve
4305 name: object
4306 /
4307
4308[clinic start generated code]*/
4309
Antoine Pitrou923df6f2011-12-19 17:16:51 +01004310static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004311_ssl__SSLContext_set_ecdh_curve(PySSLContext *self, PyObject *name)
4312/*[clinic end generated code: output=23022c196e40d7d2 input=c2bafb6f6e34726b]*/
Antoine Pitrou923df6f2011-12-19 17:16:51 +01004313{
4314 PyObject *name_bytes;
4315 int nid;
4316 EC_KEY *key;
4317
4318 if (!PyUnicode_FSConverter(name, &name_bytes))
4319 return NULL;
4320 assert(PyBytes_Check(name_bytes));
4321 nid = OBJ_sn2nid(PyBytes_AS_STRING(name_bytes));
4322 Py_DECREF(name_bytes);
4323 if (nid == 0) {
4324 PyErr_Format(PyExc_ValueError,
4325 "unknown elliptic curve name %R", name);
4326 return NULL;
4327 }
4328 key = EC_KEY_new_by_curve_name(nid);
4329 if (key == NULL) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02004330 _setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
Antoine Pitrou923df6f2011-12-19 17:16:51 +01004331 return NULL;
4332 }
4333 SSL_CTX_set_tmp_ecdh(self->ctx, key);
4334 EC_KEY_free(key);
4335 Py_RETURN_NONE;
4336}
4337
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004338static int
4339_servername_callback(SSL *s, int *al, void *args)
4340{
4341 int ret;
Christian Heimes7f1305e2021-04-17 20:06:38 +02004342 PySSLContext *sslctx = (PySSLContext *) args;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004343 PySSLSocket *ssl;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004344 PyObject *result;
4345 /* The high-level ssl.SSLSocket object */
4346 PyObject *ssl_socket;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004347 const char *servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
Stefan Krah20d60802013-01-17 17:07:17 +01004348 PyGILState_STATE gstate = PyGILState_Ensure();
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004349
Christian Heimes7f1305e2021-04-17 20:06:38 +02004350 if (sslctx->set_sni_cb == NULL) {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004351 /* remove race condition in this the call back while if removing the
4352 * callback is in progress */
4353 PyGILState_Release(gstate);
Antoine Pitrou5dd12a52013-01-06 15:25:36 +01004354 return SSL_TLSEXT_ERR_OK;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004355 }
4356
4357 ssl = SSL_get_app_data(s);
Christian Heimes7f1305e2021-04-17 20:06:38 +02004358 assert(Py_IS_TYPE(ssl, get_state_ctx(sslctx)->PySSLSocket_Type));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004359
Serhiy Storchakaf51d7152015-11-02 14:40:41 +02004360 /* The servername callback expects an argument that represents the current
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004361 * SSL connection and that has a .context attribute that can be changed to
4362 * identify the requested hostname. Since the official API is the Python
4363 * level API we want to pass the callback a Python level object rather than
4364 * a _ssl.SSLSocket instance. If there's an "owner" (typically an
4365 * SSLObject) that will be passed. Otherwise if there's a socket then that
4366 * will be passed. If both do not exist only then the C-level object is
4367 * passed. */
4368 if (ssl->owner)
4369 ssl_socket = PyWeakref_GetObject(ssl->owner);
4370 else if (ssl->Socket)
4371 ssl_socket = PyWeakref_GetObject(ssl->Socket);
4372 else
4373 ssl_socket = (PyObject *) ssl;
4374
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004375 Py_INCREF(ssl_socket);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004376 if (ssl_socket == Py_None)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004377 goto error;
Victor Stinner7e001512013-06-25 00:44:31 +02004378
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004379 if (servername == NULL) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02004380 result = PyObject_CallFunctionObjArgs(sslctx->set_sni_cb, ssl_socket,
4381 Py_None, sslctx, NULL);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004382 }
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004383 else {
Christian Heimes11a14932018-02-24 02:35:08 +01004384 PyObject *servername_bytes;
4385 PyObject *servername_str;
4386
4387 servername_bytes = PyBytes_FromString(servername);
4388 if (servername_bytes == NULL) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02004389 PyErr_WriteUnraisable((PyObject *) sslctx);
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004390 goto error;
4391 }
Christian Heimes11a14932018-02-24 02:35:08 +01004392 /* server_hostname was encoded to an A-label by our caller; put it
4393 * back into a str object, but still as an A-label (bpo-28414)
4394 */
4395 servername_str = PyUnicode_FromEncodedObject(servername_bytes, "ascii", NULL);
Christian Heimes11a14932018-02-24 02:35:08 +01004396 if (servername_str == NULL) {
4397 PyErr_WriteUnraisable(servername_bytes);
Zackery Spytzee96f322020-07-09 04:00:21 -06004398 Py_DECREF(servername_bytes);
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004399 goto error;
4400 }
Zackery Spytzee96f322020-07-09 04:00:21 -06004401 Py_DECREF(servername_bytes);
Christian Heimes11a14932018-02-24 02:35:08 +01004402 result = PyObject_CallFunctionObjArgs(
Christian Heimes7f1305e2021-04-17 20:06:38 +02004403 sslctx->set_sni_cb, ssl_socket, servername_str,
4404 sslctx, NULL);
Christian Heimes11a14932018-02-24 02:35:08 +01004405 Py_DECREF(servername_str);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004406 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004407 Py_DECREF(ssl_socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004408
4409 if (result == NULL) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02004410 PyErr_WriteUnraisable(sslctx->set_sni_cb);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004411 *al = SSL_AD_HANDSHAKE_FAILURE;
4412 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
4413 }
4414 else {
Christian Heimes11a14932018-02-24 02:35:08 +01004415 /* Result may be None, a SSLContext or an integer
4416 * None and SSLContext are OK, integer or other values are an error.
4417 */
4418 if (result == Py_None) {
4419 ret = SSL_TLSEXT_ERR_OK;
4420 } else {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004421 *al = (int) PyLong_AsLong(result);
4422 if (PyErr_Occurred()) {
4423 PyErr_WriteUnraisable(result);
4424 *al = SSL_AD_INTERNAL_ERROR;
4425 }
4426 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
4427 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004428 Py_DECREF(result);
4429 }
4430
4431 PyGILState_Release(gstate);
4432 return ret;
4433
4434error:
4435 Py_DECREF(ssl_socket);
4436 *al = SSL_AD_INTERNAL_ERROR;
4437 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
4438 PyGILState_Release(gstate);
4439 return ret;
4440}
4441
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004442static PyObject *
Christian Heimes11a14932018-02-24 02:35:08 +01004443get_sni_callback(PySSLContext *self, void *c)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004444{
Christian Heimes11a14932018-02-24 02:35:08 +01004445 PyObject *cb = self->set_sni_cb;
4446 if (cb == NULL) {
4447 Py_RETURN_NONE;
4448 }
4449 Py_INCREF(cb);
4450 return cb;
4451}
4452
4453static int
4454set_sni_callback(PySSLContext *self, PyObject *arg, void *c)
4455{
4456 if (self->protocol == PY_SSL_VERSION_TLS_CLIENT) {
4457 PyErr_SetString(PyExc_ValueError,
4458 "sni_callback cannot be set on TLS_CLIENT context");
4459 return -1;
4460 }
Christian Heimes11a14932018-02-24 02:35:08 +01004461 Py_CLEAR(self->set_sni_cb);
4462 if (arg == Py_None) {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004463 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
4464 }
4465 else {
Christian Heimes11a14932018-02-24 02:35:08 +01004466 if (!PyCallable_Check(arg)) {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004467 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
4468 PyErr_SetString(PyExc_TypeError,
4469 "not a callable object");
Christian Heimes11a14932018-02-24 02:35:08 +01004470 return -1;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004471 }
Christian Heimes11a14932018-02-24 02:35:08 +01004472 Py_INCREF(arg);
4473 self->set_sni_cb = arg;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004474 SSL_CTX_set_tlsext_servername_callback(self->ctx, _servername_callback);
4475 SSL_CTX_set_tlsext_servername_arg(self->ctx, self);
4476 }
Christian Heimes11a14932018-02-24 02:35:08 +01004477 return 0;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004478}
4479
Christian Heimes11a14932018-02-24 02:35:08 +01004480PyDoc_STRVAR(PySSLContext_sni_callback_doc,
4481"Set a callback that will be called when a server name is provided by the SSL/TLS client in the SNI extension.\n\
4482\n\
4483If the argument is None then the callback is disabled. The method is called\n\
4484with the SSLSocket, the server name as a string, and the SSLContext object.\n\
4485See RFC 6066 for details of the SNI extension.");
4486
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004487/*[clinic input]
4488_ssl._SSLContext.cert_store_stats
4489
4490Returns quantities of loaded X.509 certificates.
4491
4492X.509 certificates with a CA extension and certificate revocation lists
4493inside the context's cert store.
4494
4495NOTE: Certificates in a capath directory aren't loaded unless they have
4496been used at least once.
4497[clinic start generated code]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004498
4499static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004500_ssl__SSLContext_cert_store_stats_impl(PySSLContext *self)
4501/*[clinic end generated code: output=5f356f4d9cca874d input=eb40dd0f6d0e40cf]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004502{
4503 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02004504 STACK_OF(X509_OBJECT) *objs;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004505 X509_OBJECT *obj;
Christian Heimes598894f2016-09-05 23:19:05 +02004506 int x509 = 0, crl = 0, ca = 0, i;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004507
4508 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02004509 objs = X509_STORE_get0_objects(store);
4510 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
4511 obj = sk_X509_OBJECT_value(objs, i);
4512 switch (X509_OBJECT_get_type(obj)) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004513 case X509_LU_X509:
4514 x509++;
Christian Heimes598894f2016-09-05 23:19:05 +02004515 if (X509_check_ca(X509_OBJECT_get0_X509(obj))) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004516 ca++;
4517 }
4518 break;
4519 case X509_LU_CRL:
4520 crl++;
4521 break;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004522 default:
4523 /* Ignore X509_LU_FAIL, X509_LU_RETRY, X509_LU_PKEY.
4524 * As far as I can tell they are internal states and never
4525 * stored in a cert store */
4526 break;
4527 }
4528 }
4529 return Py_BuildValue("{sisisi}", "x509", x509, "crl", crl,
4530 "x509_ca", ca);
4531}
4532
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004533/*[clinic input]
4534_ssl._SSLContext.get_ca_certs
4535 binary_form: bool = False
4536
4537Returns a list of dicts with information of loaded CA certs.
4538
4539If the optional argument is True, returns a DER-encoded copy of the CA
4540certificate.
4541
4542NOTE: Certificates in a capath directory aren't loaded unless they have
4543been used at least once.
4544[clinic start generated code]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004545
4546static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004547_ssl__SSLContext_get_ca_certs_impl(PySSLContext *self, int binary_form)
4548/*[clinic end generated code: output=0d58f148f37e2938 input=6887b5a09b7f9076]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004549{
4550 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02004551 STACK_OF(X509_OBJECT) *objs;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004552 PyObject *ci = NULL, *rlist = NULL;
4553 int i;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004554
4555 if ((rlist = PyList_New(0)) == NULL) {
4556 return NULL;
4557 }
4558
4559 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02004560 objs = X509_STORE_get0_objects(store);
4561 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004562 X509_OBJECT *obj;
4563 X509 *cert;
4564
Christian Heimes598894f2016-09-05 23:19:05 +02004565 obj = sk_X509_OBJECT_value(objs, i);
4566 if (X509_OBJECT_get_type(obj) != X509_LU_X509) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004567 /* not a x509 cert */
4568 continue;
4569 }
4570 /* CA for any purpose */
Christian Heimes598894f2016-09-05 23:19:05 +02004571 cert = X509_OBJECT_get0_X509(obj);
Christian Heimes9a5395a2013-06-17 15:44:12 +02004572 if (!X509_check_ca(cert)) {
4573 continue;
4574 }
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004575 if (binary_form) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02004576 ci = _certificate_to_der(get_state_ctx(self), cert);
Christian Heimes9a5395a2013-06-17 15:44:12 +02004577 } else {
Christian Heimes7f1305e2021-04-17 20:06:38 +02004578 ci = _decode_certificate(get_state_ctx(self), cert);
Christian Heimes9a5395a2013-06-17 15:44:12 +02004579 }
4580 if (ci == NULL) {
4581 goto error;
4582 }
4583 if (PyList_Append(rlist, ci) == -1) {
4584 goto error;
4585 }
4586 Py_CLEAR(ci);
4587 }
4588 return rlist;
4589
4590 error:
4591 Py_XDECREF(ci);
4592 Py_XDECREF(rlist);
4593 return NULL;
4594}
4595
4596
Antoine Pitrou152efa22010-05-16 18:19:27 +00004597static PyGetSetDef context_getsetlist[] = {
Christian Heimes1aa9a752013-12-02 02:41:19 +01004598 {"check_hostname", (getter) get_check_hostname,
4599 (setter) set_check_hostname, NULL},
Christian Heimes61d478c2018-01-27 15:51:38 +01004600 {"_host_flags", (getter) get_host_flags,
4601 (setter) set_host_flags, NULL},
Christian Heimes698dde12018-02-27 11:54:43 +01004602 {"minimum_version", (getter) get_minimum_version,
4603 (setter) set_minimum_version, NULL},
4604 {"maximum_version", (getter) get_maximum_version,
4605 (setter) set_maximum_version, NULL},
Christian Heimesc7f70692019-05-31 11:44:05 +02004606 {"keylog_filename", (getter) _PySSLContext_get_keylog_filename,
4607 (setter) _PySSLContext_set_keylog_filename, NULL},
Christian Heimesc7f70692019-05-31 11:44:05 +02004608 {"_msg_callback", (getter) _PySSLContext_get_msg_callback,
4609 (setter) _PySSLContext_set_msg_callback, NULL},
Christian Heimes11a14932018-02-24 02:35:08 +01004610 {"sni_callback", (getter) get_sni_callback,
Christian Heimes698dde12018-02-27 11:54:43 +01004611 (setter) set_sni_callback, PySSLContext_sni_callback_doc},
Christian Heimes39258d32021-04-17 11:36:35 +02004612#ifdef TLS1_3_VERSION
Christian Heimes78c7d522019-06-03 21:00:10 +02004613 {"num_tickets", (getter) get_num_tickets,
4614 (setter) set_num_tickets, PySSLContext_num_tickets_doc},
4615#endif
Antoine Pitroub5218772010-05-21 09:56:06 +00004616 {"options", (getter) get_options,
4617 (setter) set_options, NULL},
Christian Heimes9fb051f2018-09-23 08:32:31 +02004618 {"post_handshake_auth", (getter) get_post_handshake_auth,
4619#ifdef TLS1_3_VERSION
4620 (setter) set_post_handshake_auth,
4621#else
4622 NULL,
4623#endif
4624 NULL},
Christian Heimes11a14932018-02-24 02:35:08 +01004625 {"protocol", (getter) get_protocol,
4626 NULL, NULL},
Christian Heimes22587792013-11-21 23:56:13 +01004627 {"verify_flags", (getter) get_verify_flags,
4628 (setter) set_verify_flags, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00004629 {"verify_mode", (getter) get_verify_mode,
4630 (setter) set_verify_mode, NULL},
matthewhughes9348e836bb2020-07-17 09:59:15 +01004631 {"security_level", (getter) get_security_level,
4632 NULL, PySSLContext_security_level_doc},
Antoine Pitrou152efa22010-05-16 18:19:27 +00004633 {NULL}, /* sentinel */
4634};
4635
4636static struct PyMethodDef context_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004637 _SSL__SSLCONTEXT__WRAP_SOCKET_METHODDEF
4638 _SSL__SSLCONTEXT__WRAP_BIO_METHODDEF
4639 _SSL__SSLCONTEXT_SET_CIPHERS_METHODDEF
4640 _SSL__SSLCONTEXT__SET_ALPN_PROTOCOLS_METHODDEF
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004641 _SSL__SSLCONTEXT_LOAD_CERT_CHAIN_METHODDEF
4642 _SSL__SSLCONTEXT_LOAD_DH_PARAMS_METHODDEF
4643 _SSL__SSLCONTEXT_LOAD_VERIFY_LOCATIONS_METHODDEF
4644 _SSL__SSLCONTEXT_SESSION_STATS_METHODDEF
4645 _SSL__SSLCONTEXT_SET_DEFAULT_VERIFY_PATHS_METHODDEF
4646 _SSL__SSLCONTEXT_SET_ECDH_CURVE_METHODDEF
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004647 _SSL__SSLCONTEXT_CERT_STORE_STATS_METHODDEF
4648 _SSL__SSLCONTEXT_GET_CA_CERTS_METHODDEF
Christian Heimes25bfcd52016-09-06 00:04:45 +02004649 _SSL__SSLCONTEXT_GET_CIPHERS_METHODDEF
Antoine Pitrou152efa22010-05-16 18:19:27 +00004650 {NULL, NULL} /* sentinel */
4651};
4652
Christian Heimes5c36da72020-11-20 09:40:12 +01004653static PyType_Slot PySSLContext_slots[] = {
4654 {Py_tp_methods, context_methods},
4655 {Py_tp_getset, context_getsetlist},
4656 {Py_tp_new, _ssl__SSLContext},
4657 {Py_tp_dealloc, context_dealloc},
4658 {Py_tp_traverse, context_traverse},
4659 {Py_tp_clear, context_clear},
4660 {0, 0},
4661};
4662
4663static PyType_Spec PySSLContext_spec = {
Miss Islington (bot)ea47a8a2021-05-27 09:25:22 -07004664 .name = "_ssl._SSLContext",
4665 .basicsize = sizeof(PySSLContext),
4666 .flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC |
4667 Py_TPFLAGS_IMMUTABLETYPE),
4668 .slots = PySSLContext_slots,
Antoine Pitrou152efa22010-05-16 18:19:27 +00004669};
4670
4671
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004672/*
4673 * MemoryBIO objects
4674 */
4675
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004676/*[clinic input]
4677@classmethod
4678_ssl.MemoryBIO.__new__
4679
4680[clinic start generated code]*/
4681
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004682static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004683_ssl_MemoryBIO_impl(PyTypeObject *type)
4684/*[clinic end generated code: output=8820a58db78330ac input=26d22e4909ecb1b5]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004685{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004686 BIO *bio;
4687 PySSLMemoryBIO *self;
4688
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004689 bio = BIO_new(BIO_s_mem());
4690 if (bio == NULL) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02004691 PyErr_SetString(PyExc_MemoryError, "failed to allocate BIO");
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004692 return NULL;
4693 }
4694 /* Since our BIO is non-blocking an empty read() does not indicate EOF,
4695 * just that no data is currently available. The SSL routines should retry
4696 * the read, which we can achieve by calling BIO_set_retry_read(). */
4697 BIO_set_retry_read(bio);
4698 BIO_set_mem_eof_return(bio, -1);
4699
4700 assert(type != NULL && type->tp_alloc != NULL);
4701 self = (PySSLMemoryBIO *) type->tp_alloc(type, 0);
4702 if (self == NULL) {
4703 BIO_free(bio);
4704 return NULL;
4705 }
4706 self->bio = bio;
4707 self->eof_written = 0;
4708
4709 return (PyObject *) self;
4710}
4711
Miss Islington (bot)ea47a8a2021-05-27 09:25:22 -07004712static int
4713memory_bio_traverse(PySSLMemoryBIO *self, visitproc visit, void *arg)
4714{
4715 Py_VISIT(Py_TYPE(self));
4716 return 0;
4717}
4718
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004719static void
4720memory_bio_dealloc(PySSLMemoryBIO *self)
4721{
Christian Heimes5c36da72020-11-20 09:40:12 +01004722 PyTypeObject *tp = Py_TYPE(self);
Miss Islington (bot)ea47a8a2021-05-27 09:25:22 -07004723 PyObject_GC_UnTrack(self);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004724 BIO_free(self->bio);
4725 Py_TYPE(self)->tp_free(self);
Christian Heimes5c36da72020-11-20 09:40:12 +01004726 Py_DECREF(tp);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004727}
4728
4729static PyObject *
4730memory_bio_get_pending(PySSLMemoryBIO *self, void *c)
4731{
Segev Finer5cff6372017-07-27 01:19:17 +03004732 return PyLong_FromSize_t(BIO_ctrl_pending(self->bio));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004733}
4734
4735PyDoc_STRVAR(PySSL_memory_bio_pending_doc,
4736"The number of bytes pending in the memory BIO.");
4737
4738static PyObject *
4739memory_bio_get_eof(PySSLMemoryBIO *self, void *c)
4740{
4741 return PyBool_FromLong((BIO_ctrl_pending(self->bio) == 0)
4742 && self->eof_written);
4743}
4744
4745PyDoc_STRVAR(PySSL_memory_bio_eof_doc,
4746"Whether the memory BIO is at EOF.");
4747
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004748/*[clinic input]
4749_ssl.MemoryBIO.read
4750 size as len: int = -1
4751 /
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004752
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004753Read up to size bytes from the memory BIO.
4754
4755If size is not specified, read the entire buffer.
4756If the return value is an empty bytes instance, this means either
4757EOF or that no data is available. Use the "eof" property to
4758distinguish between the two.
4759[clinic start generated code]*/
4760
4761static PyObject *
4762_ssl_MemoryBIO_read_impl(PySSLMemoryBIO *self, int len)
4763/*[clinic end generated code: output=a657aa1e79cd01b3 input=574d7be06a902366]*/
4764{
4765 int avail, nbytes;
4766 PyObject *result;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004767
Segev Finer5cff6372017-07-27 01:19:17 +03004768 avail = (int)Py_MIN(BIO_ctrl_pending(self->bio), INT_MAX);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004769 if ((len < 0) || (len > avail))
4770 len = avail;
4771
4772 result = PyBytes_FromStringAndSize(NULL, len);
4773 if ((result == NULL) || (len == 0))
4774 return result;
4775
4776 nbytes = BIO_read(self->bio, PyBytes_AS_STRING(result), len);
Zackery Spytz365ad2e2018-10-06 11:41:45 -06004777 if (nbytes < 0) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02004778 _sslmodulestate *state = get_state_mbio(self);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004779 Py_DECREF(result);
Christian Heimes7f1305e2021-04-17 20:06:38 +02004780 _setSSLError(state, NULL, 0, __FILE__, __LINE__);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004781 return NULL;
4782 }
4783
Zackery Spytz365ad2e2018-10-06 11:41:45 -06004784 /* There should never be any short reads but check anyway. */
4785 if (nbytes < len) {
4786 _PyBytes_Resize(&result, nbytes);
4787 }
4788
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004789 return result;
4790}
4791
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004792/*[clinic input]
4793_ssl.MemoryBIO.write
4794 b: Py_buffer
4795 /
4796
4797Writes the bytes b into the memory BIO.
4798
4799Returns the number of bytes written.
4800[clinic start generated code]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004801
4802static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004803_ssl_MemoryBIO_write_impl(PySSLMemoryBIO *self, Py_buffer *b)
4804/*[clinic end generated code: output=156ec59110d75935 input=e45757b3e17c4808]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004805{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004806 int nbytes;
4807
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004808 if (b->len > INT_MAX) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004809 PyErr_Format(PyExc_OverflowError,
4810 "string longer than %d bytes", INT_MAX);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004811 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004812 }
4813
4814 if (self->eof_written) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02004815 PyObject *module = PyType_GetModule(Py_TYPE(self));
4816 if (module == NULL)
4817 return NULL;
4818 PyErr_SetString(get_ssl_state(module)->PySSLErrorObject,
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004819 "cannot write() after write_eof()");
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004820 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004821 }
4822
Segev Finer5cff6372017-07-27 01:19:17 +03004823 nbytes = BIO_write(self->bio, b->buf, (int)b->len);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004824 if (nbytes < 0) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02004825 _sslmodulestate *state = get_state_mbio(self);
4826 _setSSLError(state, NULL, 0, __FILE__, __LINE__);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004827 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004828 }
4829
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004830 return PyLong_FromLong(nbytes);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004831}
4832
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004833/*[clinic input]
4834_ssl.MemoryBIO.write_eof
4835
4836Write an EOF marker to the memory BIO.
4837
4838When all data has been read, the "eof" property will be True.
4839[clinic start generated code]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004840
4841static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004842_ssl_MemoryBIO_write_eof_impl(PySSLMemoryBIO *self)
4843/*[clinic end generated code: output=d4106276ccd1ed34 input=56a945f1d29e8bd6]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004844{
4845 self->eof_written = 1;
4846 /* After an EOF is written, a zero return from read() should be a real EOF
4847 * i.e. it should not be retried. Clear the SHOULD_RETRY flag. */
4848 BIO_clear_retry_flags(self->bio);
4849 BIO_set_mem_eof_return(self->bio, 0);
4850
4851 Py_RETURN_NONE;
4852}
4853
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004854static PyGetSetDef memory_bio_getsetlist[] = {
4855 {"pending", (getter) memory_bio_get_pending, NULL,
4856 PySSL_memory_bio_pending_doc},
4857 {"eof", (getter) memory_bio_get_eof, NULL,
4858 PySSL_memory_bio_eof_doc},
4859 {NULL}, /* sentinel */
4860};
4861
4862static struct PyMethodDef memory_bio_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004863 _SSL_MEMORYBIO_READ_METHODDEF
4864 _SSL_MEMORYBIO_WRITE_METHODDEF
4865 _SSL_MEMORYBIO_WRITE_EOF_METHODDEF
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004866 {NULL, NULL} /* sentinel */
4867};
4868
Christian Heimes5c36da72020-11-20 09:40:12 +01004869static PyType_Slot PySSLMemoryBIO_slots[] = {
4870 {Py_tp_methods, memory_bio_methods},
4871 {Py_tp_getset, memory_bio_getsetlist},
4872 {Py_tp_new, _ssl_MemoryBIO},
4873 {Py_tp_dealloc, memory_bio_dealloc},
Miss Islington (bot)ea47a8a2021-05-27 09:25:22 -07004874 {Py_tp_traverse, memory_bio_traverse},
Christian Heimes5c36da72020-11-20 09:40:12 +01004875 {0, 0},
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004876};
4877
Christian Heimes5c36da72020-11-20 09:40:12 +01004878static PyType_Spec PySSLMemoryBIO_spec = {
Miss Islington (bot)ea47a8a2021-05-27 09:25:22 -07004879 .name = "_ssl.MemoryBIO",
4880 .basicsize = sizeof(PySSLMemoryBIO),
4881 .flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_IMMUTABLETYPE |
4882 Py_TPFLAGS_HAVE_GC),
4883 .slots = PySSLMemoryBIO_slots,
Christian Heimes5c36da72020-11-20 09:40:12 +01004884};
Antoine Pitrou152efa22010-05-16 18:19:27 +00004885
Christian Heimes99a65702016-09-10 23:44:53 +02004886/*
4887 * SSL Session object
4888 */
4889
4890static void
4891PySSLSession_dealloc(PySSLSession *self)
4892{
Christian Heimes5c36da72020-11-20 09:40:12 +01004893 PyTypeObject *tp = Py_TYPE(self);
INADA Naokia6296d32017-08-24 14:55:17 +09004894 /* bpo-31095: UnTrack is needed before calling any callbacks */
Christian Heimesa5d07652016-09-24 10:48:05 +02004895 PyObject_GC_UnTrack(self);
Christian Heimes99a65702016-09-10 23:44:53 +02004896 Py_XDECREF(self->ctx);
4897 if (self->session != NULL) {
4898 SSL_SESSION_free(self->session);
4899 }
Christian Heimesa5d07652016-09-24 10:48:05 +02004900 PyObject_GC_Del(self);
Christian Heimes5c36da72020-11-20 09:40:12 +01004901 Py_DECREF(tp);
Christian Heimes99a65702016-09-10 23:44:53 +02004902}
4903
4904static PyObject *
4905PySSLSession_richcompare(PyObject *left, PyObject *right, int op)
4906{
4907 int result;
Christian Heimes7f1305e2021-04-17 20:06:38 +02004908 PyTypeObject *sesstype = ((PySSLSession*)left)->ctx->state->PySSLSession_Type;
Christian Heimes99a65702016-09-10 23:44:53 +02004909
4910 if (left == NULL || right == NULL) {
4911 PyErr_BadInternalCall();
4912 return NULL;
4913 }
4914
Christian Heimes7f1305e2021-04-17 20:06:38 +02004915 if (!Py_IS_TYPE(left, sesstype) || !Py_IS_TYPE(right, sesstype)) {
Christian Heimes99a65702016-09-10 23:44:53 +02004916 Py_RETURN_NOTIMPLEMENTED;
4917 }
4918
4919 if (left == right) {
4920 result = 0;
4921 } else {
4922 const unsigned char *left_id, *right_id;
4923 unsigned int left_len, right_len;
4924 left_id = SSL_SESSION_get_id(((PySSLSession *)left)->session,
4925 &left_len);
4926 right_id = SSL_SESSION_get_id(((PySSLSession *)right)->session,
4927 &right_len);
4928 if (left_len == right_len) {
4929 result = memcmp(left_id, right_id, left_len);
4930 } else {
4931 result = 1;
4932 }
4933 }
4934
4935 switch (op) {
4936 case Py_EQ:
4937 if (result == 0) {
4938 Py_RETURN_TRUE;
4939 } else {
4940 Py_RETURN_FALSE;
4941 }
4942 break;
4943 case Py_NE:
4944 if (result != 0) {
4945 Py_RETURN_TRUE;
4946 } else {
4947 Py_RETURN_FALSE;
4948 }
4949 break;
4950 case Py_LT:
4951 case Py_LE:
4952 case Py_GT:
4953 case Py_GE:
4954 Py_RETURN_NOTIMPLEMENTED;
4955 break;
4956 default:
4957 PyErr_BadArgument();
4958 return NULL;
4959 }
4960}
4961
4962static int
4963PySSLSession_traverse(PySSLSession *self, visitproc visit, void *arg)
4964{
4965 Py_VISIT(self->ctx);
Miss Islington (bot)ea47a8a2021-05-27 09:25:22 -07004966 Py_VISIT(Py_TYPE(self));
Christian Heimes99a65702016-09-10 23:44:53 +02004967 return 0;
4968}
4969
4970static int
4971PySSLSession_clear(PySSLSession *self)
4972{
4973 Py_CLEAR(self->ctx);
4974 return 0;
4975}
4976
4977
4978static PyObject *
4979PySSLSession_get_time(PySSLSession *self, void *closure) {
4980 return PyLong_FromLong(SSL_SESSION_get_time(self->session));
4981}
4982
4983PyDoc_STRVAR(PySSLSession_get_time_doc,
4984"Session creation time (seconds since epoch).");
4985
4986
4987static PyObject *
4988PySSLSession_get_timeout(PySSLSession *self, void *closure) {
4989 return PyLong_FromLong(SSL_SESSION_get_timeout(self->session));
4990}
4991
4992PyDoc_STRVAR(PySSLSession_get_timeout_doc,
4993"Session timeout (delta in seconds).");
4994
4995
4996static PyObject *
4997PySSLSession_get_ticket_lifetime_hint(PySSLSession *self, void *closure) {
4998 unsigned long hint = SSL_SESSION_get_ticket_lifetime_hint(self->session);
4999 return PyLong_FromUnsignedLong(hint);
5000}
5001
5002PyDoc_STRVAR(PySSLSession_get_ticket_lifetime_hint_doc,
5003"Ticket life time hint.");
5004
5005
5006static PyObject *
5007PySSLSession_get_session_id(PySSLSession *self, void *closure) {
5008 const unsigned char *id;
5009 unsigned int len;
5010 id = SSL_SESSION_get_id(self->session, &len);
5011 return PyBytes_FromStringAndSize((const char *)id, len);
5012}
5013
5014PyDoc_STRVAR(PySSLSession_get_session_id_doc,
5015"Session id");
5016
5017
5018static PyObject *
5019PySSLSession_get_has_ticket(PySSLSession *self, void *closure) {
5020 if (SSL_SESSION_has_ticket(self->session)) {
5021 Py_RETURN_TRUE;
5022 } else {
5023 Py_RETURN_FALSE;
5024 }
5025}
5026
5027PyDoc_STRVAR(PySSLSession_get_has_ticket_doc,
5028"Does the session contain a ticket?");
5029
5030
5031static PyGetSetDef PySSLSession_getsetlist[] = {
5032 {"has_ticket", (getter) PySSLSession_get_has_ticket, NULL,
5033 PySSLSession_get_has_ticket_doc},
5034 {"id", (getter) PySSLSession_get_session_id, NULL,
5035 PySSLSession_get_session_id_doc},
5036 {"ticket_lifetime_hint", (getter) PySSLSession_get_ticket_lifetime_hint,
5037 NULL, PySSLSession_get_ticket_lifetime_hint_doc},
5038 {"time", (getter) PySSLSession_get_time, NULL,
5039 PySSLSession_get_time_doc},
5040 {"timeout", (getter) PySSLSession_get_timeout, NULL,
5041 PySSLSession_get_timeout_doc},
5042 {NULL}, /* sentinel */
5043};
5044
Christian Heimes5c36da72020-11-20 09:40:12 +01005045static PyType_Slot PySSLSession_slots[] = {
5046 {Py_tp_getset,PySSLSession_getsetlist},
5047 {Py_tp_richcompare, PySSLSession_richcompare},
5048 {Py_tp_dealloc, PySSLSession_dealloc},
5049 {Py_tp_traverse, PySSLSession_traverse},
5050 {Py_tp_clear, PySSLSession_clear},
5051 {0, 0},
5052};
5053
5054static PyType_Spec PySSLSession_spec = {
Miss Islington (bot)ea47a8a2021-05-27 09:25:22 -07005055 .name = "_ssl.SSLSession",
5056 .basicsize = sizeof(PySSLSession),
5057 .flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
5058 Py_TPFLAGS_IMMUTABLETYPE),
5059 .slots = PySSLSession_slots,
Christian Heimes99a65702016-09-10 23:44:53 +02005060};
5061
5062
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005063/* helper routines for seeding the SSL PRNG */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005064/*[clinic input]
5065_ssl.RAND_add
Larry Hastingsdbfdc382015-05-04 06:59:46 -07005066 string as view: Py_buffer(accept={str, buffer})
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005067 entropy: double
5068 /
5069
5070Mix string into the OpenSSL PRNG state.
5071
5072entropy (a float) is a lower bound on the entropy contained in
Chandan Kumar63c2c8a2017-06-09 15:13:58 +05305073string. See RFC 4086.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005074[clinic start generated code]*/
5075
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005076static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005077_ssl_RAND_add_impl(PyObject *module, Py_buffer *view, double entropy)
Serhiy Storchaka5f31d5c2017-06-10 13:13:51 +03005078/*[clinic end generated code: output=e6dd48df9c9024e9 input=5c33017422828f5c]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005079{
Serhiy Storchaka8490f5a2015-03-20 09:00:36 +02005080 const char *buf;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02005081 Py_ssize_t len, written;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005082
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005083 buf = (const char *)view->buf;
5084 len = view->len;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02005085 do {
5086 written = Py_MIN(len, INT_MAX);
5087 RAND_add(buf, (int)written, entropy);
5088 buf += written;
5089 len -= written;
5090 } while (len);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02005091 Py_RETURN_NONE;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005092}
5093
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005094static PyObject *
Christian Heimes7f1305e2021-04-17 20:06:38 +02005095PySSL_RAND(PyObject *module, int len, int pseudo)
Victor Stinner99c8b162011-05-24 12:05:19 +02005096{
5097 int ok;
5098 PyObject *bytes;
5099 unsigned long err;
5100 const char *errstr;
5101 PyObject *v;
5102
Victor Stinner1e81a392013-12-19 16:47:04 +01005103 if (len < 0) {
5104 PyErr_SetString(PyExc_ValueError, "num must be positive");
5105 return NULL;
5106 }
5107
Victor Stinner99c8b162011-05-24 12:05:19 +02005108 bytes = PyBytes_FromStringAndSize(NULL, len);
5109 if (bytes == NULL)
5110 return NULL;
5111 if (pseudo) {
Christian Heimesa871f692020-06-01 08:58:14 +02005112 ok = RAND_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
Victor Stinner99c8b162011-05-24 12:05:19 +02005113 if (ok == 0 || ok == 1)
5114 return Py_BuildValue("NO", bytes, ok == 1 ? Py_True : Py_False);
5115 }
5116 else {
5117 ok = RAND_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
5118 if (ok == 1)
5119 return bytes;
5120 }
5121 Py_DECREF(bytes);
5122
5123 err = ERR_get_error();
5124 errstr = ERR_reason_error_string(err);
5125 v = Py_BuildValue("(ks)", err, errstr);
5126 if (v != NULL) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02005127 PyErr_SetObject(get_ssl_state(module)->PySSLErrorObject, v);
Victor Stinner99c8b162011-05-24 12:05:19 +02005128 Py_DECREF(v);
5129 }
5130 return NULL;
5131}
5132
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005133/*[clinic input]
5134_ssl.RAND_bytes
5135 n: int
5136 /
5137
5138Generate n cryptographically strong pseudo-random bytes.
5139[clinic start generated code]*/
5140
Victor Stinner99c8b162011-05-24 12:05:19 +02005141static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005142_ssl_RAND_bytes_impl(PyObject *module, int n)
5143/*[clinic end generated code: output=977da635e4838bc7 input=678ddf2872dfebfc]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02005144{
Christian Heimes7f1305e2021-04-17 20:06:38 +02005145 return PySSL_RAND(module, n, 0);
Victor Stinner99c8b162011-05-24 12:05:19 +02005146}
5147
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005148/*[clinic input]
5149_ssl.RAND_pseudo_bytes
5150 n: int
5151 /
5152
5153Generate n pseudo-random bytes.
5154
5155Return a pair (bytes, is_cryptographic). is_cryptographic is True
5156if the bytes generated are cryptographically strong.
5157[clinic start generated code]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02005158
5159static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005160_ssl_RAND_pseudo_bytes_impl(PyObject *module, int n)
5161/*[clinic end generated code: output=b1509e937000e52d input=58312bd53f9bbdd0]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02005162{
Miss Islington (bot)d7930fb2021-06-11 00:36:17 -07005163 PY_SSL_DEPRECATED("ssl.RAND_pseudo_bytes() is deprecated", 1, NULL);
Christian Heimes7f1305e2021-04-17 20:06:38 +02005164 return PySSL_RAND(module, n, 1);
Victor Stinner99c8b162011-05-24 12:05:19 +02005165}
5166
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005167/*[clinic input]
5168_ssl.RAND_status
5169
Zackery Spytz7d37b862021-04-23 10:07:37 -06005170Returns True if the OpenSSL PRNG has been seeded with enough data and False if not.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005171
5172It is necessary to seed the PRNG with RAND_add() on some platforms before
5173using the ssl() function.
5174[clinic start generated code]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02005175
5176static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005177_ssl_RAND_status_impl(PyObject *module)
Zackery Spytz7d37b862021-04-23 10:07:37 -06005178/*[clinic end generated code: output=7e0aaa2d39fdc1ad input=d5ae5aea52f36e01]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005179{
Zackery Spytz7d37b862021-04-23 10:07:37 -06005180 return PyBool_FromLong(RAND_status());
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005181}
5182
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005183/*[clinic input]
5184_ssl.get_default_verify_paths
5185
5186Return search paths and environment vars that are used by SSLContext's set_default_verify_paths() to load default CAs.
5187
5188The values are 'cert_file_env', 'cert_file', 'cert_dir_env', 'cert_dir'.
5189[clinic start generated code]*/
Christian Heimes6d7ad132013-06-09 18:02:55 +02005190
5191static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005192_ssl_get_default_verify_paths_impl(PyObject *module)
5193/*[clinic end generated code: output=e5b62a466271928b input=5210c953d98c3eb5]*/
Christian Heimes6d7ad132013-06-09 18:02:55 +02005194{
5195 PyObject *ofile_env = NULL;
5196 PyObject *ofile = NULL;
5197 PyObject *odir_env = NULL;
5198 PyObject *odir = NULL;
5199
Benjamin Petersond113c962015-07-18 10:59:13 -07005200#define CONVERT(info, target) { \
Christian Heimes6d7ad132013-06-09 18:02:55 +02005201 const char *tmp = (info); \
5202 target = NULL; \
5203 if (!tmp) { Py_INCREF(Py_None); target = Py_None; } \
5204 else if ((target = PyUnicode_DecodeFSDefault(tmp)) == NULL) { \
5205 target = PyBytes_FromString(tmp); } \
5206 if (!target) goto error; \
Benjamin Peterson025a1fd2015-11-14 15:12:38 -08005207 }
Christian Heimes6d7ad132013-06-09 18:02:55 +02005208
Benjamin Petersond113c962015-07-18 10:59:13 -07005209 CONVERT(X509_get_default_cert_file_env(), ofile_env);
5210 CONVERT(X509_get_default_cert_file(), ofile);
5211 CONVERT(X509_get_default_cert_dir_env(), odir_env);
5212 CONVERT(X509_get_default_cert_dir(), odir);
5213#undef CONVERT
Christian Heimes6d7ad132013-06-09 18:02:55 +02005214
Christian Heimes200bb1b2013-06-14 15:14:29 +02005215 return Py_BuildValue("NNNN", ofile_env, ofile, odir_env, odir);
Christian Heimes6d7ad132013-06-09 18:02:55 +02005216
5217 error:
5218 Py_XDECREF(ofile_env);
5219 Py_XDECREF(ofile);
5220 Py_XDECREF(odir_env);
5221 Py_XDECREF(odir);
5222 return NULL;
5223}
5224
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005225static PyObject*
Christian Heimes7f1305e2021-04-17 20:06:38 +02005226asn1obj2py(_sslmodulestate *state, ASN1_OBJECT *obj)
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005227{
5228 int nid;
5229 const char *ln, *sn;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005230
5231 nid = OBJ_obj2nid(obj);
5232 if (nid == NID_undef) {
5233 PyErr_Format(PyExc_ValueError, "Unknown object");
5234 return NULL;
5235 }
5236 sn = OBJ_nid2sn(nid);
5237 ln = OBJ_nid2ln(nid);
Christian Heimes7f1305e2021-04-17 20:06:38 +02005238 return Py_BuildValue("issN", nid, sn, ln, _asn1obj2py(state, obj, 1));
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005239}
5240
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005241/*[clinic input]
5242_ssl.txt2obj
5243 txt: str
5244 name: bool = False
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005245
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005246Lookup NID, short name, long name and OID of an ASN1_OBJECT.
5247
5248By default objects are looked up by OID. With name=True short and
5249long name are also matched.
5250[clinic start generated code]*/
5251
5252static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005253_ssl_txt2obj_impl(PyObject *module, const char *txt, int name)
5254/*[clinic end generated code: output=c38e3991347079c1 input=1c1e7d0aa7c48602]*/
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005255{
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005256 PyObject *result = NULL;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005257 ASN1_OBJECT *obj;
5258
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005259 obj = OBJ_txt2obj(txt, name ? 0 : 1);
5260 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01005261 PyErr_Format(PyExc_ValueError, "unknown object '%.100s'", txt);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005262 return NULL;
5263 }
Christian Heimes7f1305e2021-04-17 20:06:38 +02005264 result = asn1obj2py(get_ssl_state(module), obj);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005265 ASN1_OBJECT_free(obj);
5266 return result;
5267}
5268
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005269/*[clinic input]
5270_ssl.nid2obj
5271 nid: int
5272 /
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005273
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005274Lookup NID, short name, long name and OID of an ASN1_OBJECT by NID.
5275[clinic start generated code]*/
5276
5277static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005278_ssl_nid2obj_impl(PyObject *module, int nid)
5279/*[clinic end generated code: output=4a98ab691cd4f84a input=51787a3bee7d8f98]*/
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005280{
5281 PyObject *result = NULL;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005282 ASN1_OBJECT *obj;
5283
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005284 if (nid < NID_undef) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01005285 PyErr_SetString(PyExc_ValueError, "NID must be positive.");
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005286 return NULL;
5287 }
5288 obj = OBJ_nid2obj(nid);
5289 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01005290 PyErr_Format(PyExc_ValueError, "unknown NID %i", nid);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005291 return NULL;
5292 }
Christian Heimes7f1305e2021-04-17 20:06:38 +02005293 result = asn1obj2py(get_ssl_state(module), obj);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005294 ASN1_OBJECT_free(obj);
5295 return result;
5296}
5297
Christian Heimes46bebee2013-06-09 19:03:31 +02005298#ifdef _MSC_VER
Christian Heimes44109d72013-11-22 01:51:30 +01005299
5300static PyObject*
5301certEncodingType(DWORD encodingType)
5302{
5303 static PyObject *x509_asn = NULL;
5304 static PyObject *pkcs_7_asn = NULL;
5305
5306 if (x509_asn == NULL) {
5307 x509_asn = PyUnicode_InternFromString("x509_asn");
5308 if (x509_asn == NULL)
5309 return NULL;
5310 }
5311 if (pkcs_7_asn == NULL) {
5312 pkcs_7_asn = PyUnicode_InternFromString("pkcs_7_asn");
5313 if (pkcs_7_asn == NULL)
5314 return NULL;
5315 }
5316 switch(encodingType) {
5317 case X509_ASN_ENCODING:
5318 Py_INCREF(x509_asn);
5319 return x509_asn;
5320 case PKCS_7_ASN_ENCODING:
5321 Py_INCREF(pkcs_7_asn);
5322 return pkcs_7_asn;
5323 default:
5324 return PyLong_FromLong(encodingType);
5325 }
5326}
5327
5328static PyObject*
5329parseKeyUsage(PCCERT_CONTEXT pCertCtx, DWORD flags)
5330{
5331 CERT_ENHKEY_USAGE *usage;
5332 DWORD size, error, i;
5333 PyObject *retval;
5334
5335 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, NULL, &size)) {
5336 error = GetLastError();
5337 if (error == CRYPT_E_NOT_FOUND) {
5338 Py_RETURN_TRUE;
5339 }
5340 return PyErr_SetFromWindowsErr(error);
5341 }
5342
5343 usage = (CERT_ENHKEY_USAGE*)PyMem_Malloc(size);
5344 if (usage == NULL) {
5345 return PyErr_NoMemory();
5346 }
5347
5348 /* Now get the actual enhanced usage property */
5349 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, usage, &size)) {
5350 PyMem_Free(usage);
5351 error = GetLastError();
5352 if (error == CRYPT_E_NOT_FOUND) {
5353 Py_RETURN_TRUE;
5354 }
5355 return PyErr_SetFromWindowsErr(error);
5356 }
Christian Heimes915cd3f2019-09-09 18:06:55 +02005357 retval = PyFrozenSet_New(NULL);
Christian Heimes44109d72013-11-22 01:51:30 +01005358 if (retval == NULL) {
5359 goto error;
5360 }
5361 for (i = 0; i < usage->cUsageIdentifier; ++i) {
5362 if (usage->rgpszUsageIdentifier[i]) {
5363 PyObject *oid;
5364 int err;
5365 oid = PyUnicode_FromString(usage->rgpszUsageIdentifier[i]);
5366 if (oid == NULL) {
5367 Py_CLEAR(retval);
5368 goto error;
5369 }
5370 err = PySet_Add(retval, oid);
5371 Py_DECREF(oid);
5372 if (err == -1) {
5373 Py_CLEAR(retval);
5374 goto error;
5375 }
5376 }
5377 }
5378 error:
5379 PyMem_Free(usage);
5380 return retval;
5381}
5382
kctherookied93fbbf2019-03-29 00:59:06 +07005383static HCERTSTORE
5384ssl_collect_certificates(const char *store_name)
5385{
5386/* this function collects the system certificate stores listed in
5387 * system_stores into a collection certificate store for being
5388 * enumerated. The store must be readable to be added to the
5389 * store collection.
5390 */
5391
5392 HCERTSTORE hCollectionStore = NULL, hSystemStore = NULL;
5393 static DWORD system_stores[] = {
5394 CERT_SYSTEM_STORE_LOCAL_MACHINE,
5395 CERT_SYSTEM_STORE_LOCAL_MACHINE_ENTERPRISE,
5396 CERT_SYSTEM_STORE_LOCAL_MACHINE_GROUP_POLICY,
5397 CERT_SYSTEM_STORE_CURRENT_USER,
5398 CERT_SYSTEM_STORE_CURRENT_USER_GROUP_POLICY,
5399 CERT_SYSTEM_STORE_SERVICES,
5400 CERT_SYSTEM_STORE_USERS};
5401 size_t i, storesAdded;
5402 BOOL result;
5403
5404 hCollectionStore = CertOpenStore(CERT_STORE_PROV_COLLECTION, 0,
5405 (HCRYPTPROV)NULL, 0, NULL);
5406 if (!hCollectionStore) {
5407 return NULL;
5408 }
5409 storesAdded = 0;
5410 for (i = 0; i < sizeof(system_stores) / sizeof(DWORD); i++) {
5411 hSystemStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0,
5412 (HCRYPTPROV)NULL,
5413 CERT_STORE_READONLY_FLAG |
5414 system_stores[i], store_name);
5415 if (hSystemStore) {
5416 result = CertAddStoreToCollection(hCollectionStore, hSystemStore,
5417 CERT_PHYSICAL_STORE_ADD_ENABLE_FLAG, 0);
5418 if (result) {
5419 ++storesAdded;
5420 }
neoneneed701292019-09-09 21:33:43 +09005421 CertCloseStore(hSystemStore, 0); /* flag must be 0 */
kctherookied93fbbf2019-03-29 00:59:06 +07005422 }
5423 }
5424 if (storesAdded == 0) {
5425 CertCloseStore(hCollectionStore, CERT_CLOSE_STORE_FORCE_FLAG);
5426 return NULL;
5427 }
5428
5429 return hCollectionStore;
5430}
5431
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005432/*[clinic input]
5433_ssl.enum_certificates
5434 store_name: str
5435
5436Retrieve certificates from Windows' cert store.
5437
5438store_name may be one of 'CA', 'ROOT' or 'MY'. The system may provide
5439more cert storages, too. The function returns a list of (bytes,
5440encoding_type, trust) tuples. The encoding_type flag can be interpreted
5441with X509_ASN_ENCODING or PKCS_7_ASN_ENCODING. The trust setting is either
5442a set of OIDs or the boolean True.
5443[clinic start generated code]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00005444
Christian Heimes46bebee2013-06-09 19:03:31 +02005445static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005446_ssl_enum_certificates_impl(PyObject *module, const char *store_name)
5447/*[clinic end generated code: output=5134dc8bb3a3c893 input=915f60d70461ea4e]*/
Christian Heimes46bebee2013-06-09 19:03:31 +02005448{
kctherookied93fbbf2019-03-29 00:59:06 +07005449 HCERTSTORE hCollectionStore = NULL;
Christian Heimes44109d72013-11-22 01:51:30 +01005450 PCCERT_CONTEXT pCertCtx = NULL;
5451 PyObject *keyusage = NULL, *cert = NULL, *enc = NULL, *tup = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02005452 PyObject *result = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02005453
Christian Heimes915cd3f2019-09-09 18:06:55 +02005454 result = PySet_New(NULL);
Christian Heimes44109d72013-11-22 01:51:30 +01005455 if (result == NULL) {
5456 return NULL;
5457 }
kctherookied93fbbf2019-03-29 00:59:06 +07005458 hCollectionStore = ssl_collect_certificates(store_name);
5459 if (hCollectionStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02005460 Py_DECREF(result);
5461 return PyErr_SetFromWindowsErr(GetLastError());
5462 }
5463
kctherookied93fbbf2019-03-29 00:59:06 +07005464 while (pCertCtx = CertEnumCertificatesInStore(hCollectionStore, pCertCtx)) {
Christian Heimes44109d72013-11-22 01:51:30 +01005465 cert = PyBytes_FromStringAndSize((const char*)pCertCtx->pbCertEncoded,
5466 pCertCtx->cbCertEncoded);
5467 if (!cert) {
5468 Py_CLEAR(result);
5469 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02005470 }
Christian Heimes44109d72013-11-22 01:51:30 +01005471 if ((enc = certEncodingType(pCertCtx->dwCertEncodingType)) == NULL) {
5472 Py_CLEAR(result);
5473 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02005474 }
Christian Heimes44109d72013-11-22 01:51:30 +01005475 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG);
5476 if (keyusage == Py_True) {
5477 Py_DECREF(keyusage);
5478 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_EXT_ONLY_ENHKEY_USAGE_FLAG);
Christian Heimes46bebee2013-06-09 19:03:31 +02005479 }
Christian Heimes44109d72013-11-22 01:51:30 +01005480 if (keyusage == NULL) {
5481 Py_CLEAR(result);
5482 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02005483 }
Christian Heimes44109d72013-11-22 01:51:30 +01005484 if ((tup = PyTuple_New(3)) == NULL) {
5485 Py_CLEAR(result);
5486 break;
5487 }
5488 PyTuple_SET_ITEM(tup, 0, cert);
5489 cert = NULL;
5490 PyTuple_SET_ITEM(tup, 1, enc);
5491 enc = NULL;
5492 PyTuple_SET_ITEM(tup, 2, keyusage);
5493 keyusage = NULL;
Christian Heimes915cd3f2019-09-09 18:06:55 +02005494 if (PySet_Add(result, tup) == -1) {
5495 Py_CLEAR(result);
5496 Py_CLEAR(tup);
5497 break;
Christian Heimes44109d72013-11-22 01:51:30 +01005498 }
5499 Py_CLEAR(tup);
5500 }
5501 if (pCertCtx) {
5502 /* loop ended with an error, need to clean up context manually */
5503 CertFreeCertificateContext(pCertCtx);
Christian Heimes46bebee2013-06-09 19:03:31 +02005504 }
5505
5506 /* In error cases cert, enc and tup may not be NULL */
5507 Py_XDECREF(cert);
5508 Py_XDECREF(enc);
Christian Heimes44109d72013-11-22 01:51:30 +01005509 Py_XDECREF(keyusage);
Christian Heimes46bebee2013-06-09 19:03:31 +02005510 Py_XDECREF(tup);
5511
kctherookied93fbbf2019-03-29 00:59:06 +07005512 /* CERT_CLOSE_STORE_FORCE_FLAG forces freeing of memory for all contexts
5513 associated with the store, in this case our collection store and the
5514 associated system stores. */
5515 if (!CertCloseStore(hCollectionStore, CERT_CLOSE_STORE_FORCE_FLAG)) {
Christian Heimes46bebee2013-06-09 19:03:31 +02005516 /* This error case might shadow another exception.*/
Christian Heimes44109d72013-11-22 01:51:30 +01005517 Py_XDECREF(result);
5518 return PyErr_SetFromWindowsErr(GetLastError());
5519 }
kctherookied93fbbf2019-03-29 00:59:06 +07005520
Christian Heimes915cd3f2019-09-09 18:06:55 +02005521 /* convert set to list */
5522 if (result == NULL) {
5523 return NULL;
5524 } else {
5525 PyObject *lst = PySequence_List(result);
5526 Py_DECREF(result);
5527 return lst;
5528 }
Christian Heimes44109d72013-11-22 01:51:30 +01005529}
5530
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005531/*[clinic input]
5532_ssl.enum_crls
5533 store_name: str
5534
5535Retrieve CRLs from Windows' cert store.
5536
5537store_name may be one of 'CA', 'ROOT' or 'MY'. The system may provide
5538more cert storages, too. The function returns a list of (bytes,
5539encoding_type) tuples. The encoding_type flag can be interpreted with
5540X509_ASN_ENCODING or PKCS_7_ASN_ENCODING.
5541[clinic start generated code]*/
Christian Heimes44109d72013-11-22 01:51:30 +01005542
5543static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005544_ssl_enum_crls_impl(PyObject *module, const char *store_name)
5545/*[clinic end generated code: output=bce467f60ccd03b6 input=a1f1d7629f1c5d3d]*/
Christian Heimes44109d72013-11-22 01:51:30 +01005546{
kctherookied93fbbf2019-03-29 00:59:06 +07005547 HCERTSTORE hCollectionStore = NULL;
Christian Heimes44109d72013-11-22 01:51:30 +01005548 PCCRL_CONTEXT pCrlCtx = NULL;
5549 PyObject *crl = NULL, *enc = NULL, *tup = NULL;
5550 PyObject *result = NULL;
5551
Christian Heimes915cd3f2019-09-09 18:06:55 +02005552 result = PySet_New(NULL);
Christian Heimes44109d72013-11-22 01:51:30 +01005553 if (result == NULL) {
5554 return NULL;
5555 }
kctherookied93fbbf2019-03-29 00:59:06 +07005556 hCollectionStore = ssl_collect_certificates(store_name);
5557 if (hCollectionStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02005558 Py_DECREF(result);
5559 return PyErr_SetFromWindowsErr(GetLastError());
5560 }
Christian Heimes44109d72013-11-22 01:51:30 +01005561
kctherookied93fbbf2019-03-29 00:59:06 +07005562 while (pCrlCtx = CertEnumCRLsInStore(hCollectionStore, pCrlCtx)) {
Christian Heimes44109d72013-11-22 01:51:30 +01005563 crl = PyBytes_FromStringAndSize((const char*)pCrlCtx->pbCrlEncoded,
5564 pCrlCtx->cbCrlEncoded);
5565 if (!crl) {
5566 Py_CLEAR(result);
5567 break;
5568 }
5569 if ((enc = certEncodingType(pCrlCtx->dwCertEncodingType)) == NULL) {
5570 Py_CLEAR(result);
5571 break;
5572 }
5573 if ((tup = PyTuple_New(2)) == NULL) {
5574 Py_CLEAR(result);
5575 break;
5576 }
5577 PyTuple_SET_ITEM(tup, 0, crl);
5578 crl = NULL;
5579 PyTuple_SET_ITEM(tup, 1, enc);
5580 enc = NULL;
5581
Christian Heimes915cd3f2019-09-09 18:06:55 +02005582 if (PySet_Add(result, tup) == -1) {
5583 Py_CLEAR(result);
5584 Py_CLEAR(tup);
5585 break;
Christian Heimes44109d72013-11-22 01:51:30 +01005586 }
5587 Py_CLEAR(tup);
Christian Heimes46bebee2013-06-09 19:03:31 +02005588 }
Christian Heimes44109d72013-11-22 01:51:30 +01005589 if (pCrlCtx) {
5590 /* loop ended with an error, need to clean up context manually */
5591 CertFreeCRLContext(pCrlCtx);
5592 }
5593
5594 /* In error cases cert, enc and tup may not be NULL */
5595 Py_XDECREF(crl);
5596 Py_XDECREF(enc);
5597 Py_XDECREF(tup);
5598
kctherookied93fbbf2019-03-29 00:59:06 +07005599 /* CERT_CLOSE_STORE_FORCE_FLAG forces freeing of memory for all contexts
5600 associated with the store, in this case our collection store and the
5601 associated system stores. */
5602 if (!CertCloseStore(hCollectionStore, CERT_CLOSE_STORE_FORCE_FLAG)) {
Christian Heimes44109d72013-11-22 01:51:30 +01005603 /* This error case might shadow another exception.*/
5604 Py_XDECREF(result);
5605 return PyErr_SetFromWindowsErr(GetLastError());
5606 }
Christian Heimes915cd3f2019-09-09 18:06:55 +02005607 /* convert set to list */
5608 if (result == NULL) {
5609 return NULL;
5610 } else {
5611 PyObject *lst = PySequence_List(result);
5612 Py_DECREF(result);
5613 return lst;
5614 }
Christian Heimes46bebee2013-06-09 19:03:31 +02005615}
Christian Heimes44109d72013-11-22 01:51:30 +01005616
5617#endif /* _MSC_VER */
Bill Janssen40a0f662008-08-12 16:56:25 +00005618
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005619/* List of functions exported by this module. */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005620static PyMethodDef PySSL_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005621 _SSL__TEST_DECODE_CERT_METHODDEF
5622 _SSL_RAND_ADD_METHODDEF
5623 _SSL_RAND_BYTES_METHODDEF
5624 _SSL_RAND_PSEUDO_BYTES_METHODDEF
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005625 _SSL_RAND_STATUS_METHODDEF
5626 _SSL_GET_DEFAULT_VERIFY_PATHS_METHODDEF
5627 _SSL_ENUM_CERTIFICATES_METHODDEF
5628 _SSL_ENUM_CRLS_METHODDEF
5629 _SSL_TXT2OBJ_METHODDEF
5630 _SSL_NID2OBJ_METHODDEF
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005631 {NULL, NULL} /* Sentinel */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005632};
5633
5634
Christian Heimes7f1305e2021-04-17 20:06:38 +02005635PyDoc_STRVAR(module_doc,
5636"Implementation module for SSL socket operations. See the socket module\n\
5637for documentation.");
Christian Heimes5c36da72020-11-20 09:40:12 +01005638
5639static int
5640sslmodule_init_exceptions(PyObject *module)
5641{
Christian Heimes7f1305e2021-04-17 20:06:38 +02005642 _sslmodulestate *state = get_ssl_state(module);
Christian Heimes5c36da72020-11-20 09:40:12 +01005643 PyObject *bases = NULL;
5644
Christian Heimes7f1305e2021-04-17 20:06:38 +02005645#define add_exception(exc, name, doc, base) \
5646do { \
5647 (exc) = PyErr_NewExceptionWithDoc("ssl." name, (doc), (base), NULL); \
5648 if ((state) == NULL) goto error; \
5649 if (PyModule_AddObjectRef(module, name, exc) < 0) goto error; \
Christian Heimes5c36da72020-11-20 09:40:12 +01005650} while(0)
5651
Christian Heimes7f1305e2021-04-17 20:06:38 +02005652 state->PySSLErrorObject = PyType_FromSpecWithBases(
5653 &sslerror_type_spec, PyExc_OSError);
5654 if (state->PySSLErrorObject == NULL) {
Christian Heimes5c36da72020-11-20 09:40:12 +01005655 goto error;
5656 }
Christian Heimes7f1305e2021-04-17 20:06:38 +02005657 if (PyModule_AddObjectRef(module, "SSLError", state->PySSLErrorObject) < 0) {
Christian Heimes5c36da72020-11-20 09:40:12 +01005658 goto error;
5659 }
5660
5661 /* ssl.CertificateError used to be a subclass of ValueError */
Christian Heimes7f1305e2021-04-17 20:06:38 +02005662 bases = PyTuple_Pack(2, state->PySSLErrorObject, PyExc_ValueError);
Christian Heimes5c36da72020-11-20 09:40:12 +01005663 if (bases == NULL) {
5664 goto error;
5665 }
5666 add_exception(
Christian Heimes7f1305e2021-04-17 20:06:38 +02005667 state->PySSLCertVerificationErrorObject,
Christian Heimes5c36da72020-11-20 09:40:12 +01005668 "SSLCertVerificationError",
5669 SSLCertVerificationError_doc,
5670 bases
5671 );
5672 Py_CLEAR(bases);
5673
5674 add_exception(
Christian Heimes7f1305e2021-04-17 20:06:38 +02005675 state->PySSLZeroReturnErrorObject,
Christian Heimes5c36da72020-11-20 09:40:12 +01005676 "SSLZeroReturnError",
5677 SSLZeroReturnError_doc,
Christian Heimes7f1305e2021-04-17 20:06:38 +02005678 state->PySSLErrorObject
Christian Heimes5c36da72020-11-20 09:40:12 +01005679 );
5680
5681 add_exception(
Christian Heimes7f1305e2021-04-17 20:06:38 +02005682 state->PySSLWantWriteErrorObject,
Christian Heimes5c36da72020-11-20 09:40:12 +01005683 "SSLWantWriteError",
5684 SSLWantWriteError_doc,
Christian Heimes7f1305e2021-04-17 20:06:38 +02005685 state->PySSLErrorObject
Christian Heimes5c36da72020-11-20 09:40:12 +01005686 );
5687
5688 add_exception(
Christian Heimes7f1305e2021-04-17 20:06:38 +02005689 state->PySSLWantReadErrorObject,
Christian Heimes5c36da72020-11-20 09:40:12 +01005690 "SSLWantReadError",
5691 SSLWantReadError_doc,
Christian Heimes7f1305e2021-04-17 20:06:38 +02005692 state->PySSLErrorObject
Christian Heimes5c36da72020-11-20 09:40:12 +01005693 );
5694
5695 add_exception(
Christian Heimes7f1305e2021-04-17 20:06:38 +02005696 state->PySSLSyscallErrorObject,
Christian Heimes5c36da72020-11-20 09:40:12 +01005697 "SSLSyscallError",
5698 SSLSyscallError_doc,
Christian Heimes7f1305e2021-04-17 20:06:38 +02005699 state->PySSLErrorObject
Christian Heimes5c36da72020-11-20 09:40:12 +01005700 );
5701
5702 add_exception(
Christian Heimes7f1305e2021-04-17 20:06:38 +02005703 state->PySSLEOFErrorObject,
Christian Heimes5c36da72020-11-20 09:40:12 +01005704 "SSLEOFError",
5705 SSLEOFError_doc,
Christian Heimes7f1305e2021-04-17 20:06:38 +02005706 state->PySSLErrorObject
Christian Heimes5c36da72020-11-20 09:40:12 +01005707 );
5708#undef add_exception
5709
5710 return 0;
5711 error:
5712 Py_XDECREF(bases);
5713 return -1;
5714}
5715
5716static int
5717sslmodule_init_socketapi(PyObject *module)
5718{
Christian Heimes7f1305e2021-04-17 20:06:38 +02005719 _sslmodulestate *state = get_ssl_state(module);
5720 PySocketModule_APIObject *sockmod = PySocketModule_ImportModuleAndAPI();
Christian Heimes5c36da72020-11-20 09:40:12 +01005721
Christian Heimes7f1305e2021-04-17 20:06:38 +02005722 if ((sockmod == NULL) || (sockmod->Sock_Type == NULL)) {
Christian Heimes5c36da72020-11-20 09:40:12 +01005723 return -1;
Christian Heimes5c36da72020-11-20 09:40:12 +01005724 }
Christian Heimes7f1305e2021-04-17 20:06:38 +02005725 state->Sock_Type = sockmod->Sock_Type;
5726 Py_INCREF(state->Sock_Type);
Christian Heimes5c36da72020-11-20 09:40:12 +01005727 return 0;
5728}
Christian Heimesc941e622017-09-05 15:47:11 +02005729
Christian Heimes5c36da72020-11-20 09:40:12 +01005730static int
5731sslmodule_init_constants(PyObject *m)
5732{
Christian Heimes7f1305e2021-04-17 20:06:38 +02005733
Christian Heimes892d66e2018-01-29 14:10:18 +01005734 PyModule_AddStringConstant(m, "_DEFAULT_CIPHERS",
5735 PY_SSL_DEFAULT_CIPHER_STRING);
5736
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005737 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
5738 PY_SSL_ERROR_ZERO_RETURN);
5739 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
5740 PY_SSL_ERROR_WANT_READ);
5741 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
5742 PY_SSL_ERROR_WANT_WRITE);
5743 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
5744 PY_SSL_ERROR_WANT_X509_LOOKUP);
5745 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
5746 PY_SSL_ERROR_SYSCALL);
5747 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
5748 PY_SSL_ERROR_SSL);
5749 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
5750 PY_SSL_ERROR_WANT_CONNECT);
5751 /* non ssl.h errorcodes */
5752 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
5753 PY_SSL_ERROR_EOF);
5754 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
5755 PY_SSL_ERROR_INVALID_ERROR_CODE);
5756 /* cert requirements */
5757 PyModule_AddIntConstant(m, "CERT_NONE",
5758 PY_SSL_CERT_NONE);
5759 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
5760 PY_SSL_CERT_OPTIONAL);
5761 PyModule_AddIntConstant(m, "CERT_REQUIRED",
5762 PY_SSL_CERT_REQUIRED);
Christian Heimes22587792013-11-21 23:56:13 +01005763 /* CRL verification for verification_flags */
5764 PyModule_AddIntConstant(m, "VERIFY_DEFAULT",
5765 0);
5766 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_LEAF",
5767 X509_V_FLAG_CRL_CHECK);
5768 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_CHAIN",
5769 X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
5770 PyModule_AddIntConstant(m, "VERIFY_X509_STRICT",
5771 X509_V_FLAG_X509_STRICT);
Chris Burre0b4aa02021-03-18 09:24:01 +01005772 PyModule_AddIntConstant(m, "VERIFY_ALLOW_PROXY_CERTS",
5773 X509_V_FLAG_ALLOW_PROXY_CERTS);
Benjamin Peterson990fcaa2015-03-04 22:49:41 -05005774 PyModule_AddIntConstant(m, "VERIFY_X509_TRUSTED_FIRST",
5775 X509_V_FLAG_TRUSTED_FIRST);
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00005776
l0x64d97522021-04-19 13:51:18 +02005777#ifdef X509_V_FLAG_PARTIAL_CHAIN
5778 PyModule_AddIntConstant(m, "VERIFY_X509_PARTIAL_CHAIN",
5779 X509_V_FLAG_PARTIAL_CHAIN);
5780#endif
5781
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01005782 /* Alert Descriptions from ssl.h */
5783 /* note RESERVED constants no longer intended for use have been removed */
5784 /* http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-6 */
5785
5786#define ADD_AD_CONSTANT(s) \
5787 PyModule_AddIntConstant(m, "ALERT_DESCRIPTION_"#s, \
5788 SSL_AD_##s)
5789
5790 ADD_AD_CONSTANT(CLOSE_NOTIFY);
5791 ADD_AD_CONSTANT(UNEXPECTED_MESSAGE);
5792 ADD_AD_CONSTANT(BAD_RECORD_MAC);
5793 ADD_AD_CONSTANT(RECORD_OVERFLOW);
5794 ADD_AD_CONSTANT(DECOMPRESSION_FAILURE);
5795 ADD_AD_CONSTANT(HANDSHAKE_FAILURE);
5796 ADD_AD_CONSTANT(BAD_CERTIFICATE);
5797 ADD_AD_CONSTANT(UNSUPPORTED_CERTIFICATE);
5798 ADD_AD_CONSTANT(CERTIFICATE_REVOKED);
5799 ADD_AD_CONSTANT(CERTIFICATE_EXPIRED);
5800 ADD_AD_CONSTANT(CERTIFICATE_UNKNOWN);
5801 ADD_AD_CONSTANT(ILLEGAL_PARAMETER);
5802 ADD_AD_CONSTANT(UNKNOWN_CA);
5803 ADD_AD_CONSTANT(ACCESS_DENIED);
5804 ADD_AD_CONSTANT(DECODE_ERROR);
5805 ADD_AD_CONSTANT(DECRYPT_ERROR);
5806 ADD_AD_CONSTANT(PROTOCOL_VERSION);
5807 ADD_AD_CONSTANT(INSUFFICIENT_SECURITY);
5808 ADD_AD_CONSTANT(INTERNAL_ERROR);
5809 ADD_AD_CONSTANT(USER_CANCELLED);
5810 ADD_AD_CONSTANT(NO_RENEGOTIATION);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01005811 /* Not all constants are in old OpenSSL versions */
Antoine Pitrou912fbff2013-03-30 16:29:32 +01005812#ifdef SSL_AD_UNSUPPORTED_EXTENSION
5813 ADD_AD_CONSTANT(UNSUPPORTED_EXTENSION);
5814#endif
5815#ifdef SSL_AD_CERTIFICATE_UNOBTAINABLE
5816 ADD_AD_CONSTANT(CERTIFICATE_UNOBTAINABLE);
5817#endif
5818#ifdef SSL_AD_UNRECOGNIZED_NAME
5819 ADD_AD_CONSTANT(UNRECOGNIZED_NAME);
5820#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01005821#ifdef SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE
5822 ADD_AD_CONSTANT(BAD_CERTIFICATE_STATUS_RESPONSE);
5823#endif
5824#ifdef SSL_AD_BAD_CERTIFICATE_HASH_VALUE
5825 ADD_AD_CONSTANT(BAD_CERTIFICATE_HASH_VALUE);
5826#endif
5827#ifdef SSL_AD_UNKNOWN_PSK_IDENTITY
5828 ADD_AD_CONSTANT(UNKNOWN_PSK_IDENTITY);
5829#endif
5830
5831#undef ADD_AD_CONSTANT
5832
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005833 /* protocol versions */
Victor Stinner3de49192011-05-09 00:42:58 +02005834#ifndef OPENSSL_NO_SSL2
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005835 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
5836 PY_SSL_VERSION_SSL2);
Victor Stinner3de49192011-05-09 00:42:58 +02005837#endif
Benjamin Petersone32467c2014-12-05 21:59:35 -05005838#ifndef OPENSSL_NO_SSL3
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005839 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
5840 PY_SSL_VERSION_SSL3);
Benjamin Petersone32467c2014-12-05 21:59:35 -05005841#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005842 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
Christian Heimes598894f2016-09-05 23:19:05 +02005843 PY_SSL_VERSION_TLS);
5844 PyModule_AddIntConstant(m, "PROTOCOL_TLS",
5845 PY_SSL_VERSION_TLS);
Christian Heimes5fe668c2016-09-12 00:01:11 +02005846 PyModule_AddIntConstant(m, "PROTOCOL_TLS_CLIENT",
5847 PY_SSL_VERSION_TLS_CLIENT);
5848 PyModule_AddIntConstant(m, "PROTOCOL_TLS_SERVER",
5849 PY_SSL_VERSION_TLS_SERVER);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005850 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
5851 PY_SSL_VERSION_TLS1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01005852 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_1",
5853 PY_SSL_VERSION_TLS1_1);
5854 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_2",
5855 PY_SSL_VERSION_TLS1_2);
Antoine Pitrou04f6a322010-04-05 21:40:07 +00005856
Antoine Pitroub5218772010-05-21 09:56:06 +00005857 /* protocol options */
Antoine Pitrou3f366312012-01-27 09:50:45 +01005858 PyModule_AddIntConstant(m, "OP_ALL",
5859 SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
Antoine Pitroub5218772010-05-21 09:56:06 +00005860 PyModule_AddIntConstant(m, "OP_NO_SSLv2", SSL_OP_NO_SSLv2);
5861 PyModule_AddIntConstant(m, "OP_NO_SSLv3", SSL_OP_NO_SSLv3);
5862 PyModule_AddIntConstant(m, "OP_NO_TLSv1", SSL_OP_NO_TLSv1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01005863 PyModule_AddIntConstant(m, "OP_NO_TLSv1_1", SSL_OP_NO_TLSv1_1);
5864 PyModule_AddIntConstant(m, "OP_NO_TLSv1_2", SSL_OP_NO_TLSv1_2);
Christian Heimescb5b68a2017-09-07 18:07:00 -07005865#ifdef SSL_OP_NO_TLSv1_3
5866 PyModule_AddIntConstant(m, "OP_NO_TLSv1_3", SSL_OP_NO_TLSv1_3);
5867#else
5868 PyModule_AddIntConstant(m, "OP_NO_TLSv1_3", 0);
5869#endif
Antoine Pitrou6db49442011-12-19 13:27:11 +01005870 PyModule_AddIntConstant(m, "OP_CIPHER_SERVER_PREFERENCE",
5871 SSL_OP_CIPHER_SERVER_PREFERENCE);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01005872 PyModule_AddIntConstant(m, "OP_SINGLE_DH_USE", SSL_OP_SINGLE_DH_USE);
Christian Heimes99a65702016-09-10 23:44:53 +02005873 PyModule_AddIntConstant(m, "OP_NO_TICKET", SSL_OP_NO_TICKET);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01005874#ifdef SSL_OP_SINGLE_ECDH_USE
Antoine Pitrou923df6f2011-12-19 17:16:51 +01005875 PyModule_AddIntConstant(m, "OP_SINGLE_ECDH_USE", SSL_OP_SINGLE_ECDH_USE);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01005876#endif
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01005877#ifdef SSL_OP_NO_COMPRESSION
5878 PyModule_AddIntConstant(m, "OP_NO_COMPRESSION",
5879 SSL_OP_NO_COMPRESSION);
5880#endif
Christian Heimes05d9fe32018-02-27 08:55:39 +01005881#ifdef SSL_OP_ENABLE_MIDDLEBOX_COMPAT
5882 PyModule_AddIntConstant(m, "OP_ENABLE_MIDDLEBOX_COMPAT",
5883 SSL_OP_ENABLE_MIDDLEBOX_COMPAT);
5884#endif
Christian Heimes67c48012018-05-15 16:25:40 -04005885#ifdef SSL_OP_NO_RENEGOTIATION
5886 PyModule_AddIntConstant(m, "OP_NO_RENEGOTIATION",
5887 SSL_OP_NO_RENEGOTIATION);
5888#endif
Christian Heimes6f37ebc2021-04-09 17:59:21 +02005889#ifdef SSL_OP_IGNORE_UNEXPECTED_EOF
5890 PyModule_AddIntConstant(m, "OP_IGNORE_UNEXPECTED_EOF",
5891 SSL_OP_IGNORE_UNEXPECTED_EOF);
5892#endif
Antoine Pitroub5218772010-05-21 09:56:06 +00005893
Christian Heimes61d478c2018-01-27 15:51:38 +01005894#ifdef X509_CHECK_FLAG_ALWAYS_CHECK_SUBJECT
5895 PyModule_AddIntConstant(m, "HOSTFLAG_ALWAYS_CHECK_SUBJECT",
5896 X509_CHECK_FLAG_ALWAYS_CHECK_SUBJECT);
5897#endif
5898#ifdef X509_CHECK_FLAG_NEVER_CHECK_SUBJECT
5899 PyModule_AddIntConstant(m, "HOSTFLAG_NEVER_CHECK_SUBJECT",
5900 X509_CHECK_FLAG_NEVER_CHECK_SUBJECT);
5901#endif
5902#ifdef X509_CHECK_FLAG_NO_WILDCARDS
5903 PyModule_AddIntConstant(m, "HOSTFLAG_NO_WILDCARDS",
5904 X509_CHECK_FLAG_NO_WILDCARDS);
5905#endif
5906#ifdef X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS
5907 PyModule_AddIntConstant(m, "HOSTFLAG_NO_PARTIAL_WILDCARDS",
5908 X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS);
5909#endif
5910#ifdef X509_CHECK_FLAG_MULTI_LABEL_WILDCARDS
5911 PyModule_AddIntConstant(m, "HOSTFLAG_MULTI_LABEL_WILDCARDS",
5912 X509_CHECK_FLAG_MULTI_LABEL_WILDCARDS);
5913#endif
5914#ifdef X509_CHECK_FLAG_SINGLE_LABEL_SUBDOMAINS
5915 PyModule_AddIntConstant(m, "HOSTFLAG_SINGLE_LABEL_SUBDOMAINS",
5916 X509_CHECK_FLAG_SINGLE_LABEL_SUBDOMAINS);
5917#endif
5918
Christian Heimes666991f2021-04-26 15:01:40 +02005919 /* file types */
5920 PyModule_AddIntConstant(m, "ENCODING_PEM", PY_SSL_ENCODING_PEM);
5921 PyModule_AddIntConstant(m, "ENCODING_DER", PY_SSL_ENCODING_DER);
5922
Christian Heimes698dde12018-02-27 11:54:43 +01005923 /* protocol versions */
5924 PyModule_AddIntConstant(m, "PROTO_MINIMUM_SUPPORTED",
5925 PY_PROTO_MINIMUM_SUPPORTED);
5926 PyModule_AddIntConstant(m, "PROTO_MAXIMUM_SUPPORTED",
5927 PY_PROTO_MAXIMUM_SUPPORTED);
5928 PyModule_AddIntConstant(m, "PROTO_SSLv3", PY_PROTO_SSLv3);
5929 PyModule_AddIntConstant(m, "PROTO_TLSv1", PY_PROTO_TLSv1);
5930 PyModule_AddIntConstant(m, "PROTO_TLSv1_1", PY_PROTO_TLSv1_1);
5931 PyModule_AddIntConstant(m, "PROTO_TLSv1_2", PY_PROTO_TLSv1_2);
5932 PyModule_AddIntConstant(m, "PROTO_TLSv1_3", PY_PROTO_TLSv1_3);
Antoine Pitroud5323212010-10-22 18:19:07 +00005933
Victor Stinnerb37672d2018-11-22 03:37:50 +01005934#define addbool(m, key, value) \
5935 do { \
5936 PyObject *bool_obj = (value) ? Py_True : Py_False; \
5937 Py_INCREF(bool_obj); \
5938 PyModule_AddObject((m), (key), bool_obj); \
5939 } while (0)
Christian Heimes698dde12018-02-27 11:54:43 +01005940
Christian Heimes698dde12018-02-27 11:54:43 +01005941 addbool(m, "HAS_SNI", 1);
Christian Heimes698dde12018-02-27 11:54:43 +01005942 addbool(m, "HAS_TLS_UNIQUE", 1);
Christian Heimes698dde12018-02-27 11:54:43 +01005943 addbool(m, "HAS_ECDH", 1);
Christian Heimes698dde12018-02-27 11:54:43 +01005944 addbool(m, "HAS_NPN", 0);
Christian Heimes698dde12018-02-27 11:54:43 +01005945 addbool(m, "HAS_ALPN", 1);
Christian Heimes698dde12018-02-27 11:54:43 +01005946
5947#if defined(SSL2_VERSION) && !defined(OPENSSL_NO_SSL2)
5948 addbool(m, "HAS_SSLv2", 1);
5949#else
5950 addbool(m, "HAS_SSLv2", 0);
5951#endif
5952
5953#if defined(SSL3_VERSION) && !defined(OPENSSL_NO_SSL3)
5954 addbool(m, "HAS_SSLv3", 1);
5955#else
5956 addbool(m, "HAS_SSLv3", 0);
5957#endif
5958
5959#if defined(TLS1_VERSION) && !defined(OPENSSL_NO_TLS1)
5960 addbool(m, "HAS_TLSv1", 1);
5961#else
5962 addbool(m, "HAS_TLSv1", 0);
5963#endif
5964
5965#if defined(TLS1_1_VERSION) && !defined(OPENSSL_NO_TLS1_1)
5966 addbool(m, "HAS_TLSv1_1", 1);
5967#else
5968 addbool(m, "HAS_TLSv1_1", 0);
5969#endif
5970
5971#if defined(TLS1_2_VERSION) && !defined(OPENSSL_NO_TLS1_2)
5972 addbool(m, "HAS_TLSv1_2", 1);
5973#else
5974 addbool(m, "HAS_TLSv1_2", 0);
5975#endif
Benjamin Petersoncca27322015-01-23 16:35:37 -05005976
Christian Heimescb5b68a2017-09-07 18:07:00 -07005977#if defined(TLS1_3_VERSION) && !defined(OPENSSL_NO_TLS1_3)
Christian Heimes698dde12018-02-27 11:54:43 +01005978 addbool(m, "HAS_TLSv1_3", 1);
Christian Heimescb5b68a2017-09-07 18:07:00 -07005979#else
Christian Heimes698dde12018-02-27 11:54:43 +01005980 addbool(m, "HAS_TLSv1_3", 0);
Christian Heimescb5b68a2017-09-07 18:07:00 -07005981#endif
Christian Heimescb5b68a2017-09-07 18:07:00 -07005982
Christian Heimes5c36da72020-11-20 09:40:12 +01005983 return 0;
5984}
5985
Christian Heimes7f1305e2021-04-17 20:06:38 +02005986static int
5987sslmodule_init_errorcodes(PyObject *module)
5988{
5989 _sslmodulestate *state = get_ssl_state(module);
Christian Heimes5c36da72020-11-20 09:40:12 +01005990
Christian Heimes7f1305e2021-04-17 20:06:38 +02005991 struct py_ssl_error_code *errcode;
5992 struct py_ssl_library_code *libcode;
Christian Heimes5c36da72020-11-20 09:40:12 +01005993
Christian Heimes7f1305e2021-04-17 20:06:38 +02005994 /* Mappings for error codes */
5995 state->err_codes_to_names = PyDict_New();
5996 if (state->err_codes_to_names == NULL)
5997 return -1;
5998 state->err_names_to_codes = PyDict_New();
5999 if (state->err_names_to_codes == NULL)
6000 return -1;
6001 state->lib_codes_to_names = PyDict_New();
6002 if (state->lib_codes_to_names == NULL)
6003 return -1;
6004
6005 errcode = error_codes;
6006 while (errcode->mnemonic != NULL) {
6007 PyObject *mnemo, *key;
6008 mnemo = PyUnicode_FromString(errcode->mnemonic);
6009 key = Py_BuildValue("ii", errcode->library, errcode->reason);
6010 if (mnemo == NULL || key == NULL)
6011 return -1;
6012 if (PyDict_SetItem(state->err_codes_to_names, key, mnemo))
6013 return -1;
6014 if (PyDict_SetItem(state->err_names_to_codes, mnemo, key))
6015 return -1;
6016 Py_DECREF(key);
6017 Py_DECREF(mnemo);
6018 errcode++;
6019 }
6020
6021 libcode = library_codes;
6022 while (libcode->library != NULL) {
6023 PyObject *mnemo, *key;
6024 key = PyLong_FromLong(libcode->code);
6025 mnemo = PyUnicode_FromString(libcode->library);
6026 if (key == NULL || mnemo == NULL)
6027 return -1;
6028 if (PyDict_SetItem(state->lib_codes_to_names, key, mnemo))
6029 return -1;
6030 Py_DECREF(key);
6031 Py_DECREF(mnemo);
6032 libcode++;
6033 }
6034
6035 if (PyModule_AddObjectRef(module, "err_codes_to_names", state->err_codes_to_names))
6036 return -1;
6037 if (PyModule_AddObjectRef(module, "err_names_to_codes", state->err_names_to_codes))
6038 return -1;
6039 if (PyModule_AddObjectRef(module, "lib_codes_to_names", state->lib_codes_to_names))
6040 return -1;
6041
6042 return 0;
6043}
6044
6045static void
6046parse_openssl_version(unsigned long libver,
6047 unsigned int *major, unsigned int *minor,
6048 unsigned int *fix, unsigned int *patch,
6049 unsigned int *status)
6050{
6051 *status = libver & 0xF;
6052 libver >>= 4;
6053 *patch = libver & 0xFF;
6054 libver >>= 8;
6055 *fix = libver & 0xFF;
6056 libver >>= 8;
6057 *minor = libver & 0xFF;
6058 libver >>= 8;
6059 *major = libver & 0xFF;
6060}
6061
6062static int
6063sslmodule_init_versioninfo(PyObject *m)
6064{
6065 PyObject *r;
6066 unsigned long libver;
6067 unsigned int major, minor, fix, patch, status;
6068
6069 /* OpenSSL version */
6070 /* SSLeay() gives us the version of the library linked against,
6071 which could be different from the headers version.
6072 */
6073 libver = OpenSSL_version_num();
6074 r = PyLong_FromUnsignedLong(libver);
6075 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r))
6076 return -1;
6077
6078 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
6079 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
6080 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r))
6081 return -1;
6082
6083 r = PyUnicode_FromString(OpenSSL_version(OPENSSL_VERSION));
6084 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r))
6085 return -1;
6086
6087 libver = OPENSSL_VERSION_NUMBER;
6088 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
6089 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
6090 if (r == NULL || PyModule_AddObject(m, "_OPENSSL_API_VERSION", r))
6091 return -1;
6092
6093 return 0;
6094}
6095
6096static int
6097sslmodule_init_types(PyObject *module)
6098{
6099 _sslmodulestate *state = get_ssl_state(module);
6100
6101 state->PySSLContext_Type = (PyTypeObject *)PyType_FromModuleAndSpec(
6102 module, &PySSLContext_spec, NULL
6103 );
6104 if (state->PySSLContext_Type == NULL)
6105 return -1;
6106
6107 state->PySSLSocket_Type = (PyTypeObject *)PyType_FromModuleAndSpec(
6108 module, &PySSLSocket_spec, NULL
6109 );
6110 if (state->PySSLSocket_Type == NULL)
6111 return -1;
6112
6113 state->PySSLMemoryBIO_Type = (PyTypeObject *)PyType_FromModuleAndSpec(
6114 module, &PySSLMemoryBIO_spec, NULL
6115 );
6116 if (state->PySSLMemoryBIO_Type == NULL)
6117 return -1;
6118
6119 state->PySSLSession_Type = (PyTypeObject *)PyType_FromModuleAndSpec(
6120 module, &PySSLSession_spec, NULL
6121 );
6122 if (state->PySSLSession_Type == NULL)
6123 return -1;
6124
Christian Heimes666991f2021-04-26 15:01:40 +02006125 state->PySSLCertificate_Type = (PyTypeObject *)PyType_FromModuleAndSpec(
6126 module, &PySSLCertificate_spec, NULL
6127 );
6128 if (state->PySSLCertificate_Type == NULL)
6129 return -1;
6130
Christian Heimes7f1305e2021-04-17 20:06:38 +02006131 if (PyModule_AddType(module, state->PySSLContext_Type))
6132 return -1;
6133 if (PyModule_AddType(module, state->PySSLSocket_Type))
6134 return -1;
6135 if (PyModule_AddType(module, state->PySSLMemoryBIO_Type))
6136 return -1;
6137 if (PyModule_AddType(module, state->PySSLSession_Type))
6138 return -1;
Christian Heimes666991f2021-04-26 15:01:40 +02006139 if (PyModule_AddType(module, state->PySSLCertificate_Type))
6140 return -1;
Christian Heimes7f1305e2021-04-17 20:06:38 +02006141 return 0;
6142}
6143
6144static PyModuleDef_Slot sslmodule_slots[] = {
6145 {Py_mod_exec, sslmodule_init_types},
6146 {Py_mod_exec, sslmodule_init_exceptions},
6147 {Py_mod_exec, sslmodule_init_socketapi},
6148 {Py_mod_exec, sslmodule_init_errorcodes},
6149 {Py_mod_exec, sslmodule_init_constants},
6150 {Py_mod_exec, sslmodule_init_versioninfo},
6151 {0, NULL}
6152};
6153
6154static int
6155sslmodule_traverse(PyObject *m, visitproc visit, void *arg)
6156{
6157 _sslmodulestate *state = get_ssl_state(m);
6158
6159 Py_VISIT(state->PySSLContext_Type);
6160 Py_VISIT(state->PySSLSocket_Type);
6161 Py_VISIT(state->PySSLMemoryBIO_Type);
6162 Py_VISIT(state->PySSLSession_Type);
Christian Heimes666991f2021-04-26 15:01:40 +02006163 Py_VISIT(state->PySSLCertificate_Type);
Christian Heimes7f1305e2021-04-17 20:06:38 +02006164 Py_VISIT(state->PySSLErrorObject);
6165 Py_VISIT(state->PySSLCertVerificationErrorObject);
6166 Py_VISIT(state->PySSLZeroReturnErrorObject);
6167 Py_VISIT(state->PySSLWantReadErrorObject);
6168 Py_VISIT(state->PySSLWantWriteErrorObject);
6169 Py_VISIT(state->PySSLSyscallErrorObject);
6170 Py_VISIT(state->PySSLEOFErrorObject);
6171 Py_VISIT(state->err_codes_to_names);
6172 Py_VISIT(state->err_names_to_codes);
6173 Py_VISIT(state->lib_codes_to_names);
6174 Py_VISIT(state->Sock_Type);
6175
6176 return 0;
6177}
6178
6179static int
6180sslmodule_clear(PyObject *m)
6181{
6182 _sslmodulestate *state = get_ssl_state(m);
6183
6184 Py_CLEAR(state->PySSLContext_Type);
6185 Py_CLEAR(state->PySSLSocket_Type);
6186 Py_CLEAR(state->PySSLMemoryBIO_Type);
6187 Py_CLEAR(state->PySSLSession_Type);
Christian Heimes666991f2021-04-26 15:01:40 +02006188 Py_CLEAR(state->PySSLCertificate_Type);
Christian Heimes7f1305e2021-04-17 20:06:38 +02006189 Py_CLEAR(state->PySSLErrorObject);
6190 Py_CLEAR(state->PySSLCertVerificationErrorObject);
6191 Py_CLEAR(state->PySSLZeroReturnErrorObject);
6192 Py_CLEAR(state->PySSLWantReadErrorObject);
6193 Py_CLEAR(state->PySSLWantWriteErrorObject);
6194 Py_CLEAR(state->PySSLSyscallErrorObject);
6195 Py_CLEAR(state->PySSLEOFErrorObject);
6196 Py_CLEAR(state->err_codes_to_names);
6197 Py_CLEAR(state->err_names_to_codes);
6198 Py_CLEAR(state->lib_codes_to_names);
6199 Py_CLEAR(state->Sock_Type);
6200
6201 return 0;
6202}
6203
6204static void
6205sslmodule_free(void *m)
6206{
6207 sslmodule_clear((PyObject *)m);
6208}
6209
6210static struct PyModuleDef _sslmodule_def = {
Christian Heimes5c36da72020-11-20 09:40:12 +01006211 PyModuleDef_HEAD_INIT,
Christian Heimes7f1305e2021-04-17 20:06:38 +02006212 .m_name = "_ssl",
6213 .m_doc = module_doc,
6214 .m_size = sizeof(_sslmodulestate),
6215 .m_methods = PySSL_methods,
6216 .m_slots = sslmodule_slots,
6217 .m_traverse = sslmodule_traverse,
6218 .m_clear = sslmodule_clear,
6219 .m_free = sslmodule_free
Christian Heimes5c36da72020-11-20 09:40:12 +01006220};
6221
6222PyMODINIT_FUNC
6223PyInit__ssl(void)
6224{
Christian Heimes7f1305e2021-04-17 20:06:38 +02006225 return PyModuleDef_Init(&_sslmodule_def);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00006226}