blob: af2520432a64e7accec2f318347958c18af945fd [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;
Miss Islington (bot)633d0f92022-02-21 01:37:26 -08001056 PyObject *pyattr;
1057 PyObject *pyname = _asn1obj2py(state, name, 0);
Guido van Rossumf06628b2007-11-21 20:01:53 +00001058
Miss Islington (bot)633d0f92022-02-21 01:37:26 -08001059 if (pyname == NULL) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02001060 _setSSLError(state, NULL, 0, __FILE__, __LINE__);
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001061 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001062 }
Miss Islington (bot)633d0f92022-02-21 01:37:26 -08001063
1064 if (ASN1_STRING_type(value) == V_ASN1_BIT_STRING) {
1065 buflen = ASN1_STRING_length(value);
1066 pyattr = Py_BuildValue("Ny#", pyname, ASN1_STRING_get0_data(value), buflen);
1067 } else {
1068 unsigned char *valuebuf = NULL;
1069 buflen = ASN1_STRING_to_UTF8(&valuebuf, value);
1070 if (buflen < 0) {
1071 _setSSLError(state, NULL, 0, __FILE__, __LINE__);
1072 Py_DECREF(pyname);
1073 return NULL;
1074 }
1075 pyattr = Py_BuildValue("Ns#", pyname, valuebuf, buflen);
1076 OPENSSL_free(valuebuf);
1077 }
1078 return pyattr;
Thomas Woutersed03b412007-08-28 21:37:11 +00001079}
1080
1081static PyObject *
Christian Heimes7f1305e2021-04-17 20:06:38 +02001082_create_tuple_for_X509_NAME (_sslmodulestate *state, X509_NAME *xname)
Thomas Woutersed03b412007-08-28 21:37:11 +00001083{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001084 PyObject *dn = NULL; /* tuple which represents the "distinguished name" */
1085 PyObject *rdn = NULL; /* tuple to hold a "relative distinguished name" */
1086 PyObject *rdnt;
1087 PyObject *attr = NULL; /* tuple to hold an attribute */
1088 int entry_count = X509_NAME_entry_count(xname);
1089 X509_NAME_ENTRY *entry;
1090 ASN1_OBJECT *name;
1091 ASN1_STRING *value;
1092 int index_counter;
1093 int rdn_level = -1;
1094 int retcode;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001095
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001096 dn = PyList_New(0);
1097 if (dn == NULL)
1098 return NULL;
1099 /* now create another tuple to hold the top-level RDN */
1100 rdn = PyList_New(0);
1101 if (rdn == NULL)
1102 goto fail0;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001103
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001104 for (index_counter = 0;
1105 index_counter < entry_count;
1106 index_counter++)
1107 {
1108 entry = X509_NAME_get_entry(xname, index_counter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001109
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001110 /* check to see if we've gotten to a new RDN */
1111 if (rdn_level >= 0) {
Christian Heimes598894f2016-09-05 23:19:05 +02001112 if (rdn_level != X509_NAME_ENTRY_set(entry)) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001113 /* yes, new RDN */
1114 /* add old RDN to DN */
1115 rdnt = PyList_AsTuple(rdn);
1116 Py_DECREF(rdn);
1117 if (rdnt == NULL)
1118 goto fail0;
1119 retcode = PyList_Append(dn, rdnt);
1120 Py_DECREF(rdnt);
1121 if (retcode < 0)
1122 goto fail0;
1123 /* create new RDN */
1124 rdn = PyList_New(0);
1125 if (rdn == NULL)
1126 goto fail0;
1127 }
1128 }
Christian Heimes598894f2016-09-05 23:19:05 +02001129 rdn_level = X509_NAME_ENTRY_set(entry);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001130
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001131 /* now add this attribute to the current RDN */
1132 name = X509_NAME_ENTRY_get_object(entry);
1133 value = X509_NAME_ENTRY_get_data(entry);
Christian Heimes7f1305e2021-04-17 20:06:38 +02001134 attr = _create_tuple_for_attribute(state, name, value);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001135 /*
1136 fprintf(stderr, "RDN level %d, attribute %s: %s\n",
1137 entry->set,
1138 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 0)),
1139 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 1)));
1140 */
1141 if (attr == NULL)
1142 goto fail1;
1143 retcode = PyList_Append(rdn, attr);
1144 Py_DECREF(attr);
1145 if (retcode < 0)
1146 goto fail1;
1147 }
1148 /* now, there's typically a dangling RDN */
Antoine Pitrou2f5a1632012-02-15 22:25:27 +01001149 if (rdn != NULL) {
1150 if (PyList_GET_SIZE(rdn) > 0) {
1151 rdnt = PyList_AsTuple(rdn);
1152 Py_DECREF(rdn);
1153 if (rdnt == NULL)
1154 goto fail0;
1155 retcode = PyList_Append(dn, rdnt);
1156 Py_DECREF(rdnt);
1157 if (retcode < 0)
1158 goto fail0;
1159 }
1160 else {
1161 Py_DECREF(rdn);
1162 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001163 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001164
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001165 /* convert list to tuple */
1166 rdnt = PyList_AsTuple(dn);
1167 Py_DECREF(dn);
1168 if (rdnt == NULL)
1169 return NULL;
1170 return rdnt;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001171
1172 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001173 Py_XDECREF(rdn);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001174
1175 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001176 Py_XDECREF(dn);
1177 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001178}
1179
1180static PyObject *
Christian Heimes7f1305e2021-04-17 20:06:38 +02001181_get_peer_alt_names (_sslmodulestate *state, X509 *certificate) {
Guido van Rossumf06628b2007-11-21 20:01:53 +00001182
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001183 /* this code follows the procedure outlined in
1184 OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print()
1185 function to extract the STACK_OF(GENERAL_NAME),
1186 then iterates through the stack to add the
1187 names. */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001188
Alex Gaynorb87c0df2017-06-06 07:53:11 -04001189 int j;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001190 PyObject *peer_alt_names = Py_None;
Christian Heimes60bf2fc2013-09-05 16:04:35 +02001191 PyObject *v = NULL, *t;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001192 GENERAL_NAMES *names = NULL;
1193 GENERAL_NAME *name;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001194 BIO *biobuf = NULL;
1195 char buf[2048];
1196 char *vptr;
1197 int len;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001198
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001199 if (certificate == NULL)
1200 return peer_alt_names;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001201
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001202 /* get a memory buffer */
1203 biobuf = BIO_new(BIO_s_mem());
Zackery Spytz4c49da02018-12-07 03:11:30 -07001204 if (biobuf == NULL) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02001205 PyErr_SetString(state->PySSLErrorObject, "failed to allocate BIO");
Zackery Spytz4c49da02018-12-07 03:11:30 -07001206 return NULL;
1207 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001208
Alex Gaynorb87c0df2017-06-06 07:53:11 -04001209 names = (GENERAL_NAMES *)X509_get_ext_d2i(
1210 certificate, NID_subject_alt_name, NULL, NULL);
1211 if (names != NULL) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001212 if (peer_alt_names == Py_None) {
1213 peer_alt_names = PyList_New(0);
1214 if (peer_alt_names == NULL)
1215 goto fail;
1216 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001217
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001218 for(j = 0; j < sk_GENERAL_NAME_num(names); j++) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001219 /* get a rendering of each name in the set of names */
Christian Heimes824f7f32013-08-17 00:54:47 +02001220 int gntype;
1221 ASN1_STRING *as = NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001222
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001223 name = sk_GENERAL_NAME_value(names, j);
Christian Heimes474afdd2013-08-17 17:18:56 +02001224 gntype = name->type;
Christian Heimes824f7f32013-08-17 00:54:47 +02001225 switch (gntype) {
1226 case GEN_DIRNAME:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001227 /* we special-case DirName as a tuple of
1228 tuples of attributes */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001229
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001230 t = PyTuple_New(2);
1231 if (t == NULL) {
1232 goto fail;
1233 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001234
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001235 v = PyUnicode_FromString("DirName");
1236 if (v == NULL) {
1237 Py_DECREF(t);
1238 goto fail;
1239 }
1240 PyTuple_SET_ITEM(t, 0, v);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001241
Christian Heimes7f1305e2021-04-17 20:06:38 +02001242 v = _create_tuple_for_X509_NAME(state, name->d.dirn);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001243 if (v == NULL) {
1244 Py_DECREF(t);
1245 goto fail;
1246 }
1247 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +02001248 break;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001249
Christian Heimes824f7f32013-08-17 00:54:47 +02001250 case GEN_EMAIL:
1251 case GEN_DNS:
1252 case GEN_URI:
1253 /* GENERAL_NAME_print() doesn't handle NULL bytes in ASN1_string
1254 correctly, CVE-2013-4238 */
1255 t = PyTuple_New(2);
1256 if (t == NULL)
1257 goto fail;
1258 switch (gntype) {
1259 case GEN_EMAIL:
1260 v = PyUnicode_FromString("email");
1261 as = name->d.rfc822Name;
1262 break;
1263 case GEN_DNS:
1264 v = PyUnicode_FromString("DNS");
1265 as = name->d.dNSName;
1266 break;
1267 case GEN_URI:
1268 v = PyUnicode_FromString("URI");
1269 as = name->d.uniformResourceIdentifier;
1270 break;
1271 }
1272 if (v == NULL) {
1273 Py_DECREF(t);
1274 goto fail;
1275 }
1276 PyTuple_SET_ITEM(t, 0, v);
Christian Heimesa871f692020-06-01 08:58:14 +02001277 v = PyUnicode_FromStringAndSize((char *)ASN1_STRING_get0_data(as),
Christian Heimes824f7f32013-08-17 00:54:47 +02001278 ASN1_STRING_length(as));
1279 if (v == NULL) {
1280 Py_DECREF(t);
1281 goto fail;
1282 }
1283 PyTuple_SET_ITEM(t, 1, v);
1284 break;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001285
Christian Heimes1c03abd2016-09-06 23:25:35 +02001286 case GEN_RID:
1287 t = PyTuple_New(2);
1288 if (t == NULL)
1289 goto fail;
1290
1291 v = PyUnicode_FromString("Registered ID");
1292 if (v == NULL) {
1293 Py_DECREF(t);
1294 goto fail;
1295 }
1296 PyTuple_SET_ITEM(t, 0, v);
1297
1298 len = i2t_ASN1_OBJECT(buf, sizeof(buf)-1, name->d.rid);
1299 if (len < 0) {
1300 Py_DECREF(t);
Christian Heimes7f1305e2021-04-17 20:06:38 +02001301 _setSSLError(state, NULL, 0, __FILE__, __LINE__);
Christian Heimes1c03abd2016-09-06 23:25:35 +02001302 goto fail;
1303 } else if (len >= (int)sizeof(buf)) {
1304 v = PyUnicode_FromString("<INVALID>");
1305 } else {
1306 v = PyUnicode_FromStringAndSize(buf, len);
1307 }
1308 if (v == NULL) {
1309 Py_DECREF(t);
1310 goto fail;
1311 }
1312 PyTuple_SET_ITEM(t, 1, v);
1313 break;
1314
Christian Heimes2b7de662019-12-07 17:59:36 +01001315 case GEN_IPADD:
1316 /* OpenSSL < 3.0.0 adds a trailing \n to IPv6. 3.0.0 removed
1317 * the trailing newline. Remove it in all versions
1318 */
1319 t = PyTuple_New(2);
1320 if (t == NULL)
1321 goto fail;
1322
1323 v = PyUnicode_FromString("IP Address");
1324 if (v == NULL) {
1325 Py_DECREF(t);
1326 goto fail;
1327 }
1328 PyTuple_SET_ITEM(t, 0, v);
1329
1330 if (name->d.ip->length == 4) {
1331 unsigned char *p = name->d.ip->data;
1332 v = PyUnicode_FromFormat(
1333 "%d.%d.%d.%d",
1334 p[0], p[1], p[2], p[3]
1335 );
1336 } else if (name->d.ip->length == 16) {
1337 /* PyUnicode_FromFormat() does not support %X */
1338 unsigned char *p = name->d.ip->data;
1339 len = sprintf(
1340 buf,
1341 "%X:%X:%X:%X:%X:%X:%X:%X",
1342 p[0] << 8 | p[1],
1343 p[2] << 8 | p[3],
1344 p[4] << 8 | p[5],
1345 p[6] << 8 | p[7],
1346 p[8] << 8 | p[9],
1347 p[10] << 8 | p[11],
1348 p[12] << 8 | p[13],
1349 p[14] << 8 | p[15]
1350 );
1351 v = PyUnicode_FromStringAndSize(buf, len);
1352 } else {
1353 v = PyUnicode_FromString("<invalid>");
1354 }
1355
1356 if (v == NULL) {
1357 Py_DECREF(t);
1358 goto fail;
1359 }
1360 PyTuple_SET_ITEM(t, 1, v);
1361 break;
1362
Christian Heimes824f7f32013-08-17 00:54:47 +02001363 default:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001364 /* for everything else, we use the OpenSSL print form */
Christian Heimes824f7f32013-08-17 00:54:47 +02001365 switch (gntype) {
1366 /* check for new general name type */
1367 case GEN_OTHERNAME:
1368 case GEN_X400:
1369 case GEN_EDIPARTY:
Christian Heimes824f7f32013-08-17 00:54:47 +02001370 case GEN_RID:
1371 break;
1372 default:
1373 if (PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
1374 "Unknown general name type %d",
1375 gntype) == -1) {
1376 goto fail;
1377 }
1378 break;
1379 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001380 (void) BIO_reset(biobuf);
1381 GENERAL_NAME_print(biobuf, name);
1382 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1383 if (len < 0) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02001384 _setSSLError(state, NULL, 0, __FILE__, __LINE__);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001385 goto fail;
1386 }
1387 vptr = strchr(buf, ':');
Christian Heimes1c03abd2016-09-06 23:25:35 +02001388 if (vptr == NULL) {
1389 PyErr_Format(PyExc_ValueError,
1390 "Invalid value %.200s",
1391 buf);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001392 goto fail;
Christian Heimes1c03abd2016-09-06 23:25:35 +02001393 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001394 t = PyTuple_New(2);
1395 if (t == NULL)
1396 goto fail;
1397 v = PyUnicode_FromStringAndSize(buf, (vptr - buf));
1398 if (v == NULL) {
1399 Py_DECREF(t);
1400 goto fail;
1401 }
1402 PyTuple_SET_ITEM(t, 0, v);
1403 v = PyUnicode_FromStringAndSize((vptr + 1),
1404 (len - (vptr - buf + 1)));
1405 if (v == NULL) {
1406 Py_DECREF(t);
1407 goto fail;
1408 }
1409 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +02001410 break;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001411 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001412
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001413 /* and add that rendering to the list */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001414
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001415 if (PyList_Append(peer_alt_names, t) < 0) {
1416 Py_DECREF(t);
1417 goto fail;
1418 }
1419 Py_DECREF(t);
1420 }
Antoine Pitrou116d6b92011-11-23 01:39:19 +01001421 sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001422 }
1423 BIO_free(biobuf);
1424 if (peer_alt_names != Py_None) {
1425 v = PyList_AsTuple(peer_alt_names);
1426 Py_DECREF(peer_alt_names);
1427 return v;
1428 } else {
1429 return peer_alt_names;
1430 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001431
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001432
1433 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001434 if (biobuf != NULL)
1435 BIO_free(biobuf);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001436
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001437 if (peer_alt_names != Py_None) {
1438 Py_XDECREF(peer_alt_names);
1439 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001440
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001441 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001442}
1443
1444static PyObject *
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001445_get_aia_uri(X509 *certificate, int nid) {
1446 PyObject *lst = NULL, *ostr = NULL;
1447 int i, result;
1448 AUTHORITY_INFO_ACCESS *info;
1449
1450 info = X509_get_ext_d2i(certificate, NID_info_access, NULL, NULL);
Benjamin Petersonf0c90382015-11-14 15:12:18 -08001451 if (info == NULL)
1452 return Py_None;
1453 if (sk_ACCESS_DESCRIPTION_num(info) == 0) {
1454 AUTHORITY_INFO_ACCESS_free(info);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001455 return Py_None;
1456 }
1457
1458 if ((lst = PyList_New(0)) == NULL) {
1459 goto fail;
1460 }
1461
1462 for (i = 0; i < sk_ACCESS_DESCRIPTION_num(info); i++) {
1463 ACCESS_DESCRIPTION *ad = sk_ACCESS_DESCRIPTION_value(info, i);
1464 ASN1_IA5STRING *uri;
1465
1466 if ((OBJ_obj2nid(ad->method) != nid) ||
1467 (ad->location->type != GEN_URI)) {
1468 continue;
1469 }
1470 uri = ad->location->d.uniformResourceIdentifier;
1471 ostr = PyUnicode_FromStringAndSize((char *)uri->data,
1472 uri->length);
1473 if (ostr == NULL) {
1474 goto fail;
1475 }
1476 result = PyList_Append(lst, ostr);
1477 Py_DECREF(ostr);
1478 if (result < 0) {
1479 goto fail;
1480 }
1481 }
1482 AUTHORITY_INFO_ACCESS_free(info);
1483
1484 /* convert to tuple or None */
1485 if (PyList_Size(lst) == 0) {
1486 Py_DECREF(lst);
1487 return Py_None;
1488 } else {
1489 PyObject *tup;
1490 tup = PyList_AsTuple(lst);
1491 Py_DECREF(lst);
1492 return tup;
1493 }
1494
1495 fail:
1496 AUTHORITY_INFO_ACCESS_free(info);
Christian Heimes18fc7be2013-11-21 23:57:49 +01001497 Py_XDECREF(lst);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001498 return NULL;
1499}
1500
1501static PyObject *
1502_get_crl_dp(X509 *certificate) {
1503 STACK_OF(DIST_POINT) *dps;
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001504 int i, j;
1505 PyObject *lst, *res = NULL;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001506
Christian Heimes598894f2016-09-05 23:19:05 +02001507 dps = X509_get_ext_d2i(certificate, NID_crl_distribution_points, NULL, NULL);
Christian Heimes949ec142013-11-21 16:26:51 +01001508
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001509 if (dps == NULL)
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001510 return Py_None;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001511
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001512 lst = PyList_New(0);
1513 if (lst == NULL)
1514 goto done;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001515
1516 for (i=0; i < sk_DIST_POINT_num(dps); i++) {
1517 DIST_POINT *dp;
1518 STACK_OF(GENERAL_NAME) *gns;
1519
1520 dp = sk_DIST_POINT_value(dps, i);
Christian Heimesa37f5242019-01-15 23:47:42 +01001521 if (dp->distpoint == NULL) {
1522 /* Ignore empty DP value, CVE-2019-5010 */
1523 continue;
1524 }
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001525 gns = dp->distpoint->name.fullname;
1526
1527 for (j=0; j < sk_GENERAL_NAME_num(gns); j++) {
1528 GENERAL_NAME *gn;
1529 ASN1_IA5STRING *uri;
1530 PyObject *ouri;
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001531 int err;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001532
1533 gn = sk_GENERAL_NAME_value(gns, j);
1534 if (gn->type != GEN_URI) {
1535 continue;
1536 }
1537 uri = gn->d.uniformResourceIdentifier;
1538 ouri = PyUnicode_FromStringAndSize((char *)uri->data,
1539 uri->length);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001540 if (ouri == NULL)
1541 goto done;
1542
1543 err = PyList_Append(lst, ouri);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001544 Py_DECREF(ouri);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001545 if (err < 0)
1546 goto done;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001547 }
1548 }
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001549
1550 /* Convert to tuple. */
1551 res = (PyList_GET_SIZE(lst) > 0) ? PyList_AsTuple(lst) : Py_None;
1552
1553 done:
1554 Py_XDECREF(lst);
Olivier Vielpeau2849cc32017-04-14 21:06:07 -04001555 CRL_DIST_POINTS_free(dps);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001556 return res;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001557}
1558
1559static PyObject *
Christian Heimes7f1305e2021-04-17 20:06:38 +02001560_decode_certificate(_sslmodulestate *state, X509 *certificate) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001561
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001562 PyObject *retval = NULL;
1563 BIO *biobuf = NULL;
1564 PyObject *peer;
1565 PyObject *peer_alt_names = NULL;
1566 PyObject *issuer;
1567 PyObject *version;
1568 PyObject *sn_obj;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001569 PyObject *obj;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001570 ASN1_INTEGER *serialNumber;
1571 char buf[2048];
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001572 int len, result;
Christian Heimesa871f692020-06-01 08:58:14 +02001573 const ASN1_TIME *notBefore, *notAfter;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001574 PyObject *pnotBefore, *pnotAfter;
Thomas Woutersed03b412007-08-28 21:37:11 +00001575
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001576 retval = PyDict_New();
1577 if (retval == NULL)
1578 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001579
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001580 peer = _create_tuple_for_X509_NAME(
Christian Heimes7f1305e2021-04-17 20:06:38 +02001581 state,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001582 X509_get_subject_name(certificate));
1583 if (peer == NULL)
1584 goto fail0;
1585 if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) {
1586 Py_DECREF(peer);
1587 goto fail0;
1588 }
1589 Py_DECREF(peer);
Thomas Woutersed03b412007-08-28 21:37:11 +00001590
Antoine Pitroufb046912010-11-09 20:21:19 +00001591 issuer = _create_tuple_for_X509_NAME(
Christian Heimes7f1305e2021-04-17 20:06:38 +02001592 state,
Antoine Pitroufb046912010-11-09 20:21:19 +00001593 X509_get_issuer_name(certificate));
1594 if (issuer == NULL)
1595 goto fail0;
1596 if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001597 Py_DECREF(issuer);
Antoine Pitroufb046912010-11-09 20:21:19 +00001598 goto fail0;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001599 }
Antoine Pitroufb046912010-11-09 20:21:19 +00001600 Py_DECREF(issuer);
1601
1602 version = PyLong_FromLong(X509_get_version(certificate) + 1);
Christian Heimes5962bef2013-07-26 15:51:18 +02001603 if (version == NULL)
1604 goto fail0;
Antoine Pitroufb046912010-11-09 20:21:19 +00001605 if (PyDict_SetItemString(retval, "version", version) < 0) {
1606 Py_DECREF(version);
1607 goto fail0;
1608 }
1609 Py_DECREF(version);
Guido van Rossumf06628b2007-11-21 20:01:53 +00001610
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001611 /* get a memory buffer */
1612 biobuf = BIO_new(BIO_s_mem());
Zackery Spytz4c49da02018-12-07 03:11:30 -07001613 if (biobuf == NULL) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02001614 PyErr_SetString(state->PySSLErrorObject, "failed to allocate BIO");
Zackery Spytz4c49da02018-12-07 03:11:30 -07001615 goto fail0;
1616 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001617
Antoine Pitroufb046912010-11-09 20:21:19 +00001618 (void) BIO_reset(biobuf);
1619 serialNumber = X509_get_serialNumber(certificate);
1620 /* should not exceed 20 octets, 160 bits, so buf is big enough */
1621 i2a_ASN1_INTEGER(biobuf, serialNumber);
1622 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1623 if (len < 0) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02001624 _setSSLError(state, NULL, 0, __FILE__, __LINE__);
Antoine Pitroufb046912010-11-09 20:21:19 +00001625 goto fail1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001626 }
Antoine Pitroufb046912010-11-09 20:21:19 +00001627 sn_obj = PyUnicode_FromStringAndSize(buf, len);
1628 if (sn_obj == NULL)
1629 goto fail1;
1630 if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) {
1631 Py_DECREF(sn_obj);
1632 goto fail1;
1633 }
1634 Py_DECREF(sn_obj);
1635
1636 (void) BIO_reset(biobuf);
Christian Heimesa871f692020-06-01 08:58:14 +02001637 notBefore = X509_get0_notBefore(certificate);
Antoine Pitroufb046912010-11-09 20:21:19 +00001638 ASN1_TIME_print(biobuf, notBefore);
1639 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1640 if (len < 0) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02001641 _setSSLError(state, NULL, 0, __FILE__, __LINE__);
Antoine Pitroufb046912010-11-09 20:21:19 +00001642 goto fail1;
1643 }
1644 pnotBefore = PyUnicode_FromStringAndSize(buf, len);
1645 if (pnotBefore == NULL)
1646 goto fail1;
1647 if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) {
1648 Py_DECREF(pnotBefore);
1649 goto fail1;
1650 }
1651 Py_DECREF(pnotBefore);
Thomas Woutersed03b412007-08-28 21:37:11 +00001652
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001653 (void) BIO_reset(biobuf);
Christian Heimesa871f692020-06-01 08:58:14 +02001654 notAfter = X509_get0_notAfter(certificate);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001655 ASN1_TIME_print(biobuf, notAfter);
1656 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1657 if (len < 0) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02001658 _setSSLError(state, NULL, 0, __FILE__, __LINE__);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001659 goto fail1;
1660 }
1661 pnotAfter = PyUnicode_FromStringAndSize(buf, len);
1662 if (pnotAfter == NULL)
1663 goto fail1;
1664 if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) {
1665 Py_DECREF(pnotAfter);
1666 goto fail1;
1667 }
1668 Py_DECREF(pnotAfter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001669
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001670 /* Now look for subjectAltName */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001671
Christian Heimes7f1305e2021-04-17 20:06:38 +02001672 peer_alt_names = _get_peer_alt_names(state, certificate);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001673 if (peer_alt_names == NULL)
1674 goto fail1;
1675 else if (peer_alt_names != Py_None) {
1676 if (PyDict_SetItemString(retval, "subjectAltName",
1677 peer_alt_names) < 0) {
1678 Py_DECREF(peer_alt_names);
1679 goto fail1;
1680 }
1681 Py_DECREF(peer_alt_names);
1682 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001683
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001684 /* Authority Information Access: OCSP URIs */
1685 obj = _get_aia_uri(certificate, NID_ad_OCSP);
1686 if (obj == NULL) {
1687 goto fail1;
1688 } else if (obj != Py_None) {
1689 result = PyDict_SetItemString(retval, "OCSP", obj);
1690 Py_DECREF(obj);
1691 if (result < 0) {
1692 goto fail1;
1693 }
1694 }
1695
1696 obj = _get_aia_uri(certificate, NID_ad_ca_issuers);
1697 if (obj == NULL) {
1698 goto fail1;
1699 } else if (obj != Py_None) {
1700 result = PyDict_SetItemString(retval, "caIssuers", obj);
1701 Py_DECREF(obj);
1702 if (result < 0) {
1703 goto fail1;
1704 }
1705 }
1706
1707 /* CDP (CRL distribution points) */
1708 obj = _get_crl_dp(certificate);
1709 if (obj == NULL) {
1710 goto fail1;
1711 } else if (obj != Py_None) {
1712 result = PyDict_SetItemString(retval, "crlDistributionPoints", obj);
1713 Py_DECREF(obj);
1714 if (result < 0) {
1715 goto fail1;
1716 }
1717 }
1718
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001719 BIO_free(biobuf);
1720 return retval;
Thomas Woutersed03b412007-08-28 21:37:11 +00001721
1722 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001723 if (biobuf != NULL)
1724 BIO_free(biobuf);
Thomas Woutersed03b412007-08-28 21:37:11 +00001725 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001726 Py_XDECREF(retval);
1727 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001728}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001729
Christian Heimes9a5395a2013-06-17 15:44:12 +02001730static PyObject *
Christian Heimes7f1305e2021-04-17 20:06:38 +02001731_certificate_to_der(_sslmodulestate *state, X509 *certificate)
Christian Heimes9a5395a2013-06-17 15:44:12 +02001732{
1733 unsigned char *bytes_buf = NULL;
1734 int len;
1735 PyObject *retval;
1736
1737 bytes_buf = NULL;
1738 len = i2d_X509(certificate, &bytes_buf);
1739 if (len < 0) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02001740 _setSSLError(state, NULL, 0, __FILE__, __LINE__);
Christian Heimes9a5395a2013-06-17 15:44:12 +02001741 return NULL;
1742 }
1743 /* this is actually an immutable bytes sequence */
1744 retval = PyBytes_FromStringAndSize((const char *) bytes_buf, len);
1745 OPENSSL_free(bytes_buf);
1746 return retval;
1747}
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001748
Christian Heimes666991f2021-04-26 15:01:40 +02001749#include "_ssl/misc.c"
1750#include "_ssl/cert.c"
1751
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001752/*[clinic input]
1753_ssl._test_decode_cert
1754 path: object(converter="PyUnicode_FSConverter")
1755 /
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001756
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001757[clinic start generated code]*/
1758
1759static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001760_ssl__test_decode_cert_impl(PyObject *module, PyObject *path)
1761/*[clinic end generated code: output=96becb9abb23c091 input=cdeaaf02d4346628]*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001762{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001763 PyObject *retval = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001764 X509 *x=NULL;
1765 BIO *cert;
Christian Heimes7f1305e2021-04-17 20:06:38 +02001766 _sslmodulestate *state = get_ssl_state(module);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001767
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001768 if ((cert=BIO_new(BIO_s_file())) == NULL) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02001769 PyErr_SetString(state->PySSLErrorObject,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001770 "Can't malloc memory to read file");
1771 goto fail0;
1772 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001773
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001774 if (BIO_read_filename(cert, PyBytes_AsString(path)) <= 0) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02001775 PyErr_SetString(state->PySSLErrorObject,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001776 "Can't open file");
1777 goto fail0;
1778 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001779
Alex Gaynor40dad952019-08-15 08:31:28 -04001780 x = PEM_read_bio_X509(cert, NULL, NULL, NULL);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001781 if (x == NULL) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02001782 PyErr_SetString(state->PySSLErrorObject,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001783 "Error decoding PEM-encoded file");
1784 goto fail0;
1785 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001786
Christian Heimes7f1305e2021-04-17 20:06:38 +02001787 retval = _decode_certificate(state, x);
Mark Dickinsonee55df52010-08-03 18:31:54 +00001788 X509_free(x);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001789
1790 fail0:
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001791 Py_DECREF(path);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001792 if (cert != NULL) BIO_free(cert);
1793 return retval;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001794}
1795
1796
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001797/*[clinic input]
Christian Heimes141c5e82018-02-24 21:10:57 +01001798_ssl._SSLSocket.getpeercert
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001799 der as binary_mode: bool = False
1800 /
1801
1802Returns the certificate for the peer.
1803
1804If no certificate was provided, returns None. If a certificate was
1805provided, but not validated, returns an empty dictionary. Otherwise
1806returns a dict containing information about the peer certificate.
1807
1808If the optional argument is True, returns a DER-encoded copy of the
1809peer certificate, or None if no certificate was provided. This will
1810return the certificate even if it wasn't validated.
1811[clinic start generated code]*/
1812
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001813static PyObject *
Christian Heimes141c5e82018-02-24 21:10:57 +01001814_ssl__SSLSocket_getpeercert_impl(PySSLSocket *self, int binary_mode)
1815/*[clinic end generated code: output=1f0ab66dfb693c88 input=c0fbe802e57629b7]*/
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001816{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001817 int verification;
Christian Heimes66dc33b2017-05-23 16:02:02 -07001818 X509 *peer_cert;
1819 PyObject *result;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001820
Christian Heimes66dc33b2017-05-23 16:02:02 -07001821 if (!SSL_is_init_finished(self->ssl)) {
Antoine Pitrou20b85552013-09-29 19:50:53 +02001822 PyErr_SetString(PyExc_ValueError,
1823 "handshake not done yet");
1824 return NULL;
1825 }
Christian Heimes66dc33b2017-05-23 16:02:02 -07001826 peer_cert = SSL_get_peer_certificate(self->ssl);
1827 if (peer_cert == NULL)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001828 Py_RETURN_NONE;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001829
Antoine Pitrou721738f2012-08-15 23:20:39 +02001830 if (binary_mode) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001831 /* return cert in DER-encoded format */
Christian Heimes7f1305e2021-04-17 20:06:38 +02001832 result = _certificate_to_der(get_state_sock(self), peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001833 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00001834 verification = SSL_CTX_get_verify_mode(SSL_get_SSL_CTX(self->ssl));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001835 if ((verification & SSL_VERIFY_PEER) == 0)
Christian Heimes66dc33b2017-05-23 16:02:02 -07001836 result = PyDict_New();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001837 else
Christian Heimes7f1305e2021-04-17 20:06:38 +02001838 result = _decode_certificate(get_state_sock(self), peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001839 }
Christian Heimes66dc33b2017-05-23 16:02:02 -07001840 X509_free(peer_cert);
1841 return result;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001842}
1843
Christian Heimes666991f2021-04-26 15:01:40 +02001844/*[clinic input]
1845_ssl._SSLSocket.get_verified_chain
1846
1847[clinic start generated code]*/
1848
1849static PyObject *
1850_ssl__SSLSocket_get_verified_chain_impl(PySSLSocket *self)
1851/*[clinic end generated code: output=802421163cdc3110 input=5fb0714f77e2bd51]*/
1852{
1853 /* borrowed reference */
1854 STACK_OF(X509) *chain = SSL_get0_verified_chain(self->ssl);
1855 if (chain == NULL) {
1856 Py_RETURN_NONE;
1857 }
1858 return _PySSL_CertificateFromX509Stack(self->ctx->state, chain, 1);
1859}
1860
1861/*[clinic input]
1862_ssl._SSLSocket.get_unverified_chain
1863
1864[clinic start generated code]*/
1865
1866static PyObject *
1867_ssl__SSLSocket_get_unverified_chain_impl(PySSLSocket *self)
1868/*[clinic end generated code: output=5acdae414e13f913 input=78c33c360c635cb5]*/
1869{
1870 PyObject *retval;
1871 /* borrowed reference */
1872 /* TODO: include SSL_get_peer_certificate() for server-side sockets */
1873 STACK_OF(X509) *chain = SSL_get_peer_cert_chain(self->ssl);
1874 if (chain == NULL) {
1875 Py_RETURN_NONE;
1876 }
1877 retval = _PySSL_CertificateFromX509Stack(self->ctx->state, chain, 1);
1878 if (retval == NULL) {
1879 return NULL;
1880 }
1881 /* OpenSSL does not include peer cert for server side connections */
1882 if (self->socket_type == PY_SSL_SERVER) {
1883 PyObject *peerobj = NULL;
1884 X509 *peer = SSL_get_peer_certificate(self->ssl);
1885
1886 if (peer == NULL) {
1887 peerobj = Py_None;
1888 Py_INCREF(peerobj);
1889 } else {
1890 /* consume X509 reference on success */
1891 peerobj = _PySSL_CertificateFromX509(self->ctx->state, peer, 0);
1892 if (peerobj == NULL) {
1893 X509_free(peer);
1894 Py_DECREF(retval);
1895 return NULL;
1896 }
1897 }
1898 int res = PyList_Insert(retval, 0, peerobj);
1899 Py_DECREF(peerobj);
1900 if (res < 0) {
1901 Py_DECREF(retval);
1902 return NULL;
1903 }
1904 }
1905 return retval;
1906}
1907
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001908static PyObject *
1909cipher_to_tuple(const SSL_CIPHER *cipher)
1910{
1911 const char *cipher_name, *cipher_protocol;
1912 PyObject *v, *retval = PyTuple_New(3);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001913 if (retval == NULL)
1914 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001915
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001916 cipher_name = SSL_CIPHER_get_name(cipher);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001917 if (cipher_name == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001918 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001919 PyTuple_SET_ITEM(retval, 0, Py_None);
1920 } else {
1921 v = PyUnicode_FromString(cipher_name);
1922 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001923 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001924 PyTuple_SET_ITEM(retval, 0, v);
1925 }
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001926
1927 cipher_protocol = SSL_CIPHER_get_version(cipher);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001928 if (cipher_protocol == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001929 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001930 PyTuple_SET_ITEM(retval, 1, Py_None);
1931 } else {
1932 v = PyUnicode_FromString(cipher_protocol);
1933 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001934 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001935 PyTuple_SET_ITEM(retval, 1, v);
1936 }
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001937
1938 v = PyLong_FromLong(SSL_CIPHER_get_bits(cipher, NULL));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001939 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001940 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001941 PyTuple_SET_ITEM(retval, 2, v);
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001942
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001943 return retval;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001944
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001945 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001946 Py_DECREF(retval);
1947 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001948}
1949
Christian Heimes25bfcd52016-09-06 00:04:45 +02001950static PyObject *
1951cipher_to_dict(const SSL_CIPHER *cipher)
1952{
1953 const char *cipher_name, *cipher_protocol;
1954
1955 unsigned long cipher_id;
1956 int alg_bits, strength_bits, len;
1957 char buf[512] = {0};
Christian Heimes25bfcd52016-09-06 00:04:45 +02001958 int aead, nid;
1959 const char *skcipher = NULL, *digest = NULL, *kx = NULL, *auth = NULL;
Christian Heimes25bfcd52016-09-06 00:04:45 +02001960
1961 /* can be NULL */
1962 cipher_name = SSL_CIPHER_get_name(cipher);
1963 cipher_protocol = SSL_CIPHER_get_version(cipher);
1964 cipher_id = SSL_CIPHER_get_id(cipher);
1965 SSL_CIPHER_description(cipher, buf, sizeof(buf) - 1);
Segev Finer5cff6372017-07-27 01:19:17 +03001966 /* Downcast to avoid a warning. Safe since buf is always 512 bytes */
1967 len = (int)strlen(buf);
Christian Heimes25bfcd52016-09-06 00:04:45 +02001968 if (len > 1 && buf[len-1] == '\n')
1969 buf[len-1] = '\0';
1970 strength_bits = SSL_CIPHER_get_bits(cipher, &alg_bits);
1971
Christian Heimes25bfcd52016-09-06 00:04:45 +02001972 aead = SSL_CIPHER_is_aead(cipher);
1973 nid = SSL_CIPHER_get_cipher_nid(cipher);
1974 skcipher = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1975 nid = SSL_CIPHER_get_digest_nid(cipher);
1976 digest = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1977 nid = SSL_CIPHER_get_kx_nid(cipher);
1978 kx = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1979 nid = SSL_CIPHER_get_auth_nid(cipher);
1980 auth = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
Christian Heimes25bfcd52016-09-06 00:04:45 +02001981
Victor Stinner410b9882016-09-12 12:00:23 +02001982 return Py_BuildValue(
Christian Heimes25bfcd52016-09-06 00:04:45 +02001983 "{sksssssssisi"
Christian Heimes25bfcd52016-09-06 00:04:45 +02001984 "sOssssssss"
Christian Heimes25bfcd52016-09-06 00:04:45 +02001985 "}",
1986 "id", cipher_id,
1987 "name", cipher_name,
1988 "protocol", cipher_protocol,
1989 "description", buf,
1990 "strength_bits", strength_bits,
1991 "alg_bits", alg_bits
Christian Heimes25bfcd52016-09-06 00:04:45 +02001992 ,"aead", aead ? Py_True : Py_False,
1993 "symmetric", skcipher,
1994 "digest", digest,
1995 "kea", kx,
1996 "auth", auth
Christian Heimes25bfcd52016-09-06 00:04:45 +02001997 );
Christian Heimes25bfcd52016-09-06 00:04:45 +02001998}
Christian Heimes25bfcd52016-09-06 00:04:45 +02001999
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002000/*[clinic input]
2001_ssl._SSLSocket.shared_ciphers
2002[clinic start generated code]*/
2003
2004static PyObject *
2005_ssl__SSLSocket_shared_ciphers_impl(PySSLSocket *self)
2006/*[clinic end generated code: output=3d174ead2e42c4fd input=0bfe149da8fe6306]*/
Benjamin Peterson4cb17812015-01-07 11:14:26 -06002007{
2008 STACK_OF(SSL_CIPHER) *ciphers;
2009 int i;
2010 PyObject *res;
2011
Christian Heimes598894f2016-09-05 23:19:05 +02002012 ciphers = SSL_get_ciphers(self->ssl);
2013 if (!ciphers)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06002014 Py_RETURN_NONE;
Benjamin Peterson4cb17812015-01-07 11:14:26 -06002015 res = PyList_New(sk_SSL_CIPHER_num(ciphers));
2016 if (!res)
2017 return NULL;
2018 for (i = 0; i < sk_SSL_CIPHER_num(ciphers); i++) {
2019 PyObject *tup = cipher_to_tuple(sk_SSL_CIPHER_value(ciphers, i));
2020 if (!tup) {
2021 Py_DECREF(res);
2022 return NULL;
2023 }
2024 PyList_SET_ITEM(res, i, tup);
2025 }
2026 return res;
2027}
2028
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002029/*[clinic input]
2030_ssl._SSLSocket.cipher
2031[clinic start generated code]*/
2032
2033static PyObject *
2034_ssl__SSLSocket_cipher_impl(PySSLSocket *self)
2035/*[clinic end generated code: output=376417c16d0e5815 input=548fb0e27243796d]*/
Benjamin Peterson4cb17812015-01-07 11:14:26 -06002036{
2037 const SSL_CIPHER *current;
2038
2039 if (self->ssl == NULL)
2040 Py_RETURN_NONE;
2041 current = SSL_get_current_cipher(self->ssl);
2042 if (current == NULL)
2043 Py_RETURN_NONE;
2044 return cipher_to_tuple(current);
2045}
2046
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002047/*[clinic input]
2048_ssl._SSLSocket.version
2049[clinic start generated code]*/
2050
2051static PyObject *
2052_ssl__SSLSocket_version_impl(PySSLSocket *self)
2053/*[clinic end generated code: output=178aed33193b2cdb input=900186a503436fd6]*/
Antoine Pitrou47e40422014-09-04 21:00:10 +02002054{
2055 const char *version;
2056
2057 if (self->ssl == NULL)
2058 Py_RETURN_NONE;
Christian Heimes68771112017-09-05 21:55:40 -07002059 if (!SSL_is_init_finished(self->ssl)) {
2060 /* handshake not finished */
2061 Py_RETURN_NONE;
2062 }
Antoine Pitrou47e40422014-09-04 21:00:10 +02002063 version = SSL_get_version(self->ssl);
2064 if (!strcmp(version, "unknown"))
2065 Py_RETURN_NONE;
2066 return PyUnicode_FromString(version);
2067}
2068
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002069/*[clinic input]
2070_ssl._SSLSocket.selected_alpn_protocol
2071[clinic start generated code]*/
2072
2073static PyObject *
2074_ssl__SSLSocket_selected_alpn_protocol_impl(PySSLSocket *self)
2075/*[clinic end generated code: output=ec33688b303d250f input=442de30e35bc2913]*/
2076{
Benjamin Petersoncca27322015-01-23 16:35:37 -05002077 const unsigned char *out;
2078 unsigned int outlen;
2079
2080 SSL_get0_alpn_selected(self->ssl, &out, &outlen);
2081
2082 if (out == NULL)
2083 Py_RETURN_NONE;
2084 return PyUnicode_FromStringAndSize((char *)out, outlen);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002085}
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002086
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002087/*[clinic input]
2088_ssl._SSLSocket.compression
2089[clinic start generated code]*/
2090
2091static PyObject *
2092_ssl__SSLSocket_compression_impl(PySSLSocket *self)
2093/*[clinic end generated code: output=bd16cb1bb4646ae7 input=5d059d0a2bbc32c8]*/
2094{
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01002095#ifdef OPENSSL_NO_COMP
2096 Py_RETURN_NONE;
2097#else
2098 const COMP_METHOD *comp_method;
2099 const char *short_name;
2100
2101 if (self->ssl == NULL)
2102 Py_RETURN_NONE;
2103 comp_method = SSL_get_current_compression(self->ssl);
Christian Heimes598894f2016-09-05 23:19:05 +02002104 if (comp_method == NULL || COMP_get_type(comp_method) == NID_undef)
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01002105 Py_RETURN_NONE;
Christian Heimes281e5f82016-09-06 01:10:39 +02002106 short_name = OBJ_nid2sn(COMP_get_type(comp_method));
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01002107 if (short_name == NULL)
2108 Py_RETURN_NONE;
2109 return PyUnicode_DecodeFSDefault(short_name);
2110#endif
2111}
2112
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002113static PySSLContext *PySSL_get_context(PySSLSocket *self, void *closure) {
2114 Py_INCREF(self->ctx);
2115 return self->ctx;
2116}
2117
2118static int PySSL_set_context(PySSLSocket *self, PyObject *value,
2119 void *closure) {
2120
Christian Heimes7f1305e2021-04-17 20:06:38 +02002121 if (PyObject_TypeCheck(value, self->ctx->state->PySSLContext_Type)) {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002122 Py_INCREF(value);
Serhiy Storchaka57a01d32016-04-10 18:05:40 +03002123 Py_SETREF(self->ctx, (PySSLContext *)value);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002124 SSL_set_SSL_CTX(self->ssl, self->ctx->ctx);
Christian Heimes77cde502021-03-21 16:13:09 +01002125 /* Set SSL* internal msg_callback to state of new context's state */
2126 SSL_set_msg_callback(
2127 self->ssl,
2128 self->ctx->msg_cb ? _PySSL_msg_callback : NULL
2129 );
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002130 } else {
Ned Deily4531ec72018-06-11 20:26:28 -04002131 PyErr_SetString(PyExc_TypeError, "The value must be a SSLContext");
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002132 return -1;
2133 }
2134
2135 return 0;
2136}
2137
2138PyDoc_STRVAR(PySSL_set_context_doc,
2139"_setter_context(ctx)\n\
2140\
2141This changes the context associated with the SSLSocket. This is typically\n\
Christian Heimes11a14932018-02-24 02:35:08 +01002142used from within a callback function set by the sni_callback\n\
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002143on the SSLContext to change the certificate information associated with the\n\
2144SSLSocket before the cryptographic exchange handshake messages\n");
2145
2146
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002147static PyObject *
2148PySSL_get_server_side(PySSLSocket *self, void *c)
2149{
2150 return PyBool_FromLong(self->socket_type == PY_SSL_SERVER);
2151}
2152
2153PyDoc_STRVAR(PySSL_get_server_side_doc,
2154"Whether this is a server-side socket.");
2155
2156static PyObject *
2157PySSL_get_server_hostname(PySSLSocket *self, void *c)
2158{
2159 if (self->server_hostname == NULL)
2160 Py_RETURN_NONE;
2161 Py_INCREF(self->server_hostname);
2162 return self->server_hostname;
2163}
2164
2165PyDoc_STRVAR(PySSL_get_server_hostname_doc,
2166"The currently set server hostname (for SNI).");
2167
2168static PyObject *
2169PySSL_get_owner(PySSLSocket *self, void *c)
2170{
2171 PyObject *owner;
2172
2173 if (self->owner == NULL)
2174 Py_RETURN_NONE;
2175
2176 owner = PyWeakref_GetObject(self->owner);
2177 Py_INCREF(owner);
2178 return owner;
2179}
2180
2181static int
2182PySSL_set_owner(PySSLSocket *self, PyObject *value, void *c)
2183{
Serhiy Storchaka48842712016-04-06 09:45:48 +03002184 Py_XSETREF(self->owner, PyWeakref_NewRef(value, NULL));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002185 if (self->owner == NULL)
2186 return -1;
2187 return 0;
2188}
2189
2190PyDoc_STRVAR(PySSL_get_owner_doc,
2191"The Python-level owner of this object.\
2192Passed as \"self\" in servername callback.");
2193
Christian Heimesc7f70692019-05-31 11:44:05 +02002194static int
2195PySSL_traverse(PySSLSocket *self, visitproc visit, void *arg)
2196{
2197 Py_VISIT(self->exc_type);
2198 Py_VISIT(self->exc_value);
2199 Py_VISIT(self->exc_tb);
Miss Islington (bot)ea47a8a2021-05-27 09:25:22 -07002200 Py_VISIT(Py_TYPE(self));
Christian Heimesc7f70692019-05-31 11:44:05 +02002201 return 0;
2202}
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002203
Christian Heimesc7f70692019-05-31 11:44:05 +02002204static int
2205PySSL_clear(PySSLSocket *self)
2206{
2207 Py_CLEAR(self->exc_type);
2208 Py_CLEAR(self->exc_value);
2209 Py_CLEAR(self->exc_tb);
2210 return 0;
2211}
2212
2213static void
2214PySSL_dealloc(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002215{
Christian Heimes5c36da72020-11-20 09:40:12 +01002216 PyTypeObject *tp = Py_TYPE(self);
Miss Islington (bot)ea47a8a2021-05-27 09:25:22 -07002217 PyObject_GC_UnTrack(self);
2218 if (self->ssl) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002219 SSL_free(self->ssl);
Miss Islington (bot)ea47a8a2021-05-27 09:25:22 -07002220 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002221 Py_XDECREF(self->Socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002222 Py_XDECREF(self->ctx);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002223 Py_XDECREF(self->server_hostname);
2224 Py_XDECREF(self->owner);
Miss Islington (bot)ea47a8a2021-05-27 09:25:22 -07002225 PyObject_GC_Del(self);
Christian Heimes5c36da72020-11-20 09:40:12 +01002226 Py_DECREF(tp);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002227}
2228
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002229/* If the socket has a timeout, do a select()/poll() on the socket.
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002230 The argument writing indicates the direction.
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00002231 Returns one of the possibilities in the timeout_state enum (above).
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002232 */
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00002233
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002234static int
Victor Stinner14690702015-04-06 22:46:13 +02002235PySSL_select(PySocketSockObject *s, int writing, _PyTime_t timeout)
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002236{
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002237 int rc;
2238#ifdef HAVE_POLL
2239 struct pollfd pollfd;
2240 _PyTime_t ms;
2241#else
2242 int nfds;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002243 fd_set fds;
2244 struct timeval tv;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002245#endif
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002246
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002247 /* Nothing to do unless we're in timeout mode (not non-blocking) */
Victor Stinner14690702015-04-06 22:46:13 +02002248 if ((s == NULL) || (timeout == 0))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002249 return SOCKET_IS_NONBLOCKING;
Victor Stinner14690702015-04-06 22:46:13 +02002250 else if (timeout < 0) {
2251 if (s->sock_timeout > 0)
2252 return SOCKET_HAS_TIMED_OUT;
2253 else
2254 return SOCKET_IS_BLOCKING;
2255 }
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002256
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002257 /* Guard against closed socket */
Victor Stinner524714e2016-07-22 17:43:59 +02002258 if (s->sock_fd == INVALID_SOCKET)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002259 return SOCKET_HAS_BEEN_CLOSED;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002260
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002261 /* Prefer poll, if available, since you can poll() any fd
2262 * which can't be done with select(). */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002263#ifdef HAVE_POLL
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002264 pollfd.fd = s->sock_fd;
2265 pollfd.events = writing ? POLLOUT : POLLIN;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002266
Victor Stinner14690702015-04-06 22:46:13 +02002267 /* timeout is in seconds, poll() uses milliseconds */
2268 ms = (int)_PyTime_AsMilliseconds(timeout, _PyTime_ROUND_CEILING);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002269 assert(ms <= INT_MAX);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002270
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002271 PySSL_BEGIN_ALLOW_THREADS
2272 rc = poll(&pollfd, 1, (int)ms);
2273 PySSL_END_ALLOW_THREADS
2274#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002275 /* Guard against socket too large for select*/
Charles-François Nataliaa26b272011-08-28 17:51:43 +02002276 if (!_PyIsSelectable_fd(s->sock_fd))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002277 return SOCKET_TOO_LARGE_FOR_SELECT;
Neal Norwitz082b2df2006-02-07 07:04:46 +00002278
Victor Stinner14690702015-04-06 22:46:13 +02002279 _PyTime_AsTimeval_noraise(timeout, &tv, _PyTime_ROUND_CEILING);
Victor Stinnere2452312015-03-28 03:00:46 +01002280
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002281 FD_ZERO(&fds);
2282 FD_SET(s->sock_fd, &fds);
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002283
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002284 /* Wait until the socket becomes ready */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002285 PySSL_BEGIN_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002286 nfds = Py_SAFE_DOWNCAST(s->sock_fd+1, SOCKET_T, int);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002287 if (writing)
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002288 rc = select(nfds, NULL, &fds, NULL, &tv);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002289 else
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002290 rc = select(nfds, &fds, NULL, NULL, &tv);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002291 PySSL_END_ALLOW_THREADS
Bill Janssen6e027db2007-11-15 22:23:56 +00002292#endif
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002293
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002294 /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
2295 (when we are able to write or when there's something to read) */
2296 return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002297}
2298
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002299/*[clinic input]
2300_ssl._SSLSocket.write
2301 b: Py_buffer
2302 /
2303
2304Writes the bytes-like object b into the SSL object.
2305
2306Returns the number of bytes written.
2307[clinic start generated code]*/
2308
2309static PyObject *
2310_ssl__SSLSocket_write_impl(PySSLSocket *self, Py_buffer *b)
2311/*[clinic end generated code: output=aa7a6be5527358d8 input=77262d994fe5100a]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002312{
Christian Heimes89d15502021-04-19 06:55:30 +02002313 size_t count = 0;
2314 int retval;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002315 int sockstate;
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002316 _PySSLError err;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002317 int nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002318 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002319 _PyTime_t timeout, deadline = 0;
2320 int has_timeout;
Bill Janssen54cc54c2007-12-14 22:08:56 +00002321
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002322 if (sock != NULL) {
2323 if (((PyObject*)sock) == Py_None) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02002324 _setSSLError(get_state_sock(self),
2325 "Underlying socket connection gone",
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002326 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2327 return NULL;
2328 }
2329 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002330 }
2331
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002332 if (sock != NULL) {
2333 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002334 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002335 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2336 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
2337 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002338
Victor Stinner14690702015-04-06 22:46:13 +02002339 timeout = GET_SOCKET_TIMEOUT(sock);
2340 has_timeout = (timeout > 0);
2341 if (has_timeout)
2342 deadline = _PyTime_GetMonotonicClock() + timeout;
2343
2344 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002345 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Christian Heimes03c8ddd2020-11-20 09:26:07 +01002346 PyErr_SetString(PyExc_TimeoutError,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002347 "The write operation timed out");
2348 goto error;
2349 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02002350 PyErr_SetString(get_state_sock(self)->PySSLErrorObject,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002351 "Underlying socket has been closed.");
2352 goto error;
2353 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02002354 PyErr_SetString(get_state_sock(self)->PySSLErrorObject,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002355 "Underlying socket too large for select().");
2356 goto error;
2357 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002358
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002359 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002360 PySSL_BEGIN_ALLOW_THREADS
Miss Islington (bot)5ec27572021-07-23 08:25:54 -07002361 retval = SSL_write_ex(self->ssl, b->buf, (size_t)b->len, &count);
Christian Heimes89d15502021-04-19 06:55:30 +02002362 err = _PySSL_errno(retval == 0, self->ssl, retval);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002363 PySSL_END_ALLOW_THREADS
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002364 self->err = err;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002365
2366 if (PyErr_CheckSignals())
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002367 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002368
Victor Stinner14690702015-04-06 22:46:13 +02002369 if (has_timeout)
2370 timeout = deadline - _PyTime_GetMonotonicClock();
2371
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002372 if (err.ssl == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +02002373 sockstate = PySSL_select(sock, 0, timeout);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002374 } else if (err.ssl == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +02002375 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002376 } else {
2377 sockstate = SOCKET_OPERATION_OK;
2378 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002379
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002380 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Christian Heimes03c8ddd2020-11-20 09:26:07 +01002381 PyErr_SetString(PyExc_TimeoutError,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002382 "The write operation timed out");
2383 goto error;
2384 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02002385 PyErr_SetString(get_state_sock(self)->PySSLErrorObject,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002386 "Underlying socket has been closed.");
2387 goto error;
2388 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
2389 break;
2390 }
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002391 } while (err.ssl == SSL_ERROR_WANT_READ ||
2392 err.ssl == SSL_ERROR_WANT_WRITE);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002393
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002394 Py_XDECREF(sock);
Christian Heimes89d15502021-04-19 06:55:30 +02002395 if (retval == 0)
2396 return PySSL_SetError(self, retval, __FILE__, __LINE__);
Christian Heimesc7f70692019-05-31 11:44:05 +02002397 if (PySSL_ChainExceptions(self) < 0)
2398 return NULL;
Christian Heimes89d15502021-04-19 06:55:30 +02002399 return PyLong_FromSize_t(count);
Antoine Pitrou7d7aede2009-11-25 18:55:32 +00002400error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002401 Py_XDECREF(sock);
Christian Heimesc7f70692019-05-31 11:44:05 +02002402 PySSL_ChainExceptions(self);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002403 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002404}
2405
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002406/*[clinic input]
2407_ssl._SSLSocket.pending
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002408
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002409Returns the number of already decrypted bytes available for read, pending on the connection.
2410[clinic start generated code]*/
2411
2412static PyObject *
2413_ssl__SSLSocket_pending_impl(PySSLSocket *self)
2414/*[clinic end generated code: output=983d9fecdc308a83 input=2b77487d6dfd597f]*/
Bill Janssen6e027db2007-11-15 22:23:56 +00002415{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002416 int count = 0;
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002417 _PySSLError err;
Bill Janssen6e027db2007-11-15 22:23:56 +00002418
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002419 PySSL_BEGIN_ALLOW_THREADS
2420 count = SSL_pending(self->ssl);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002421 err = _PySSL_errno(count < 0, self->ssl, count);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002422 PySSL_END_ALLOW_THREADS
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002423 self->err = err;
2424
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002425 if (count < 0)
2426 return PySSL_SetError(self, count, __FILE__, __LINE__);
2427 else
2428 return PyLong_FromLong(count);
Bill Janssen6e027db2007-11-15 22:23:56 +00002429}
2430
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002431/*[clinic input]
2432_ssl._SSLSocket.read
Miss Islington (bot)5ec27572021-07-23 08:25:54 -07002433 size as len: Py_ssize_t
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002434 [
Larry Hastingsdbfdc382015-05-04 06:59:46 -07002435 buffer: Py_buffer(accept={rwbuffer})
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002436 ]
2437 /
Bill Janssen6e027db2007-11-15 22:23:56 +00002438
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002439Read up to size bytes from the SSL socket.
2440[clinic start generated code]*/
2441
2442static PyObject *
Miss Islington (bot)5ec27572021-07-23 08:25:54 -07002443_ssl__SSLSocket_read_impl(PySSLSocket *self, Py_ssize_t len,
2444 int group_right_1, Py_buffer *buffer)
2445/*[clinic end generated code: output=49b16e6406023734 input=ec48bf622be1c4a1]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002446{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002447 PyObject *dest = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002448 char *mem;
Christian Heimes89d15502021-04-19 06:55:30 +02002449 size_t count = 0;
2450 int retval;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002451 int sockstate;
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002452 _PySSLError err;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002453 int nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002454 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002455 _PyTime_t timeout, deadline = 0;
2456 int has_timeout;
Bill Janssen54cc54c2007-12-14 22:08:56 +00002457
Martin Panter5503d472016-03-27 05:35:19 +00002458 if (!group_right_1 && len < 0) {
2459 PyErr_SetString(PyExc_ValueError, "size should not be negative");
2460 return NULL;
2461 }
2462
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002463 if (sock != NULL) {
2464 if (((PyObject*)sock) == Py_None) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02002465 _setSSLError(get_state_sock(self),
2466 "Underlying socket connection gone",
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002467 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2468 return NULL;
2469 }
2470 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002471 }
2472
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002473 if (!group_right_1) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002474 dest = PyBytes_FromStringAndSize(NULL, len);
2475 if (dest == NULL)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002476 goto error;
Martin Panterbed7f1a2016-07-11 00:17:13 +00002477 if (len == 0) {
2478 Py_XDECREF(sock);
2479 return dest;
2480 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002481 mem = PyBytes_AS_STRING(dest);
2482 }
2483 else {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002484 mem = buffer->buf;
2485 if (len <= 0 || len > buffer->len) {
2486 len = (int) buffer->len;
2487 if (buffer->len != len) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002488 PyErr_SetString(PyExc_OverflowError,
2489 "maximum length can't fit in a C 'int'");
2490 goto error;
2491 }
Martin Panterbed7f1a2016-07-11 00:17:13 +00002492 if (len == 0) {
2493 count = 0;
2494 goto done;
2495 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002496 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002497 }
2498
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002499 if (sock != NULL) {
2500 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002501 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002502 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2503 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
2504 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002505
Victor Stinner14690702015-04-06 22:46:13 +02002506 timeout = GET_SOCKET_TIMEOUT(sock);
2507 has_timeout = (timeout > 0);
2508 if (has_timeout)
2509 deadline = _PyTime_GetMonotonicClock() + timeout;
2510
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002511 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002512 PySSL_BEGIN_ALLOW_THREADS
Miss Islington (bot)5ec27572021-07-23 08:25:54 -07002513 retval = SSL_read_ex(self->ssl, mem, (size_t)len, &count);
Christian Heimes89d15502021-04-19 06:55:30 +02002514 err = _PySSL_errno(retval == 0, self->ssl, retval);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002515 PySSL_END_ALLOW_THREADS
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002516 self->err = err;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002517
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002518 if (PyErr_CheckSignals())
2519 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002520
Victor Stinner14690702015-04-06 22:46:13 +02002521 if (has_timeout)
2522 timeout = deadline - _PyTime_GetMonotonicClock();
2523
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002524 if (err.ssl == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +02002525 sockstate = PySSL_select(sock, 0, timeout);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002526 } else if (err.ssl == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +02002527 sockstate = PySSL_select(sock, 1, timeout);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002528 } else if (err.ssl == SSL_ERROR_ZERO_RETURN &&
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002529 SSL_get_shutdown(self->ssl) == SSL_RECEIVED_SHUTDOWN)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002530 {
2531 count = 0;
2532 goto done;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002533 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002534 else
2535 sockstate = SOCKET_OPERATION_OK;
2536
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002537 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Christian Heimes03c8ddd2020-11-20 09:26:07 +01002538 PyErr_SetString(PyExc_TimeoutError,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002539 "The read operation timed out");
2540 goto error;
2541 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
2542 break;
2543 }
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002544 } while (err.ssl == SSL_ERROR_WANT_READ ||
2545 err.ssl == SSL_ERROR_WANT_WRITE);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002546
Christian Heimes89d15502021-04-19 06:55:30 +02002547 if (retval == 0) {
2548 PySSL_SetError(self, retval, __FILE__, __LINE__);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002549 goto error;
2550 }
Christian Heimesc7f70692019-05-31 11:44:05 +02002551 if (self->exc_type != NULL)
2552 goto error;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002553
2554done:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002555 Py_XDECREF(sock);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002556 if (!group_right_1) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002557 _PyBytes_Resize(&dest, count);
2558 return dest;
2559 }
2560 else {
Christian Heimes89d15502021-04-19 06:55:30 +02002561 return PyLong_FromSize_t(count);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002562 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002563
2564error:
Christian Heimesc7f70692019-05-31 11:44:05 +02002565 PySSL_ChainExceptions(self);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002566 Py_XDECREF(sock);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002567 if (!group_right_1)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002568 Py_XDECREF(dest);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002569 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002570}
2571
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002572/*[clinic input]
2573_ssl._SSLSocket.shutdown
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002574
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002575Does the SSL shutdown handshake with the remote end.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002576[clinic start generated code]*/
2577
2578static PyObject *
2579_ssl__SSLSocket_shutdown_impl(PySSLSocket *self)
Christian Heimes141c5e82018-02-24 21:10:57 +01002580/*[clinic end generated code: output=ca1aa7ed9d25ca42 input=11d39e69b0a2bf4a]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00002581{
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002582 _PySSLError err;
2583 int sockstate, nonblocking, ret;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002584 int zeros = 0;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002585 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002586 _PyTime_t timeout, deadline = 0;
2587 int has_timeout;
Bill Janssen40a0f662008-08-12 16:56:25 +00002588
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002589 if (sock != NULL) {
2590 /* Guard against closed socket */
Victor Stinner524714e2016-07-22 17:43:59 +02002591 if ((((PyObject*)sock) == Py_None) || (sock->sock_fd == INVALID_SOCKET)) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02002592 _setSSLError(get_state_sock(self),
2593 "Underlying socket connection gone",
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002594 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2595 return NULL;
2596 }
2597 Py_INCREF(sock);
2598
2599 /* Just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002600 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002601 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2602 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002603 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002604
Victor Stinner14690702015-04-06 22:46:13 +02002605 timeout = GET_SOCKET_TIMEOUT(sock);
2606 has_timeout = (timeout > 0);
2607 if (has_timeout)
2608 deadline = _PyTime_GetMonotonicClock() + timeout;
2609
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002610 while (1) {
2611 PySSL_BEGIN_ALLOW_THREADS
2612 /* Disable read-ahead so that unwrap can work correctly.
2613 * Otherwise OpenSSL might read in too much data,
2614 * eating clear text data that happens to be
2615 * transmitted after the SSL shutdown.
Ezio Melotti85a86292013-08-17 16:57:41 +03002616 * Should be safe to call repeatedly every time this
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002617 * function is used and the shutdown_seen_zero != 0
2618 * condition is met.
2619 */
2620 if (self->shutdown_seen_zero)
2621 SSL_set_read_ahead(self->ssl, 0);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002622 ret = SSL_shutdown(self->ssl);
2623 err = _PySSL_errno(ret < 0, self->ssl, ret);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002624 PySSL_END_ALLOW_THREADS
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002625 self->err = err;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002626
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002627 /* If err == 1, a secure shutdown with SSL_shutdown() is complete */
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002628 if (ret > 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002629 break;
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002630 if (ret == 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002631 /* Don't loop endlessly; instead preserve legacy
2632 behaviour of trying SSL_shutdown() only twice.
2633 This looks necessary for OpenSSL < 0.9.8m */
2634 if (++zeros > 1)
2635 break;
2636 /* Shutdown was sent, now try receiving */
2637 self->shutdown_seen_zero = 1;
2638 continue;
Bill Janssen40a0f662008-08-12 16:56:25 +00002639 }
2640
Victor Stinner14690702015-04-06 22:46:13 +02002641 if (has_timeout)
2642 timeout = deadline - _PyTime_GetMonotonicClock();
2643
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002644 /* Possibly retry shutdown until timeout or failure */
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002645 if (err.ssl == SSL_ERROR_WANT_READ)
Victor Stinner14690702015-04-06 22:46:13 +02002646 sockstate = PySSL_select(sock, 0, timeout);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002647 else if (err.ssl == SSL_ERROR_WANT_WRITE)
Victor Stinner14690702015-04-06 22:46:13 +02002648 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002649 else
2650 break;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002651
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002652 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002653 if (err.ssl == SSL_ERROR_WANT_READ)
Christian Heimes03c8ddd2020-11-20 09:26:07 +01002654 PyErr_SetString(PyExc_TimeoutError,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002655 "The read operation timed out");
2656 else
Christian Heimes03c8ddd2020-11-20 09:26:07 +01002657 PyErr_SetString(PyExc_TimeoutError,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002658 "The write operation timed out");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002659 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002660 }
2661 else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02002662 PyErr_SetString(get_state_sock(self)->PySSLErrorObject,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002663 "Underlying socket too large for select().");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002664 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002665 }
2666 else if (sockstate != SOCKET_OPERATION_OK)
2667 /* Retain the SSL error code */
2668 break;
2669 }
Nathaniel J. Smithc0da5822018-09-21 21:44:12 -07002670 if (ret < 0) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002671 Py_XDECREF(sock);
Christian Heimesc7f70692019-05-31 11:44:05 +02002672 PySSL_SetError(self, ret, __FILE__, __LINE__);
2673 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002674 }
Christian Heimesc7f70692019-05-31 11:44:05 +02002675 if (self->exc_type != NULL)
2676 goto error;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002677 if (sock)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002678 /* It's already INCREF'ed */
2679 return (PyObject *) sock;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002680 else
2681 Py_RETURN_NONE;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002682
2683error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002684 Py_XDECREF(sock);
Christian Heimesc7f70692019-05-31 11:44:05 +02002685 PySSL_ChainExceptions(self);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002686 return NULL;
Bill Janssen40a0f662008-08-12 16:56:25 +00002687}
2688
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002689/*[clinic input]
Christian Heimes141c5e82018-02-24 21:10:57 +01002690_ssl._SSLSocket.get_channel_binding
2691 cb_type: str = "tls-unique"
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002692
Christian Heimes141c5e82018-02-24 21:10:57 +01002693Get channel binding data for current connection.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002694
Christian Heimes141c5e82018-02-24 21:10:57 +01002695Raise ValueError if the requested `cb_type` is not supported. Return bytes
2696of the data or None if the data is not available (e.g. before the handshake).
2697Only 'tls-unique' channel binding data from RFC 5929 is supported.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002698[clinic start generated code]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00002699
Antoine Pitroud6494802011-07-21 01:11:30 +02002700static PyObject *
Christian Heimes141c5e82018-02-24 21:10:57 +01002701_ssl__SSLSocket_get_channel_binding_impl(PySSLSocket *self,
2702 const char *cb_type)
2703/*[clinic end generated code: output=34bac9acb6a61d31 input=08b7e43b99c17d41]*/
Antoine Pitroud6494802011-07-21 01:11:30 +02002704{
Antoine Pitroud6494802011-07-21 01:11:30 +02002705 char buf[PySSL_CB_MAXLEN];
Victor Stinner9ee02032013-06-23 15:08:23 +02002706 size_t len;
Antoine Pitroud6494802011-07-21 01:11:30 +02002707
Christian Heimes141c5e82018-02-24 21:10:57 +01002708 if (strcmp(cb_type, "tls-unique") == 0) {
2709 if (SSL_session_reused(self->ssl) ^ !self->socket_type) {
2710 /* if session is resumed XOR we are the client */
2711 len = SSL_get_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2712 }
2713 else {
2714 /* if a new session XOR we are the server */
2715 len = SSL_get_peer_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2716 }
Antoine Pitroud6494802011-07-21 01:11:30 +02002717 }
2718 else {
Christian Heimes141c5e82018-02-24 21:10:57 +01002719 PyErr_Format(
2720 PyExc_ValueError,
2721 "'%s' channel binding type not implemented",
2722 cb_type
2723 );
2724 return NULL;
Antoine Pitroud6494802011-07-21 01:11:30 +02002725 }
2726
2727 /* It cannot be negative in current OpenSSL version as of July 2011 */
Antoine Pitroud6494802011-07-21 01:11:30 +02002728 if (len == 0)
2729 Py_RETURN_NONE;
2730
Christian Heimes141c5e82018-02-24 21:10:57 +01002731 return PyBytes_FromStringAndSize(buf, len);
Antoine Pitroud6494802011-07-21 01:11:30 +02002732}
2733
Christian Heimes9fb051f2018-09-23 08:32:31 +02002734/*[clinic input]
2735_ssl._SSLSocket.verify_client_post_handshake
2736
2737Initiate TLS 1.3 post-handshake authentication
2738[clinic start generated code]*/
2739
2740static PyObject *
2741_ssl__SSLSocket_verify_client_post_handshake_impl(PySSLSocket *self)
2742/*[clinic end generated code: output=532147f3b1341425 input=6bfa874810a3d889]*/
2743{
2744#ifdef TLS1_3_VERSION
2745 int err = SSL_verify_client_post_handshake(self->ssl);
2746 if (err == 0)
Christian Heimes7f1305e2021-04-17 20:06:38 +02002747 return _setSSLError(get_state_sock(self), NULL, 0, __FILE__, __LINE__);
Christian Heimes9fb051f2018-09-23 08:32:31 +02002748 else
2749 Py_RETURN_NONE;
2750#else
2751 PyErr_SetString(PyExc_NotImplementedError,
2752 "Post-handshake auth is not supported by your "
2753 "OpenSSL version.");
2754 return NULL;
2755#endif
2756}
2757
Christian Heimes99a65702016-09-10 23:44:53 +02002758static SSL_SESSION*
2759_ssl_session_dup(SSL_SESSION *session) {
2760 SSL_SESSION *newsession = NULL;
2761 int slen;
2762 unsigned char *senc = NULL, *p;
2763 const unsigned char *const_p;
2764
2765 if (session == NULL) {
2766 PyErr_SetString(PyExc_ValueError, "Invalid session");
2767 goto error;
2768 }
2769
2770 /* get length */
2771 slen = i2d_SSL_SESSION(session, NULL);
2772 if (slen == 0 || slen > 0xFF00) {
2773 PyErr_SetString(PyExc_ValueError, "i2d() failed.");
2774 goto error;
2775 }
2776 if ((senc = PyMem_Malloc(slen)) == NULL) {
2777 PyErr_NoMemory();
2778 goto error;
2779 }
2780 p = senc;
2781 if (!i2d_SSL_SESSION(session, &p)) {
2782 PyErr_SetString(PyExc_ValueError, "i2d() failed.");
2783 goto error;
2784 }
2785 const_p = senc;
2786 newsession = d2i_SSL_SESSION(NULL, &const_p, slen);
2787 if (session == NULL) {
2788 goto error;
2789 }
2790 PyMem_Free(senc);
2791 return newsession;
2792 error:
2793 if (senc != NULL) {
2794 PyMem_Free(senc);
2795 }
2796 return NULL;
2797}
Christian Heimes99a65702016-09-10 23:44:53 +02002798
2799static PyObject *
2800PySSL_get_session(PySSLSocket *self, void *closure) {
2801 /* get_session can return sessions from a server-side connection,
2802 * it does not check for handshake done or client socket. */
2803 PySSLSession *pysess;
2804 SSL_SESSION *session;
2805
Christian Heimes99a65702016-09-10 23:44:53 +02002806 /* duplicate session as workaround for session bug in OpenSSL 1.1.0,
2807 * https://github.com/openssl/openssl/issues/1550 */
2808 session = SSL_get0_session(self->ssl); /* borrowed reference */
2809 if (session == NULL) {
2810 Py_RETURN_NONE;
2811 }
2812 if ((session = _ssl_session_dup(session)) == NULL) {
2813 return NULL;
2814 }
Christian Heimes99a65702016-09-10 23:44:53 +02002815 session = SSL_get1_session(self->ssl);
2816 if (session == NULL) {
2817 Py_RETURN_NONE;
2818 }
Christian Heimes7f1305e2021-04-17 20:06:38 +02002819 pysess = PyObject_GC_New(PySSLSession, self->ctx->state->PySSLSession_Type);
Christian Heimes99a65702016-09-10 23:44:53 +02002820 if (pysess == NULL) {
2821 SSL_SESSION_free(session);
2822 return NULL;
2823 }
2824
2825 assert(self->ctx);
2826 pysess->ctx = self->ctx;
2827 Py_INCREF(pysess->ctx);
2828 pysess->session = session;
Christian Heimesa5d07652016-09-24 10:48:05 +02002829 PyObject_GC_Track(pysess);
Christian Heimes99a65702016-09-10 23:44:53 +02002830 return (PyObject *)pysess;
2831}
2832
2833static int PySSL_set_session(PySSLSocket *self, PyObject *value,
2834 void *closure)
2835 {
2836 PySSLSession *pysess;
Christian Heimes99a65702016-09-10 23:44:53 +02002837 SSL_SESSION *session;
Christian Heimes99a65702016-09-10 23:44:53 +02002838 int result;
2839
Christian Heimes7f1305e2021-04-17 20:06:38 +02002840 if (!Py_IS_TYPE(value, get_state_sock(self)->PySSLSession_Type)) {
Ned Deily4531ec72018-06-11 20:26:28 -04002841 PyErr_SetString(PyExc_TypeError, "Value is not a SSLSession.");
Christian Heimes99a65702016-09-10 23:44:53 +02002842 return -1;
2843 }
2844 pysess = (PySSLSession *)value;
2845
2846 if (self->ctx->ctx != pysess->ctx->ctx) {
2847 PyErr_SetString(PyExc_ValueError,
2848 "Session refers to a different SSLContext.");
2849 return -1;
2850 }
2851 if (self->socket_type != PY_SSL_CLIENT) {
2852 PyErr_SetString(PyExc_ValueError,
2853 "Cannot set session for server-side SSLSocket.");
2854 return -1;
2855 }
Christian Heimes66dc33b2017-05-23 16:02:02 -07002856 if (SSL_is_init_finished(self->ssl)) {
Christian Heimes99a65702016-09-10 23:44:53 +02002857 PyErr_SetString(PyExc_ValueError,
2858 "Cannot set session after handshake.");
2859 return -1;
2860 }
Christian Heimes99a65702016-09-10 23:44:53 +02002861 /* duplicate session */
2862 if ((session = _ssl_session_dup(pysess->session)) == NULL) {
2863 return -1;
2864 }
2865 result = SSL_set_session(self->ssl, session);
2866 /* free duplicate, SSL_set_session() bumps ref count */
2867 SSL_SESSION_free(session);
Christian Heimes99a65702016-09-10 23:44:53 +02002868 if (result == 0) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02002869 _setSSLError(get_state_sock(self), NULL, 0, __FILE__, __LINE__);
Christian Heimes99a65702016-09-10 23:44:53 +02002870 return -1;
2871 }
2872 return 0;
2873}
2874
2875PyDoc_STRVAR(PySSL_set_session_doc,
2876"_setter_session(session)\n\
2877\
2878Get / set SSLSession.");
2879
2880static PyObject *
2881PySSL_get_session_reused(PySSLSocket *self, void *closure) {
2882 if (SSL_session_reused(self->ssl)) {
2883 Py_RETURN_TRUE;
2884 } else {
2885 Py_RETURN_FALSE;
2886 }
2887}
2888
2889PyDoc_STRVAR(PySSL_get_session_reused_doc,
2890"Was the client session reused during handshake?");
2891
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002892static PyGetSetDef ssl_getsetlist[] = {
2893 {"context", (getter) PySSL_get_context,
2894 (setter) PySSL_set_context, PySSL_set_context_doc},
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002895 {"server_side", (getter) PySSL_get_server_side, NULL,
2896 PySSL_get_server_side_doc},
2897 {"server_hostname", (getter) PySSL_get_server_hostname, NULL,
2898 PySSL_get_server_hostname_doc},
2899 {"owner", (getter) PySSL_get_owner, (setter) PySSL_set_owner,
2900 PySSL_get_owner_doc},
Christian Heimes99a65702016-09-10 23:44:53 +02002901 {"session", (getter) PySSL_get_session,
2902 (setter) PySSL_set_session, PySSL_set_session_doc},
2903 {"session_reused", (getter) PySSL_get_session_reused, NULL,
2904 PySSL_get_session_reused_doc},
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002905 {NULL}, /* sentinel */
2906};
2907
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002908static PyMethodDef PySSLMethods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002909 _SSL__SSLSOCKET_DO_HANDSHAKE_METHODDEF
2910 _SSL__SSLSOCKET_WRITE_METHODDEF
2911 _SSL__SSLSOCKET_READ_METHODDEF
2912 _SSL__SSLSOCKET_PENDING_METHODDEF
Christian Heimes141c5e82018-02-24 21:10:57 +01002913 _SSL__SSLSOCKET_GETPEERCERT_METHODDEF
2914 _SSL__SSLSOCKET_GET_CHANNEL_BINDING_METHODDEF
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002915 _SSL__SSLSOCKET_CIPHER_METHODDEF
2916 _SSL__SSLSOCKET_SHARED_CIPHERS_METHODDEF
2917 _SSL__SSLSOCKET_VERSION_METHODDEF
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002918 _SSL__SSLSOCKET_SELECTED_ALPN_PROTOCOL_METHODDEF
2919 _SSL__SSLSOCKET_COMPRESSION_METHODDEF
2920 _SSL__SSLSOCKET_SHUTDOWN_METHODDEF
Christian Heimes9fb051f2018-09-23 08:32:31 +02002921 _SSL__SSLSOCKET_VERIFY_CLIENT_POST_HANDSHAKE_METHODDEF
Christian Heimes666991f2021-04-26 15:01:40 +02002922 _SSL__SSLSOCKET_GET_UNVERIFIED_CHAIN_METHODDEF
2923 _SSL__SSLSOCKET_GET_VERIFIED_CHAIN_METHODDEF
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002924 {NULL, NULL}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002925};
2926
Christian Heimes5c36da72020-11-20 09:40:12 +01002927static PyType_Slot PySSLSocket_slots[] = {
2928 {Py_tp_methods, PySSLMethods},
2929 {Py_tp_getset, ssl_getsetlist},
2930 {Py_tp_dealloc, PySSL_dealloc},
2931 {Py_tp_traverse, PySSL_traverse},
2932 {Py_tp_clear, PySSL_clear},
2933 {0, 0},
2934};
2935
2936static PyType_Spec PySSLSocket_spec = {
Miss Islington (bot)ea47a8a2021-05-27 09:25:22 -07002937 .name = "_ssl._SSLSocket",
2938 .basicsize = sizeof(PySSLSocket),
2939 .flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_IMMUTABLETYPE |
2940 Py_TPFLAGS_HAVE_GC),
2941 .slots = PySSLSocket_slots,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002942};
2943
Antoine Pitrou152efa22010-05-16 18:19:27 +00002944/*
2945 * _SSLContext objects
2946 */
2947
Christian Heimes5fe668c2016-09-12 00:01:11 +02002948static int
Christian Heimes9fb051f2018-09-23 08:32:31 +02002949_set_verify_mode(PySSLContext *self, enum py_ssl_cert_requirements n)
Christian Heimes5fe668c2016-09-12 00:01:11 +02002950{
2951 int mode;
2952 int (*verify_cb)(int, X509_STORE_CTX *) = NULL;
2953
2954 switch(n) {
2955 case PY_SSL_CERT_NONE:
2956 mode = SSL_VERIFY_NONE;
2957 break;
2958 case PY_SSL_CERT_OPTIONAL:
2959 mode = SSL_VERIFY_PEER;
2960 break;
2961 case PY_SSL_CERT_REQUIRED:
2962 mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
2963 break;
2964 default:
2965 PyErr_SetString(PyExc_ValueError,
2966 "invalid value for verify_mode");
2967 return -1;
2968 }
Christian Heimesf0f59302019-07-01 08:29:17 +02002969
2970 /* bpo-37428: newPySSLSocket() sets SSL_VERIFY_POST_HANDSHAKE flag for
2971 * server sockets and SSL_set_post_handshake_auth() for client. */
2972
Christian Heimes5fe668c2016-09-12 00:01:11 +02002973 /* keep current verify cb */
Christian Heimes9fb051f2018-09-23 08:32:31 +02002974 verify_cb = SSL_CTX_get_verify_callback(self->ctx);
2975 SSL_CTX_set_verify(self->ctx, mode, verify_cb);
Christian Heimes5fe668c2016-09-12 00:01:11 +02002976 return 0;
2977}
2978
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002979/*[clinic input]
2980@classmethod
2981_ssl._SSLContext.__new__
2982 protocol as proto_version: int
2983 /
2984[clinic start generated code]*/
2985
Antoine Pitrou152efa22010-05-16 18:19:27 +00002986static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002987_ssl__SSLContext_impl(PyTypeObject *type, int proto_version)
2988/*[clinic end generated code: output=2cf0d7a0741b6bd1 input=8d58a805b95fc534]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00002989{
Antoine Pitrou152efa22010-05-16 18:19:27 +00002990 PySSLContext *self;
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01002991 long options;
Christian Heimes2875c602021-04-19 07:27:10 +02002992 const SSL_METHOD *method = NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002993 SSL_CTX *ctx = NULL;
Christian Heimes61d478c2018-01-27 15:51:38 +01002994 X509_VERIFY_PARAM *params;
Christian Heimes358cfd42016-09-10 22:43:48 +02002995 int result;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002996
Christian Heimes7f1305e2021-04-17 20:06:38 +02002997 /* slower approach, walk MRO and get borrowed reference to module.
2998 * _PyType_GetModuleByDef is required for SSLContext subclasses */
2999 PyObject *module = _PyType_GetModuleByDef(type, &_sslmodule_def);
3000 if (module == NULL) {
3001 PyErr_SetString(PyExc_RuntimeError,
3002 "Cannot find internal module state");
3003 return NULL;
3004 }
3005
Christian Heimes6e8cda92020-05-16 03:33:05 +02003006 switch(proto_version) {
3007#if defined(SSL3_VERSION) && !defined(OPENSSL_NO_SSL3)
3008 case PY_SSL_VERSION_SSL3:
Miss Islington (bot)d7930fb2021-06-11 00:36:17 -07003009 PY_SSL_DEPRECATED("ssl.PROTOCOL_SSLv3 is deprecated", 2, NULL);
Christian Heimes2875c602021-04-19 07:27:10 +02003010 method = SSLv3_method();
Christian Heimes6e8cda92020-05-16 03:33:05 +02003011 break;
Benjamin Petersone32467c2014-12-05 21:59:35 -05003012#endif
Christian Heimesa871f692020-06-01 08:58:14 +02003013#if (defined(TLS1_VERSION) && \
3014 !defined(OPENSSL_NO_TLS1) && \
3015 !defined(OPENSSL_NO_TLS1_METHOD))
Christian Heimes6e8cda92020-05-16 03:33:05 +02003016 case PY_SSL_VERSION_TLS1:
Miss Islington (bot)d7930fb2021-06-11 00:36:17 -07003017 PY_SSL_DEPRECATED("ssl.PROTOCOL_TLSv1 is deprecated", 2, NULL);
Christian Heimes2875c602021-04-19 07:27:10 +02003018 method = TLSv1_method();
Christian Heimes6e8cda92020-05-16 03:33:05 +02003019 break;
Victor Stinner3de49192011-05-09 00:42:58 +02003020#endif
Christian Heimesa871f692020-06-01 08:58:14 +02003021#if (defined(TLS1_1_VERSION) && \
3022 !defined(OPENSSL_NO_TLS1_1) && \
3023 !defined(OPENSSL_NO_TLS1_1_METHOD))
Christian Heimes6e8cda92020-05-16 03:33:05 +02003024 case PY_SSL_VERSION_TLS1_1:
Miss Islington (bot)d7930fb2021-06-11 00:36:17 -07003025 PY_SSL_DEPRECATED("ssl.PROTOCOL_TLSv1_1 is deprecated", 2, NULL);
Christian Heimes2875c602021-04-19 07:27:10 +02003026 method = TLSv1_1_method();
Christian Heimes6e8cda92020-05-16 03:33:05 +02003027 break;
3028#endif
Christian Heimesa871f692020-06-01 08:58:14 +02003029#if (defined(TLS1_2_VERSION) && \
3030 !defined(OPENSSL_NO_TLS1_2) && \
3031 !defined(OPENSSL_NO_TLS1_2_METHOD))
Christian Heimes6e8cda92020-05-16 03:33:05 +02003032 case PY_SSL_VERSION_TLS1_2:
Miss Islington (bot)d7930fb2021-06-11 00:36:17 -07003033 PY_SSL_DEPRECATED("ssl.PROTOCOL_TLSv1_2 is deprecated", 2, NULL);
Christian Heimes2875c602021-04-19 07:27:10 +02003034 method = TLSv1_2_method();
Christian Heimes6e8cda92020-05-16 03:33:05 +02003035 break;
3036#endif
3037 case PY_SSL_VERSION_TLS:
Miss Islington (bot)d7930fb2021-06-11 00:36:17 -07003038 PY_SSL_DEPRECATED("ssl.PROTOCOL_TLS is deprecated", 2, NULL);
Christian Heimes2875c602021-04-19 07:27:10 +02003039 method = TLS_method();
Christian Heimes6e8cda92020-05-16 03:33:05 +02003040 break;
3041 case PY_SSL_VERSION_TLS_CLIENT:
Christian Heimes2875c602021-04-19 07:27:10 +02003042 method = TLS_client_method();
Christian Heimes6e8cda92020-05-16 03:33:05 +02003043 break;
3044 case PY_SSL_VERSION_TLS_SERVER:
Christian Heimes2875c602021-04-19 07:27:10 +02003045 method = TLS_server_method();
Christian Heimes6e8cda92020-05-16 03:33:05 +02003046 break;
3047 default:
Christian Heimes2875c602021-04-19 07:27:10 +02003048 method = NULL;
Christian Heimes6e8cda92020-05-16 03:33:05 +02003049 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003050
Christian Heimes2875c602021-04-19 07:27:10 +02003051 if (method == NULL) {
3052 PyErr_Format(PyExc_ValueError,
3053 "invalid or unsupported protocol version %i",
3054 proto_version);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003055 return NULL;
3056 }
Christian Heimes2875c602021-04-19 07:27:10 +02003057
3058 PySSL_BEGIN_ALLOW_THREADS
3059 ctx = SSL_CTX_new(method);
3060 PySSL_END_ALLOW_THREADS
3061
Antoine Pitrou152efa22010-05-16 18:19:27 +00003062 if (ctx == NULL) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02003063 _setSSLError(get_ssl_state(module), NULL, 0, __FILE__, __LINE__);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003064 return NULL;
3065 }
3066
3067 assert(type != NULL && type->tp_alloc != NULL);
3068 self = (PySSLContext *) type->tp_alloc(type, 0);
3069 if (self == NULL) {
3070 SSL_CTX_free(ctx);
3071 return NULL;
3072 }
3073 self->ctx = ctx;
Christian Heimes61d478c2018-01-27 15:51:38 +01003074 self->hostflags = X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS;
Christian Heimes11a14932018-02-24 02:35:08 +01003075 self->protocol = proto_version;
Christian Heimesc7f70692019-05-31 11:44:05 +02003076 self->msg_cb = NULL;
Christian Heimesc7f70692019-05-31 11:44:05 +02003077 self->keylog_filename = NULL;
3078 self->keylog_bio = NULL;
Benjamin Petersoncca27322015-01-23 16:35:37 -05003079 self->alpn_protocols = NULL;
Christian Heimes11a14932018-02-24 02:35:08 +01003080 self->set_sni_cb = NULL;
Christian Heimes7f1305e2021-04-17 20:06:38 +02003081 self->state = get_ssl_state(module);
3082
Christian Heimes1aa9a752013-12-02 02:41:19 +01003083 /* Don't check host name by default */
Christian Heimes5fe668c2016-09-12 00:01:11 +02003084 if (proto_version == PY_SSL_VERSION_TLS_CLIENT) {
3085 self->check_hostname = 1;
Christian Heimes9fb051f2018-09-23 08:32:31 +02003086 if (_set_verify_mode(self, PY_SSL_CERT_REQUIRED) == -1) {
Christian Heimes5fe668c2016-09-12 00:01:11 +02003087 Py_DECREF(self);
3088 return NULL;
3089 }
3090 } else {
3091 self->check_hostname = 0;
Christian Heimes9fb051f2018-09-23 08:32:31 +02003092 if (_set_verify_mode(self, PY_SSL_CERT_NONE) == -1) {
Christian Heimes5fe668c2016-09-12 00:01:11 +02003093 Py_DECREF(self);
3094 return NULL;
3095 }
3096 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003097 /* Defaults */
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01003098 options = SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
3099 if (proto_version != PY_SSL_VERSION_SSL2)
3100 options |= SSL_OP_NO_SSLv2;
Benjamin Petersona9dcdab2015-11-11 22:38:41 -08003101 if (proto_version != PY_SSL_VERSION_SSL3)
3102 options |= SSL_OP_NO_SSLv3;
Christian Heimes358cfd42016-09-10 22:43:48 +02003103 /* Minimal security flags for server and client side context.
3104 * Client sockets ignore server-side parameters. */
3105#ifdef SSL_OP_NO_COMPRESSION
3106 options |= SSL_OP_NO_COMPRESSION;
3107#endif
3108#ifdef SSL_OP_CIPHER_SERVER_PREFERENCE
3109 options |= SSL_OP_CIPHER_SERVER_PREFERENCE;
3110#endif
3111#ifdef SSL_OP_SINGLE_DH_USE
3112 options |= SSL_OP_SINGLE_DH_USE;
3113#endif
3114#ifdef SSL_OP_SINGLE_ECDH_USE
3115 options |= SSL_OP_SINGLE_ECDH_USE;
3116#endif
Christian Heimes6f37ebc2021-04-09 17:59:21 +02003117#ifdef SSL_OP_IGNORE_UNEXPECTED_EOF
3118 /* Make OpenSSL 3.0.0 behave like 1.1.1 */
3119 options |= SSL_OP_IGNORE_UNEXPECTED_EOF;
3120#endif
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01003121 SSL_CTX_set_options(self->ctx, options);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003122
Semen Zhydenko1295e112017-10-15 21:28:31 +02003123 /* A bare minimum cipher list without completely broken cipher suites.
Christian Heimes358cfd42016-09-10 22:43:48 +02003124 * It's far from perfect but gives users a better head start. */
3125 if (proto_version != PY_SSL_VERSION_SSL2) {
Christian Heimes892d66e2018-01-29 14:10:18 +01003126#if PY_SSL_DEFAULT_CIPHERS == 2
3127 /* stick to OpenSSL's default settings */
3128 result = 1;
3129#else
3130 result = SSL_CTX_set_cipher_list(ctx, PY_SSL_DEFAULT_CIPHER_STRING);
3131#endif
Christian Heimes358cfd42016-09-10 22:43:48 +02003132 } else {
3133 /* SSLv2 needs MD5 */
3134 result = SSL_CTX_set_cipher_list(ctx, "HIGH:!aNULL:!eNULL");
3135 }
3136 if (result == 0) {
3137 Py_DECREF(self);
3138 ERR_clear_error();
Christian Heimes7f1305e2021-04-17 20:06:38 +02003139 PyErr_SetString(get_state_ctx(self)->PySSLErrorObject,
Christian Heimes358cfd42016-09-10 22:43:48 +02003140 "No cipher can be selected.");
Christian Heimese9832522021-05-01 20:53:10 +02003141 goto error;
Christian Heimes358cfd42016-09-10 22:43:48 +02003142 }
Christian Heimese9832522021-05-01 20:53:10 +02003143#ifdef PY_SSL_MIN_PROTOCOL
3144 switch(proto_version) {
3145 case PY_SSL_VERSION_TLS:
3146 case PY_SSL_VERSION_TLS_CLIENT:
3147 case PY_SSL_VERSION_TLS_SERVER:
3148 result = SSL_CTX_set_min_proto_version(ctx, PY_SSL_MIN_PROTOCOL);
3149 if (result == 0) {
3150 PyErr_Format(PyExc_ValueError,
3151 "Failed to set minimum protocol 0x%x",
3152 PY_SSL_MIN_PROTOCOL);
3153 goto error;
3154 }
3155 break;
3156 default:
3157 break;
3158 }
3159#endif
Christian Heimes358cfd42016-09-10 22:43:48 +02003160
Benjamin Peterson3b1a8b32016-01-07 21:37:37 -08003161 /* Set SSL_MODE_RELEASE_BUFFERS. This potentially greatly reduces memory
Christian Heimes39258d32021-04-17 11:36:35 +02003162 usage for no cost at all. */
3163 SSL_CTX_set_mode(self->ctx, SSL_MODE_RELEASE_BUFFERS);
Antoine Pitrou0bebbc32014-03-22 18:13:50 +01003164
Antoine Pitroufc113ee2010-10-13 12:46:13 +00003165#define SID_CTX "Python"
3166 SSL_CTX_set_session_id_context(self->ctx, (const unsigned char *) SID_CTX,
3167 sizeof(SID_CTX));
3168#undef SID_CTX
3169
Christian Heimes61d478c2018-01-27 15:51:38 +01003170 params = SSL_CTX_get0_param(self->ctx);
Christian Heimes61d478c2018-01-27 15:51:38 +01003171 /* Improve trust chain building when cross-signed intermediate
3172 certificates are present. See https://bugs.python.org/issue23476. */
3173 X509_VERIFY_PARAM_set_flags(params, X509_V_FLAG_TRUSTED_FIRST);
Christian Heimes61d478c2018-01-27 15:51:38 +01003174 X509_VERIFY_PARAM_set_hostflags(params, self->hostflags);
Benjamin Petersonfdb19712015-03-04 22:11:12 -05003175
Christian Heimes9fb051f2018-09-23 08:32:31 +02003176#ifdef TLS1_3_VERSION
3177 self->post_handshake_auth = 0;
3178 SSL_CTX_set_post_handshake_auth(self->ctx, self->post_handshake_auth);
3179#endif
3180
Antoine Pitrou152efa22010-05-16 18:19:27 +00003181 return (PyObject *)self;
Christian Heimese9832522021-05-01 20:53:10 +02003182 error:
3183 Py_XDECREF(self);
3184 ERR_clear_error();
3185 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003186}
3187
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003188static int
3189context_traverse(PySSLContext *self, visitproc visit, void *arg)
3190{
Christian Heimes11a14932018-02-24 02:35:08 +01003191 Py_VISIT(self->set_sni_cb);
Christian Heimesc7f70692019-05-31 11:44:05 +02003192 Py_VISIT(self->msg_cb);
Miss Islington (bot)ea47a8a2021-05-27 09:25:22 -07003193 Py_VISIT(Py_TYPE(self));
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003194 return 0;
3195}
3196
3197static int
3198context_clear(PySSLContext *self)
3199{
Christian Heimes11a14932018-02-24 02:35:08 +01003200 Py_CLEAR(self->set_sni_cb);
Christian Heimesc7f70692019-05-31 11:44:05 +02003201 Py_CLEAR(self->msg_cb);
Christian Heimesc7f70692019-05-31 11:44:05 +02003202 Py_CLEAR(self->keylog_filename);
3203 if (self->keylog_bio != NULL) {
3204 PySSL_BEGIN_ALLOW_THREADS
3205 BIO_free_all(self->keylog_bio);
3206 PySSL_END_ALLOW_THREADS
3207 self->keylog_bio = NULL;
3208 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003209 return 0;
3210}
3211
Antoine Pitrou152efa22010-05-16 18:19:27 +00003212static void
3213context_dealloc(PySSLContext *self)
3214{
Christian Heimes5c36da72020-11-20 09:40:12 +01003215 PyTypeObject *tp = Py_TYPE(self);
INADA Naokia6296d32017-08-24 14:55:17 +09003216 /* bpo-31095: UnTrack is needed before calling any callbacks */
3217 PyObject_GC_UnTrack(self);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003218 context_clear(self);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003219 SSL_CTX_free(self->ctx);
Christian Heimes39258d32021-04-17 11:36:35 +02003220 PyMem_FREE(self->alpn_protocols);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003221 Py_TYPE(self)->tp_free(self);
Christian Heimes5c36da72020-11-20 09:40:12 +01003222 Py_DECREF(tp);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003223}
3224
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003225/*[clinic input]
3226_ssl._SSLContext.set_ciphers
3227 cipherlist: str
3228 /
3229[clinic start generated code]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003230
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003231static PyObject *
3232_ssl__SSLContext_set_ciphers_impl(PySSLContext *self, const char *cipherlist)
3233/*[clinic end generated code: output=3a3162f3557c0f3f input=a7ac931b9f3ca7fc]*/
3234{
3235 int ret = SSL_CTX_set_cipher_list(self->ctx, cipherlist);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003236 if (ret == 0) {
Antoine Pitrou65ec8ae2010-05-16 19:56:32 +00003237 /* Clearing the error queue is necessary on some OpenSSL versions,
3238 otherwise the error will be reported again when another SSL call
3239 is done. */
3240 ERR_clear_error();
Christian Heimes7f1305e2021-04-17 20:06:38 +02003241 PyErr_SetString(get_state_ctx(self)->PySSLErrorObject,
Antoine Pitrou152efa22010-05-16 18:19:27 +00003242 "No cipher can be selected.");
3243 return NULL;
3244 }
3245 Py_RETURN_NONE;
3246}
3247
Christian Heimes25bfcd52016-09-06 00:04:45 +02003248/*[clinic input]
3249_ssl._SSLContext.get_ciphers
3250[clinic start generated code]*/
3251
3252static PyObject *
3253_ssl__SSLContext_get_ciphers_impl(PySSLContext *self)
3254/*[clinic end generated code: output=a56e4d68a406dfc4 input=a2aadc9af89b79c5]*/
3255{
3256 SSL *ssl = NULL;
3257 STACK_OF(SSL_CIPHER) *sk = NULL;
Christian Heimes99a65702016-09-10 23:44:53 +02003258 const SSL_CIPHER *cipher;
Christian Heimes25bfcd52016-09-06 00:04:45 +02003259 int i=0;
3260 PyObject *result = NULL, *dct;
3261
3262 ssl = SSL_new(self->ctx);
3263 if (ssl == NULL) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02003264 _setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
Christian Heimes25bfcd52016-09-06 00:04:45 +02003265 goto exit;
3266 }
3267 sk = SSL_get_ciphers(ssl);
3268
3269 result = PyList_New(sk_SSL_CIPHER_num(sk));
3270 if (result == NULL) {
3271 goto exit;
3272 }
3273
3274 for (i = 0; i < sk_SSL_CIPHER_num(sk); i++) {
3275 cipher = sk_SSL_CIPHER_value(sk, i);
3276 dct = cipher_to_dict(cipher);
3277 if (dct == NULL) {
3278 Py_CLEAR(result);
3279 goto exit;
3280 }
3281 PyList_SET_ITEM(result, i, dct);
3282 }
3283
3284 exit:
3285 if (ssl != NULL)
3286 SSL_free(ssl);
3287 return result;
3288
3289}
Christian Heimes25bfcd52016-09-06 00:04:45 +02003290
3291
Benjamin Petersoncca27322015-01-23 16:35:37 -05003292static int
Benjamin Peterson88615022015-01-23 17:30:26 -05003293do_protocol_selection(int alpn, unsigned char **out, unsigned char *outlen,
3294 const unsigned char *server_protocols, unsigned int server_protocols_len,
3295 const unsigned char *client_protocols, unsigned int client_protocols_len)
Benjamin Petersoncca27322015-01-23 16:35:37 -05003296{
Benjamin Peterson88615022015-01-23 17:30:26 -05003297 int ret;
3298 if (client_protocols == NULL) {
3299 client_protocols = (unsigned char *)"";
3300 client_protocols_len = 0;
3301 }
3302 if (server_protocols == NULL) {
3303 server_protocols = (unsigned char *)"";
3304 server_protocols_len = 0;
Benjamin Petersoncca27322015-01-23 16:35:37 -05003305 }
3306
Benjamin Peterson88615022015-01-23 17:30:26 -05003307 ret = SSL_select_next_proto(out, outlen,
3308 server_protocols, server_protocols_len,
3309 client_protocols, client_protocols_len);
3310 if (alpn && ret != OPENSSL_NPN_NEGOTIATED)
3311 return SSL_TLSEXT_ERR_NOACK;
Benjamin Petersoncca27322015-01-23 16:35:37 -05003312
3313 return SSL_TLSEXT_ERR_OK;
3314}
3315
Benjamin Petersoncca27322015-01-23 16:35:37 -05003316static int
3317_selectALPN_cb(SSL *s,
3318 const unsigned char **out, unsigned char *outlen,
3319 const unsigned char *client_protocols, unsigned int client_protocols_len,
3320 void *args)
3321{
3322 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Peterson88615022015-01-23 17:30:26 -05003323 return do_protocol_selection(1, (unsigned char **)out, outlen,
3324 ctx->alpn_protocols, ctx->alpn_protocols_len,
3325 client_protocols, client_protocols_len);
Benjamin Petersoncca27322015-01-23 16:35:37 -05003326}
Benjamin Petersoncca27322015-01-23 16:35:37 -05003327
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003328/*[clinic input]
3329_ssl._SSLContext._set_alpn_protocols
3330 protos: Py_buffer
3331 /
3332[clinic start generated code]*/
3333
Benjamin Petersoncca27322015-01-23 16:35:37 -05003334static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003335_ssl__SSLContext__set_alpn_protocols_impl(PySSLContext *self,
3336 Py_buffer *protos)
3337/*[clinic end generated code: output=87599a7f76651a9b input=9bba964595d519be]*/
Benjamin Petersoncca27322015-01-23 16:35:37 -05003338{
Victor Stinner5a615592017-09-14 01:10:30 -07003339 if ((size_t)protos->len > UINT_MAX) {
Segev Finer5cff6372017-07-27 01:19:17 +03003340 PyErr_Format(PyExc_OverflowError,
Serhiy Storchakad53fe5f2019-03-13 22:59:55 +02003341 "protocols longer than %u bytes", UINT_MAX);
Segev Finer5cff6372017-07-27 01:19:17 +03003342 return NULL;
3343 }
3344
Victor Stinner00d7abd2020-12-01 09:56:42 +01003345 PyMem_Free(self->alpn_protocols);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003346 self->alpn_protocols = PyMem_Malloc(protos->len);
Benjamin Petersoncca27322015-01-23 16:35:37 -05003347 if (!self->alpn_protocols)
3348 return PyErr_NoMemory();
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003349 memcpy(self->alpn_protocols, protos->buf, protos->len);
Segev Finer5cff6372017-07-27 01:19:17 +03003350 self->alpn_protocols_len = (unsigned int)protos->len;
Benjamin Petersoncca27322015-01-23 16:35:37 -05003351
3352 if (SSL_CTX_set_alpn_protos(self->ctx, self->alpn_protocols, self->alpn_protocols_len))
3353 return PyErr_NoMemory();
3354 SSL_CTX_set_alpn_select_cb(self->ctx, _selectALPN_cb, self);
3355
Benjamin Petersoncca27322015-01-23 16:35:37 -05003356 Py_RETURN_NONE;
Benjamin Petersoncca27322015-01-23 16:35:37 -05003357}
3358
Antoine Pitrou152efa22010-05-16 18:19:27 +00003359static PyObject *
3360get_verify_mode(PySSLContext *self, void *c)
3361{
Christian Heimes9fb051f2018-09-23 08:32:31 +02003362 /* ignore SSL_VERIFY_CLIENT_ONCE and SSL_VERIFY_POST_HANDSHAKE */
3363 int mask = (SSL_VERIFY_NONE | SSL_VERIFY_PEER |
3364 SSL_VERIFY_FAIL_IF_NO_PEER_CERT);
3365 switch (SSL_CTX_get_verify_mode(self->ctx) & mask) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003366 case SSL_VERIFY_NONE:
3367 return PyLong_FromLong(PY_SSL_CERT_NONE);
3368 case SSL_VERIFY_PEER:
3369 return PyLong_FromLong(PY_SSL_CERT_OPTIONAL);
3370 case SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT:
3371 return PyLong_FromLong(PY_SSL_CERT_REQUIRED);
3372 }
Christian Heimes7f1305e2021-04-17 20:06:38 +02003373 PyErr_SetString(get_state_ctx(self)->PySSLErrorObject,
Antoine Pitrou152efa22010-05-16 18:19:27 +00003374 "invalid return value from SSL_CTX_get_verify_mode");
3375 return NULL;
3376}
3377
3378static int
3379set_verify_mode(PySSLContext *self, PyObject *arg, void *c)
3380{
Christian Heimes5fe668c2016-09-12 00:01:11 +02003381 int n;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003382 if (!PyArg_Parse(arg, "i", &n))
3383 return -1;
Christian Heimes5fe668c2016-09-12 00:01:11 +02003384 if (n == PY_SSL_CERT_NONE && self->check_hostname) {
Christian Heimes1aa9a752013-12-02 02:41:19 +01003385 PyErr_SetString(PyExc_ValueError,
3386 "Cannot set verify_mode to CERT_NONE when "
3387 "check_hostname is enabled.");
3388 return -1;
3389 }
Christian Heimes9fb051f2018-09-23 08:32:31 +02003390 return _set_verify_mode(self, n);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003391}
3392
3393static PyObject *
Christian Heimes22587792013-11-21 23:56:13 +01003394get_verify_flags(PySSLContext *self, void *c)
3395{
Christian Heimes598894f2016-09-05 23:19:05 +02003396 X509_VERIFY_PARAM *param;
Christian Heimes22587792013-11-21 23:56:13 +01003397 unsigned long flags;
3398
Christian Heimes61d478c2018-01-27 15:51:38 +01003399 param = SSL_CTX_get0_param(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02003400 flags = X509_VERIFY_PARAM_get_flags(param);
Christian Heimes22587792013-11-21 23:56:13 +01003401 return PyLong_FromUnsignedLong(flags);
3402}
3403
3404static int
3405set_verify_flags(PySSLContext *self, PyObject *arg, void *c)
3406{
Christian Heimes598894f2016-09-05 23:19:05 +02003407 X509_VERIFY_PARAM *param;
Christian Heimes22587792013-11-21 23:56:13 +01003408 unsigned long new_flags, flags, set, clear;
3409
3410 if (!PyArg_Parse(arg, "k", &new_flags))
3411 return -1;
Christian Heimes61d478c2018-01-27 15:51:38 +01003412 param = SSL_CTX_get0_param(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02003413 flags = X509_VERIFY_PARAM_get_flags(param);
Christian Heimes22587792013-11-21 23:56:13 +01003414 clear = flags & ~new_flags;
3415 set = ~flags & new_flags;
3416 if (clear) {
Christian Heimes598894f2016-09-05 23:19:05 +02003417 if (!X509_VERIFY_PARAM_clear_flags(param, clear)) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02003418 _setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
Christian Heimes22587792013-11-21 23:56:13 +01003419 return -1;
3420 }
3421 }
3422 if (set) {
Christian Heimes598894f2016-09-05 23:19:05 +02003423 if (!X509_VERIFY_PARAM_set_flags(param, set)) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02003424 _setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
Christian Heimes22587792013-11-21 23:56:13 +01003425 return -1;
3426 }
3427 }
3428 return 0;
3429}
3430
Christian Heimes698dde12018-02-27 11:54:43 +01003431/* Getter and setter for protocol version */
Christian Heimes698dde12018-02-27 11:54:43 +01003432static int
3433set_min_max_proto_version(PySSLContext *self, PyObject *arg, int what)
3434{
3435 long v;
3436 int result;
3437
3438 if (!PyArg_Parse(arg, "l", &v))
3439 return -1;
3440 if (v > INT_MAX) {
3441 PyErr_SetString(PyExc_OverflowError, "Option is too long");
3442 return -1;
3443 }
3444
3445 switch(self->protocol) {
3446 case PY_SSL_VERSION_TLS_CLIENT: /* fall through */
3447 case PY_SSL_VERSION_TLS_SERVER: /* fall through */
3448 case PY_SSL_VERSION_TLS:
3449 break;
3450 default:
3451 PyErr_SetString(
3452 PyExc_ValueError,
3453 "The context's protocol doesn't support modification of "
3454 "highest and lowest version."
3455 );
3456 return -1;
3457 }
3458
Christian Heimes2875c602021-04-19 07:27:10 +02003459 /* check for deprecations and supported values */
3460 switch(v) {
3461 case PY_PROTO_SSLv3:
Miss Islington (bot)d7930fb2021-06-11 00:36:17 -07003462 PY_SSL_DEPRECATED("ssl.TLSVersion.SSLv3 is deprecated", 2, -1);
Christian Heimes2875c602021-04-19 07:27:10 +02003463 break;
3464 case PY_PROTO_TLSv1:
Miss Islington (bot)d7930fb2021-06-11 00:36:17 -07003465 PY_SSL_DEPRECATED("ssl.TLSVersion.TLSv1 is deprecated", 2, -1);
Christian Heimes2875c602021-04-19 07:27:10 +02003466 break;
3467 case PY_PROTO_TLSv1_1:
Miss Islington (bot)d7930fb2021-06-11 00:36:17 -07003468 PY_SSL_DEPRECATED("ssl.TLSVersion.TLSv1_1 is deprecated", 2, -1);
Christian Heimes2875c602021-04-19 07:27:10 +02003469 break;
3470 case PY_PROTO_MINIMUM_SUPPORTED:
3471 case PY_PROTO_MAXIMUM_SUPPORTED:
3472 case PY_PROTO_TLSv1_2:
3473 case PY_PROTO_TLSv1_3:
3474 /* ok */
3475 break;
3476 default:
3477 PyErr_Format(PyExc_ValueError,
3478 "Unsupported TLS/SSL version 0x%x", v);
3479 return -1;
3480 }
3481
Christian Heimes698dde12018-02-27 11:54:43 +01003482 if (what == 0) {
3483 switch(v) {
3484 case PY_PROTO_MINIMUM_SUPPORTED:
3485 v = 0;
3486 break;
3487 case PY_PROTO_MAXIMUM_SUPPORTED:
3488 /* Emulate max for set_min_proto_version */
3489 v = PY_PROTO_MAXIMUM_AVAILABLE;
3490 break;
3491 default:
3492 break;
3493 }
3494 result = SSL_CTX_set_min_proto_version(self->ctx, v);
3495 }
3496 else {
3497 switch(v) {
3498 case PY_PROTO_MAXIMUM_SUPPORTED:
3499 v = 0;
3500 break;
3501 case PY_PROTO_MINIMUM_SUPPORTED:
3502 /* Emulate max for set_min_proto_version */
3503 v = PY_PROTO_MINIMUM_AVAILABLE;
3504 break;
3505 default:
3506 break;
3507 }
3508 result = SSL_CTX_set_max_proto_version(self->ctx, v);
3509 }
3510 if (result == 0) {
3511 PyErr_Format(PyExc_ValueError,
3512 "Unsupported protocol version 0x%x", v);
3513 return -1;
3514 }
3515 return 0;
3516}
3517
3518static PyObject *
3519get_minimum_version(PySSLContext *self, void *c)
3520{
3521 int v = SSL_CTX_ctrl(self->ctx, SSL_CTRL_GET_MIN_PROTO_VERSION, 0, NULL);
3522 if (v == 0) {
3523 v = PY_PROTO_MINIMUM_SUPPORTED;
3524 }
3525 return PyLong_FromLong(v);
3526}
3527
3528static int
3529set_minimum_version(PySSLContext *self, PyObject *arg, void *c)
3530{
3531 return set_min_max_proto_version(self, arg, 0);
3532}
3533
3534static PyObject *
3535get_maximum_version(PySSLContext *self, void *c)
3536{
3537 int v = SSL_CTX_ctrl(self->ctx, SSL_CTRL_GET_MAX_PROTO_VERSION, 0, NULL);
3538 if (v == 0) {
3539 v = PY_PROTO_MAXIMUM_SUPPORTED;
3540 }
3541 return PyLong_FromLong(v);
3542}
3543
3544static int
3545set_maximum_version(PySSLContext *self, PyObject *arg, void *c)
3546{
3547 return set_min_max_proto_version(self, arg, 1);
3548}
Christian Heimes698dde12018-02-27 11:54:43 +01003549
Christian Heimes39258d32021-04-17 11:36:35 +02003550#ifdef TLS1_3_VERSION
Christian Heimes78c7d522019-06-03 21:00:10 +02003551static PyObject *
3552get_num_tickets(PySSLContext *self, void *c)
3553{
Victor Stinner76611c72019-07-09 13:30:52 +02003554 return PyLong_FromSize_t(SSL_CTX_get_num_tickets(self->ctx));
Christian Heimes78c7d522019-06-03 21:00:10 +02003555}
3556
3557static int
3558set_num_tickets(PySSLContext *self, PyObject *arg, void *c)
3559{
3560 long num;
3561 if (!PyArg_Parse(arg, "l", &num))
3562 return -1;
3563 if (num < 0) {
3564 PyErr_SetString(PyExc_ValueError, "value must be non-negative");
3565 return -1;
3566 }
3567 if (self->protocol != PY_SSL_VERSION_TLS_SERVER) {
3568 PyErr_SetString(PyExc_ValueError,
3569 "SSLContext is not a server context.");
3570 return -1;
3571 }
3572 if (SSL_CTX_set_num_tickets(self->ctx, num) != 1) {
3573 PyErr_SetString(PyExc_ValueError, "failed to set num tickets.");
3574 return -1;
3575 }
3576 return 0;
3577}
3578
3579PyDoc_STRVAR(PySSLContext_num_tickets_doc,
3580"Control the number of TLSv1.3 session tickets");
Christian Heimes39258d32021-04-17 11:36:35 +02003581#endif /* TLS1_3_VERSION */
Christian Heimes78c7d522019-06-03 21:00:10 +02003582
matthewhughes9348e836bb2020-07-17 09:59:15 +01003583static PyObject *
3584get_security_level(PySSLContext *self, void *c)
3585{
3586 return PyLong_FromLong(SSL_CTX_get_security_level(self->ctx));
3587}
3588PyDoc_STRVAR(PySSLContext_security_level_doc, "The current security level");
matthewhughes9348e836bb2020-07-17 09:59:15 +01003589
Christian Heimes22587792013-11-21 23:56:13 +01003590static PyObject *
Antoine Pitroub5218772010-05-21 09:56:06 +00003591get_options(PySSLContext *self, void *c)
3592{
3593 return PyLong_FromLong(SSL_CTX_get_options(self->ctx));
3594}
3595
3596static int
3597set_options(PySSLContext *self, PyObject *arg, void *c)
3598{
3599 long new_opts, opts, set, clear;
Christian Heimes2875c602021-04-19 07:27:10 +02003600 long opt_no = (
3601 SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1 |
Miss Islington (bot)4becc562021-06-13 05:07:00 -07003602 SSL_OP_NO_TLSv1_1 | SSL_OP_NO_TLSv1_2 | SSL_OP_NO_TLSv1_3
Christian Heimes2875c602021-04-19 07:27:10 +02003603 );
3604
Antoine Pitroub5218772010-05-21 09:56:06 +00003605 if (!PyArg_Parse(arg, "l", &new_opts))
3606 return -1;
3607 opts = SSL_CTX_get_options(self->ctx);
3608 clear = opts & ~new_opts;
3609 set = ~opts & new_opts;
Christian Heimes2875c602021-04-19 07:27:10 +02003610
3611 if ((set & opt_no) != 0) {
Miss Islington (bot)08f2b9d2021-06-17 03:00:56 -07003612 if (_ssl_deprecated("ssl.OP_NO_SSL*/ssl.OP_NO_TLS* options are "
Christian Heimes2875c602021-04-19 07:27:10 +02003613 "deprecated", 2) < 0) {
3614 return -1;
3615 }
3616 }
Antoine Pitroub5218772010-05-21 09:56:06 +00003617 if (clear) {
Antoine Pitroub5218772010-05-21 09:56:06 +00003618 SSL_CTX_clear_options(self->ctx, clear);
Antoine Pitroub5218772010-05-21 09:56:06 +00003619 }
3620 if (set)
3621 SSL_CTX_set_options(self->ctx, set);
3622 return 0;
3623}
3624
Christian Heimes1aa9a752013-12-02 02:41:19 +01003625static PyObject *
Christian Heimes61d478c2018-01-27 15:51:38 +01003626get_host_flags(PySSLContext *self, void *c)
3627{
3628 return PyLong_FromUnsignedLong(self->hostflags);
3629}
3630
3631static int
3632set_host_flags(PySSLContext *self, PyObject *arg, void *c)
3633{
3634 X509_VERIFY_PARAM *param;
3635 unsigned int new_flags = 0;
3636
3637 if (!PyArg_Parse(arg, "I", &new_flags))
3638 return -1;
3639
3640 param = SSL_CTX_get0_param(self->ctx);
3641 self->hostflags = new_flags;
3642 X509_VERIFY_PARAM_set_hostflags(param, new_flags);
3643 return 0;
3644}
3645
3646static PyObject *
Christian Heimes1aa9a752013-12-02 02:41:19 +01003647get_check_hostname(PySSLContext *self, void *c)
3648{
3649 return PyBool_FromLong(self->check_hostname);
3650}
3651
3652static int
3653set_check_hostname(PySSLContext *self, PyObject *arg, void *c)
3654{
3655 int check_hostname;
3656 if (!PyArg_Parse(arg, "p", &check_hostname))
3657 return -1;
3658 if (check_hostname &&
3659 SSL_CTX_get_verify_mode(self->ctx) == SSL_VERIFY_NONE) {
Christian Heimese82c0342017-09-15 20:29:57 +02003660 /* check_hostname = True sets verify_mode = CERT_REQUIRED */
Christian Heimes9fb051f2018-09-23 08:32:31 +02003661 if (_set_verify_mode(self, PY_SSL_CERT_REQUIRED) == -1) {
Christian Heimese82c0342017-09-15 20:29:57 +02003662 return -1;
3663 }
Christian Heimes1aa9a752013-12-02 02:41:19 +01003664 }
3665 self->check_hostname = check_hostname;
3666 return 0;
3667}
3668
Christian Heimes11a14932018-02-24 02:35:08 +01003669static PyObject *
Christian Heimes9fb051f2018-09-23 08:32:31 +02003670get_post_handshake_auth(PySSLContext *self, void *c) {
3671#if TLS1_3_VERSION
3672 return PyBool_FromLong(self->post_handshake_auth);
3673#else
3674 Py_RETURN_NONE;
3675#endif
3676}
3677
3678#if TLS1_3_VERSION
3679static int
3680set_post_handshake_auth(PySSLContext *self, PyObject *arg, void *c) {
Zackery Spytz842acaa2018-12-17 07:52:45 -07003681 if (arg == NULL) {
3682 PyErr_SetString(PyExc_AttributeError, "cannot delete attribute");
3683 return -1;
3684 }
Christian Heimes9fb051f2018-09-23 08:32:31 +02003685 int pha = PyObject_IsTrue(arg);
3686
3687 if (pha == -1) {
3688 return -1;
3689 }
3690 self->post_handshake_auth = pha;
3691
Christian Heimesf0f59302019-07-01 08:29:17 +02003692 /* bpo-37428: newPySSLSocket() sets SSL_VERIFY_POST_HANDSHAKE flag for
3693 * server sockets and SSL_set_post_handshake_auth() for client. */
Christian Heimes9fb051f2018-09-23 08:32:31 +02003694
3695 return 0;
3696}
3697#endif
3698
3699static PyObject *
Christian Heimes11a14932018-02-24 02:35:08 +01003700get_protocol(PySSLContext *self, void *c) {
3701 return PyLong_FromLong(self->protocol);
3702}
Christian Heimes1aa9a752013-12-02 02:41:19 +01003703
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003704typedef struct {
3705 PyThreadState *thread_state;
3706 PyObject *callable;
3707 char *password;
Victor Stinner9ee02032013-06-23 15:08:23 +02003708 int size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003709 int error;
3710} _PySSLPasswordInfo;
3711
3712static int
3713_pwinfo_set(_PySSLPasswordInfo *pw_info, PyObject* password,
3714 const char *bad_type_error)
3715{
3716 /* Set the password and size fields of a _PySSLPasswordInfo struct
3717 from a unicode, bytes, or byte array object.
3718 The password field will be dynamically allocated and must be freed
3719 by the caller */
3720 PyObject *password_bytes = NULL;
3721 const char *data = NULL;
3722 Py_ssize_t size;
3723
3724 if (PyUnicode_Check(password)) {
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03003725 password_bytes = PyUnicode_AsUTF8String(password);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003726 if (!password_bytes) {
3727 goto error;
3728 }
3729 data = PyBytes_AS_STRING(password_bytes);
3730 size = PyBytes_GET_SIZE(password_bytes);
3731 } else if (PyBytes_Check(password)) {
3732 data = PyBytes_AS_STRING(password);
3733 size = PyBytes_GET_SIZE(password);
3734 } else if (PyByteArray_Check(password)) {
3735 data = PyByteArray_AS_STRING(password);
3736 size = PyByteArray_GET_SIZE(password);
3737 } else {
3738 PyErr_SetString(PyExc_TypeError, bad_type_error);
3739 goto error;
3740 }
3741
Victor Stinner9ee02032013-06-23 15:08:23 +02003742 if (size > (Py_ssize_t)INT_MAX) {
3743 PyErr_Format(PyExc_ValueError,
3744 "password cannot be longer than %d bytes", INT_MAX);
3745 goto error;
3746 }
3747
Victor Stinner11ebff22013-07-07 17:07:52 +02003748 PyMem_Free(pw_info->password);
3749 pw_info->password = PyMem_Malloc(size);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003750 if (!pw_info->password) {
3751 PyErr_SetString(PyExc_MemoryError,
3752 "unable to allocate password buffer");
3753 goto error;
3754 }
3755 memcpy(pw_info->password, data, size);
Victor Stinner9ee02032013-06-23 15:08:23 +02003756 pw_info->size = (int)size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003757
3758 Py_XDECREF(password_bytes);
3759 return 1;
3760
3761error:
3762 Py_XDECREF(password_bytes);
3763 return 0;
3764}
3765
3766static int
3767_password_callback(char *buf, int size, int rwflag, void *userdata)
3768{
3769 _PySSLPasswordInfo *pw_info = (_PySSLPasswordInfo*) userdata;
3770 PyObject *fn_ret = NULL;
3771
3772 PySSL_END_ALLOW_THREADS_S(pw_info->thread_state);
3773
Christian Heimesd3b73f32021-04-09 15:23:38 +02003774 if (pw_info->error) {
3775 /* already failed previously. OpenSSL 3.0.0-alpha14 invokes the
3776 * callback multiple times which can lead to fatal Python error in
3777 * exception check. */
3778 goto error;
3779 }
3780
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003781 if (pw_info->callable) {
Victor Stinnerf17c3de2016-12-06 18:46:19 +01003782 fn_ret = _PyObject_CallNoArg(pw_info->callable);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003783 if (!fn_ret) {
3784 /* TODO: It would be nice to move _ctypes_add_traceback() into the
3785 core python API, so we could use it to add a frame here */
3786 goto error;
3787 }
3788
3789 if (!_pwinfo_set(pw_info, fn_ret,
3790 "password callback must return a string")) {
3791 goto error;
3792 }
3793 Py_CLEAR(fn_ret);
3794 }
3795
3796 if (pw_info->size > size) {
3797 PyErr_Format(PyExc_ValueError,
3798 "password cannot be longer than %d bytes", size);
3799 goto error;
3800 }
3801
3802 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
3803 memcpy(buf, pw_info->password, pw_info->size);
3804 return pw_info->size;
3805
3806error:
3807 Py_XDECREF(fn_ret);
3808 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
3809 pw_info->error = 1;
3810 return -1;
3811}
3812
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003813/*[clinic input]
3814_ssl._SSLContext.load_cert_chain
3815 certfile: object
Serhiy Storchaka279f4462019-09-14 12:24:05 +03003816 keyfile: object = None
3817 password: object = None
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003818
3819[clinic start generated code]*/
3820
Antoine Pitroub5218772010-05-21 09:56:06 +00003821static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003822_ssl__SSLContext_load_cert_chain_impl(PySSLContext *self, PyObject *certfile,
3823 PyObject *keyfile, PyObject *password)
Serhiy Storchaka279f4462019-09-14 12:24:05 +03003824/*[clinic end generated code: output=9480bc1c380e2095 input=30bc7e967ea01a58]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003825{
Antoine Pitrou152efa22010-05-16 18:19:27 +00003826 PyObject *certfile_bytes = NULL, *keyfile_bytes = NULL;
Christian Heimes598894f2016-09-05 23:19:05 +02003827 pem_password_cb *orig_passwd_cb = SSL_CTX_get_default_passwd_cb(self->ctx);
3828 void *orig_passwd_userdata = SSL_CTX_get_default_passwd_cb_userdata(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003829 _PySSLPasswordInfo pw_info = { NULL, NULL, NULL, 0, 0 };
Antoine Pitrou152efa22010-05-16 18:19:27 +00003830 int r;
3831
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003832 errno = 0;
Antoine Pitrou67e8e562010-09-01 20:55:41 +00003833 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00003834 if (keyfile == Py_None)
3835 keyfile = NULL;
3836 if (!PyUnicode_FSConverter(certfile, &certfile_bytes)) {
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03003837 if (PyErr_ExceptionMatches(PyExc_TypeError)) {
3838 PyErr_SetString(PyExc_TypeError,
3839 "certfile should be a valid filesystem path");
3840 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003841 return NULL;
3842 }
3843 if (keyfile && !PyUnicode_FSConverter(keyfile, &keyfile_bytes)) {
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03003844 if (PyErr_ExceptionMatches(PyExc_TypeError)) {
3845 PyErr_SetString(PyExc_TypeError,
3846 "keyfile should be a valid filesystem path");
3847 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003848 goto error;
3849 }
Serhiy Storchaka279f4462019-09-14 12:24:05 +03003850 if (password != Py_None) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003851 if (PyCallable_Check(password)) {
3852 pw_info.callable = password;
3853 } else if (!_pwinfo_set(&pw_info, password,
3854 "password should be a string or callable")) {
3855 goto error;
3856 }
3857 SSL_CTX_set_default_passwd_cb(self->ctx, _password_callback);
3858 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, &pw_info);
3859 }
3860 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003861 r = SSL_CTX_use_certificate_chain_file(self->ctx,
3862 PyBytes_AS_STRING(certfile_bytes));
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003863 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003864 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003865 if (pw_info.error) {
3866 ERR_clear_error();
3867 /* the password callback has already set the error information */
3868 }
3869 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00003870 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03003871 PyErr_SetFromErrno(PyExc_OSError);
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003872 }
3873 else {
Christian Heimes7f1305e2021-04-17 20:06:38 +02003874 _setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003875 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003876 goto error;
3877 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003878 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou9c254862011-04-03 18:15:34 +02003879 r = SSL_CTX_use_PrivateKey_file(self->ctx,
Antoine Pitrou152efa22010-05-16 18:19:27 +00003880 PyBytes_AS_STRING(keyfile ? keyfile_bytes : certfile_bytes),
3881 SSL_FILETYPE_PEM);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003882 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
3883 Py_CLEAR(keyfile_bytes);
3884 Py_CLEAR(certfile_bytes);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003885 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003886 if (pw_info.error) {
3887 ERR_clear_error();
3888 /* the password callback has already set the error information */
3889 }
3890 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00003891 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03003892 PyErr_SetFromErrno(PyExc_OSError);
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003893 }
3894 else {
Christian Heimes7f1305e2021-04-17 20:06:38 +02003895 _setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003896 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003897 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003898 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003899 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003900 r = SSL_CTX_check_private_key(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003901 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003902 if (r != 1) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02003903 _setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003904 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003905 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003906 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
3907 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02003908 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003909 Py_RETURN_NONE;
3910
3911error:
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003912 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
3913 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02003914 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003915 Py_XDECREF(keyfile_bytes);
3916 Py_XDECREF(certfile_bytes);
3917 return NULL;
3918}
3919
Christian Heimesefff7062013-11-21 03:35:02 +01003920/* internal helper function, returns -1 on error
3921 */
3922static int
Serhiy Storchaka8f87eef2020-04-12 14:58:27 +03003923_add_ca_certs(PySSLContext *self, const void *data, Py_ssize_t len,
Christian Heimesefff7062013-11-21 03:35:02 +01003924 int filetype)
3925{
3926 BIO *biobuf = NULL;
3927 X509_STORE *store;
Christian Heimesb9ad88b2021-04-23 13:51:40 +02003928 int retval = -1, err, loaded = 0;
Christian Heimesefff7062013-11-21 03:35:02 +01003929
3930 assert(filetype == SSL_FILETYPE_ASN1 || filetype == SSL_FILETYPE_PEM);
3931
3932 if (len <= 0) {
3933 PyErr_SetString(PyExc_ValueError,
3934 "Empty certificate data");
3935 return -1;
3936 } else if (len > INT_MAX) {
3937 PyErr_SetString(PyExc_OverflowError,
3938 "Certificate data is too long.");
3939 return -1;
3940 }
3941
Christian Heimes1dbf61f2013-11-22 00:34:18 +01003942 biobuf = BIO_new_mem_buf(data, (int)len);
Christian Heimesefff7062013-11-21 03:35:02 +01003943 if (biobuf == NULL) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02003944 _setSSLError(get_state_ctx(self), "Can't allocate buffer", 0, __FILE__, __LINE__);
Christian Heimesefff7062013-11-21 03:35:02 +01003945 return -1;
3946 }
3947
3948 store = SSL_CTX_get_cert_store(self->ctx);
3949 assert(store != NULL);
3950
3951 while (1) {
3952 X509 *cert = NULL;
3953 int r;
3954
3955 if (filetype == SSL_FILETYPE_ASN1) {
3956 cert = d2i_X509_bio(biobuf, NULL);
3957 } else {
3958 cert = PEM_read_bio_X509(biobuf, NULL,
Christian Heimes598894f2016-09-05 23:19:05 +02003959 SSL_CTX_get_default_passwd_cb(self->ctx),
3960 SSL_CTX_get_default_passwd_cb_userdata(self->ctx)
3961 );
Christian Heimesefff7062013-11-21 03:35:02 +01003962 }
3963 if (cert == NULL) {
3964 break;
3965 }
3966 r = X509_STORE_add_cert(store, cert);
3967 X509_free(cert);
3968 if (!r) {
3969 err = ERR_peek_last_error();
3970 if ((ERR_GET_LIB(err) == ERR_LIB_X509) &&
3971 (ERR_GET_REASON(err) == X509_R_CERT_ALREADY_IN_HASH_TABLE)) {
3972 /* cert already in hash table, not an error */
3973 ERR_clear_error();
3974 } else {
3975 break;
3976 }
3977 }
3978 loaded++;
3979 }
3980
3981 err = ERR_peek_last_error();
Christian Heimesb9ad88b2021-04-23 13:51:40 +02003982 if (loaded == 0) {
3983 const char *msg = NULL;
3984 if (filetype == SSL_FILETYPE_PEM) {
3985 msg = "no start line: cadata does not contain a certificate";
3986 } else {
3987 msg = "not enough data: cadata does not contain a certificate";
3988 }
3989 _setSSLError(get_state_ctx(self), msg, 0, __FILE__, __LINE__);
3990 retval = -1;
3991 } else if ((filetype == SSL_FILETYPE_ASN1) &&
3992 (ERR_GET_LIB(err) == ERR_LIB_ASN1) &&
3993 (ERR_GET_REASON(err) == ASN1_R_HEADER_TOO_LONG)) {
Christian Heimesefff7062013-11-21 03:35:02 +01003994 /* EOF ASN1 file, not an error */
3995 ERR_clear_error();
3996 retval = 0;
3997 } else if ((filetype == SSL_FILETYPE_PEM) &&
Christian Heimesefff7062013-11-21 03:35:02 +01003998 (ERR_GET_LIB(err) == ERR_LIB_PEM) &&
3999 (ERR_GET_REASON(err) == PEM_R_NO_START_LINE)) {
4000 /* EOF PEM file, not an error */
4001 ERR_clear_error();
4002 retval = 0;
Christian Heimesb9ad88b2021-04-23 13:51:40 +02004003 } else if (err != 0) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02004004 _setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
Christian Heimesefff7062013-11-21 03:35:02 +01004005 retval = -1;
Christian Heimesb9ad88b2021-04-23 13:51:40 +02004006 } else {
4007 retval = 0;
Christian Heimesefff7062013-11-21 03:35:02 +01004008 }
4009
4010 BIO_free(biobuf);
4011 return retval;
4012}
4013
4014
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004015/*[clinic input]
4016_ssl._SSLContext.load_verify_locations
Serhiy Storchaka279f4462019-09-14 12:24:05 +03004017 cafile: object = None
4018 capath: object = None
4019 cadata: object = None
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004020
4021[clinic start generated code]*/
4022
Antoine Pitrou152efa22010-05-16 18:19:27 +00004023static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004024_ssl__SSLContext_load_verify_locations_impl(PySSLContext *self,
4025 PyObject *cafile,
4026 PyObject *capath,
4027 PyObject *cadata)
Serhiy Storchaka279f4462019-09-14 12:24:05 +03004028/*[clinic end generated code: output=454c7e41230ca551 input=42ecfe258233e194]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004029{
Antoine Pitrou152efa22010-05-16 18:19:27 +00004030 PyObject *cafile_bytes = NULL, *capath_bytes = NULL;
4031 const char *cafile_buf = NULL, *capath_buf = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01004032 int r = 0, ok = 1;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004033
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00004034 errno = 0;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004035 if (cafile == Py_None)
4036 cafile = NULL;
4037 if (capath == Py_None)
4038 capath = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01004039 if (cadata == Py_None)
4040 cadata = NULL;
4041
4042 if (cafile == NULL && capath == NULL && cadata == NULL) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00004043 PyErr_SetString(PyExc_TypeError,
Christian Heimesefff7062013-11-21 03:35:02 +01004044 "cafile, capath and cadata cannot be all omitted");
4045 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004046 }
4047 if (cafile && !PyUnicode_FSConverter(cafile, &cafile_bytes)) {
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03004048 if (PyErr_ExceptionMatches(PyExc_TypeError)) {
4049 PyErr_SetString(PyExc_TypeError,
4050 "cafile should be a valid filesystem path");
4051 }
Christian Heimesefff7062013-11-21 03:35:02 +01004052 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004053 }
4054 if (capath && !PyUnicode_FSConverter(capath, &capath_bytes)) {
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03004055 if (PyErr_ExceptionMatches(PyExc_TypeError)) {
4056 PyErr_SetString(PyExc_TypeError,
4057 "capath should be a valid filesystem path");
4058 }
Christian Heimesefff7062013-11-21 03:35:02 +01004059 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004060 }
Christian Heimesefff7062013-11-21 03:35:02 +01004061
Miss Islington (bot)e5f259e2021-09-06 14:35:07 -07004062 /* validate cadata type and load cadata */
Christian Heimesefff7062013-11-21 03:35:02 +01004063 if (cadata) {
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03004064 if (PyUnicode_Check(cadata)) {
4065 PyObject *cadata_ascii = PyUnicode_AsASCIIString(cadata);
4066 if (cadata_ascii == NULL) {
4067 if (PyErr_ExceptionMatches(PyExc_UnicodeEncodeError)) {
4068 goto invalid_cadata;
4069 }
4070 goto error;
4071 }
4072 r = _add_ca_certs(self,
4073 PyBytes_AS_STRING(cadata_ascii),
4074 PyBytes_GET_SIZE(cadata_ascii),
4075 SSL_FILETYPE_PEM);
4076 Py_DECREF(cadata_ascii);
4077 if (r == -1) {
4078 goto error;
4079 }
4080 }
4081 else if (PyObject_CheckBuffer(cadata)) {
4082 Py_buffer buf;
4083 if (PyObject_GetBuffer(cadata, &buf, PyBUF_SIMPLE)) {
4084 goto error;
4085 }
Christian Heimesefff7062013-11-21 03:35:02 +01004086 if (!PyBuffer_IsContiguous(&buf, 'C') || buf.ndim > 1) {
4087 PyBuffer_Release(&buf);
4088 PyErr_SetString(PyExc_TypeError,
4089 "cadata should be a contiguous buffer with "
4090 "a single dimension");
4091 goto error;
4092 }
4093 r = _add_ca_certs(self, buf.buf, buf.len, SSL_FILETYPE_ASN1);
4094 PyBuffer_Release(&buf);
4095 if (r == -1) {
4096 goto error;
4097 }
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03004098 }
4099 else {
4100 invalid_cadata:
4101 PyErr_SetString(PyExc_TypeError,
4102 "cadata should be an ASCII string or a "
4103 "bytes-like object");
4104 goto error;
Christian Heimesefff7062013-11-21 03:35:02 +01004105 }
4106 }
4107
4108 /* load cafile or capath */
4109 if (cafile || capath) {
4110 if (cafile)
4111 cafile_buf = PyBytes_AS_STRING(cafile_bytes);
4112 if (capath)
4113 capath_buf = PyBytes_AS_STRING(capath_bytes);
4114 PySSL_BEGIN_ALLOW_THREADS
4115 r = SSL_CTX_load_verify_locations(self->ctx, cafile_buf, capath_buf);
4116 PySSL_END_ALLOW_THREADS
4117 if (r != 1) {
Christian Heimesefff7062013-11-21 03:35:02 +01004118 if (errno != 0) {
4119 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03004120 PyErr_SetFromErrno(PyExc_OSError);
Christian Heimesefff7062013-11-21 03:35:02 +01004121 }
4122 else {
Christian Heimes7f1305e2021-04-17 20:06:38 +02004123 _setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
Christian Heimesefff7062013-11-21 03:35:02 +01004124 }
4125 goto error;
4126 }
4127 }
4128 goto end;
4129
4130 error:
4131 ok = 0;
4132 end:
Antoine Pitrou152efa22010-05-16 18:19:27 +00004133 Py_XDECREF(cafile_bytes);
4134 Py_XDECREF(capath_bytes);
Christian Heimesefff7062013-11-21 03:35:02 +01004135 if (ok) {
4136 Py_RETURN_NONE;
4137 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00004138 return NULL;
4139 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00004140}
4141
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004142/*[clinic input]
4143_ssl._SSLContext.load_dh_params
4144 path as filepath: object
4145 /
4146
4147[clinic start generated code]*/
4148
Antoine Pitrou152efa22010-05-16 18:19:27 +00004149static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004150_ssl__SSLContext_load_dh_params(PySSLContext *self, PyObject *filepath)
4151/*[clinic end generated code: output=1c8e57a38e055af0 input=c8871f3c796ae1d6]*/
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004152{
4153 FILE *f;
4154 DH *dh;
4155
Victor Stinnerdaf45552013-08-28 00:53:59 +02004156 f = _Py_fopen_obj(filepath, "rb");
Victor Stinnere42ccd22015-03-18 01:39:23 +01004157 if (f == NULL)
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004158 return NULL;
Victor Stinnere42ccd22015-03-18 01:39:23 +01004159
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004160 errno = 0;
4161 PySSL_BEGIN_ALLOW_THREADS
4162 dh = PEM_read_DHparams(f, NULL, NULL, NULL);
Antoine Pitrou457a2292013-01-12 21:43:45 +01004163 fclose(f);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004164 PySSL_END_ALLOW_THREADS
4165 if (dh == NULL) {
4166 if (errno != 0) {
4167 ERR_clear_error();
4168 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
4169 }
4170 else {
Christian Heimes7f1305e2021-04-17 20:06:38 +02004171 _setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004172 }
4173 return NULL;
4174 }
Zackery Spytzaebc0492020-07-07 22:21:58 -06004175 if (!SSL_CTX_set_tmp_dh(self->ctx, dh)) {
4176 DH_free(dh);
Christian Heimes7f1305e2021-04-17 20:06:38 +02004177 return _setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
Zackery Spytzaebc0492020-07-07 22:21:58 -06004178 }
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004179 DH_free(dh);
4180 Py_RETURN_NONE;
4181}
4182
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004183/*[clinic input]
4184_ssl._SSLContext._wrap_socket
Christian Heimes7f1305e2021-04-17 20:06:38 +02004185 sock: object(subclass_of="get_state_ctx(self)->Sock_Type")
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004186 server_side: int
4187 server_hostname as hostname_obj: object = None
Christian Heimes141c5e82018-02-24 21:10:57 +01004188 *
4189 owner: object = None
4190 session: object = None
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004191
4192[clinic start generated code]*/
4193
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004194static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004195_ssl__SSLContext__wrap_socket_impl(PySSLContext *self, PyObject *sock,
Christian Heimes141c5e82018-02-24 21:10:57 +01004196 int server_side, PyObject *hostname_obj,
4197 PyObject *owner, PyObject *session)
Christian Heimes7f1305e2021-04-17 20:06:38 +02004198/*[clinic end generated code: output=f103f238633940b4 input=f5916eadbc6eae81]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004199{
Antoine Pitroud5323212010-10-22 18:19:07 +00004200 char *hostname = NULL;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004201 PyObject *res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004202
Antoine Pitroud5323212010-10-22 18:19:07 +00004203 /* server_hostname is either None (or absent), or to be encoded
Christian Heimesd02ac252018-03-25 12:36:13 +02004204 as IDN A-label (ASCII str) without NULL bytes. */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004205 if (hostname_obj != Py_None) {
Christian Heimes11a14932018-02-24 02:35:08 +01004206 if (!PyArg_Parse(hostname_obj, "es", "ascii", &hostname))
Antoine Pitroud5323212010-10-22 18:19:07 +00004207 return NULL;
Antoine Pitroud5323212010-10-22 18:19:07 +00004208 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00004209
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004210 res = (PyObject *) newPySSLSocket(self, (PySocketSockObject *)sock,
4211 server_side, hostname,
Christian Heimes141c5e82018-02-24 21:10:57 +01004212 owner, session,
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004213 NULL, NULL);
Antoine Pitroud5323212010-10-22 18:19:07 +00004214 if (hostname != NULL)
4215 PyMem_Free(hostname);
4216 return res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004217}
4218
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004219/*[clinic input]
4220_ssl._SSLContext._wrap_bio
Christian Heimes7f1305e2021-04-17 20:06:38 +02004221 incoming: object(subclass_of="get_state_ctx(self)->PySSLMemoryBIO_Type", type="PySSLMemoryBIO *")
4222 outgoing: object(subclass_of="get_state_ctx(self)->PySSLMemoryBIO_Type", type="PySSLMemoryBIO *")
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004223 server_side: int
4224 server_hostname as hostname_obj: object = None
Christian Heimes141c5e82018-02-24 21:10:57 +01004225 *
4226 owner: object = None
4227 session: object = None
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004228
4229[clinic start generated code]*/
4230
Antoine Pitroub0182c82010-10-12 20:09:02 +00004231static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004232_ssl__SSLContext__wrap_bio_impl(PySSLContext *self, PySSLMemoryBIO *incoming,
4233 PySSLMemoryBIO *outgoing, int server_side,
Christian Heimes141c5e82018-02-24 21:10:57 +01004234 PyObject *hostname_obj, PyObject *owner,
4235 PyObject *session)
Christian Heimes7f1305e2021-04-17 20:06:38 +02004236/*[clinic end generated code: output=5c5d6d9b41f99332 input=331edeec9c738382]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004237{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004238 char *hostname = NULL;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004239 PyObject *res;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004240
4241 /* server_hostname is either None (or absent), or to be encoded
Christian Heimesd02ac252018-03-25 12:36:13 +02004242 as IDN A-label (ASCII str) without NULL bytes. */
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004243 if (hostname_obj != Py_None) {
Christian Heimes11a14932018-02-24 02:35:08 +01004244 if (!PyArg_Parse(hostname_obj, "es", "ascii", &hostname))
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004245 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004246 }
4247
4248 res = (PyObject *) newPySSLSocket(self, NULL, server_side, hostname,
Christian Heimes141c5e82018-02-24 21:10:57 +01004249 owner, session,
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004250 incoming, outgoing);
4251
4252 PyMem_Free(hostname);
4253 return res;
4254}
4255
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004256/*[clinic input]
4257_ssl._SSLContext.session_stats
4258[clinic start generated code]*/
4259
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004260static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004261_ssl__SSLContext_session_stats_impl(PySSLContext *self)
4262/*[clinic end generated code: output=0d96411c42893bfb input=7e0a81fb11102c8b]*/
Antoine Pitroub0182c82010-10-12 20:09:02 +00004263{
4264 int r;
4265 PyObject *value, *stats = PyDict_New();
4266 if (!stats)
4267 return NULL;
4268
4269#define ADD_STATS(SSL_NAME, KEY_NAME) \
4270 value = PyLong_FromLong(SSL_CTX_sess_ ## SSL_NAME (self->ctx)); \
4271 if (value == NULL) \
4272 goto error; \
4273 r = PyDict_SetItemString(stats, KEY_NAME, value); \
4274 Py_DECREF(value); \
4275 if (r < 0) \
4276 goto error;
4277
4278 ADD_STATS(number, "number");
4279 ADD_STATS(connect, "connect");
4280 ADD_STATS(connect_good, "connect_good");
4281 ADD_STATS(connect_renegotiate, "connect_renegotiate");
4282 ADD_STATS(accept, "accept");
4283 ADD_STATS(accept_good, "accept_good");
4284 ADD_STATS(accept_renegotiate, "accept_renegotiate");
4285 ADD_STATS(accept, "accept");
4286 ADD_STATS(hits, "hits");
4287 ADD_STATS(misses, "misses");
4288 ADD_STATS(timeouts, "timeouts");
4289 ADD_STATS(cache_full, "cache_full");
4290
4291#undef ADD_STATS
4292
4293 return stats;
4294
4295error:
4296 Py_DECREF(stats);
4297 return NULL;
4298}
4299
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004300/*[clinic input]
4301_ssl._SSLContext.set_default_verify_paths
4302[clinic start generated code]*/
4303
Antoine Pitrou664c2d12010-11-17 20:29:42 +00004304static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004305_ssl__SSLContext_set_default_verify_paths_impl(PySSLContext *self)
4306/*[clinic end generated code: output=0bee74e6e09deaaa input=35f3408021463d74]*/
Antoine Pitrou664c2d12010-11-17 20:29:42 +00004307{
4308 if (!SSL_CTX_set_default_verify_paths(self->ctx)) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02004309 _setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
Antoine Pitrou664c2d12010-11-17 20:29:42 +00004310 return NULL;
4311 }
4312 Py_RETURN_NONE;
4313}
4314
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004315/*[clinic input]
4316_ssl._SSLContext.set_ecdh_curve
4317 name: object
4318 /
4319
4320[clinic start generated code]*/
4321
Antoine Pitrou923df6f2011-12-19 17:16:51 +01004322static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004323_ssl__SSLContext_set_ecdh_curve(PySSLContext *self, PyObject *name)
4324/*[clinic end generated code: output=23022c196e40d7d2 input=c2bafb6f6e34726b]*/
Antoine Pitrou923df6f2011-12-19 17:16:51 +01004325{
4326 PyObject *name_bytes;
4327 int nid;
4328 EC_KEY *key;
4329
4330 if (!PyUnicode_FSConverter(name, &name_bytes))
4331 return NULL;
4332 assert(PyBytes_Check(name_bytes));
4333 nid = OBJ_sn2nid(PyBytes_AS_STRING(name_bytes));
4334 Py_DECREF(name_bytes);
4335 if (nid == 0) {
4336 PyErr_Format(PyExc_ValueError,
4337 "unknown elliptic curve name %R", name);
4338 return NULL;
4339 }
4340 key = EC_KEY_new_by_curve_name(nid);
4341 if (key == NULL) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02004342 _setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
Antoine Pitrou923df6f2011-12-19 17:16:51 +01004343 return NULL;
4344 }
4345 SSL_CTX_set_tmp_ecdh(self->ctx, key);
4346 EC_KEY_free(key);
4347 Py_RETURN_NONE;
4348}
4349
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004350static int
4351_servername_callback(SSL *s, int *al, void *args)
4352{
4353 int ret;
Christian Heimes7f1305e2021-04-17 20:06:38 +02004354 PySSLContext *sslctx = (PySSLContext *) args;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004355 PySSLSocket *ssl;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004356 PyObject *result;
4357 /* The high-level ssl.SSLSocket object */
4358 PyObject *ssl_socket;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004359 const char *servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
Stefan Krah20d60802013-01-17 17:07:17 +01004360 PyGILState_STATE gstate = PyGILState_Ensure();
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004361
Christian Heimes7f1305e2021-04-17 20:06:38 +02004362 if (sslctx->set_sni_cb == NULL) {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004363 /* remove race condition in this the call back while if removing the
4364 * callback is in progress */
4365 PyGILState_Release(gstate);
Antoine Pitrou5dd12a52013-01-06 15:25:36 +01004366 return SSL_TLSEXT_ERR_OK;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004367 }
4368
4369 ssl = SSL_get_app_data(s);
Christian Heimes7f1305e2021-04-17 20:06:38 +02004370 assert(Py_IS_TYPE(ssl, get_state_ctx(sslctx)->PySSLSocket_Type));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004371
Serhiy Storchakaf51d7152015-11-02 14:40:41 +02004372 /* The servername callback expects an argument that represents the current
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004373 * SSL connection and that has a .context attribute that can be changed to
4374 * identify the requested hostname. Since the official API is the Python
4375 * level API we want to pass the callback a Python level object rather than
4376 * a _ssl.SSLSocket instance. If there's an "owner" (typically an
4377 * SSLObject) that will be passed. Otherwise if there's a socket then that
4378 * will be passed. If both do not exist only then the C-level object is
4379 * passed. */
4380 if (ssl->owner)
4381 ssl_socket = PyWeakref_GetObject(ssl->owner);
4382 else if (ssl->Socket)
4383 ssl_socket = PyWeakref_GetObject(ssl->Socket);
4384 else
4385 ssl_socket = (PyObject *) ssl;
4386
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004387 Py_INCREF(ssl_socket);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004388 if (ssl_socket == Py_None)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004389 goto error;
Victor Stinner7e001512013-06-25 00:44:31 +02004390
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004391 if (servername == NULL) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02004392 result = PyObject_CallFunctionObjArgs(sslctx->set_sni_cb, ssl_socket,
4393 Py_None, sslctx, NULL);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004394 }
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004395 else {
Christian Heimes11a14932018-02-24 02:35:08 +01004396 PyObject *servername_bytes;
4397 PyObject *servername_str;
4398
4399 servername_bytes = PyBytes_FromString(servername);
4400 if (servername_bytes == NULL) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02004401 PyErr_WriteUnraisable((PyObject *) sslctx);
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004402 goto error;
4403 }
Christian Heimes11a14932018-02-24 02:35:08 +01004404 /* server_hostname was encoded to an A-label by our caller; put it
4405 * back into a str object, but still as an A-label (bpo-28414)
4406 */
4407 servername_str = PyUnicode_FromEncodedObject(servername_bytes, "ascii", NULL);
Christian Heimes11a14932018-02-24 02:35:08 +01004408 if (servername_str == NULL) {
4409 PyErr_WriteUnraisable(servername_bytes);
Zackery Spytzee96f322020-07-09 04:00:21 -06004410 Py_DECREF(servername_bytes);
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004411 goto error;
4412 }
Zackery Spytzee96f322020-07-09 04:00:21 -06004413 Py_DECREF(servername_bytes);
Christian Heimes11a14932018-02-24 02:35:08 +01004414 result = PyObject_CallFunctionObjArgs(
Christian Heimes7f1305e2021-04-17 20:06:38 +02004415 sslctx->set_sni_cb, ssl_socket, servername_str,
4416 sslctx, NULL);
Christian Heimes11a14932018-02-24 02:35:08 +01004417 Py_DECREF(servername_str);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004418 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004419 Py_DECREF(ssl_socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004420
4421 if (result == NULL) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02004422 PyErr_WriteUnraisable(sslctx->set_sni_cb);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004423 *al = SSL_AD_HANDSHAKE_FAILURE;
4424 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
4425 }
4426 else {
Christian Heimes11a14932018-02-24 02:35:08 +01004427 /* Result may be None, a SSLContext or an integer
4428 * None and SSLContext are OK, integer or other values are an error.
4429 */
4430 if (result == Py_None) {
4431 ret = SSL_TLSEXT_ERR_OK;
4432 } else {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004433 *al = (int) PyLong_AsLong(result);
4434 if (PyErr_Occurred()) {
4435 PyErr_WriteUnraisable(result);
4436 *al = SSL_AD_INTERNAL_ERROR;
4437 }
4438 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
4439 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004440 Py_DECREF(result);
4441 }
4442
4443 PyGILState_Release(gstate);
4444 return ret;
4445
4446error:
4447 Py_DECREF(ssl_socket);
4448 *al = SSL_AD_INTERNAL_ERROR;
4449 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
4450 PyGILState_Release(gstate);
4451 return ret;
4452}
4453
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004454static PyObject *
Christian Heimes11a14932018-02-24 02:35:08 +01004455get_sni_callback(PySSLContext *self, void *c)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004456{
Christian Heimes11a14932018-02-24 02:35:08 +01004457 PyObject *cb = self->set_sni_cb;
4458 if (cb == NULL) {
4459 Py_RETURN_NONE;
4460 }
4461 Py_INCREF(cb);
4462 return cb;
4463}
4464
4465static int
4466set_sni_callback(PySSLContext *self, PyObject *arg, void *c)
4467{
4468 if (self->protocol == PY_SSL_VERSION_TLS_CLIENT) {
4469 PyErr_SetString(PyExc_ValueError,
4470 "sni_callback cannot be set on TLS_CLIENT context");
4471 return -1;
4472 }
Christian Heimes11a14932018-02-24 02:35:08 +01004473 Py_CLEAR(self->set_sni_cb);
4474 if (arg == Py_None) {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004475 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
4476 }
4477 else {
Christian Heimes11a14932018-02-24 02:35:08 +01004478 if (!PyCallable_Check(arg)) {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004479 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
4480 PyErr_SetString(PyExc_TypeError,
4481 "not a callable object");
Christian Heimes11a14932018-02-24 02:35:08 +01004482 return -1;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004483 }
Christian Heimes11a14932018-02-24 02:35:08 +01004484 Py_INCREF(arg);
4485 self->set_sni_cb = arg;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004486 SSL_CTX_set_tlsext_servername_callback(self->ctx, _servername_callback);
4487 SSL_CTX_set_tlsext_servername_arg(self->ctx, self);
4488 }
Christian Heimes11a14932018-02-24 02:35:08 +01004489 return 0;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004490}
4491
Christian Heimes11a14932018-02-24 02:35:08 +01004492PyDoc_STRVAR(PySSLContext_sni_callback_doc,
4493"Set a callback that will be called when a server name is provided by the SSL/TLS client in the SNI extension.\n\
4494\n\
4495If the argument is None then the callback is disabled. The method is called\n\
4496with the SSLSocket, the server name as a string, and the SSLContext object.\n\
4497See RFC 6066 for details of the SNI extension.");
4498
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004499/*[clinic input]
4500_ssl._SSLContext.cert_store_stats
4501
4502Returns quantities of loaded X.509 certificates.
4503
4504X.509 certificates with a CA extension and certificate revocation lists
4505inside the context's cert store.
4506
4507NOTE: Certificates in a capath directory aren't loaded unless they have
4508been used at least once.
4509[clinic start generated code]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004510
4511static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004512_ssl__SSLContext_cert_store_stats_impl(PySSLContext *self)
4513/*[clinic end generated code: output=5f356f4d9cca874d input=eb40dd0f6d0e40cf]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004514{
4515 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02004516 STACK_OF(X509_OBJECT) *objs;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004517 X509_OBJECT *obj;
Christian Heimes598894f2016-09-05 23:19:05 +02004518 int x509 = 0, crl = 0, ca = 0, i;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004519
4520 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02004521 objs = X509_STORE_get0_objects(store);
4522 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
4523 obj = sk_X509_OBJECT_value(objs, i);
4524 switch (X509_OBJECT_get_type(obj)) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004525 case X509_LU_X509:
4526 x509++;
Christian Heimes598894f2016-09-05 23:19:05 +02004527 if (X509_check_ca(X509_OBJECT_get0_X509(obj))) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004528 ca++;
4529 }
4530 break;
4531 case X509_LU_CRL:
4532 crl++;
4533 break;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004534 default:
4535 /* Ignore X509_LU_FAIL, X509_LU_RETRY, X509_LU_PKEY.
4536 * As far as I can tell they are internal states and never
4537 * stored in a cert store */
4538 break;
4539 }
4540 }
4541 return Py_BuildValue("{sisisi}", "x509", x509, "crl", crl,
4542 "x509_ca", ca);
4543}
4544
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004545/*[clinic input]
4546_ssl._SSLContext.get_ca_certs
4547 binary_form: bool = False
4548
4549Returns a list of dicts with information of loaded CA certs.
4550
4551If the optional argument is True, returns a DER-encoded copy of the CA
4552certificate.
4553
4554NOTE: Certificates in a capath directory aren't loaded unless they have
4555been used at least once.
4556[clinic start generated code]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004557
4558static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004559_ssl__SSLContext_get_ca_certs_impl(PySSLContext *self, int binary_form)
4560/*[clinic end generated code: output=0d58f148f37e2938 input=6887b5a09b7f9076]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004561{
4562 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02004563 STACK_OF(X509_OBJECT) *objs;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004564 PyObject *ci = NULL, *rlist = NULL;
4565 int i;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004566
4567 if ((rlist = PyList_New(0)) == NULL) {
4568 return NULL;
4569 }
4570
4571 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02004572 objs = X509_STORE_get0_objects(store);
4573 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004574 X509_OBJECT *obj;
4575 X509 *cert;
4576
Christian Heimes598894f2016-09-05 23:19:05 +02004577 obj = sk_X509_OBJECT_value(objs, i);
4578 if (X509_OBJECT_get_type(obj) != X509_LU_X509) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004579 /* not a x509 cert */
4580 continue;
4581 }
4582 /* CA for any purpose */
Christian Heimes598894f2016-09-05 23:19:05 +02004583 cert = X509_OBJECT_get0_X509(obj);
Christian Heimes9a5395a2013-06-17 15:44:12 +02004584 if (!X509_check_ca(cert)) {
4585 continue;
4586 }
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004587 if (binary_form) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02004588 ci = _certificate_to_der(get_state_ctx(self), cert);
Christian Heimes9a5395a2013-06-17 15:44:12 +02004589 } else {
Christian Heimes7f1305e2021-04-17 20:06:38 +02004590 ci = _decode_certificate(get_state_ctx(self), cert);
Christian Heimes9a5395a2013-06-17 15:44:12 +02004591 }
4592 if (ci == NULL) {
4593 goto error;
4594 }
4595 if (PyList_Append(rlist, ci) == -1) {
4596 goto error;
4597 }
4598 Py_CLEAR(ci);
4599 }
4600 return rlist;
4601
4602 error:
4603 Py_XDECREF(ci);
4604 Py_XDECREF(rlist);
4605 return NULL;
4606}
4607
4608
Antoine Pitrou152efa22010-05-16 18:19:27 +00004609static PyGetSetDef context_getsetlist[] = {
Christian Heimes1aa9a752013-12-02 02:41:19 +01004610 {"check_hostname", (getter) get_check_hostname,
4611 (setter) set_check_hostname, NULL},
Christian Heimes61d478c2018-01-27 15:51:38 +01004612 {"_host_flags", (getter) get_host_flags,
4613 (setter) set_host_flags, NULL},
Christian Heimes698dde12018-02-27 11:54:43 +01004614 {"minimum_version", (getter) get_minimum_version,
4615 (setter) set_minimum_version, NULL},
4616 {"maximum_version", (getter) get_maximum_version,
4617 (setter) set_maximum_version, NULL},
Christian Heimesc7f70692019-05-31 11:44:05 +02004618 {"keylog_filename", (getter) _PySSLContext_get_keylog_filename,
4619 (setter) _PySSLContext_set_keylog_filename, NULL},
Christian Heimesc7f70692019-05-31 11:44:05 +02004620 {"_msg_callback", (getter) _PySSLContext_get_msg_callback,
4621 (setter) _PySSLContext_set_msg_callback, NULL},
Christian Heimes11a14932018-02-24 02:35:08 +01004622 {"sni_callback", (getter) get_sni_callback,
Christian Heimes698dde12018-02-27 11:54:43 +01004623 (setter) set_sni_callback, PySSLContext_sni_callback_doc},
Christian Heimes39258d32021-04-17 11:36:35 +02004624#ifdef TLS1_3_VERSION
Christian Heimes78c7d522019-06-03 21:00:10 +02004625 {"num_tickets", (getter) get_num_tickets,
4626 (setter) set_num_tickets, PySSLContext_num_tickets_doc},
4627#endif
Antoine Pitroub5218772010-05-21 09:56:06 +00004628 {"options", (getter) get_options,
4629 (setter) set_options, NULL},
Christian Heimes9fb051f2018-09-23 08:32:31 +02004630 {"post_handshake_auth", (getter) get_post_handshake_auth,
4631#ifdef TLS1_3_VERSION
4632 (setter) set_post_handshake_auth,
4633#else
4634 NULL,
4635#endif
4636 NULL},
Christian Heimes11a14932018-02-24 02:35:08 +01004637 {"protocol", (getter) get_protocol,
4638 NULL, NULL},
Christian Heimes22587792013-11-21 23:56:13 +01004639 {"verify_flags", (getter) get_verify_flags,
4640 (setter) set_verify_flags, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00004641 {"verify_mode", (getter) get_verify_mode,
4642 (setter) set_verify_mode, NULL},
matthewhughes9348e836bb2020-07-17 09:59:15 +01004643 {"security_level", (getter) get_security_level,
4644 NULL, PySSLContext_security_level_doc},
Antoine Pitrou152efa22010-05-16 18:19:27 +00004645 {NULL}, /* sentinel */
4646};
4647
4648static struct PyMethodDef context_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004649 _SSL__SSLCONTEXT__WRAP_SOCKET_METHODDEF
4650 _SSL__SSLCONTEXT__WRAP_BIO_METHODDEF
4651 _SSL__SSLCONTEXT_SET_CIPHERS_METHODDEF
4652 _SSL__SSLCONTEXT__SET_ALPN_PROTOCOLS_METHODDEF
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004653 _SSL__SSLCONTEXT_LOAD_CERT_CHAIN_METHODDEF
4654 _SSL__SSLCONTEXT_LOAD_DH_PARAMS_METHODDEF
4655 _SSL__SSLCONTEXT_LOAD_VERIFY_LOCATIONS_METHODDEF
4656 _SSL__SSLCONTEXT_SESSION_STATS_METHODDEF
4657 _SSL__SSLCONTEXT_SET_DEFAULT_VERIFY_PATHS_METHODDEF
4658 _SSL__SSLCONTEXT_SET_ECDH_CURVE_METHODDEF
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004659 _SSL__SSLCONTEXT_CERT_STORE_STATS_METHODDEF
4660 _SSL__SSLCONTEXT_GET_CA_CERTS_METHODDEF
Christian Heimes25bfcd52016-09-06 00:04:45 +02004661 _SSL__SSLCONTEXT_GET_CIPHERS_METHODDEF
Antoine Pitrou152efa22010-05-16 18:19:27 +00004662 {NULL, NULL} /* sentinel */
4663};
4664
Christian Heimes5c36da72020-11-20 09:40:12 +01004665static PyType_Slot PySSLContext_slots[] = {
4666 {Py_tp_methods, context_methods},
4667 {Py_tp_getset, context_getsetlist},
4668 {Py_tp_new, _ssl__SSLContext},
4669 {Py_tp_dealloc, context_dealloc},
4670 {Py_tp_traverse, context_traverse},
4671 {Py_tp_clear, context_clear},
4672 {0, 0},
4673};
4674
4675static PyType_Spec PySSLContext_spec = {
Miss Islington (bot)ea47a8a2021-05-27 09:25:22 -07004676 .name = "_ssl._SSLContext",
4677 .basicsize = sizeof(PySSLContext),
4678 .flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC |
4679 Py_TPFLAGS_IMMUTABLETYPE),
4680 .slots = PySSLContext_slots,
Antoine Pitrou152efa22010-05-16 18:19:27 +00004681};
4682
4683
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004684/*
4685 * MemoryBIO objects
4686 */
4687
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004688/*[clinic input]
4689@classmethod
4690_ssl.MemoryBIO.__new__
4691
4692[clinic start generated code]*/
4693
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004694static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004695_ssl_MemoryBIO_impl(PyTypeObject *type)
4696/*[clinic end generated code: output=8820a58db78330ac input=26d22e4909ecb1b5]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004697{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004698 BIO *bio;
4699 PySSLMemoryBIO *self;
4700
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004701 bio = BIO_new(BIO_s_mem());
4702 if (bio == NULL) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02004703 PyErr_SetString(PyExc_MemoryError, "failed to allocate BIO");
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004704 return NULL;
4705 }
4706 /* Since our BIO is non-blocking an empty read() does not indicate EOF,
4707 * just that no data is currently available. The SSL routines should retry
4708 * the read, which we can achieve by calling BIO_set_retry_read(). */
4709 BIO_set_retry_read(bio);
4710 BIO_set_mem_eof_return(bio, -1);
4711
4712 assert(type != NULL && type->tp_alloc != NULL);
4713 self = (PySSLMemoryBIO *) type->tp_alloc(type, 0);
4714 if (self == NULL) {
4715 BIO_free(bio);
4716 return NULL;
4717 }
4718 self->bio = bio;
4719 self->eof_written = 0;
4720
4721 return (PyObject *) self;
4722}
4723
Miss Islington (bot)ea47a8a2021-05-27 09:25:22 -07004724static int
4725memory_bio_traverse(PySSLMemoryBIO *self, visitproc visit, void *arg)
4726{
4727 Py_VISIT(Py_TYPE(self));
4728 return 0;
4729}
4730
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004731static void
4732memory_bio_dealloc(PySSLMemoryBIO *self)
4733{
Christian Heimes5c36da72020-11-20 09:40:12 +01004734 PyTypeObject *tp = Py_TYPE(self);
Miss Islington (bot)ea47a8a2021-05-27 09:25:22 -07004735 PyObject_GC_UnTrack(self);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004736 BIO_free(self->bio);
4737 Py_TYPE(self)->tp_free(self);
Christian Heimes5c36da72020-11-20 09:40:12 +01004738 Py_DECREF(tp);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004739}
4740
4741static PyObject *
4742memory_bio_get_pending(PySSLMemoryBIO *self, void *c)
4743{
Segev Finer5cff6372017-07-27 01:19:17 +03004744 return PyLong_FromSize_t(BIO_ctrl_pending(self->bio));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004745}
4746
4747PyDoc_STRVAR(PySSL_memory_bio_pending_doc,
4748"The number of bytes pending in the memory BIO.");
4749
4750static PyObject *
4751memory_bio_get_eof(PySSLMemoryBIO *self, void *c)
4752{
4753 return PyBool_FromLong((BIO_ctrl_pending(self->bio) == 0)
4754 && self->eof_written);
4755}
4756
4757PyDoc_STRVAR(PySSL_memory_bio_eof_doc,
4758"Whether the memory BIO is at EOF.");
4759
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004760/*[clinic input]
4761_ssl.MemoryBIO.read
4762 size as len: int = -1
4763 /
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004764
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004765Read up to size bytes from the memory BIO.
4766
4767If size is not specified, read the entire buffer.
4768If the return value is an empty bytes instance, this means either
4769EOF or that no data is available. Use the "eof" property to
4770distinguish between the two.
4771[clinic start generated code]*/
4772
4773static PyObject *
4774_ssl_MemoryBIO_read_impl(PySSLMemoryBIO *self, int len)
4775/*[clinic end generated code: output=a657aa1e79cd01b3 input=574d7be06a902366]*/
4776{
4777 int avail, nbytes;
4778 PyObject *result;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004779
Segev Finer5cff6372017-07-27 01:19:17 +03004780 avail = (int)Py_MIN(BIO_ctrl_pending(self->bio), INT_MAX);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004781 if ((len < 0) || (len > avail))
4782 len = avail;
4783
4784 result = PyBytes_FromStringAndSize(NULL, len);
4785 if ((result == NULL) || (len == 0))
4786 return result;
4787
4788 nbytes = BIO_read(self->bio, PyBytes_AS_STRING(result), len);
Zackery Spytz365ad2e2018-10-06 11:41:45 -06004789 if (nbytes < 0) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02004790 _sslmodulestate *state = get_state_mbio(self);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004791 Py_DECREF(result);
Christian Heimes7f1305e2021-04-17 20:06:38 +02004792 _setSSLError(state, NULL, 0, __FILE__, __LINE__);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004793 return NULL;
4794 }
4795
Zackery Spytz365ad2e2018-10-06 11:41:45 -06004796 /* There should never be any short reads but check anyway. */
4797 if (nbytes < len) {
4798 _PyBytes_Resize(&result, nbytes);
4799 }
4800
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004801 return result;
4802}
4803
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004804/*[clinic input]
4805_ssl.MemoryBIO.write
4806 b: Py_buffer
4807 /
4808
4809Writes the bytes b into the memory BIO.
4810
4811Returns the number of bytes written.
4812[clinic start generated code]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004813
4814static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004815_ssl_MemoryBIO_write_impl(PySSLMemoryBIO *self, Py_buffer *b)
4816/*[clinic end generated code: output=156ec59110d75935 input=e45757b3e17c4808]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004817{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004818 int nbytes;
4819
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004820 if (b->len > INT_MAX) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004821 PyErr_Format(PyExc_OverflowError,
4822 "string longer than %d bytes", INT_MAX);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004823 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004824 }
4825
4826 if (self->eof_written) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02004827 PyObject *module = PyType_GetModule(Py_TYPE(self));
4828 if (module == NULL)
4829 return NULL;
4830 PyErr_SetString(get_ssl_state(module)->PySSLErrorObject,
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004831 "cannot write() after write_eof()");
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004832 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004833 }
4834
Segev Finer5cff6372017-07-27 01:19:17 +03004835 nbytes = BIO_write(self->bio, b->buf, (int)b->len);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004836 if (nbytes < 0) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02004837 _sslmodulestate *state = get_state_mbio(self);
4838 _setSSLError(state, NULL, 0, __FILE__, __LINE__);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004839 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004840 }
4841
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004842 return PyLong_FromLong(nbytes);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004843}
4844
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004845/*[clinic input]
4846_ssl.MemoryBIO.write_eof
4847
4848Write an EOF marker to the memory BIO.
4849
4850When all data has been read, the "eof" property will be True.
4851[clinic start generated code]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004852
4853static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004854_ssl_MemoryBIO_write_eof_impl(PySSLMemoryBIO *self)
4855/*[clinic end generated code: output=d4106276ccd1ed34 input=56a945f1d29e8bd6]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004856{
4857 self->eof_written = 1;
4858 /* After an EOF is written, a zero return from read() should be a real EOF
4859 * i.e. it should not be retried. Clear the SHOULD_RETRY flag. */
4860 BIO_clear_retry_flags(self->bio);
4861 BIO_set_mem_eof_return(self->bio, 0);
4862
4863 Py_RETURN_NONE;
4864}
4865
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004866static PyGetSetDef memory_bio_getsetlist[] = {
4867 {"pending", (getter) memory_bio_get_pending, NULL,
4868 PySSL_memory_bio_pending_doc},
4869 {"eof", (getter) memory_bio_get_eof, NULL,
4870 PySSL_memory_bio_eof_doc},
4871 {NULL}, /* sentinel */
4872};
4873
4874static struct PyMethodDef memory_bio_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004875 _SSL_MEMORYBIO_READ_METHODDEF
4876 _SSL_MEMORYBIO_WRITE_METHODDEF
4877 _SSL_MEMORYBIO_WRITE_EOF_METHODDEF
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004878 {NULL, NULL} /* sentinel */
4879};
4880
Christian Heimes5c36da72020-11-20 09:40:12 +01004881static PyType_Slot PySSLMemoryBIO_slots[] = {
4882 {Py_tp_methods, memory_bio_methods},
4883 {Py_tp_getset, memory_bio_getsetlist},
4884 {Py_tp_new, _ssl_MemoryBIO},
4885 {Py_tp_dealloc, memory_bio_dealloc},
Miss Islington (bot)ea47a8a2021-05-27 09:25:22 -07004886 {Py_tp_traverse, memory_bio_traverse},
Christian Heimes5c36da72020-11-20 09:40:12 +01004887 {0, 0},
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004888};
4889
Christian Heimes5c36da72020-11-20 09:40:12 +01004890static PyType_Spec PySSLMemoryBIO_spec = {
Miss Islington (bot)ea47a8a2021-05-27 09:25:22 -07004891 .name = "_ssl.MemoryBIO",
4892 .basicsize = sizeof(PySSLMemoryBIO),
4893 .flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_IMMUTABLETYPE |
4894 Py_TPFLAGS_HAVE_GC),
4895 .slots = PySSLMemoryBIO_slots,
Christian Heimes5c36da72020-11-20 09:40:12 +01004896};
Antoine Pitrou152efa22010-05-16 18:19:27 +00004897
Christian Heimes99a65702016-09-10 23:44:53 +02004898/*
4899 * SSL Session object
4900 */
4901
4902static void
4903PySSLSession_dealloc(PySSLSession *self)
4904{
Christian Heimes5c36da72020-11-20 09:40:12 +01004905 PyTypeObject *tp = Py_TYPE(self);
INADA Naokia6296d32017-08-24 14:55:17 +09004906 /* bpo-31095: UnTrack is needed before calling any callbacks */
Christian Heimesa5d07652016-09-24 10:48:05 +02004907 PyObject_GC_UnTrack(self);
Christian Heimes99a65702016-09-10 23:44:53 +02004908 Py_XDECREF(self->ctx);
4909 if (self->session != NULL) {
4910 SSL_SESSION_free(self->session);
4911 }
Christian Heimesa5d07652016-09-24 10:48:05 +02004912 PyObject_GC_Del(self);
Christian Heimes5c36da72020-11-20 09:40:12 +01004913 Py_DECREF(tp);
Christian Heimes99a65702016-09-10 23:44:53 +02004914}
4915
4916static PyObject *
4917PySSLSession_richcompare(PyObject *left, PyObject *right, int op)
4918{
4919 int result;
Christian Heimes7f1305e2021-04-17 20:06:38 +02004920 PyTypeObject *sesstype = ((PySSLSession*)left)->ctx->state->PySSLSession_Type;
Christian Heimes99a65702016-09-10 23:44:53 +02004921
4922 if (left == NULL || right == NULL) {
4923 PyErr_BadInternalCall();
4924 return NULL;
4925 }
4926
Christian Heimes7f1305e2021-04-17 20:06:38 +02004927 if (!Py_IS_TYPE(left, sesstype) || !Py_IS_TYPE(right, sesstype)) {
Christian Heimes99a65702016-09-10 23:44:53 +02004928 Py_RETURN_NOTIMPLEMENTED;
4929 }
4930
4931 if (left == right) {
4932 result = 0;
4933 } else {
4934 const unsigned char *left_id, *right_id;
4935 unsigned int left_len, right_len;
4936 left_id = SSL_SESSION_get_id(((PySSLSession *)left)->session,
4937 &left_len);
4938 right_id = SSL_SESSION_get_id(((PySSLSession *)right)->session,
4939 &right_len);
4940 if (left_len == right_len) {
4941 result = memcmp(left_id, right_id, left_len);
4942 } else {
4943 result = 1;
4944 }
4945 }
4946
4947 switch (op) {
4948 case Py_EQ:
4949 if (result == 0) {
4950 Py_RETURN_TRUE;
4951 } else {
4952 Py_RETURN_FALSE;
4953 }
4954 break;
4955 case Py_NE:
4956 if (result != 0) {
4957 Py_RETURN_TRUE;
4958 } else {
4959 Py_RETURN_FALSE;
4960 }
4961 break;
4962 case Py_LT:
4963 case Py_LE:
4964 case Py_GT:
4965 case Py_GE:
4966 Py_RETURN_NOTIMPLEMENTED;
4967 break;
4968 default:
4969 PyErr_BadArgument();
4970 return NULL;
4971 }
4972}
4973
4974static int
4975PySSLSession_traverse(PySSLSession *self, visitproc visit, void *arg)
4976{
4977 Py_VISIT(self->ctx);
Miss Islington (bot)ea47a8a2021-05-27 09:25:22 -07004978 Py_VISIT(Py_TYPE(self));
Christian Heimes99a65702016-09-10 23:44:53 +02004979 return 0;
4980}
4981
4982static int
4983PySSLSession_clear(PySSLSession *self)
4984{
4985 Py_CLEAR(self->ctx);
4986 return 0;
4987}
4988
4989
4990static PyObject *
4991PySSLSession_get_time(PySSLSession *self, void *closure) {
4992 return PyLong_FromLong(SSL_SESSION_get_time(self->session));
4993}
4994
4995PyDoc_STRVAR(PySSLSession_get_time_doc,
4996"Session creation time (seconds since epoch).");
4997
4998
4999static PyObject *
5000PySSLSession_get_timeout(PySSLSession *self, void *closure) {
5001 return PyLong_FromLong(SSL_SESSION_get_timeout(self->session));
5002}
5003
5004PyDoc_STRVAR(PySSLSession_get_timeout_doc,
5005"Session timeout (delta in seconds).");
5006
5007
5008static PyObject *
5009PySSLSession_get_ticket_lifetime_hint(PySSLSession *self, void *closure) {
5010 unsigned long hint = SSL_SESSION_get_ticket_lifetime_hint(self->session);
5011 return PyLong_FromUnsignedLong(hint);
5012}
5013
5014PyDoc_STRVAR(PySSLSession_get_ticket_lifetime_hint_doc,
5015"Ticket life time hint.");
5016
5017
5018static PyObject *
5019PySSLSession_get_session_id(PySSLSession *self, void *closure) {
5020 const unsigned char *id;
5021 unsigned int len;
5022 id = SSL_SESSION_get_id(self->session, &len);
5023 return PyBytes_FromStringAndSize((const char *)id, len);
5024}
5025
5026PyDoc_STRVAR(PySSLSession_get_session_id_doc,
5027"Session id");
5028
5029
5030static PyObject *
5031PySSLSession_get_has_ticket(PySSLSession *self, void *closure) {
5032 if (SSL_SESSION_has_ticket(self->session)) {
5033 Py_RETURN_TRUE;
5034 } else {
5035 Py_RETURN_FALSE;
5036 }
5037}
5038
5039PyDoc_STRVAR(PySSLSession_get_has_ticket_doc,
5040"Does the session contain a ticket?");
5041
5042
5043static PyGetSetDef PySSLSession_getsetlist[] = {
5044 {"has_ticket", (getter) PySSLSession_get_has_ticket, NULL,
5045 PySSLSession_get_has_ticket_doc},
5046 {"id", (getter) PySSLSession_get_session_id, NULL,
5047 PySSLSession_get_session_id_doc},
5048 {"ticket_lifetime_hint", (getter) PySSLSession_get_ticket_lifetime_hint,
5049 NULL, PySSLSession_get_ticket_lifetime_hint_doc},
5050 {"time", (getter) PySSLSession_get_time, NULL,
5051 PySSLSession_get_time_doc},
5052 {"timeout", (getter) PySSLSession_get_timeout, NULL,
5053 PySSLSession_get_timeout_doc},
5054 {NULL}, /* sentinel */
5055};
5056
Christian Heimes5c36da72020-11-20 09:40:12 +01005057static PyType_Slot PySSLSession_slots[] = {
5058 {Py_tp_getset,PySSLSession_getsetlist},
5059 {Py_tp_richcompare, PySSLSession_richcompare},
5060 {Py_tp_dealloc, PySSLSession_dealloc},
5061 {Py_tp_traverse, PySSLSession_traverse},
5062 {Py_tp_clear, PySSLSession_clear},
5063 {0, 0},
5064};
5065
5066static PyType_Spec PySSLSession_spec = {
Miss Islington (bot)ea47a8a2021-05-27 09:25:22 -07005067 .name = "_ssl.SSLSession",
5068 .basicsize = sizeof(PySSLSession),
5069 .flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
5070 Py_TPFLAGS_IMMUTABLETYPE),
5071 .slots = PySSLSession_slots,
Christian Heimes99a65702016-09-10 23:44:53 +02005072};
5073
5074
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005075/* helper routines for seeding the SSL PRNG */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005076/*[clinic input]
5077_ssl.RAND_add
Larry Hastingsdbfdc382015-05-04 06:59:46 -07005078 string as view: Py_buffer(accept={str, buffer})
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005079 entropy: double
5080 /
5081
5082Mix string into the OpenSSL PRNG state.
5083
5084entropy (a float) is a lower bound on the entropy contained in
Chandan Kumar63c2c8a2017-06-09 15:13:58 +05305085string. See RFC 4086.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005086[clinic start generated code]*/
5087
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005088static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005089_ssl_RAND_add_impl(PyObject *module, Py_buffer *view, double entropy)
Serhiy Storchaka5f31d5c2017-06-10 13:13:51 +03005090/*[clinic end generated code: output=e6dd48df9c9024e9 input=5c33017422828f5c]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005091{
Serhiy Storchaka8490f5a2015-03-20 09:00:36 +02005092 const char *buf;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02005093 Py_ssize_t len, written;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005094
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005095 buf = (const char *)view->buf;
5096 len = view->len;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02005097 do {
5098 written = Py_MIN(len, INT_MAX);
5099 RAND_add(buf, (int)written, entropy);
5100 buf += written;
5101 len -= written;
5102 } while (len);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02005103 Py_RETURN_NONE;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005104}
5105
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005106static PyObject *
Christian Heimes7f1305e2021-04-17 20:06:38 +02005107PySSL_RAND(PyObject *module, int len, int pseudo)
Victor Stinner99c8b162011-05-24 12:05:19 +02005108{
5109 int ok;
5110 PyObject *bytes;
5111 unsigned long err;
5112 const char *errstr;
5113 PyObject *v;
5114
Victor Stinner1e81a392013-12-19 16:47:04 +01005115 if (len < 0) {
5116 PyErr_SetString(PyExc_ValueError, "num must be positive");
5117 return NULL;
5118 }
5119
Victor Stinner99c8b162011-05-24 12:05:19 +02005120 bytes = PyBytes_FromStringAndSize(NULL, len);
5121 if (bytes == NULL)
5122 return NULL;
5123 if (pseudo) {
Christian Heimesa871f692020-06-01 08:58:14 +02005124 ok = RAND_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
Victor Stinner99c8b162011-05-24 12:05:19 +02005125 if (ok == 0 || ok == 1)
5126 return Py_BuildValue("NO", bytes, ok == 1 ? Py_True : Py_False);
5127 }
5128 else {
5129 ok = RAND_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
5130 if (ok == 1)
5131 return bytes;
5132 }
5133 Py_DECREF(bytes);
5134
5135 err = ERR_get_error();
5136 errstr = ERR_reason_error_string(err);
5137 v = Py_BuildValue("(ks)", err, errstr);
5138 if (v != NULL) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02005139 PyErr_SetObject(get_ssl_state(module)->PySSLErrorObject, v);
Victor Stinner99c8b162011-05-24 12:05:19 +02005140 Py_DECREF(v);
5141 }
5142 return NULL;
5143}
5144
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005145/*[clinic input]
5146_ssl.RAND_bytes
5147 n: int
5148 /
5149
5150Generate n cryptographically strong pseudo-random bytes.
5151[clinic start generated code]*/
5152
Victor Stinner99c8b162011-05-24 12:05:19 +02005153static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005154_ssl_RAND_bytes_impl(PyObject *module, int n)
5155/*[clinic end generated code: output=977da635e4838bc7 input=678ddf2872dfebfc]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02005156{
Christian Heimes7f1305e2021-04-17 20:06:38 +02005157 return PySSL_RAND(module, n, 0);
Victor Stinner99c8b162011-05-24 12:05:19 +02005158}
5159
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005160/*[clinic input]
5161_ssl.RAND_pseudo_bytes
5162 n: int
5163 /
5164
5165Generate n pseudo-random bytes.
5166
5167Return a pair (bytes, is_cryptographic). is_cryptographic is True
5168if the bytes generated are cryptographically strong.
5169[clinic start generated code]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02005170
5171static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005172_ssl_RAND_pseudo_bytes_impl(PyObject *module, int n)
5173/*[clinic end generated code: output=b1509e937000e52d input=58312bd53f9bbdd0]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02005174{
Miss Islington (bot)d7930fb2021-06-11 00:36:17 -07005175 PY_SSL_DEPRECATED("ssl.RAND_pseudo_bytes() is deprecated", 1, NULL);
Christian Heimes7f1305e2021-04-17 20:06:38 +02005176 return PySSL_RAND(module, n, 1);
Victor Stinner99c8b162011-05-24 12:05:19 +02005177}
5178
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005179/*[clinic input]
5180_ssl.RAND_status
5181
Zackery Spytz7d37b862021-04-23 10:07:37 -06005182Returns True if the OpenSSL PRNG has been seeded with enough data and False if not.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005183
5184It is necessary to seed the PRNG with RAND_add() on some platforms before
5185using the ssl() function.
5186[clinic start generated code]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02005187
5188static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005189_ssl_RAND_status_impl(PyObject *module)
Zackery Spytz7d37b862021-04-23 10:07:37 -06005190/*[clinic end generated code: output=7e0aaa2d39fdc1ad input=d5ae5aea52f36e01]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005191{
Zackery Spytz7d37b862021-04-23 10:07:37 -06005192 return PyBool_FromLong(RAND_status());
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005193}
5194
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005195/*[clinic input]
5196_ssl.get_default_verify_paths
5197
5198Return search paths and environment vars that are used by SSLContext's set_default_verify_paths() to load default CAs.
5199
5200The values are 'cert_file_env', 'cert_file', 'cert_dir_env', 'cert_dir'.
5201[clinic start generated code]*/
Christian Heimes6d7ad132013-06-09 18:02:55 +02005202
5203static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005204_ssl_get_default_verify_paths_impl(PyObject *module)
5205/*[clinic end generated code: output=e5b62a466271928b input=5210c953d98c3eb5]*/
Christian Heimes6d7ad132013-06-09 18:02:55 +02005206{
5207 PyObject *ofile_env = NULL;
5208 PyObject *ofile = NULL;
5209 PyObject *odir_env = NULL;
5210 PyObject *odir = NULL;
5211
Benjamin Petersond113c962015-07-18 10:59:13 -07005212#define CONVERT(info, target) { \
Christian Heimes6d7ad132013-06-09 18:02:55 +02005213 const char *tmp = (info); \
5214 target = NULL; \
5215 if (!tmp) { Py_INCREF(Py_None); target = Py_None; } \
5216 else if ((target = PyUnicode_DecodeFSDefault(tmp)) == NULL) { \
5217 target = PyBytes_FromString(tmp); } \
5218 if (!target) goto error; \
Benjamin Peterson025a1fd2015-11-14 15:12:38 -08005219 }
Christian Heimes6d7ad132013-06-09 18:02:55 +02005220
Benjamin Petersond113c962015-07-18 10:59:13 -07005221 CONVERT(X509_get_default_cert_file_env(), ofile_env);
5222 CONVERT(X509_get_default_cert_file(), ofile);
5223 CONVERT(X509_get_default_cert_dir_env(), odir_env);
5224 CONVERT(X509_get_default_cert_dir(), odir);
5225#undef CONVERT
Christian Heimes6d7ad132013-06-09 18:02:55 +02005226
Christian Heimes200bb1b2013-06-14 15:14:29 +02005227 return Py_BuildValue("NNNN", ofile_env, ofile, odir_env, odir);
Christian Heimes6d7ad132013-06-09 18:02:55 +02005228
5229 error:
5230 Py_XDECREF(ofile_env);
5231 Py_XDECREF(ofile);
5232 Py_XDECREF(odir_env);
5233 Py_XDECREF(odir);
5234 return NULL;
5235}
5236
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005237static PyObject*
Christian Heimes7f1305e2021-04-17 20:06:38 +02005238asn1obj2py(_sslmodulestate *state, ASN1_OBJECT *obj)
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005239{
5240 int nid;
5241 const char *ln, *sn;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005242
5243 nid = OBJ_obj2nid(obj);
5244 if (nid == NID_undef) {
5245 PyErr_Format(PyExc_ValueError, "Unknown object");
5246 return NULL;
5247 }
5248 sn = OBJ_nid2sn(nid);
5249 ln = OBJ_nid2ln(nid);
Christian Heimes7f1305e2021-04-17 20:06:38 +02005250 return Py_BuildValue("issN", nid, sn, ln, _asn1obj2py(state, obj, 1));
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005251}
5252
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005253/*[clinic input]
5254_ssl.txt2obj
5255 txt: str
5256 name: bool = False
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005257
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005258Lookup NID, short name, long name and OID of an ASN1_OBJECT.
5259
5260By default objects are looked up by OID. With name=True short and
5261long name are also matched.
5262[clinic start generated code]*/
5263
5264static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005265_ssl_txt2obj_impl(PyObject *module, const char *txt, int name)
5266/*[clinic end generated code: output=c38e3991347079c1 input=1c1e7d0aa7c48602]*/
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005267{
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005268 PyObject *result = NULL;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005269 ASN1_OBJECT *obj;
5270
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005271 obj = OBJ_txt2obj(txt, name ? 0 : 1);
5272 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01005273 PyErr_Format(PyExc_ValueError, "unknown object '%.100s'", txt);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005274 return NULL;
5275 }
Christian Heimes7f1305e2021-04-17 20:06:38 +02005276 result = asn1obj2py(get_ssl_state(module), obj);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005277 ASN1_OBJECT_free(obj);
5278 return result;
5279}
5280
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005281/*[clinic input]
5282_ssl.nid2obj
5283 nid: int
5284 /
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005285
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005286Lookup NID, short name, long name and OID of an ASN1_OBJECT by NID.
5287[clinic start generated code]*/
5288
5289static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005290_ssl_nid2obj_impl(PyObject *module, int nid)
5291/*[clinic end generated code: output=4a98ab691cd4f84a input=51787a3bee7d8f98]*/
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005292{
5293 PyObject *result = NULL;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005294 ASN1_OBJECT *obj;
5295
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005296 if (nid < NID_undef) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01005297 PyErr_SetString(PyExc_ValueError, "NID must be positive.");
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005298 return NULL;
5299 }
5300 obj = OBJ_nid2obj(nid);
5301 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01005302 PyErr_Format(PyExc_ValueError, "unknown NID %i", nid);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005303 return NULL;
5304 }
Christian Heimes7f1305e2021-04-17 20:06:38 +02005305 result = asn1obj2py(get_ssl_state(module), obj);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005306 ASN1_OBJECT_free(obj);
5307 return result;
5308}
5309
Christian Heimes46bebee2013-06-09 19:03:31 +02005310#ifdef _MSC_VER
Christian Heimes44109d72013-11-22 01:51:30 +01005311
5312static PyObject*
5313certEncodingType(DWORD encodingType)
5314{
5315 static PyObject *x509_asn = NULL;
5316 static PyObject *pkcs_7_asn = NULL;
5317
5318 if (x509_asn == NULL) {
5319 x509_asn = PyUnicode_InternFromString("x509_asn");
5320 if (x509_asn == NULL)
5321 return NULL;
5322 }
5323 if (pkcs_7_asn == NULL) {
5324 pkcs_7_asn = PyUnicode_InternFromString("pkcs_7_asn");
5325 if (pkcs_7_asn == NULL)
5326 return NULL;
5327 }
5328 switch(encodingType) {
5329 case X509_ASN_ENCODING:
5330 Py_INCREF(x509_asn);
5331 return x509_asn;
5332 case PKCS_7_ASN_ENCODING:
5333 Py_INCREF(pkcs_7_asn);
5334 return pkcs_7_asn;
5335 default:
5336 return PyLong_FromLong(encodingType);
5337 }
5338}
5339
5340static PyObject*
5341parseKeyUsage(PCCERT_CONTEXT pCertCtx, DWORD flags)
5342{
5343 CERT_ENHKEY_USAGE *usage;
5344 DWORD size, error, i;
5345 PyObject *retval;
5346
5347 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, NULL, &size)) {
5348 error = GetLastError();
5349 if (error == CRYPT_E_NOT_FOUND) {
5350 Py_RETURN_TRUE;
5351 }
5352 return PyErr_SetFromWindowsErr(error);
5353 }
5354
5355 usage = (CERT_ENHKEY_USAGE*)PyMem_Malloc(size);
5356 if (usage == NULL) {
5357 return PyErr_NoMemory();
5358 }
5359
5360 /* Now get the actual enhanced usage property */
5361 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, usage, &size)) {
5362 PyMem_Free(usage);
5363 error = GetLastError();
5364 if (error == CRYPT_E_NOT_FOUND) {
5365 Py_RETURN_TRUE;
5366 }
5367 return PyErr_SetFromWindowsErr(error);
5368 }
Christian Heimes915cd3f2019-09-09 18:06:55 +02005369 retval = PyFrozenSet_New(NULL);
Christian Heimes44109d72013-11-22 01:51:30 +01005370 if (retval == NULL) {
5371 goto error;
5372 }
5373 for (i = 0; i < usage->cUsageIdentifier; ++i) {
5374 if (usage->rgpszUsageIdentifier[i]) {
5375 PyObject *oid;
5376 int err;
5377 oid = PyUnicode_FromString(usage->rgpszUsageIdentifier[i]);
5378 if (oid == NULL) {
5379 Py_CLEAR(retval);
5380 goto error;
5381 }
5382 err = PySet_Add(retval, oid);
5383 Py_DECREF(oid);
5384 if (err == -1) {
5385 Py_CLEAR(retval);
5386 goto error;
5387 }
5388 }
5389 }
5390 error:
5391 PyMem_Free(usage);
5392 return retval;
5393}
5394
kctherookied93fbbf2019-03-29 00:59:06 +07005395static HCERTSTORE
5396ssl_collect_certificates(const char *store_name)
5397{
5398/* this function collects the system certificate stores listed in
5399 * system_stores into a collection certificate store for being
5400 * enumerated. The store must be readable to be added to the
5401 * store collection.
5402 */
5403
5404 HCERTSTORE hCollectionStore = NULL, hSystemStore = NULL;
5405 static DWORD system_stores[] = {
5406 CERT_SYSTEM_STORE_LOCAL_MACHINE,
5407 CERT_SYSTEM_STORE_LOCAL_MACHINE_ENTERPRISE,
5408 CERT_SYSTEM_STORE_LOCAL_MACHINE_GROUP_POLICY,
5409 CERT_SYSTEM_STORE_CURRENT_USER,
5410 CERT_SYSTEM_STORE_CURRENT_USER_GROUP_POLICY,
5411 CERT_SYSTEM_STORE_SERVICES,
5412 CERT_SYSTEM_STORE_USERS};
5413 size_t i, storesAdded;
5414 BOOL result;
5415
5416 hCollectionStore = CertOpenStore(CERT_STORE_PROV_COLLECTION, 0,
5417 (HCRYPTPROV)NULL, 0, NULL);
5418 if (!hCollectionStore) {
5419 return NULL;
5420 }
5421 storesAdded = 0;
5422 for (i = 0; i < sizeof(system_stores) / sizeof(DWORD); i++) {
5423 hSystemStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0,
5424 (HCRYPTPROV)NULL,
5425 CERT_STORE_READONLY_FLAG |
5426 system_stores[i], store_name);
5427 if (hSystemStore) {
5428 result = CertAddStoreToCollection(hCollectionStore, hSystemStore,
5429 CERT_PHYSICAL_STORE_ADD_ENABLE_FLAG, 0);
5430 if (result) {
5431 ++storesAdded;
5432 }
neoneneed701292019-09-09 21:33:43 +09005433 CertCloseStore(hSystemStore, 0); /* flag must be 0 */
kctherookied93fbbf2019-03-29 00:59:06 +07005434 }
5435 }
5436 if (storesAdded == 0) {
5437 CertCloseStore(hCollectionStore, CERT_CLOSE_STORE_FORCE_FLAG);
5438 return NULL;
5439 }
5440
5441 return hCollectionStore;
5442}
5443
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005444/*[clinic input]
5445_ssl.enum_certificates
5446 store_name: str
5447
5448Retrieve certificates from Windows' cert store.
5449
5450store_name may be one of 'CA', 'ROOT' or 'MY'. The system may provide
5451more cert storages, too. The function returns a list of (bytes,
5452encoding_type, trust) tuples. The encoding_type flag can be interpreted
5453with X509_ASN_ENCODING or PKCS_7_ASN_ENCODING. The trust setting is either
5454a set of OIDs or the boolean True.
5455[clinic start generated code]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00005456
Christian Heimes46bebee2013-06-09 19:03:31 +02005457static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005458_ssl_enum_certificates_impl(PyObject *module, const char *store_name)
5459/*[clinic end generated code: output=5134dc8bb3a3c893 input=915f60d70461ea4e]*/
Christian Heimes46bebee2013-06-09 19:03:31 +02005460{
kctherookied93fbbf2019-03-29 00:59:06 +07005461 HCERTSTORE hCollectionStore = NULL;
Christian Heimes44109d72013-11-22 01:51:30 +01005462 PCCERT_CONTEXT pCertCtx = NULL;
5463 PyObject *keyusage = NULL, *cert = NULL, *enc = NULL, *tup = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02005464 PyObject *result = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02005465
Christian Heimes915cd3f2019-09-09 18:06:55 +02005466 result = PySet_New(NULL);
Christian Heimes44109d72013-11-22 01:51:30 +01005467 if (result == NULL) {
5468 return NULL;
5469 }
kctherookied93fbbf2019-03-29 00:59:06 +07005470 hCollectionStore = ssl_collect_certificates(store_name);
5471 if (hCollectionStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02005472 Py_DECREF(result);
5473 return PyErr_SetFromWindowsErr(GetLastError());
5474 }
5475
kctherookied93fbbf2019-03-29 00:59:06 +07005476 while (pCertCtx = CertEnumCertificatesInStore(hCollectionStore, pCertCtx)) {
Christian Heimes44109d72013-11-22 01:51:30 +01005477 cert = PyBytes_FromStringAndSize((const char*)pCertCtx->pbCertEncoded,
5478 pCertCtx->cbCertEncoded);
5479 if (!cert) {
5480 Py_CLEAR(result);
5481 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02005482 }
Christian Heimes44109d72013-11-22 01:51:30 +01005483 if ((enc = certEncodingType(pCertCtx->dwCertEncodingType)) == NULL) {
5484 Py_CLEAR(result);
5485 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02005486 }
Christian Heimes44109d72013-11-22 01:51:30 +01005487 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG);
5488 if (keyusage == Py_True) {
5489 Py_DECREF(keyusage);
5490 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_EXT_ONLY_ENHKEY_USAGE_FLAG);
Christian Heimes46bebee2013-06-09 19:03:31 +02005491 }
Christian Heimes44109d72013-11-22 01:51:30 +01005492 if (keyusage == NULL) {
5493 Py_CLEAR(result);
5494 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02005495 }
Christian Heimes44109d72013-11-22 01:51:30 +01005496 if ((tup = PyTuple_New(3)) == NULL) {
5497 Py_CLEAR(result);
5498 break;
5499 }
5500 PyTuple_SET_ITEM(tup, 0, cert);
5501 cert = NULL;
5502 PyTuple_SET_ITEM(tup, 1, enc);
5503 enc = NULL;
5504 PyTuple_SET_ITEM(tup, 2, keyusage);
5505 keyusage = NULL;
Christian Heimes915cd3f2019-09-09 18:06:55 +02005506 if (PySet_Add(result, tup) == -1) {
5507 Py_CLEAR(result);
5508 Py_CLEAR(tup);
5509 break;
Christian Heimes44109d72013-11-22 01:51:30 +01005510 }
5511 Py_CLEAR(tup);
5512 }
5513 if (pCertCtx) {
5514 /* loop ended with an error, need to clean up context manually */
5515 CertFreeCertificateContext(pCertCtx);
Christian Heimes46bebee2013-06-09 19:03:31 +02005516 }
5517
5518 /* In error cases cert, enc and tup may not be NULL */
5519 Py_XDECREF(cert);
5520 Py_XDECREF(enc);
Christian Heimes44109d72013-11-22 01:51:30 +01005521 Py_XDECREF(keyusage);
Christian Heimes46bebee2013-06-09 19:03:31 +02005522 Py_XDECREF(tup);
5523
kctherookied93fbbf2019-03-29 00:59:06 +07005524 /* CERT_CLOSE_STORE_FORCE_FLAG forces freeing of memory for all contexts
5525 associated with the store, in this case our collection store and the
5526 associated system stores. */
5527 if (!CertCloseStore(hCollectionStore, CERT_CLOSE_STORE_FORCE_FLAG)) {
Christian Heimes46bebee2013-06-09 19:03:31 +02005528 /* This error case might shadow another exception.*/
Christian Heimes44109d72013-11-22 01:51:30 +01005529 Py_XDECREF(result);
5530 return PyErr_SetFromWindowsErr(GetLastError());
5531 }
kctherookied93fbbf2019-03-29 00:59:06 +07005532
Christian Heimes915cd3f2019-09-09 18:06:55 +02005533 /* convert set to list */
5534 if (result == NULL) {
5535 return NULL;
5536 } else {
5537 PyObject *lst = PySequence_List(result);
5538 Py_DECREF(result);
5539 return lst;
5540 }
Christian Heimes44109d72013-11-22 01:51:30 +01005541}
5542
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005543/*[clinic input]
5544_ssl.enum_crls
5545 store_name: str
5546
5547Retrieve CRLs from Windows' cert store.
5548
5549store_name may be one of 'CA', 'ROOT' or 'MY'. The system may provide
5550more cert storages, too. The function returns a list of (bytes,
5551encoding_type) tuples. The encoding_type flag can be interpreted with
5552X509_ASN_ENCODING or PKCS_7_ASN_ENCODING.
5553[clinic start generated code]*/
Christian Heimes44109d72013-11-22 01:51:30 +01005554
5555static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005556_ssl_enum_crls_impl(PyObject *module, const char *store_name)
5557/*[clinic end generated code: output=bce467f60ccd03b6 input=a1f1d7629f1c5d3d]*/
Christian Heimes44109d72013-11-22 01:51:30 +01005558{
kctherookied93fbbf2019-03-29 00:59:06 +07005559 HCERTSTORE hCollectionStore = NULL;
Christian Heimes44109d72013-11-22 01:51:30 +01005560 PCCRL_CONTEXT pCrlCtx = NULL;
5561 PyObject *crl = NULL, *enc = NULL, *tup = NULL;
5562 PyObject *result = NULL;
5563
Christian Heimes915cd3f2019-09-09 18:06:55 +02005564 result = PySet_New(NULL);
Christian Heimes44109d72013-11-22 01:51:30 +01005565 if (result == NULL) {
5566 return NULL;
5567 }
kctherookied93fbbf2019-03-29 00:59:06 +07005568 hCollectionStore = ssl_collect_certificates(store_name);
5569 if (hCollectionStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02005570 Py_DECREF(result);
5571 return PyErr_SetFromWindowsErr(GetLastError());
5572 }
Christian Heimes44109d72013-11-22 01:51:30 +01005573
kctherookied93fbbf2019-03-29 00:59:06 +07005574 while (pCrlCtx = CertEnumCRLsInStore(hCollectionStore, pCrlCtx)) {
Christian Heimes44109d72013-11-22 01:51:30 +01005575 crl = PyBytes_FromStringAndSize((const char*)pCrlCtx->pbCrlEncoded,
5576 pCrlCtx->cbCrlEncoded);
5577 if (!crl) {
5578 Py_CLEAR(result);
5579 break;
5580 }
5581 if ((enc = certEncodingType(pCrlCtx->dwCertEncodingType)) == NULL) {
5582 Py_CLEAR(result);
5583 break;
5584 }
5585 if ((tup = PyTuple_New(2)) == NULL) {
5586 Py_CLEAR(result);
5587 break;
5588 }
5589 PyTuple_SET_ITEM(tup, 0, crl);
5590 crl = NULL;
5591 PyTuple_SET_ITEM(tup, 1, enc);
5592 enc = NULL;
5593
Christian Heimes915cd3f2019-09-09 18:06:55 +02005594 if (PySet_Add(result, tup) == -1) {
5595 Py_CLEAR(result);
5596 Py_CLEAR(tup);
5597 break;
Christian Heimes44109d72013-11-22 01:51:30 +01005598 }
5599 Py_CLEAR(tup);
Christian Heimes46bebee2013-06-09 19:03:31 +02005600 }
Christian Heimes44109d72013-11-22 01:51:30 +01005601 if (pCrlCtx) {
5602 /* loop ended with an error, need to clean up context manually */
5603 CertFreeCRLContext(pCrlCtx);
5604 }
5605
5606 /* In error cases cert, enc and tup may not be NULL */
5607 Py_XDECREF(crl);
5608 Py_XDECREF(enc);
5609 Py_XDECREF(tup);
5610
kctherookied93fbbf2019-03-29 00:59:06 +07005611 /* CERT_CLOSE_STORE_FORCE_FLAG forces freeing of memory for all contexts
5612 associated with the store, in this case our collection store and the
5613 associated system stores. */
5614 if (!CertCloseStore(hCollectionStore, CERT_CLOSE_STORE_FORCE_FLAG)) {
Christian Heimes44109d72013-11-22 01:51:30 +01005615 /* This error case might shadow another exception.*/
5616 Py_XDECREF(result);
5617 return PyErr_SetFromWindowsErr(GetLastError());
5618 }
Christian Heimes915cd3f2019-09-09 18:06:55 +02005619 /* convert set to list */
5620 if (result == NULL) {
5621 return NULL;
5622 } else {
5623 PyObject *lst = PySequence_List(result);
5624 Py_DECREF(result);
5625 return lst;
5626 }
Christian Heimes46bebee2013-06-09 19:03:31 +02005627}
Christian Heimes44109d72013-11-22 01:51:30 +01005628
5629#endif /* _MSC_VER */
Bill Janssen40a0f662008-08-12 16:56:25 +00005630
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005631/* List of functions exported by this module. */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005632static PyMethodDef PySSL_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005633 _SSL__TEST_DECODE_CERT_METHODDEF
5634 _SSL_RAND_ADD_METHODDEF
5635 _SSL_RAND_BYTES_METHODDEF
5636 _SSL_RAND_PSEUDO_BYTES_METHODDEF
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005637 _SSL_RAND_STATUS_METHODDEF
5638 _SSL_GET_DEFAULT_VERIFY_PATHS_METHODDEF
5639 _SSL_ENUM_CERTIFICATES_METHODDEF
5640 _SSL_ENUM_CRLS_METHODDEF
5641 _SSL_TXT2OBJ_METHODDEF
5642 _SSL_NID2OBJ_METHODDEF
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005643 {NULL, NULL} /* Sentinel */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005644};
5645
5646
Christian Heimes7f1305e2021-04-17 20:06:38 +02005647PyDoc_STRVAR(module_doc,
5648"Implementation module for SSL socket operations. See the socket module\n\
5649for documentation.");
Christian Heimes5c36da72020-11-20 09:40:12 +01005650
5651static int
5652sslmodule_init_exceptions(PyObject *module)
5653{
Christian Heimes7f1305e2021-04-17 20:06:38 +02005654 _sslmodulestate *state = get_ssl_state(module);
Christian Heimes5c36da72020-11-20 09:40:12 +01005655 PyObject *bases = NULL;
5656
Christian Heimes7f1305e2021-04-17 20:06:38 +02005657#define add_exception(exc, name, doc, base) \
5658do { \
5659 (exc) = PyErr_NewExceptionWithDoc("ssl." name, (doc), (base), NULL); \
5660 if ((state) == NULL) goto error; \
5661 if (PyModule_AddObjectRef(module, name, exc) < 0) goto error; \
Christian Heimes5c36da72020-11-20 09:40:12 +01005662} while(0)
5663
Christian Heimes7f1305e2021-04-17 20:06:38 +02005664 state->PySSLErrorObject = PyType_FromSpecWithBases(
5665 &sslerror_type_spec, PyExc_OSError);
5666 if (state->PySSLErrorObject == NULL) {
Christian Heimes5c36da72020-11-20 09:40:12 +01005667 goto error;
5668 }
Christian Heimes7f1305e2021-04-17 20:06:38 +02005669 if (PyModule_AddObjectRef(module, "SSLError", state->PySSLErrorObject) < 0) {
Christian Heimes5c36da72020-11-20 09:40:12 +01005670 goto error;
5671 }
5672
5673 /* ssl.CertificateError used to be a subclass of ValueError */
Christian Heimes7f1305e2021-04-17 20:06:38 +02005674 bases = PyTuple_Pack(2, state->PySSLErrorObject, PyExc_ValueError);
Christian Heimes5c36da72020-11-20 09:40:12 +01005675 if (bases == NULL) {
5676 goto error;
5677 }
5678 add_exception(
Christian Heimes7f1305e2021-04-17 20:06:38 +02005679 state->PySSLCertVerificationErrorObject,
Christian Heimes5c36da72020-11-20 09:40:12 +01005680 "SSLCertVerificationError",
5681 SSLCertVerificationError_doc,
5682 bases
5683 );
5684 Py_CLEAR(bases);
5685
5686 add_exception(
Christian Heimes7f1305e2021-04-17 20:06:38 +02005687 state->PySSLZeroReturnErrorObject,
Christian Heimes5c36da72020-11-20 09:40:12 +01005688 "SSLZeroReturnError",
5689 SSLZeroReturnError_doc,
Christian Heimes7f1305e2021-04-17 20:06:38 +02005690 state->PySSLErrorObject
Christian Heimes5c36da72020-11-20 09:40:12 +01005691 );
5692
5693 add_exception(
Christian Heimes7f1305e2021-04-17 20:06:38 +02005694 state->PySSLWantWriteErrorObject,
Christian Heimes5c36da72020-11-20 09:40:12 +01005695 "SSLWantWriteError",
5696 SSLWantWriteError_doc,
Christian Heimes7f1305e2021-04-17 20:06:38 +02005697 state->PySSLErrorObject
Christian Heimes5c36da72020-11-20 09:40:12 +01005698 );
5699
5700 add_exception(
Christian Heimes7f1305e2021-04-17 20:06:38 +02005701 state->PySSLWantReadErrorObject,
Christian Heimes5c36da72020-11-20 09:40:12 +01005702 "SSLWantReadError",
5703 SSLWantReadError_doc,
Christian Heimes7f1305e2021-04-17 20:06:38 +02005704 state->PySSLErrorObject
Christian Heimes5c36da72020-11-20 09:40:12 +01005705 );
5706
5707 add_exception(
Christian Heimes7f1305e2021-04-17 20:06:38 +02005708 state->PySSLSyscallErrorObject,
Christian Heimes5c36da72020-11-20 09:40:12 +01005709 "SSLSyscallError",
5710 SSLSyscallError_doc,
Christian Heimes7f1305e2021-04-17 20:06:38 +02005711 state->PySSLErrorObject
Christian Heimes5c36da72020-11-20 09:40:12 +01005712 );
5713
5714 add_exception(
Christian Heimes7f1305e2021-04-17 20:06:38 +02005715 state->PySSLEOFErrorObject,
Christian Heimes5c36da72020-11-20 09:40:12 +01005716 "SSLEOFError",
5717 SSLEOFError_doc,
Christian Heimes7f1305e2021-04-17 20:06:38 +02005718 state->PySSLErrorObject
Christian Heimes5c36da72020-11-20 09:40:12 +01005719 );
5720#undef add_exception
5721
5722 return 0;
5723 error:
5724 Py_XDECREF(bases);
5725 return -1;
5726}
5727
5728static int
5729sslmodule_init_socketapi(PyObject *module)
5730{
Christian Heimes7f1305e2021-04-17 20:06:38 +02005731 _sslmodulestate *state = get_ssl_state(module);
5732 PySocketModule_APIObject *sockmod = PySocketModule_ImportModuleAndAPI();
Christian Heimes5c36da72020-11-20 09:40:12 +01005733
Christian Heimes7f1305e2021-04-17 20:06:38 +02005734 if ((sockmod == NULL) || (sockmod->Sock_Type == NULL)) {
Christian Heimes5c36da72020-11-20 09:40:12 +01005735 return -1;
Christian Heimes5c36da72020-11-20 09:40:12 +01005736 }
Christian Heimes7f1305e2021-04-17 20:06:38 +02005737 state->Sock_Type = sockmod->Sock_Type;
5738 Py_INCREF(state->Sock_Type);
Christian Heimes5c36da72020-11-20 09:40:12 +01005739 return 0;
5740}
Christian Heimesc941e622017-09-05 15:47:11 +02005741
Christian Heimes5c36da72020-11-20 09:40:12 +01005742static int
5743sslmodule_init_constants(PyObject *m)
5744{
Christian Heimes7f1305e2021-04-17 20:06:38 +02005745
Christian Heimes892d66e2018-01-29 14:10:18 +01005746 PyModule_AddStringConstant(m, "_DEFAULT_CIPHERS",
5747 PY_SSL_DEFAULT_CIPHER_STRING);
5748
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005749 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
5750 PY_SSL_ERROR_ZERO_RETURN);
5751 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
5752 PY_SSL_ERROR_WANT_READ);
5753 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
5754 PY_SSL_ERROR_WANT_WRITE);
5755 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
5756 PY_SSL_ERROR_WANT_X509_LOOKUP);
5757 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
5758 PY_SSL_ERROR_SYSCALL);
5759 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
5760 PY_SSL_ERROR_SSL);
5761 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
5762 PY_SSL_ERROR_WANT_CONNECT);
5763 /* non ssl.h errorcodes */
5764 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
5765 PY_SSL_ERROR_EOF);
5766 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
5767 PY_SSL_ERROR_INVALID_ERROR_CODE);
5768 /* cert requirements */
5769 PyModule_AddIntConstant(m, "CERT_NONE",
5770 PY_SSL_CERT_NONE);
5771 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
5772 PY_SSL_CERT_OPTIONAL);
5773 PyModule_AddIntConstant(m, "CERT_REQUIRED",
5774 PY_SSL_CERT_REQUIRED);
Christian Heimes22587792013-11-21 23:56:13 +01005775 /* CRL verification for verification_flags */
5776 PyModule_AddIntConstant(m, "VERIFY_DEFAULT",
5777 0);
5778 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_LEAF",
5779 X509_V_FLAG_CRL_CHECK);
5780 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_CHAIN",
5781 X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
5782 PyModule_AddIntConstant(m, "VERIFY_X509_STRICT",
5783 X509_V_FLAG_X509_STRICT);
Chris Burre0b4aa02021-03-18 09:24:01 +01005784 PyModule_AddIntConstant(m, "VERIFY_ALLOW_PROXY_CERTS",
5785 X509_V_FLAG_ALLOW_PROXY_CERTS);
Benjamin Peterson990fcaa2015-03-04 22:49:41 -05005786 PyModule_AddIntConstant(m, "VERIFY_X509_TRUSTED_FIRST",
5787 X509_V_FLAG_TRUSTED_FIRST);
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00005788
l0x64d97522021-04-19 13:51:18 +02005789#ifdef X509_V_FLAG_PARTIAL_CHAIN
5790 PyModule_AddIntConstant(m, "VERIFY_X509_PARTIAL_CHAIN",
5791 X509_V_FLAG_PARTIAL_CHAIN);
5792#endif
5793
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01005794 /* Alert Descriptions from ssl.h */
5795 /* note RESERVED constants no longer intended for use have been removed */
5796 /* http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-6 */
5797
5798#define ADD_AD_CONSTANT(s) \
5799 PyModule_AddIntConstant(m, "ALERT_DESCRIPTION_"#s, \
5800 SSL_AD_##s)
5801
5802 ADD_AD_CONSTANT(CLOSE_NOTIFY);
5803 ADD_AD_CONSTANT(UNEXPECTED_MESSAGE);
5804 ADD_AD_CONSTANT(BAD_RECORD_MAC);
5805 ADD_AD_CONSTANT(RECORD_OVERFLOW);
5806 ADD_AD_CONSTANT(DECOMPRESSION_FAILURE);
5807 ADD_AD_CONSTANT(HANDSHAKE_FAILURE);
5808 ADD_AD_CONSTANT(BAD_CERTIFICATE);
5809 ADD_AD_CONSTANT(UNSUPPORTED_CERTIFICATE);
5810 ADD_AD_CONSTANT(CERTIFICATE_REVOKED);
5811 ADD_AD_CONSTANT(CERTIFICATE_EXPIRED);
5812 ADD_AD_CONSTANT(CERTIFICATE_UNKNOWN);
5813 ADD_AD_CONSTANT(ILLEGAL_PARAMETER);
5814 ADD_AD_CONSTANT(UNKNOWN_CA);
5815 ADD_AD_CONSTANT(ACCESS_DENIED);
5816 ADD_AD_CONSTANT(DECODE_ERROR);
5817 ADD_AD_CONSTANT(DECRYPT_ERROR);
5818 ADD_AD_CONSTANT(PROTOCOL_VERSION);
5819 ADD_AD_CONSTANT(INSUFFICIENT_SECURITY);
5820 ADD_AD_CONSTANT(INTERNAL_ERROR);
5821 ADD_AD_CONSTANT(USER_CANCELLED);
5822 ADD_AD_CONSTANT(NO_RENEGOTIATION);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01005823 /* Not all constants are in old OpenSSL versions */
Antoine Pitrou912fbff2013-03-30 16:29:32 +01005824#ifdef SSL_AD_UNSUPPORTED_EXTENSION
5825 ADD_AD_CONSTANT(UNSUPPORTED_EXTENSION);
5826#endif
5827#ifdef SSL_AD_CERTIFICATE_UNOBTAINABLE
5828 ADD_AD_CONSTANT(CERTIFICATE_UNOBTAINABLE);
5829#endif
5830#ifdef SSL_AD_UNRECOGNIZED_NAME
5831 ADD_AD_CONSTANT(UNRECOGNIZED_NAME);
5832#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01005833#ifdef SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE
5834 ADD_AD_CONSTANT(BAD_CERTIFICATE_STATUS_RESPONSE);
5835#endif
5836#ifdef SSL_AD_BAD_CERTIFICATE_HASH_VALUE
5837 ADD_AD_CONSTANT(BAD_CERTIFICATE_HASH_VALUE);
5838#endif
5839#ifdef SSL_AD_UNKNOWN_PSK_IDENTITY
5840 ADD_AD_CONSTANT(UNKNOWN_PSK_IDENTITY);
5841#endif
5842
5843#undef ADD_AD_CONSTANT
5844
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005845 /* protocol versions */
Victor Stinner3de49192011-05-09 00:42:58 +02005846#ifndef OPENSSL_NO_SSL2
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005847 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
5848 PY_SSL_VERSION_SSL2);
Victor Stinner3de49192011-05-09 00:42:58 +02005849#endif
Benjamin Petersone32467c2014-12-05 21:59:35 -05005850#ifndef OPENSSL_NO_SSL3
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005851 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
5852 PY_SSL_VERSION_SSL3);
Benjamin Petersone32467c2014-12-05 21:59:35 -05005853#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005854 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
Christian Heimes598894f2016-09-05 23:19:05 +02005855 PY_SSL_VERSION_TLS);
5856 PyModule_AddIntConstant(m, "PROTOCOL_TLS",
5857 PY_SSL_VERSION_TLS);
Christian Heimes5fe668c2016-09-12 00:01:11 +02005858 PyModule_AddIntConstant(m, "PROTOCOL_TLS_CLIENT",
5859 PY_SSL_VERSION_TLS_CLIENT);
5860 PyModule_AddIntConstant(m, "PROTOCOL_TLS_SERVER",
5861 PY_SSL_VERSION_TLS_SERVER);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005862 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
5863 PY_SSL_VERSION_TLS1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01005864 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_1",
5865 PY_SSL_VERSION_TLS1_1);
5866 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_2",
5867 PY_SSL_VERSION_TLS1_2);
Antoine Pitrou04f6a322010-04-05 21:40:07 +00005868
Antoine Pitroub5218772010-05-21 09:56:06 +00005869 /* protocol options */
Antoine Pitrou3f366312012-01-27 09:50:45 +01005870 PyModule_AddIntConstant(m, "OP_ALL",
5871 SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
Antoine Pitroub5218772010-05-21 09:56:06 +00005872 PyModule_AddIntConstant(m, "OP_NO_SSLv2", SSL_OP_NO_SSLv2);
5873 PyModule_AddIntConstant(m, "OP_NO_SSLv3", SSL_OP_NO_SSLv3);
5874 PyModule_AddIntConstant(m, "OP_NO_TLSv1", SSL_OP_NO_TLSv1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01005875 PyModule_AddIntConstant(m, "OP_NO_TLSv1_1", SSL_OP_NO_TLSv1_1);
5876 PyModule_AddIntConstant(m, "OP_NO_TLSv1_2", SSL_OP_NO_TLSv1_2);
Christian Heimescb5b68a2017-09-07 18:07:00 -07005877#ifdef SSL_OP_NO_TLSv1_3
5878 PyModule_AddIntConstant(m, "OP_NO_TLSv1_3", SSL_OP_NO_TLSv1_3);
5879#else
5880 PyModule_AddIntConstant(m, "OP_NO_TLSv1_3", 0);
5881#endif
Antoine Pitrou6db49442011-12-19 13:27:11 +01005882 PyModule_AddIntConstant(m, "OP_CIPHER_SERVER_PREFERENCE",
5883 SSL_OP_CIPHER_SERVER_PREFERENCE);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01005884 PyModule_AddIntConstant(m, "OP_SINGLE_DH_USE", SSL_OP_SINGLE_DH_USE);
Christian Heimes99a65702016-09-10 23:44:53 +02005885 PyModule_AddIntConstant(m, "OP_NO_TICKET", SSL_OP_NO_TICKET);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01005886#ifdef SSL_OP_SINGLE_ECDH_USE
Antoine Pitrou923df6f2011-12-19 17:16:51 +01005887 PyModule_AddIntConstant(m, "OP_SINGLE_ECDH_USE", SSL_OP_SINGLE_ECDH_USE);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01005888#endif
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01005889#ifdef SSL_OP_NO_COMPRESSION
5890 PyModule_AddIntConstant(m, "OP_NO_COMPRESSION",
5891 SSL_OP_NO_COMPRESSION);
5892#endif
Christian Heimes05d9fe32018-02-27 08:55:39 +01005893#ifdef SSL_OP_ENABLE_MIDDLEBOX_COMPAT
5894 PyModule_AddIntConstant(m, "OP_ENABLE_MIDDLEBOX_COMPAT",
5895 SSL_OP_ENABLE_MIDDLEBOX_COMPAT);
5896#endif
Christian Heimes67c48012018-05-15 16:25:40 -04005897#ifdef SSL_OP_NO_RENEGOTIATION
5898 PyModule_AddIntConstant(m, "OP_NO_RENEGOTIATION",
5899 SSL_OP_NO_RENEGOTIATION);
5900#endif
Christian Heimes6f37ebc2021-04-09 17:59:21 +02005901#ifdef SSL_OP_IGNORE_UNEXPECTED_EOF
5902 PyModule_AddIntConstant(m, "OP_IGNORE_UNEXPECTED_EOF",
5903 SSL_OP_IGNORE_UNEXPECTED_EOF);
5904#endif
Antoine Pitroub5218772010-05-21 09:56:06 +00005905
Christian Heimes61d478c2018-01-27 15:51:38 +01005906#ifdef X509_CHECK_FLAG_ALWAYS_CHECK_SUBJECT
5907 PyModule_AddIntConstant(m, "HOSTFLAG_ALWAYS_CHECK_SUBJECT",
5908 X509_CHECK_FLAG_ALWAYS_CHECK_SUBJECT);
5909#endif
5910#ifdef X509_CHECK_FLAG_NEVER_CHECK_SUBJECT
5911 PyModule_AddIntConstant(m, "HOSTFLAG_NEVER_CHECK_SUBJECT",
5912 X509_CHECK_FLAG_NEVER_CHECK_SUBJECT);
5913#endif
5914#ifdef X509_CHECK_FLAG_NO_WILDCARDS
5915 PyModule_AddIntConstant(m, "HOSTFLAG_NO_WILDCARDS",
5916 X509_CHECK_FLAG_NO_WILDCARDS);
5917#endif
5918#ifdef X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS
5919 PyModule_AddIntConstant(m, "HOSTFLAG_NO_PARTIAL_WILDCARDS",
5920 X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS);
5921#endif
5922#ifdef X509_CHECK_FLAG_MULTI_LABEL_WILDCARDS
5923 PyModule_AddIntConstant(m, "HOSTFLAG_MULTI_LABEL_WILDCARDS",
5924 X509_CHECK_FLAG_MULTI_LABEL_WILDCARDS);
5925#endif
5926#ifdef X509_CHECK_FLAG_SINGLE_LABEL_SUBDOMAINS
5927 PyModule_AddIntConstant(m, "HOSTFLAG_SINGLE_LABEL_SUBDOMAINS",
5928 X509_CHECK_FLAG_SINGLE_LABEL_SUBDOMAINS);
5929#endif
5930
Christian Heimes666991f2021-04-26 15:01:40 +02005931 /* file types */
5932 PyModule_AddIntConstant(m, "ENCODING_PEM", PY_SSL_ENCODING_PEM);
5933 PyModule_AddIntConstant(m, "ENCODING_DER", PY_SSL_ENCODING_DER);
5934
Christian Heimes698dde12018-02-27 11:54:43 +01005935 /* protocol versions */
5936 PyModule_AddIntConstant(m, "PROTO_MINIMUM_SUPPORTED",
5937 PY_PROTO_MINIMUM_SUPPORTED);
5938 PyModule_AddIntConstant(m, "PROTO_MAXIMUM_SUPPORTED",
5939 PY_PROTO_MAXIMUM_SUPPORTED);
5940 PyModule_AddIntConstant(m, "PROTO_SSLv3", PY_PROTO_SSLv3);
5941 PyModule_AddIntConstant(m, "PROTO_TLSv1", PY_PROTO_TLSv1);
5942 PyModule_AddIntConstant(m, "PROTO_TLSv1_1", PY_PROTO_TLSv1_1);
5943 PyModule_AddIntConstant(m, "PROTO_TLSv1_2", PY_PROTO_TLSv1_2);
5944 PyModule_AddIntConstant(m, "PROTO_TLSv1_3", PY_PROTO_TLSv1_3);
Antoine Pitroud5323212010-10-22 18:19:07 +00005945
Victor Stinnerb37672d2018-11-22 03:37:50 +01005946#define addbool(m, key, value) \
5947 do { \
5948 PyObject *bool_obj = (value) ? Py_True : Py_False; \
5949 Py_INCREF(bool_obj); \
5950 PyModule_AddObject((m), (key), bool_obj); \
5951 } while (0)
Christian Heimes698dde12018-02-27 11:54:43 +01005952
Christian Heimes698dde12018-02-27 11:54:43 +01005953 addbool(m, "HAS_SNI", 1);
Christian Heimes698dde12018-02-27 11:54:43 +01005954 addbool(m, "HAS_TLS_UNIQUE", 1);
Christian Heimes698dde12018-02-27 11:54:43 +01005955 addbool(m, "HAS_ECDH", 1);
Christian Heimes698dde12018-02-27 11:54:43 +01005956 addbool(m, "HAS_NPN", 0);
Christian Heimes698dde12018-02-27 11:54:43 +01005957 addbool(m, "HAS_ALPN", 1);
Christian Heimes698dde12018-02-27 11:54:43 +01005958
5959#if defined(SSL2_VERSION) && !defined(OPENSSL_NO_SSL2)
5960 addbool(m, "HAS_SSLv2", 1);
5961#else
5962 addbool(m, "HAS_SSLv2", 0);
5963#endif
5964
5965#if defined(SSL3_VERSION) && !defined(OPENSSL_NO_SSL3)
5966 addbool(m, "HAS_SSLv3", 1);
5967#else
5968 addbool(m, "HAS_SSLv3", 0);
5969#endif
5970
5971#if defined(TLS1_VERSION) && !defined(OPENSSL_NO_TLS1)
5972 addbool(m, "HAS_TLSv1", 1);
5973#else
5974 addbool(m, "HAS_TLSv1", 0);
5975#endif
5976
5977#if defined(TLS1_1_VERSION) && !defined(OPENSSL_NO_TLS1_1)
5978 addbool(m, "HAS_TLSv1_1", 1);
5979#else
5980 addbool(m, "HAS_TLSv1_1", 0);
5981#endif
5982
5983#if defined(TLS1_2_VERSION) && !defined(OPENSSL_NO_TLS1_2)
5984 addbool(m, "HAS_TLSv1_2", 1);
5985#else
5986 addbool(m, "HAS_TLSv1_2", 0);
5987#endif
Benjamin Petersoncca27322015-01-23 16:35:37 -05005988
Christian Heimescb5b68a2017-09-07 18:07:00 -07005989#if defined(TLS1_3_VERSION) && !defined(OPENSSL_NO_TLS1_3)
Christian Heimes698dde12018-02-27 11:54:43 +01005990 addbool(m, "HAS_TLSv1_3", 1);
Christian Heimescb5b68a2017-09-07 18:07:00 -07005991#else
Christian Heimes698dde12018-02-27 11:54:43 +01005992 addbool(m, "HAS_TLSv1_3", 0);
Christian Heimescb5b68a2017-09-07 18:07:00 -07005993#endif
Christian Heimescb5b68a2017-09-07 18:07:00 -07005994
Christian Heimes5c36da72020-11-20 09:40:12 +01005995 return 0;
5996}
5997
Christian Heimes7f1305e2021-04-17 20:06:38 +02005998static int
5999sslmodule_init_errorcodes(PyObject *module)
6000{
6001 _sslmodulestate *state = get_ssl_state(module);
Christian Heimes5c36da72020-11-20 09:40:12 +01006002
Christian Heimes7f1305e2021-04-17 20:06:38 +02006003 struct py_ssl_error_code *errcode;
6004 struct py_ssl_library_code *libcode;
Christian Heimes5c36da72020-11-20 09:40:12 +01006005
Christian Heimes7f1305e2021-04-17 20:06:38 +02006006 /* Mappings for error codes */
6007 state->err_codes_to_names = PyDict_New();
6008 if (state->err_codes_to_names == NULL)
6009 return -1;
6010 state->err_names_to_codes = PyDict_New();
6011 if (state->err_names_to_codes == NULL)
6012 return -1;
6013 state->lib_codes_to_names = PyDict_New();
6014 if (state->lib_codes_to_names == NULL)
6015 return -1;
6016
6017 errcode = error_codes;
6018 while (errcode->mnemonic != NULL) {
6019 PyObject *mnemo, *key;
6020 mnemo = PyUnicode_FromString(errcode->mnemonic);
6021 key = Py_BuildValue("ii", errcode->library, errcode->reason);
6022 if (mnemo == NULL || key == NULL)
6023 return -1;
6024 if (PyDict_SetItem(state->err_codes_to_names, key, mnemo))
6025 return -1;
6026 if (PyDict_SetItem(state->err_names_to_codes, mnemo, key))
6027 return -1;
6028 Py_DECREF(key);
6029 Py_DECREF(mnemo);
6030 errcode++;
6031 }
6032
6033 libcode = library_codes;
6034 while (libcode->library != NULL) {
6035 PyObject *mnemo, *key;
6036 key = PyLong_FromLong(libcode->code);
6037 mnemo = PyUnicode_FromString(libcode->library);
6038 if (key == NULL || mnemo == NULL)
6039 return -1;
6040 if (PyDict_SetItem(state->lib_codes_to_names, key, mnemo))
6041 return -1;
6042 Py_DECREF(key);
6043 Py_DECREF(mnemo);
6044 libcode++;
6045 }
6046
6047 if (PyModule_AddObjectRef(module, "err_codes_to_names", state->err_codes_to_names))
6048 return -1;
6049 if (PyModule_AddObjectRef(module, "err_names_to_codes", state->err_names_to_codes))
6050 return -1;
6051 if (PyModule_AddObjectRef(module, "lib_codes_to_names", state->lib_codes_to_names))
6052 return -1;
6053
6054 return 0;
6055}
6056
6057static void
6058parse_openssl_version(unsigned long libver,
6059 unsigned int *major, unsigned int *minor,
6060 unsigned int *fix, unsigned int *patch,
6061 unsigned int *status)
6062{
6063 *status = libver & 0xF;
6064 libver >>= 4;
6065 *patch = libver & 0xFF;
6066 libver >>= 8;
6067 *fix = libver & 0xFF;
6068 libver >>= 8;
6069 *minor = libver & 0xFF;
6070 libver >>= 8;
6071 *major = libver & 0xFF;
6072}
6073
6074static int
6075sslmodule_init_versioninfo(PyObject *m)
6076{
6077 PyObject *r;
6078 unsigned long libver;
6079 unsigned int major, minor, fix, patch, status;
6080
6081 /* OpenSSL version */
6082 /* SSLeay() gives us the version of the library linked against,
6083 which could be different from the headers version.
6084 */
6085 libver = OpenSSL_version_num();
6086 r = PyLong_FromUnsignedLong(libver);
6087 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r))
6088 return -1;
6089
6090 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
6091 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
6092 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r))
6093 return -1;
6094
6095 r = PyUnicode_FromString(OpenSSL_version(OPENSSL_VERSION));
6096 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r))
6097 return -1;
6098
6099 libver = OPENSSL_VERSION_NUMBER;
6100 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
6101 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
6102 if (r == NULL || PyModule_AddObject(m, "_OPENSSL_API_VERSION", r))
6103 return -1;
6104
6105 return 0;
6106}
6107
6108static int
6109sslmodule_init_types(PyObject *module)
6110{
6111 _sslmodulestate *state = get_ssl_state(module);
6112
6113 state->PySSLContext_Type = (PyTypeObject *)PyType_FromModuleAndSpec(
6114 module, &PySSLContext_spec, NULL
6115 );
6116 if (state->PySSLContext_Type == NULL)
6117 return -1;
6118
6119 state->PySSLSocket_Type = (PyTypeObject *)PyType_FromModuleAndSpec(
6120 module, &PySSLSocket_spec, NULL
6121 );
6122 if (state->PySSLSocket_Type == NULL)
6123 return -1;
6124
6125 state->PySSLMemoryBIO_Type = (PyTypeObject *)PyType_FromModuleAndSpec(
6126 module, &PySSLMemoryBIO_spec, NULL
6127 );
6128 if (state->PySSLMemoryBIO_Type == NULL)
6129 return -1;
6130
6131 state->PySSLSession_Type = (PyTypeObject *)PyType_FromModuleAndSpec(
6132 module, &PySSLSession_spec, NULL
6133 );
6134 if (state->PySSLSession_Type == NULL)
6135 return -1;
6136
Christian Heimes666991f2021-04-26 15:01:40 +02006137 state->PySSLCertificate_Type = (PyTypeObject *)PyType_FromModuleAndSpec(
6138 module, &PySSLCertificate_spec, NULL
6139 );
6140 if (state->PySSLCertificate_Type == NULL)
6141 return -1;
6142
Christian Heimes7f1305e2021-04-17 20:06:38 +02006143 if (PyModule_AddType(module, state->PySSLContext_Type))
6144 return -1;
6145 if (PyModule_AddType(module, state->PySSLSocket_Type))
6146 return -1;
6147 if (PyModule_AddType(module, state->PySSLMemoryBIO_Type))
6148 return -1;
6149 if (PyModule_AddType(module, state->PySSLSession_Type))
6150 return -1;
Christian Heimes666991f2021-04-26 15:01:40 +02006151 if (PyModule_AddType(module, state->PySSLCertificate_Type))
6152 return -1;
Christian Heimes7f1305e2021-04-17 20:06:38 +02006153 return 0;
6154}
6155
6156static PyModuleDef_Slot sslmodule_slots[] = {
6157 {Py_mod_exec, sslmodule_init_types},
6158 {Py_mod_exec, sslmodule_init_exceptions},
6159 {Py_mod_exec, sslmodule_init_socketapi},
6160 {Py_mod_exec, sslmodule_init_errorcodes},
6161 {Py_mod_exec, sslmodule_init_constants},
6162 {Py_mod_exec, sslmodule_init_versioninfo},
6163 {0, NULL}
6164};
6165
6166static int
6167sslmodule_traverse(PyObject *m, visitproc visit, void *arg)
6168{
6169 _sslmodulestate *state = get_ssl_state(m);
6170
6171 Py_VISIT(state->PySSLContext_Type);
6172 Py_VISIT(state->PySSLSocket_Type);
6173 Py_VISIT(state->PySSLMemoryBIO_Type);
6174 Py_VISIT(state->PySSLSession_Type);
Christian Heimes666991f2021-04-26 15:01:40 +02006175 Py_VISIT(state->PySSLCertificate_Type);
Christian Heimes7f1305e2021-04-17 20:06:38 +02006176 Py_VISIT(state->PySSLErrorObject);
6177 Py_VISIT(state->PySSLCertVerificationErrorObject);
6178 Py_VISIT(state->PySSLZeroReturnErrorObject);
6179 Py_VISIT(state->PySSLWantReadErrorObject);
6180 Py_VISIT(state->PySSLWantWriteErrorObject);
6181 Py_VISIT(state->PySSLSyscallErrorObject);
6182 Py_VISIT(state->PySSLEOFErrorObject);
6183 Py_VISIT(state->err_codes_to_names);
6184 Py_VISIT(state->err_names_to_codes);
6185 Py_VISIT(state->lib_codes_to_names);
6186 Py_VISIT(state->Sock_Type);
6187
6188 return 0;
6189}
6190
6191static int
6192sslmodule_clear(PyObject *m)
6193{
6194 _sslmodulestate *state = get_ssl_state(m);
6195
6196 Py_CLEAR(state->PySSLContext_Type);
6197 Py_CLEAR(state->PySSLSocket_Type);
6198 Py_CLEAR(state->PySSLMemoryBIO_Type);
6199 Py_CLEAR(state->PySSLSession_Type);
Christian Heimes666991f2021-04-26 15:01:40 +02006200 Py_CLEAR(state->PySSLCertificate_Type);
Christian Heimes7f1305e2021-04-17 20:06:38 +02006201 Py_CLEAR(state->PySSLErrorObject);
6202 Py_CLEAR(state->PySSLCertVerificationErrorObject);
6203 Py_CLEAR(state->PySSLZeroReturnErrorObject);
6204 Py_CLEAR(state->PySSLWantReadErrorObject);
6205 Py_CLEAR(state->PySSLWantWriteErrorObject);
6206 Py_CLEAR(state->PySSLSyscallErrorObject);
6207 Py_CLEAR(state->PySSLEOFErrorObject);
6208 Py_CLEAR(state->err_codes_to_names);
6209 Py_CLEAR(state->err_names_to_codes);
6210 Py_CLEAR(state->lib_codes_to_names);
6211 Py_CLEAR(state->Sock_Type);
6212
6213 return 0;
6214}
6215
6216static void
6217sslmodule_free(void *m)
6218{
6219 sslmodule_clear((PyObject *)m);
6220}
6221
6222static struct PyModuleDef _sslmodule_def = {
Christian Heimes5c36da72020-11-20 09:40:12 +01006223 PyModuleDef_HEAD_INIT,
Christian Heimes7f1305e2021-04-17 20:06:38 +02006224 .m_name = "_ssl",
6225 .m_doc = module_doc,
6226 .m_size = sizeof(_sslmodulestate),
6227 .m_methods = PySSL_methods,
6228 .m_slots = sslmodule_slots,
6229 .m_traverse = sslmodule_traverse,
6230 .m_clear = sslmodule_clear,
6231 .m_free = sslmodule_free
Christian Heimes5c36da72020-11-20 09:40:12 +01006232};
6233
6234PyMODINIT_FUNC
6235PyInit__ssl(void)
6236{
Christian Heimes7f1305e2021-04-17 20:06:38 +02006237 return PyModuleDef_Init(&_sslmodule_def);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00006238}