blob: 0daa13e92d6a7e5bb5bdb1da3c16b627814b4540 [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
155#elif PY_SSL_DEFAULT_CIPHERS == 1
Stéphane Wirtel07fbbfd2018-10-05 16:17:18 +0200156/* Python custom selection of sensible cipher suites
Christian Heimes892d66e2018-01-29 14:10:18 +0100157 * DEFAULT: OpenSSL's default cipher list. Since 1.0.2 the list is in sensible order.
158 * !aNULL:!eNULL: really no NULL ciphers
159 * !MD5:!3DES:!DES:!RC4:!IDEA:!SEED: no weak or broken algorithms on old OpenSSL versions.
160 * !aDSS: no authentication with discrete logarithm DSA algorithm
161 * !SRP:!PSK: no secure remote password or pre-shared key authentication
162 */
163 #define PY_SSL_DEFAULT_CIPHER_STRING "DEFAULT:!aNULL:!eNULL:!MD5:!3DES:!DES:!RC4:!IDEA:!SEED:!aDSS:!SRP:!PSK"
164#elif PY_SSL_DEFAULT_CIPHERS == 2
165/* Ignored in SSLContext constructor, only used to as _ssl.DEFAULT_CIPHER_STRING */
166 #define PY_SSL_DEFAULT_CIPHER_STRING SSL_DEFAULT_CIPHER_LIST
167#else
168 #error "Unsupported PY_SSL_DEFAULT_CIPHERS"
169#endif
170
Christian Heimes598894f2016-09-05 23:19:05 +0200171
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000172enum py_ssl_error {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000173 /* these mirror ssl.h */
174 PY_SSL_ERROR_NONE,
175 PY_SSL_ERROR_SSL,
176 PY_SSL_ERROR_WANT_READ,
177 PY_SSL_ERROR_WANT_WRITE,
178 PY_SSL_ERROR_WANT_X509_LOOKUP,
179 PY_SSL_ERROR_SYSCALL, /* look at error stack/return value/errno */
180 PY_SSL_ERROR_ZERO_RETURN,
181 PY_SSL_ERROR_WANT_CONNECT,
182 /* start of non ssl.h errorcodes */
183 PY_SSL_ERROR_EOF, /* special case of SSL_ERROR_SYSCALL */
184 PY_SSL_ERROR_NO_SOCKET, /* socket has been GC'd */
185 PY_SSL_ERROR_INVALID_ERROR_CODE
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000186};
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000187
Thomas Woutersed03b412007-08-28 21:37:11 +0000188enum py_ssl_server_or_client {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000189 PY_SSL_CLIENT,
190 PY_SSL_SERVER
Thomas Woutersed03b412007-08-28 21:37:11 +0000191};
192
193enum py_ssl_cert_requirements {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000194 PY_SSL_CERT_NONE,
195 PY_SSL_CERT_OPTIONAL,
196 PY_SSL_CERT_REQUIRED
Thomas Woutersed03b412007-08-28 21:37:11 +0000197};
198
199enum py_ssl_version {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000200 PY_SSL_VERSION_SSL2,
Victor Stinner3de49192011-05-09 00:42:58 +0200201 PY_SSL_VERSION_SSL3=1,
Christian Heimes5fe668c2016-09-12 00:01:11 +0200202 PY_SSL_VERSION_TLS, /* SSLv23 */
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100203 PY_SSL_VERSION_TLS1,
204 PY_SSL_VERSION_TLS1_1,
Christian Heimes5fe668c2016-09-12 00:01:11 +0200205 PY_SSL_VERSION_TLS1_2,
Christian Heimes5fe668c2016-09-12 00:01:11 +0200206 PY_SSL_VERSION_TLS_CLIENT=0x10,
207 PY_SSL_VERSION_TLS_SERVER,
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100208};
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200209
Christian Heimes698dde12018-02-27 11:54:43 +0100210enum py_proto_version {
211 PY_PROTO_MINIMUM_SUPPORTED = -2,
212 PY_PROTO_SSLv3 = SSL3_VERSION,
213 PY_PROTO_TLSv1 = TLS1_VERSION,
214 PY_PROTO_TLSv1_1 = TLS1_1_VERSION,
215 PY_PROTO_TLSv1_2 = TLS1_2_VERSION,
216#ifdef TLS1_3_VERSION
217 PY_PROTO_TLSv1_3 = TLS1_3_VERSION,
218#else
219 PY_PROTO_TLSv1_3 = 0x304,
220#endif
221 PY_PROTO_MAXIMUM_SUPPORTED = -1,
222
223/* OpenSSL has no dedicated API to set the minimum version to the maximum
224 * available version, and the other way around. We have to figure out the
225 * minimum and maximum available version on our own and hope for the best.
226 */
227#if defined(SSL3_VERSION) && !defined(OPENSSL_NO_SSL3)
228 PY_PROTO_MINIMUM_AVAILABLE = PY_PROTO_SSLv3,
229#elif defined(TLS1_VERSION) && !defined(OPENSSL_NO_TLS1)
230 PY_PROTO_MINIMUM_AVAILABLE = PY_PROTO_TLSv1,
231#elif defined(TLS1_1_VERSION) && !defined(OPENSSL_NO_TLS1_1)
232 PY_PROTO_MINIMUM_AVAILABLE = PY_PROTO_TLSv1_1,
233#elif defined(TLS1_2_VERSION) && !defined(OPENSSL_NO_TLS1_2)
234 PY_PROTO_MINIMUM_AVAILABLE = PY_PROTO_TLSv1_2,
235#elif defined(TLS1_3_VERSION) && !defined(OPENSSL_NO_TLS1_3)
236 PY_PROTO_MINIMUM_AVAILABLE = PY_PROTO_TLSv1_3,
237#else
238 #error "PY_PROTO_MINIMUM_AVAILABLE not found"
239#endif
240
241#if defined(TLS1_3_VERSION) && !defined(OPENSSL_NO_TLS1_3)
242 PY_PROTO_MAXIMUM_AVAILABLE = PY_PROTO_TLSv1_3,
243#elif defined(TLS1_2_VERSION) && !defined(OPENSSL_NO_TLS1_2)
244 PY_PROTO_MAXIMUM_AVAILABLE = PY_PROTO_TLSv1_2,
245#elif defined(TLS1_1_VERSION) && !defined(OPENSSL_NO_TLS1_1)
246 PY_PROTO_MAXIMUM_AVAILABLE = PY_PROTO_TLSv1_1,
247#elif defined(TLS1_VERSION) && !defined(OPENSSL_NO_TLS1)
248 PY_PROTO_MAXIMUM_AVAILABLE = PY_PROTO_TLSv1,
249#elif defined(SSL3_VERSION) && !defined(OPENSSL_NO_SSL3)
250 PY_PROTO_MAXIMUM_AVAILABLE = PY_PROTO_SSLv3,
251#else
252 #error "PY_PROTO_MAXIMUM_AVAILABLE not found"
253#endif
254};
255
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000256/* SSL socket object */
257
258#define X509_NAME_MAXLEN 256
259
Antoine Pitroub5218772010-05-21 09:56:06 +0000260
Antoine Pitroud6494802011-07-21 01:11:30 +0200261/* In case of 'tls-unique' it will be 12 bytes for TLS, 36 bytes for
262 * older SSL, but let's be safe */
263#define PySSL_CB_MAXLEN 128
264
Antoine Pitroua9bf2ac2012-02-17 18:47:54 +0100265
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000266typedef struct {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000267 PyObject_HEAD
Antoine Pitrou152efa22010-05-16 18:19:27 +0000268 SSL_CTX *ctx;
Benjamin Petersoncca27322015-01-23 16:35:37 -0500269 unsigned char *alpn_protocols;
Segev Finer5cff6372017-07-27 01:19:17 +0300270 unsigned int alpn_protocols_len;
Christian Heimes11a14932018-02-24 02:35:08 +0100271 PyObject *set_sni_cb;
Christian Heimes1aa9a752013-12-02 02:41:19 +0100272 int check_hostname;
Christian Heimes61d478c2018-01-27 15:51:38 +0100273 /* OpenSSL has no API to get hostflags from X509_VERIFY_PARAM* struct.
274 * We have to maintain our own copy. OpenSSL's hostflags default to 0.
275 */
276 unsigned int hostflags;
Christian Heimes11a14932018-02-24 02:35:08 +0100277 int protocol;
Christian Heimes9fb051f2018-09-23 08:32:31 +0200278#ifdef TLS1_3_VERSION
279 int post_handshake_auth;
280#endif
Christian Heimesc7f70692019-05-31 11:44:05 +0200281 PyObject *msg_cb;
Christian Heimesc7f70692019-05-31 11:44:05 +0200282 PyObject *keylog_filename;
283 BIO *keylog_bio;
Christian Heimes7f1305e2021-04-17 20:06:38 +0200284 /* Cached module state, also used in SSLSocket and SSLSession code. */
285 _sslmodulestate *state;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000286} PySSLContext;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000287
Antoine Pitrou152efa22010-05-16 18:19:27 +0000288typedef struct {
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700289 int ssl; /* last seen error from SSL */
290 int c; /* last seen error from libc */
291#ifdef MS_WINDOWS
292 int ws; /* last seen error from winsock */
293#endif
294} _PySSLError;
295
296typedef struct {
Antoine Pitrou152efa22010-05-16 18:19:27 +0000297 PyObject_HEAD
298 PyObject *Socket; /* weakref to socket on which we're layered */
299 SSL *ssl;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100300 PySSLContext *ctx; /* weakref to SSL context */
Antoine Pitrou20b85552013-09-29 19:50:53 +0200301 char shutdown_seen_zero;
Antoine Pitroud6494802011-07-21 01:11:30 +0200302 enum py_ssl_server_or_client socket_type;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200303 PyObject *owner; /* Python level "owner" passed to servername callback */
304 PyObject *server_hostname;
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700305 _PySSLError err; /* last seen error from various sources */
Christian Heimesc7f70692019-05-31 11:44:05 +0200306 /* Some SSL callbacks don't have error reporting. Callback wrappers
307 * store exception information on the socket. The handshake, read, write,
308 * and shutdown methods check for chained exceptions.
309 */
310 PyObject *exc_type;
311 PyObject *exc_value;
312 PyObject *exc_tb;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000313} PySSLSocket;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000314
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200315typedef struct {
316 PyObject_HEAD
317 BIO *bio;
318 int eof_written;
319} PySSLMemoryBIO;
320
Christian Heimes99a65702016-09-10 23:44:53 +0200321typedef struct {
322 PyObject_HEAD
323 SSL_SESSION *session;
324 PySSLContext *ctx;
325} PySSLSession;
326
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700327static inline _PySSLError _PySSL_errno(int failed, const SSL *ssl, int retcode)
328{
329 _PySSLError err = { 0 };
330 if (failed) {
Steve Dowere6eb48c2017-09-08 15:16:15 -0700331#ifdef MS_WINDOWS
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700332 err.ws = WSAGetLastError();
333 _PySSL_FIX_ERRNO;
Steve Dowere6eb48c2017-09-08 15:16:15 -0700334#endif
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700335 err.c = errno;
336 err.ssl = SSL_get_error(ssl, retcode);
337 }
338 return err;
339}
Steve Dowere6eb48c2017-09-08 15:16:15 -0700340
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +0300341/*[clinic input]
342module _ssl
Christian Heimes7f1305e2021-04-17 20:06:38 +0200343class _ssl._SSLContext "PySSLContext *" "get_state_type(type)->PySSLContext_Type"
344class _ssl._SSLSocket "PySSLSocket *" "get_state_type(type)->PySSLSocket_Type"
345class _ssl.MemoryBIO "PySSLMemoryBIO *" "get_state_type(type)->PySSLMemoryBIO_Type"
346class _ssl.SSLSession "PySSLSession *" "get_state_type(type)->PySSLSession_Type"
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +0300347[clinic start generated code]*/
Christian Heimes7f1305e2021-04-17 20:06:38 +0200348/*[clinic end generated code: output=da39a3ee5e6b4b0d input=d293bed8bae240fd]*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +0300349
350#include "clinic/_ssl.c.h"
351
Victor Stinner14690702015-04-06 22:46:13 +0200352static int PySSL_select(PySocketSockObject *s, int writing, _PyTime_t timeout);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000353
Christian Heimes141c5e82018-02-24 21:10:57 +0100354static int PySSL_set_owner(PySSLSocket *, PyObject *, void *);
355static int PySSL_set_session(PySSLSocket *, PyObject *, void *);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000356
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000357typedef enum {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000358 SOCKET_IS_NONBLOCKING,
359 SOCKET_IS_BLOCKING,
360 SOCKET_HAS_TIMED_OUT,
361 SOCKET_HAS_BEEN_CLOSED,
362 SOCKET_TOO_LARGE_FOR_SELECT,
363 SOCKET_OPERATION_OK
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000364} timeout_state;
365
Thomas Woutersed03b412007-08-28 21:37:11 +0000366/* Wrap error strings with filename and line # */
Thomas Woutersed03b412007-08-28 21:37:11 +0000367#define ERRSTR1(x,y,z) (x ":" y ": " z)
Victor Stinner45e8e2f2014-05-14 17:24:35 +0200368#define ERRSTR(x) ERRSTR1("_ssl.c", Py_STRINGIFY(__LINE__), x)
Thomas Woutersed03b412007-08-28 21:37:11 +0000369
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200370/* Get the socket from a PySSLSocket, if it has one */
371#define GET_SOCKET(obj) ((obj)->Socket ? \
372 (PySocketSockObject *) PyWeakref_GetObject((obj)->Socket) : NULL)
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200373
Victor Stinner14690702015-04-06 22:46:13 +0200374/* If sock is NULL, use a timeout of 0 second */
375#define GET_SOCKET_TIMEOUT(sock) \
376 ((sock != NULL) ? (sock)->sock_timeout : 0)
377
Christian Heimesc7f70692019-05-31 11:44:05 +0200378#include "_ssl/debughelpers.c"
379
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200380/*
381 * SSL errors.
382 */
383
384PyDoc_STRVAR(SSLError_doc,
385"An error occurred in the SSL implementation.");
386
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700387PyDoc_STRVAR(SSLCertVerificationError_doc,
388"A certificate could not be verified.");
389
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200390PyDoc_STRVAR(SSLZeroReturnError_doc,
391"SSL/TLS session closed cleanly.");
392
393PyDoc_STRVAR(SSLWantReadError_doc,
394"Non-blocking SSL socket needs to read more data\n"
395"before the requested operation can be completed.");
396
397PyDoc_STRVAR(SSLWantWriteError_doc,
398"Non-blocking SSL socket needs to write more data\n"
399"before the requested operation can be completed.");
400
401PyDoc_STRVAR(SSLSyscallError_doc,
402"System error when attempting SSL operation.");
403
404PyDoc_STRVAR(SSLEOFError_doc,
405"SSL/TLS connection terminated abruptly.");
406
407static PyObject *
408SSLError_str(PyOSErrorObject *self)
409{
410 if (self->strerror != NULL && PyUnicode_Check(self->strerror)) {
411 Py_INCREF(self->strerror);
412 return self->strerror;
413 }
414 else
415 return PyObject_Str(self->args);
416}
417
418static PyType_Slot sslerror_type_slots[] = {
Inada Naoki926b0cb2019-04-17 08:39:46 +0900419 {Py_tp_doc, (void*)SSLError_doc},
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200420 {Py_tp_str, SSLError_str},
421 {0, 0},
422};
423
424static PyType_Spec sslerror_type_spec = {
425 "ssl.SSLError",
426 sizeof(PyOSErrorObject),
427 0,
428 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
429 sslerror_type_slots
430};
431
432static void
Christian Heimes7f1305e2021-04-17 20:06:38 +0200433fill_and_set_sslerror(_sslmodulestate *state,
434 PySSLSocket *sslsock, PyObject *type, int ssl_errno,
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700435 const char *errstr, int lineno, unsigned long errcode)
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200436{
437 PyObject *err_value = NULL, *reason_obj = NULL, *lib_obj = NULL;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700438 PyObject *verify_obj = NULL, *verify_code_obj = NULL;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200439 PyObject *init_value, *msg, *key;
440 _Py_IDENTIFIER(reason);
441 _Py_IDENTIFIER(library);
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700442 _Py_IDENTIFIER(verify_message);
443 _Py_IDENTIFIER(verify_code);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200444
445 if (errcode != 0) {
446 int lib, reason;
447
448 lib = ERR_GET_LIB(errcode);
449 reason = ERR_GET_REASON(errcode);
450 key = Py_BuildValue("ii", lib, reason);
451 if (key == NULL)
452 goto fail;
Christian Heimes7f1305e2021-04-17 20:06:38 +0200453 reason_obj = PyDict_GetItemWithError(state->err_codes_to_names, key);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200454 Py_DECREF(key);
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +0300455 if (reason_obj == NULL && PyErr_Occurred()) {
456 goto fail;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200457 }
458 key = PyLong_FromLong(lib);
459 if (key == NULL)
460 goto fail;
Christian Heimes7f1305e2021-04-17 20:06:38 +0200461 lib_obj = PyDict_GetItemWithError(state->lib_codes_to_names, key);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200462 Py_DECREF(key);
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +0300463 if (lib_obj == NULL && PyErr_Occurred()) {
464 goto fail;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200465 }
466 if (errstr == NULL)
467 errstr = ERR_reason_error_string(errcode);
468 }
469 if (errstr == NULL)
470 errstr = "unknown error";
471
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700472 /* verify code for cert validation error */
Christian Heimes7f1305e2021-04-17 20:06:38 +0200473 if ((sslsock != NULL) && (type == state->PySSLCertVerificationErrorObject)) {
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700474 const char *verify_str = NULL;
475 long verify_code;
476
477 verify_code = SSL_get_verify_result(sslsock->ssl);
478 verify_code_obj = PyLong_FromLong(verify_code);
479 if (verify_code_obj == NULL) {
480 goto fail;
481 }
482
483 switch (verify_code) {
484 case X509_V_ERR_HOSTNAME_MISMATCH:
485 verify_obj = PyUnicode_FromFormat(
486 "Hostname mismatch, certificate is not valid for '%S'.",
487 sslsock->server_hostname
488 );
489 break;
490 case X509_V_ERR_IP_ADDRESS_MISMATCH:
491 verify_obj = PyUnicode_FromFormat(
492 "IP address mismatch, certificate is not valid for '%S'.",
493 sslsock->server_hostname
494 );
495 break;
496 default:
497 verify_str = X509_verify_cert_error_string(verify_code);
498 if (verify_str != NULL) {
499 verify_obj = PyUnicode_FromString(verify_str);
500 } else {
501 verify_obj = Py_None;
502 Py_INCREF(verify_obj);
503 }
504 break;
505 }
506 if (verify_obj == NULL) {
507 goto fail;
508 }
509 }
510
511 if (verify_obj && reason_obj && lib_obj)
512 msg = PyUnicode_FromFormat("[%S: %S] %s: %S (_ssl.c:%d)",
513 lib_obj, reason_obj, errstr, verify_obj,
514 lineno);
515 else if (reason_obj && lib_obj)
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200516 msg = PyUnicode_FromFormat("[%S: %S] %s (_ssl.c:%d)",
517 lib_obj, reason_obj, errstr, lineno);
518 else if (lib_obj)
519 msg = PyUnicode_FromFormat("[%S] %s (_ssl.c:%d)",
520 lib_obj, errstr, lineno);
521 else
522 msg = PyUnicode_FromFormat("%s (_ssl.c:%d)", errstr, lineno);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200523 if (msg == NULL)
524 goto fail;
Victor Stinnerba9be472013-10-31 15:00:24 +0100525
Paul Monsonfb7e7502019-05-15 15:38:55 -0700526 init_value = Py_BuildValue("iN", ERR_GET_REASON(ssl_errno), msg);
Victor Stinnerba9be472013-10-31 15:00:24 +0100527 if (init_value == NULL)
528 goto fail;
529
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200530 err_value = PyObject_CallObject(type, init_value);
531 Py_DECREF(init_value);
532 if (err_value == NULL)
533 goto fail;
Victor Stinnerba9be472013-10-31 15:00:24 +0100534
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200535 if (reason_obj == NULL)
536 reason_obj = Py_None;
537 if (_PyObject_SetAttrId(err_value, &PyId_reason, reason_obj))
538 goto fail;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700539
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200540 if (lib_obj == NULL)
541 lib_obj = Py_None;
542 if (_PyObject_SetAttrId(err_value, &PyId_library, lib_obj))
543 goto fail;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700544
Christian Heimes7f1305e2021-04-17 20:06:38 +0200545 if ((sslsock != NULL) && (type == state->PySSLCertVerificationErrorObject)) {
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700546 /* Only set verify code / message for SSLCertVerificationError */
547 if (_PyObject_SetAttrId(err_value, &PyId_verify_code,
548 verify_code_obj))
549 goto fail;
550 if (_PyObject_SetAttrId(err_value, &PyId_verify_message, verify_obj))
551 goto fail;
552 }
553
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200554 PyErr_SetObject(type, err_value);
555fail:
556 Py_XDECREF(err_value);
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700557 Py_XDECREF(verify_code_obj);
558 Py_XDECREF(verify_obj);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200559}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000560
Christian Heimesc7f70692019-05-31 11:44:05 +0200561static int
562PySSL_ChainExceptions(PySSLSocket *sslsock) {
563 if (sslsock->exc_type == NULL)
564 return 0;
565
566 _PyErr_ChainExceptions(sslsock->exc_type, sslsock->exc_value, sslsock->exc_tb);
567 sslsock->exc_type = NULL;
568 sslsock->exc_value = NULL;
569 sslsock->exc_tb = NULL;
570 return -1;
571}
572
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000573static PyObject *
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700574PySSL_SetError(PySSLSocket *sslsock, int ret, const char *filename, int lineno)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000575{
Christian Heimes7f1305e2021-04-17 20:06:38 +0200576 PyObject *type;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200577 char *errstr = NULL;
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700578 _PySSLError err;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000579 enum py_ssl_error p = PY_SSL_ERROR_NONE;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200580 unsigned long e = 0;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000581
Christian Heimes7f1305e2021-04-17 20:06:38 +0200582 assert(sslsock != NULL);
583
584 _sslmodulestate *state = get_state_sock(sslsock);
585 type = state->PySSLErrorObject;
586
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000587 assert(ret <= 0);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200588 e = ERR_peek_last_error();
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000589
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700590 if (sslsock->ssl != NULL) {
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700591 err = sslsock->err;
Thomas Woutersed03b412007-08-28 21:37:11 +0000592
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700593 switch (err.ssl) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000594 case SSL_ERROR_ZERO_RETURN:
Antoine Pitrou41032a62011-10-27 23:56:55 +0200595 errstr = "TLS/SSL connection has been closed (EOF)";
Christian Heimes7f1305e2021-04-17 20:06:38 +0200596 type = state->PySSLZeroReturnErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000597 p = PY_SSL_ERROR_ZERO_RETURN;
598 break;
599 case SSL_ERROR_WANT_READ:
600 errstr = "The operation did not complete (read)";
Christian Heimes7f1305e2021-04-17 20:06:38 +0200601 type = state->PySSLWantReadErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000602 p = PY_SSL_ERROR_WANT_READ;
603 break;
604 case SSL_ERROR_WANT_WRITE:
605 p = PY_SSL_ERROR_WANT_WRITE;
Christian Heimes7f1305e2021-04-17 20:06:38 +0200606 type = state->PySSLWantWriteErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000607 errstr = "The operation did not complete (write)";
608 break;
609 case SSL_ERROR_WANT_X509_LOOKUP:
610 p = PY_SSL_ERROR_WANT_X509_LOOKUP;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000611 errstr = "The operation did not complete (X509 lookup)";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000612 break;
613 case SSL_ERROR_WANT_CONNECT:
614 p = PY_SSL_ERROR_WANT_CONNECT;
615 errstr = "The operation did not complete (connect)";
616 break;
617 case SSL_ERROR_SYSCALL:
618 {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000619 if (e == 0) {
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700620 PySocketSockObject *s = GET_SOCKET(sslsock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000621 if (ret == 0 || (((PyObject *)s) == Py_None)) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000622 p = PY_SSL_ERROR_EOF;
Christian Heimes7f1305e2021-04-17 20:06:38 +0200623 type = state->PySSLEOFErrorObject;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000624 errstr = "EOF occurred in violation of protocol";
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200625 } else if (s && ret == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000626 /* underlying BIO reported an I/O error */
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000627 ERR_clear_error();
Steve Dowere6eb48c2017-09-08 15:16:15 -0700628#ifdef MS_WINDOWS
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700629 if (err.ws) {
630 return PyErr_SetFromWindowsErr(err.ws);
631 }
Steve Dowere6eb48c2017-09-08 15:16:15 -0700632#endif
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700633 if (err.c) {
634 errno = err.c;
Steve Dowere6eb48c2017-09-08 15:16:15 -0700635 return PyErr_SetFromErrno(PyExc_OSError);
636 }
Dima Tisnek495bd032020-08-16 02:01:19 +0900637 else {
638 p = PY_SSL_ERROR_EOF;
Christian Heimes7f1305e2021-04-17 20:06:38 +0200639 type = state->PySSLEOFErrorObject;
Dima Tisnek495bd032020-08-16 02:01:19 +0900640 errstr = "EOF occurred in violation of protocol";
641 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000642 } else { /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000643 p = PY_SSL_ERROR_SYSCALL;
Christian Heimes7f1305e2021-04-17 20:06:38 +0200644 type = state->PySSLSyscallErrorObject;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000645 errstr = "Some I/O error occurred";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000646 }
647 } else {
648 p = PY_SSL_ERROR_SYSCALL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000649 }
650 break;
651 }
652 case SSL_ERROR_SSL:
653 {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000654 p = PY_SSL_ERROR_SSL;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700655 if (e == 0) {
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200656 /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000657 errstr = "A failure in the SSL library occurred";
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700658 }
659 if (ERR_GET_LIB(e) == ERR_LIB_SSL &&
660 ERR_GET_REASON(e) == SSL_R_CERTIFICATE_VERIFY_FAILED) {
Christian Heimes7f1305e2021-04-17 20:06:38 +0200661 type = state->PySSLCertVerificationErrorObject;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700662 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000663 break;
664 }
665 default:
666 p = PY_SSL_ERROR_INVALID_ERROR_CODE;
667 errstr = "Invalid error code";
668 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000669 }
Christian Heimes7f1305e2021-04-17 20:06:38 +0200670 fill_and_set_sslerror(state, sslsock, type, p, errstr, lineno, e);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000671 ERR_clear_error();
Christian Heimesc7f70692019-05-31 11:44:05 +0200672 PySSL_ChainExceptions(sslsock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000673 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000674}
675
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000676static PyObject *
Christian Heimes7f1305e2021-04-17 20:06:38 +0200677_setSSLError (_sslmodulestate *state, const char *errstr, int errcode, const char *filename, int lineno)
678{
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200679 if (errstr == NULL)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000680 errcode = ERR_peek_last_error();
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200681 else
682 errcode = 0;
Christian Heimes7f1305e2021-04-17 20:06:38 +0200683 fill_and_set_sslerror(state, NULL, state->PySSLErrorObject, errcode, errstr, lineno, errcode);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000684 ERR_clear_error();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000685 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000686}
687
Christian Heimes2875c602021-04-19 07:27:10 +0200688static int
689_ssl_deprecated(const char* name, int stacklevel) {
690 return PyErr_WarnFormat(
691 PyExc_DeprecationWarning, stacklevel,
692 "ssl module: %s is deprecated", name
693 );
694}
695
696#define PY_SSL_DEPRECATED(name, stacklevel, ret) \
697 if (_ssl_deprecated((name), (stacklevel)) == -1) return (ret)
698
Christian Heimes61d478c2018-01-27 15:51:38 +0100699/*
700 * SSL objects
701 */
702
703static int
704_ssl_configure_hostname(PySSLSocket *self, const char* server_hostname)
705{
706 int retval = -1;
707 ASN1_OCTET_STRING *ip;
708 PyObject *hostname;
709 size_t len;
710
711 assert(server_hostname);
712
713 /* Disable OpenSSL's special mode with leading dot in hostname:
714 * When name starts with a dot (e.g ".example.com"), it will be
715 * matched by a certificate valid for any sub-domain of name.
716 */
717 len = strlen(server_hostname);
718 if (len == 0 || *server_hostname == '.') {
719 PyErr_SetString(
720 PyExc_ValueError,
721 "server_hostname cannot be an empty string or start with a "
722 "leading dot.");
723 return retval;
724 }
725
726 /* inet_pton is not available on all platforms. */
727 ip = a2i_IPADDRESS(server_hostname);
728 if (ip == NULL) {
729 ERR_clear_error();
730 }
731
Christian Heimes11a14932018-02-24 02:35:08 +0100732 hostname = PyUnicode_Decode(server_hostname, len, "ascii", "strict");
Christian Heimes61d478c2018-01-27 15:51:38 +0100733 if (hostname == NULL) {
734 goto error;
735 }
736 self->server_hostname = hostname;
737
738 /* Only send SNI extension for non-IP hostnames */
739 if (ip == NULL) {
740 if (!SSL_set_tlsext_host_name(self->ssl, server_hostname)) {
Christian Heimes7f1305e2021-04-17 20:06:38 +0200741 _setSSLError(get_state_sock(self), NULL, 0, __FILE__, __LINE__);
Zackery Spytzc32f2972020-10-25 12:02:30 -0600742 goto error;
Christian Heimes61d478c2018-01-27 15:51:38 +0100743 }
744 }
745 if (self->ctx->check_hostname) {
746 X509_VERIFY_PARAM *param = SSL_get0_param(self->ssl);
747 if (ip == NULL) {
Christian Heimesd02ac252018-03-25 12:36:13 +0200748 if (!X509_VERIFY_PARAM_set1_host(param, server_hostname,
749 strlen(server_hostname))) {
Christian Heimes7f1305e2021-04-17 20:06:38 +0200750 _setSSLError(get_state_sock(self), NULL, 0, __FILE__, __LINE__);
Christian Heimes61d478c2018-01-27 15:51:38 +0100751 goto error;
752 }
753 } else {
Christian Heimesa871f692020-06-01 08:58:14 +0200754 if (!X509_VERIFY_PARAM_set1_ip(param, ASN1_STRING_get0_data(ip),
Christian Heimes61d478c2018-01-27 15:51:38 +0100755 ASN1_STRING_length(ip))) {
Christian Heimes7f1305e2021-04-17 20:06:38 +0200756 _setSSLError(get_state_sock(self), NULL, 0, __FILE__, __LINE__);
Christian Heimes61d478c2018-01-27 15:51:38 +0100757 goto error;
758 }
759 }
760 }
761 retval = 0;
762 error:
763 if (ip != NULL) {
764 ASN1_OCTET_STRING_free(ip);
765 }
766 return retval;
767}
768
Antoine Pitrou152efa22010-05-16 18:19:27 +0000769static PySSLSocket *
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100770newPySSLSocket(PySSLContext *sslctx, PySocketSockObject *sock,
Antoine Pitroud5323212010-10-22 18:19:07 +0000771 enum py_ssl_server_or_client socket_type,
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200772 char *server_hostname,
Christian Heimes141c5e82018-02-24 21:10:57 +0100773 PyObject *owner, PyObject *session,
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200774 PySSLMemoryBIO *inbio, PySSLMemoryBIO *outbio)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000775{
Antoine Pitrou152efa22010-05-16 18:19:27 +0000776 PySSLSocket *self;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100777 SSL_CTX *ctx = sslctx->ctx;
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700778 _PySSLError err = { 0 };
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000779
Christian Heimes7f1305e2021-04-17 20:06:38 +0200780 self = PyObject_New(PySSLSocket, get_state_ctx(sslctx)->PySSLSocket_Type);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000781 if (self == NULL)
782 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000783
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000784 self->ssl = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000785 self->Socket = NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100786 self->ctx = sslctx;
Nathaniel J. Smith65ece7c2017-06-07 23:30:43 -0700787 Py_INCREF(sslctx);
Antoine Pitrou860aee72013-09-29 19:52:45 +0200788 self->shutdown_seen_zero = 0;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200789 self->owner = NULL;
Benjamin Peterson81b9ecd2016-08-15 21:55:37 -0700790 self->server_hostname = NULL;
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700791 self->err = err;
Christian Heimesc7f70692019-05-31 11:44:05 +0200792 self->exc_type = NULL;
793 self->exc_value = NULL;
794 self->exc_tb = NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200795
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000796 /* Make sure the SSL error state is initialized */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000797 ERR_clear_error();
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000798
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000799 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitrou152efa22010-05-16 18:19:27 +0000800 self->ssl = SSL_new(ctx);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000801 PySSL_END_ALLOW_THREADS
Zackery Spytz4c49da02018-12-07 03:11:30 -0700802 if (self->ssl == NULL) {
803 Py_DECREF(self);
Christian Heimes7f1305e2021-04-17 20:06:38 +0200804 _setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
Zackery Spytz4c49da02018-12-07 03:11:30 -0700805 return NULL;
806 }
Christian Heimesb467d9a2021-04-17 10:07:19 +0200807 /* bpo43522 and OpenSSL < 1.1.1l: copy hostflags manually */
808#if !defined(LIBRESSL_VERSION_NUMBER) && OPENSSL_VERSION < 0x101010cf
809 X509_VERIFY_PARAM *ssl_params = SSL_get0_param(self->ssl);
810 X509_VERIFY_PARAM_set_hostflags(ssl_params, sslctx->hostflags);
811#endif
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200812 SSL_set_app_data(self->ssl, self);
813 if (sock) {
814 SSL_set_fd(self->ssl, Py_SAFE_DOWNCAST(sock->sock_fd, SOCKET_T, int));
815 } else {
816 /* BIOs are reference counted and SSL_set_bio borrows our reference.
817 * To prevent a double free in memory_bio_dealloc() we need to take an
818 * extra reference here. */
Christian Heimes598894f2016-09-05 23:19:05 +0200819 BIO_up_ref(inbio->bio);
820 BIO_up_ref(outbio->bio);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200821 SSL_set_bio(self->ssl, inbio->bio, outbio->bio);
822 }
Alex Gaynorf0422422018-05-14 11:51:45 -0400823 SSL_set_mode(self->ssl,
824 SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER | SSL_MODE_AUTO_RETRY);
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000825
Christian Heimesf0f59302019-07-01 08:29:17 +0200826#ifdef TLS1_3_VERSION
827 if (sslctx->post_handshake_auth == 1) {
828 if (socket_type == PY_SSL_SERVER) {
829 /* bpo-37428: OpenSSL does not ignore SSL_VERIFY_POST_HANDSHAKE.
830 * Set SSL_VERIFY_POST_HANDSHAKE flag only for server sockets and
831 * only in combination with SSL_VERIFY_PEER flag. */
832 int mode = SSL_get_verify_mode(self->ssl);
833 if (mode & SSL_VERIFY_PEER) {
834 int (*verify_cb)(int, X509_STORE_CTX *) = NULL;
835 verify_cb = SSL_get_verify_callback(self->ssl);
836 mode |= SSL_VERIFY_POST_HANDSHAKE;
837 SSL_set_verify(self->ssl, mode, verify_cb);
838 }
839 } else {
840 /* client socket */
841 SSL_set_post_handshake_auth(self->ssl, 1);
842 }
843 }
844#endif
845
Christian Heimes61d478c2018-01-27 15:51:38 +0100846 if (server_hostname != NULL) {
847 if (_ssl_configure_hostname(self, server_hostname) < 0) {
848 Py_DECREF(self);
849 return NULL;
850 }
851 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000852 /* If the socket is in non-blocking mode or timeout mode, set the BIO
853 * to non-blocking mode (blocking is the default)
854 */
Victor Stinnere2452312015-03-28 03:00:46 +0100855 if (sock && sock->sock_timeout >= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000856 BIO_set_nbio(SSL_get_rbio(self->ssl), 1);
857 BIO_set_nbio(SSL_get_wbio(self->ssl), 1);
858 }
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000859
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000860 PySSL_BEGIN_ALLOW_THREADS
861 if (socket_type == PY_SSL_CLIENT)
862 SSL_set_connect_state(self->ssl);
863 else
864 SSL_set_accept_state(self->ssl);
865 PySSL_END_ALLOW_THREADS
Martin v. Löwis09c35f72002-07-28 09:57:45 +0000866
Antoine Pitroud6494802011-07-21 01:11:30 +0200867 self->socket_type = socket_type;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200868 if (sock != NULL) {
869 self->Socket = PyWeakref_NewRef((PyObject *) sock, NULL);
870 if (self->Socket == NULL) {
871 Py_DECREF(self);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200872 return NULL;
873 }
Victor Stinnera9eb38f2013-10-31 16:35:38 +0100874 }
Christian Heimes141c5e82018-02-24 21:10:57 +0100875 if (owner && owner != Py_None) {
876 if (PySSL_set_owner(self, owner, NULL) == -1) {
877 Py_DECREF(self);
878 return NULL;
879 }
880 }
881 if (session && session != Py_None) {
882 if (PySSL_set_session(self, session, NULL) == -1) {
883 Py_DECREF(self);
884 return NULL;
885 }
886 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000887 return self;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000888}
889
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000890/* SSL object methods */
891
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +0300892/*[clinic input]
893_ssl._SSLSocket.do_handshake
894[clinic start generated code]*/
895
896static PyObject *
897_ssl__SSLSocket_do_handshake_impl(PySSLSocket *self)
898/*[clinic end generated code: output=6c0898a8936548f6 input=d2d737de3df018c8]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000899{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000900 int ret;
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700901 _PySSLError err;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000902 int sockstate, nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200903 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +0200904 _PyTime_t timeout, deadline = 0;
905 int has_timeout;
Antoine Pitroud3f8ab82010-04-24 21:26:44 +0000906
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200907 if (sock) {
908 if (((PyObject*)sock) == Py_None) {
Christian Heimes7f1305e2021-04-17 20:06:38 +0200909 _setSSLError(get_state_sock(self),
910 "Underlying socket connection gone",
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200911 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
912 return NULL;
913 }
914 Py_INCREF(sock);
915
916 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +0100917 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200918 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
919 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000920 }
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000921
Victor Stinner14690702015-04-06 22:46:13 +0200922 timeout = GET_SOCKET_TIMEOUT(sock);
923 has_timeout = (timeout > 0);
924 if (has_timeout)
925 deadline = _PyTime_GetMonotonicClock() + timeout;
926
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000927 /* Actually negotiate SSL connection */
928 /* XXX If SSL_do_handshake() returns 0, it's also a failure. */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000929 do {
Bill Janssen6e027db2007-11-15 22:23:56 +0000930 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000931 ret = SSL_do_handshake(self->ssl);
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700932 err = _PySSL_errno(ret < 1, self->ssl, ret);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000933 PySSL_END_ALLOW_THREADS
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700934 self->err = err;
Victor Stinner4e3cfa42015-04-02 21:28:28 +0200935
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000936 if (PyErr_CheckSignals())
937 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +0200938
Victor Stinner14690702015-04-06 22:46:13 +0200939 if (has_timeout)
940 timeout = deadline - _PyTime_GetMonotonicClock();
941
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700942 if (err.ssl == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +0200943 sockstate = PySSL_select(sock, 0, timeout);
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700944 } else if (err.ssl == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +0200945 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000946 } else {
947 sockstate = SOCKET_OPERATION_OK;
948 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +0200949
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000950 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Christian Heimes03c8ddd2020-11-20 09:26:07 +0100951 PyErr_SetString(PyExc_TimeoutError,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000952 ERRSTR("The handshake operation timed out"));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000953 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000954 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
Christian Heimes7f1305e2021-04-17 20:06:38 +0200955 PyErr_SetString(get_state_sock(self)->PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000956 ERRSTR("Underlying socket has been closed."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000957 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000958 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
Christian Heimes7f1305e2021-04-17 20:06:38 +0200959 PyErr_SetString(get_state_sock(self)->PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000960 ERRSTR("Underlying socket too large for select()."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000961 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000962 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
963 break;
964 }
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700965 } while (err.ssl == SSL_ERROR_WANT_READ ||
966 err.ssl == SSL_ERROR_WANT_WRITE);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200967 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000968 if (ret < 1)
969 return PySSL_SetError(self, ret, __FILE__, __LINE__);
Christian Heimesc7f70692019-05-31 11:44:05 +0200970 if (PySSL_ChainExceptions(self) < 0)
971 return NULL;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200972 Py_RETURN_NONE;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000973error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200974 Py_XDECREF(sock);
Christian Heimesc7f70692019-05-31 11:44:05 +0200975 PySSL_ChainExceptions(self);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000976 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000977}
978
Thomas Woutersed03b412007-08-28 21:37:11 +0000979static PyObject *
Christian Heimes7f1305e2021-04-17 20:06:38 +0200980_asn1obj2py(_sslmodulestate *state, const ASN1_OBJECT *name, int no_name)
Serhiy Storchakae503ca52017-09-05 01:28:53 +0300981{
982 char buf[X509_NAME_MAXLEN];
983 char *namebuf = buf;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000984 int buflen;
Serhiy Storchakae503ca52017-09-05 01:28:53 +0300985 PyObject *name_obj = NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000986
Serhiy Storchakae503ca52017-09-05 01:28:53 +0300987 buflen = OBJ_obj2txt(namebuf, X509_NAME_MAXLEN, name, no_name);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000988 if (buflen < 0) {
Christian Heimes7f1305e2021-04-17 20:06:38 +0200989 _setSSLError(state, NULL, 0, __FILE__, __LINE__);
Serhiy Storchakae503ca52017-09-05 01:28:53 +0300990 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000991 }
Serhiy Storchakae503ca52017-09-05 01:28:53 +0300992 /* initial buffer is too small for oid + terminating null byte */
993 if (buflen > X509_NAME_MAXLEN - 1) {
994 /* make OBJ_obj2txt() calculate the required buflen */
995 buflen = OBJ_obj2txt(NULL, 0, name, no_name);
996 /* allocate len + 1 for terminating NULL byte */
997 namebuf = PyMem_Malloc(buflen + 1);
998 if (namebuf == NULL) {
999 PyErr_NoMemory();
1000 return NULL;
1001 }
1002 buflen = OBJ_obj2txt(namebuf, buflen + 1, name, no_name);
1003 if (buflen < 0) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02001004 _setSSLError(state, NULL, 0, __FILE__, __LINE__);
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001005 goto done;
1006 }
1007 }
1008 if (!buflen && no_name) {
1009 Py_INCREF(Py_None);
1010 name_obj = Py_None;
1011 }
1012 else {
1013 name_obj = PyUnicode_FromStringAndSize(namebuf, buflen);
1014 }
1015
1016 done:
1017 if (buf != namebuf) {
1018 PyMem_Free(namebuf);
1019 }
1020 return name_obj;
1021}
1022
1023static PyObject *
Christian Heimes7f1305e2021-04-17 20:06:38 +02001024_create_tuple_for_attribute(_sslmodulestate *state,
1025 ASN1_OBJECT *name, ASN1_STRING *value)
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001026{
1027 Py_ssize_t buflen;
1028 unsigned char *valuebuf = NULL;
1029 PyObject *attr;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001030
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001031 buflen = ASN1_STRING_to_UTF8(&valuebuf, value);
1032 if (buflen < 0) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02001033 _setSSLError(state, NULL, 0, __FILE__, __LINE__);
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001034 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001035 }
Christian Heimes7f1305e2021-04-17 20:06:38 +02001036 attr = Py_BuildValue("Ns#", _asn1obj2py(state, name, 0), valuebuf, buflen);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001037 OPENSSL_free(valuebuf);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001038 return attr;
Thomas Woutersed03b412007-08-28 21:37:11 +00001039}
1040
1041static PyObject *
Christian Heimes7f1305e2021-04-17 20:06:38 +02001042_create_tuple_for_X509_NAME (_sslmodulestate *state, X509_NAME *xname)
Thomas Woutersed03b412007-08-28 21:37:11 +00001043{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001044 PyObject *dn = NULL; /* tuple which represents the "distinguished name" */
1045 PyObject *rdn = NULL; /* tuple to hold a "relative distinguished name" */
1046 PyObject *rdnt;
1047 PyObject *attr = NULL; /* tuple to hold an attribute */
1048 int entry_count = X509_NAME_entry_count(xname);
1049 X509_NAME_ENTRY *entry;
1050 ASN1_OBJECT *name;
1051 ASN1_STRING *value;
1052 int index_counter;
1053 int rdn_level = -1;
1054 int retcode;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001055
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001056 dn = PyList_New(0);
1057 if (dn == NULL)
1058 return NULL;
1059 /* now create another tuple to hold the top-level RDN */
1060 rdn = PyList_New(0);
1061 if (rdn == NULL)
1062 goto fail0;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001063
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001064 for (index_counter = 0;
1065 index_counter < entry_count;
1066 index_counter++)
1067 {
1068 entry = X509_NAME_get_entry(xname, index_counter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001069
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001070 /* check to see if we've gotten to a new RDN */
1071 if (rdn_level >= 0) {
Christian Heimes598894f2016-09-05 23:19:05 +02001072 if (rdn_level != X509_NAME_ENTRY_set(entry)) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001073 /* yes, new RDN */
1074 /* add old RDN to DN */
1075 rdnt = PyList_AsTuple(rdn);
1076 Py_DECREF(rdn);
1077 if (rdnt == NULL)
1078 goto fail0;
1079 retcode = PyList_Append(dn, rdnt);
1080 Py_DECREF(rdnt);
1081 if (retcode < 0)
1082 goto fail0;
1083 /* create new RDN */
1084 rdn = PyList_New(0);
1085 if (rdn == NULL)
1086 goto fail0;
1087 }
1088 }
Christian Heimes598894f2016-09-05 23:19:05 +02001089 rdn_level = X509_NAME_ENTRY_set(entry);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001090
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001091 /* now add this attribute to the current RDN */
1092 name = X509_NAME_ENTRY_get_object(entry);
1093 value = X509_NAME_ENTRY_get_data(entry);
Christian Heimes7f1305e2021-04-17 20:06:38 +02001094 attr = _create_tuple_for_attribute(state, name, value);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001095 /*
1096 fprintf(stderr, "RDN level %d, attribute %s: %s\n",
1097 entry->set,
1098 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 0)),
1099 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 1)));
1100 */
1101 if (attr == NULL)
1102 goto fail1;
1103 retcode = PyList_Append(rdn, attr);
1104 Py_DECREF(attr);
1105 if (retcode < 0)
1106 goto fail1;
1107 }
1108 /* now, there's typically a dangling RDN */
Antoine Pitrou2f5a1632012-02-15 22:25:27 +01001109 if (rdn != NULL) {
1110 if (PyList_GET_SIZE(rdn) > 0) {
1111 rdnt = PyList_AsTuple(rdn);
1112 Py_DECREF(rdn);
1113 if (rdnt == NULL)
1114 goto fail0;
1115 retcode = PyList_Append(dn, rdnt);
1116 Py_DECREF(rdnt);
1117 if (retcode < 0)
1118 goto fail0;
1119 }
1120 else {
1121 Py_DECREF(rdn);
1122 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001123 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001124
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001125 /* convert list to tuple */
1126 rdnt = PyList_AsTuple(dn);
1127 Py_DECREF(dn);
1128 if (rdnt == NULL)
1129 return NULL;
1130 return rdnt;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001131
1132 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001133 Py_XDECREF(rdn);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001134
1135 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001136 Py_XDECREF(dn);
1137 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001138}
1139
1140static PyObject *
Christian Heimes7f1305e2021-04-17 20:06:38 +02001141_get_peer_alt_names (_sslmodulestate *state, X509 *certificate) {
Guido van Rossumf06628b2007-11-21 20:01:53 +00001142
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001143 /* this code follows the procedure outlined in
1144 OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print()
1145 function to extract the STACK_OF(GENERAL_NAME),
1146 then iterates through the stack to add the
1147 names. */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001148
Alex Gaynorb87c0df2017-06-06 07:53:11 -04001149 int j;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001150 PyObject *peer_alt_names = Py_None;
Christian Heimes60bf2fc2013-09-05 16:04:35 +02001151 PyObject *v = NULL, *t;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001152 GENERAL_NAMES *names = NULL;
1153 GENERAL_NAME *name;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001154 BIO *biobuf = NULL;
1155 char buf[2048];
1156 char *vptr;
1157 int len;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001158
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001159 if (certificate == NULL)
1160 return peer_alt_names;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001161
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001162 /* get a memory buffer */
1163 biobuf = BIO_new(BIO_s_mem());
Zackery Spytz4c49da02018-12-07 03:11:30 -07001164 if (biobuf == NULL) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02001165 PyErr_SetString(state->PySSLErrorObject, "failed to allocate BIO");
Zackery Spytz4c49da02018-12-07 03:11:30 -07001166 return NULL;
1167 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001168
Alex Gaynorb87c0df2017-06-06 07:53:11 -04001169 names = (GENERAL_NAMES *)X509_get_ext_d2i(
1170 certificate, NID_subject_alt_name, NULL, NULL);
1171 if (names != NULL) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001172 if (peer_alt_names == Py_None) {
1173 peer_alt_names = PyList_New(0);
1174 if (peer_alt_names == NULL)
1175 goto fail;
1176 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001177
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001178 for(j = 0; j < sk_GENERAL_NAME_num(names); j++) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001179 /* get a rendering of each name in the set of names */
Christian Heimes824f7f32013-08-17 00:54:47 +02001180 int gntype;
1181 ASN1_STRING *as = NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001182
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001183 name = sk_GENERAL_NAME_value(names, j);
Christian Heimes474afdd2013-08-17 17:18:56 +02001184 gntype = name->type;
Christian Heimes824f7f32013-08-17 00:54:47 +02001185 switch (gntype) {
1186 case GEN_DIRNAME:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001187 /* we special-case DirName as a tuple of
1188 tuples of attributes */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001189
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001190 t = PyTuple_New(2);
1191 if (t == NULL) {
1192 goto fail;
1193 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001194
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001195 v = PyUnicode_FromString("DirName");
1196 if (v == NULL) {
1197 Py_DECREF(t);
1198 goto fail;
1199 }
1200 PyTuple_SET_ITEM(t, 0, v);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001201
Christian Heimes7f1305e2021-04-17 20:06:38 +02001202 v = _create_tuple_for_X509_NAME(state, name->d.dirn);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001203 if (v == NULL) {
1204 Py_DECREF(t);
1205 goto fail;
1206 }
1207 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +02001208 break;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001209
Christian Heimes824f7f32013-08-17 00:54:47 +02001210 case GEN_EMAIL:
1211 case GEN_DNS:
1212 case GEN_URI:
1213 /* GENERAL_NAME_print() doesn't handle NULL bytes in ASN1_string
1214 correctly, CVE-2013-4238 */
1215 t = PyTuple_New(2);
1216 if (t == NULL)
1217 goto fail;
1218 switch (gntype) {
1219 case GEN_EMAIL:
1220 v = PyUnicode_FromString("email");
1221 as = name->d.rfc822Name;
1222 break;
1223 case GEN_DNS:
1224 v = PyUnicode_FromString("DNS");
1225 as = name->d.dNSName;
1226 break;
1227 case GEN_URI:
1228 v = PyUnicode_FromString("URI");
1229 as = name->d.uniformResourceIdentifier;
1230 break;
1231 }
1232 if (v == NULL) {
1233 Py_DECREF(t);
1234 goto fail;
1235 }
1236 PyTuple_SET_ITEM(t, 0, v);
Christian Heimesa871f692020-06-01 08:58:14 +02001237 v = PyUnicode_FromStringAndSize((char *)ASN1_STRING_get0_data(as),
Christian Heimes824f7f32013-08-17 00:54:47 +02001238 ASN1_STRING_length(as));
1239 if (v == NULL) {
1240 Py_DECREF(t);
1241 goto fail;
1242 }
1243 PyTuple_SET_ITEM(t, 1, v);
1244 break;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001245
Christian Heimes1c03abd2016-09-06 23:25:35 +02001246 case GEN_RID:
1247 t = PyTuple_New(2);
1248 if (t == NULL)
1249 goto fail;
1250
1251 v = PyUnicode_FromString("Registered ID");
1252 if (v == NULL) {
1253 Py_DECREF(t);
1254 goto fail;
1255 }
1256 PyTuple_SET_ITEM(t, 0, v);
1257
1258 len = i2t_ASN1_OBJECT(buf, sizeof(buf)-1, name->d.rid);
1259 if (len < 0) {
1260 Py_DECREF(t);
Christian Heimes7f1305e2021-04-17 20:06:38 +02001261 _setSSLError(state, NULL, 0, __FILE__, __LINE__);
Christian Heimes1c03abd2016-09-06 23:25:35 +02001262 goto fail;
1263 } else if (len >= (int)sizeof(buf)) {
1264 v = PyUnicode_FromString("<INVALID>");
1265 } else {
1266 v = PyUnicode_FromStringAndSize(buf, len);
1267 }
1268 if (v == NULL) {
1269 Py_DECREF(t);
1270 goto fail;
1271 }
1272 PyTuple_SET_ITEM(t, 1, v);
1273 break;
1274
Christian Heimes2b7de662019-12-07 17:59:36 +01001275 case GEN_IPADD:
1276 /* OpenSSL < 3.0.0 adds a trailing \n to IPv6. 3.0.0 removed
1277 * the trailing newline. Remove it in all versions
1278 */
1279 t = PyTuple_New(2);
1280 if (t == NULL)
1281 goto fail;
1282
1283 v = PyUnicode_FromString("IP Address");
1284 if (v == NULL) {
1285 Py_DECREF(t);
1286 goto fail;
1287 }
1288 PyTuple_SET_ITEM(t, 0, v);
1289
1290 if (name->d.ip->length == 4) {
1291 unsigned char *p = name->d.ip->data;
1292 v = PyUnicode_FromFormat(
1293 "%d.%d.%d.%d",
1294 p[0], p[1], p[2], p[3]
1295 );
1296 } else if (name->d.ip->length == 16) {
1297 /* PyUnicode_FromFormat() does not support %X */
1298 unsigned char *p = name->d.ip->data;
1299 len = sprintf(
1300 buf,
1301 "%X:%X:%X:%X:%X:%X:%X:%X",
1302 p[0] << 8 | p[1],
1303 p[2] << 8 | p[3],
1304 p[4] << 8 | p[5],
1305 p[6] << 8 | p[7],
1306 p[8] << 8 | p[9],
1307 p[10] << 8 | p[11],
1308 p[12] << 8 | p[13],
1309 p[14] << 8 | p[15]
1310 );
1311 v = PyUnicode_FromStringAndSize(buf, len);
1312 } else {
1313 v = PyUnicode_FromString("<invalid>");
1314 }
1315
1316 if (v == NULL) {
1317 Py_DECREF(t);
1318 goto fail;
1319 }
1320 PyTuple_SET_ITEM(t, 1, v);
1321 break;
1322
Christian Heimes824f7f32013-08-17 00:54:47 +02001323 default:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001324 /* for everything else, we use the OpenSSL print form */
Christian Heimes824f7f32013-08-17 00:54:47 +02001325 switch (gntype) {
1326 /* check for new general name type */
1327 case GEN_OTHERNAME:
1328 case GEN_X400:
1329 case GEN_EDIPARTY:
Christian Heimes824f7f32013-08-17 00:54:47 +02001330 case GEN_RID:
1331 break;
1332 default:
1333 if (PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
1334 "Unknown general name type %d",
1335 gntype) == -1) {
1336 goto fail;
1337 }
1338 break;
1339 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001340 (void) BIO_reset(biobuf);
1341 GENERAL_NAME_print(biobuf, name);
1342 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1343 if (len < 0) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02001344 _setSSLError(state, NULL, 0, __FILE__, __LINE__);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001345 goto fail;
1346 }
1347 vptr = strchr(buf, ':');
Christian Heimes1c03abd2016-09-06 23:25:35 +02001348 if (vptr == NULL) {
1349 PyErr_Format(PyExc_ValueError,
1350 "Invalid value %.200s",
1351 buf);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001352 goto fail;
Christian Heimes1c03abd2016-09-06 23:25:35 +02001353 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001354 t = PyTuple_New(2);
1355 if (t == NULL)
1356 goto fail;
1357 v = PyUnicode_FromStringAndSize(buf, (vptr - buf));
1358 if (v == NULL) {
1359 Py_DECREF(t);
1360 goto fail;
1361 }
1362 PyTuple_SET_ITEM(t, 0, v);
1363 v = PyUnicode_FromStringAndSize((vptr + 1),
1364 (len - (vptr - buf + 1)));
1365 if (v == NULL) {
1366 Py_DECREF(t);
1367 goto fail;
1368 }
1369 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +02001370 break;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001371 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001372
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001373 /* and add that rendering to the list */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001374
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001375 if (PyList_Append(peer_alt_names, t) < 0) {
1376 Py_DECREF(t);
1377 goto fail;
1378 }
1379 Py_DECREF(t);
1380 }
Antoine Pitrou116d6b92011-11-23 01:39:19 +01001381 sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001382 }
1383 BIO_free(biobuf);
1384 if (peer_alt_names != Py_None) {
1385 v = PyList_AsTuple(peer_alt_names);
1386 Py_DECREF(peer_alt_names);
1387 return v;
1388 } else {
1389 return peer_alt_names;
1390 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001391
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001392
1393 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001394 if (biobuf != NULL)
1395 BIO_free(biobuf);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001396
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001397 if (peer_alt_names != Py_None) {
1398 Py_XDECREF(peer_alt_names);
1399 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001400
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001401 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001402}
1403
1404static PyObject *
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001405_get_aia_uri(X509 *certificate, int nid) {
1406 PyObject *lst = NULL, *ostr = NULL;
1407 int i, result;
1408 AUTHORITY_INFO_ACCESS *info;
1409
1410 info = X509_get_ext_d2i(certificate, NID_info_access, NULL, NULL);
Benjamin Petersonf0c90382015-11-14 15:12:18 -08001411 if (info == NULL)
1412 return Py_None;
1413 if (sk_ACCESS_DESCRIPTION_num(info) == 0) {
1414 AUTHORITY_INFO_ACCESS_free(info);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001415 return Py_None;
1416 }
1417
1418 if ((lst = PyList_New(0)) == NULL) {
1419 goto fail;
1420 }
1421
1422 for (i = 0; i < sk_ACCESS_DESCRIPTION_num(info); i++) {
1423 ACCESS_DESCRIPTION *ad = sk_ACCESS_DESCRIPTION_value(info, i);
1424 ASN1_IA5STRING *uri;
1425
1426 if ((OBJ_obj2nid(ad->method) != nid) ||
1427 (ad->location->type != GEN_URI)) {
1428 continue;
1429 }
1430 uri = ad->location->d.uniformResourceIdentifier;
1431 ostr = PyUnicode_FromStringAndSize((char *)uri->data,
1432 uri->length);
1433 if (ostr == NULL) {
1434 goto fail;
1435 }
1436 result = PyList_Append(lst, ostr);
1437 Py_DECREF(ostr);
1438 if (result < 0) {
1439 goto fail;
1440 }
1441 }
1442 AUTHORITY_INFO_ACCESS_free(info);
1443
1444 /* convert to tuple or None */
1445 if (PyList_Size(lst) == 0) {
1446 Py_DECREF(lst);
1447 return Py_None;
1448 } else {
1449 PyObject *tup;
1450 tup = PyList_AsTuple(lst);
1451 Py_DECREF(lst);
1452 return tup;
1453 }
1454
1455 fail:
1456 AUTHORITY_INFO_ACCESS_free(info);
Christian Heimes18fc7be2013-11-21 23:57:49 +01001457 Py_XDECREF(lst);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001458 return NULL;
1459}
1460
1461static PyObject *
1462_get_crl_dp(X509 *certificate) {
1463 STACK_OF(DIST_POINT) *dps;
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001464 int i, j;
1465 PyObject *lst, *res = NULL;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001466
Christian Heimes598894f2016-09-05 23:19:05 +02001467 dps = X509_get_ext_d2i(certificate, NID_crl_distribution_points, NULL, NULL);
Christian Heimes949ec142013-11-21 16:26:51 +01001468
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001469 if (dps == NULL)
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001470 return Py_None;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001471
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001472 lst = PyList_New(0);
1473 if (lst == NULL)
1474 goto done;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001475
1476 for (i=0; i < sk_DIST_POINT_num(dps); i++) {
1477 DIST_POINT *dp;
1478 STACK_OF(GENERAL_NAME) *gns;
1479
1480 dp = sk_DIST_POINT_value(dps, i);
Christian Heimesa37f5242019-01-15 23:47:42 +01001481 if (dp->distpoint == NULL) {
1482 /* Ignore empty DP value, CVE-2019-5010 */
1483 continue;
1484 }
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001485 gns = dp->distpoint->name.fullname;
1486
1487 for (j=0; j < sk_GENERAL_NAME_num(gns); j++) {
1488 GENERAL_NAME *gn;
1489 ASN1_IA5STRING *uri;
1490 PyObject *ouri;
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001491 int err;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001492
1493 gn = sk_GENERAL_NAME_value(gns, j);
1494 if (gn->type != GEN_URI) {
1495 continue;
1496 }
1497 uri = gn->d.uniformResourceIdentifier;
1498 ouri = PyUnicode_FromStringAndSize((char *)uri->data,
1499 uri->length);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001500 if (ouri == NULL)
1501 goto done;
1502
1503 err = PyList_Append(lst, ouri);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001504 Py_DECREF(ouri);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001505 if (err < 0)
1506 goto done;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001507 }
1508 }
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001509
1510 /* Convert to tuple. */
1511 res = (PyList_GET_SIZE(lst) > 0) ? PyList_AsTuple(lst) : Py_None;
1512
1513 done:
1514 Py_XDECREF(lst);
Olivier Vielpeau2849cc32017-04-14 21:06:07 -04001515 CRL_DIST_POINTS_free(dps);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001516 return res;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001517}
1518
1519static PyObject *
Christian Heimes7f1305e2021-04-17 20:06:38 +02001520_decode_certificate(_sslmodulestate *state, X509 *certificate) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001521
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001522 PyObject *retval = NULL;
1523 BIO *biobuf = NULL;
1524 PyObject *peer;
1525 PyObject *peer_alt_names = NULL;
1526 PyObject *issuer;
1527 PyObject *version;
1528 PyObject *sn_obj;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001529 PyObject *obj;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001530 ASN1_INTEGER *serialNumber;
1531 char buf[2048];
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001532 int len, result;
Christian Heimesa871f692020-06-01 08:58:14 +02001533 const ASN1_TIME *notBefore, *notAfter;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001534 PyObject *pnotBefore, *pnotAfter;
Thomas Woutersed03b412007-08-28 21:37:11 +00001535
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001536 retval = PyDict_New();
1537 if (retval == NULL)
1538 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001539
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001540 peer = _create_tuple_for_X509_NAME(
Christian Heimes7f1305e2021-04-17 20:06:38 +02001541 state,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001542 X509_get_subject_name(certificate));
1543 if (peer == NULL)
1544 goto fail0;
1545 if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) {
1546 Py_DECREF(peer);
1547 goto fail0;
1548 }
1549 Py_DECREF(peer);
Thomas Woutersed03b412007-08-28 21:37:11 +00001550
Antoine Pitroufb046912010-11-09 20:21:19 +00001551 issuer = _create_tuple_for_X509_NAME(
Christian Heimes7f1305e2021-04-17 20:06:38 +02001552 state,
Antoine Pitroufb046912010-11-09 20:21:19 +00001553 X509_get_issuer_name(certificate));
1554 if (issuer == NULL)
1555 goto fail0;
1556 if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001557 Py_DECREF(issuer);
Antoine Pitroufb046912010-11-09 20:21:19 +00001558 goto fail0;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001559 }
Antoine Pitroufb046912010-11-09 20:21:19 +00001560 Py_DECREF(issuer);
1561
1562 version = PyLong_FromLong(X509_get_version(certificate) + 1);
Christian Heimes5962bef2013-07-26 15:51:18 +02001563 if (version == NULL)
1564 goto fail0;
Antoine Pitroufb046912010-11-09 20:21:19 +00001565 if (PyDict_SetItemString(retval, "version", version) < 0) {
1566 Py_DECREF(version);
1567 goto fail0;
1568 }
1569 Py_DECREF(version);
Guido van Rossumf06628b2007-11-21 20:01:53 +00001570
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001571 /* get a memory buffer */
1572 biobuf = BIO_new(BIO_s_mem());
Zackery Spytz4c49da02018-12-07 03:11:30 -07001573 if (biobuf == NULL) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02001574 PyErr_SetString(state->PySSLErrorObject, "failed to allocate BIO");
Zackery Spytz4c49da02018-12-07 03:11:30 -07001575 goto fail0;
1576 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001577
Antoine Pitroufb046912010-11-09 20:21:19 +00001578 (void) BIO_reset(biobuf);
1579 serialNumber = X509_get_serialNumber(certificate);
1580 /* should not exceed 20 octets, 160 bits, so buf is big enough */
1581 i2a_ASN1_INTEGER(biobuf, serialNumber);
1582 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1583 if (len < 0) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02001584 _setSSLError(state, NULL, 0, __FILE__, __LINE__);
Antoine Pitroufb046912010-11-09 20:21:19 +00001585 goto fail1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001586 }
Antoine Pitroufb046912010-11-09 20:21:19 +00001587 sn_obj = PyUnicode_FromStringAndSize(buf, len);
1588 if (sn_obj == NULL)
1589 goto fail1;
1590 if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) {
1591 Py_DECREF(sn_obj);
1592 goto fail1;
1593 }
1594 Py_DECREF(sn_obj);
1595
1596 (void) BIO_reset(biobuf);
Christian Heimesa871f692020-06-01 08:58:14 +02001597 notBefore = X509_get0_notBefore(certificate);
Antoine Pitroufb046912010-11-09 20:21:19 +00001598 ASN1_TIME_print(biobuf, notBefore);
1599 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1600 if (len < 0) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02001601 _setSSLError(state, NULL, 0, __FILE__, __LINE__);
Antoine Pitroufb046912010-11-09 20:21:19 +00001602 goto fail1;
1603 }
1604 pnotBefore = PyUnicode_FromStringAndSize(buf, len);
1605 if (pnotBefore == NULL)
1606 goto fail1;
1607 if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) {
1608 Py_DECREF(pnotBefore);
1609 goto fail1;
1610 }
1611 Py_DECREF(pnotBefore);
Thomas Woutersed03b412007-08-28 21:37:11 +00001612
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001613 (void) BIO_reset(biobuf);
Christian Heimesa871f692020-06-01 08:58:14 +02001614 notAfter = X509_get0_notAfter(certificate);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001615 ASN1_TIME_print(biobuf, notAfter);
1616 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1617 if (len < 0) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02001618 _setSSLError(state, NULL, 0, __FILE__, __LINE__);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001619 goto fail1;
1620 }
1621 pnotAfter = PyUnicode_FromStringAndSize(buf, len);
1622 if (pnotAfter == NULL)
1623 goto fail1;
1624 if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) {
1625 Py_DECREF(pnotAfter);
1626 goto fail1;
1627 }
1628 Py_DECREF(pnotAfter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001629
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001630 /* Now look for subjectAltName */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001631
Christian Heimes7f1305e2021-04-17 20:06:38 +02001632 peer_alt_names = _get_peer_alt_names(state, certificate);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001633 if (peer_alt_names == NULL)
1634 goto fail1;
1635 else if (peer_alt_names != Py_None) {
1636 if (PyDict_SetItemString(retval, "subjectAltName",
1637 peer_alt_names) < 0) {
1638 Py_DECREF(peer_alt_names);
1639 goto fail1;
1640 }
1641 Py_DECREF(peer_alt_names);
1642 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001643
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001644 /* Authority Information Access: OCSP URIs */
1645 obj = _get_aia_uri(certificate, NID_ad_OCSP);
1646 if (obj == NULL) {
1647 goto fail1;
1648 } else if (obj != Py_None) {
1649 result = PyDict_SetItemString(retval, "OCSP", obj);
1650 Py_DECREF(obj);
1651 if (result < 0) {
1652 goto fail1;
1653 }
1654 }
1655
1656 obj = _get_aia_uri(certificate, NID_ad_ca_issuers);
1657 if (obj == NULL) {
1658 goto fail1;
1659 } else if (obj != Py_None) {
1660 result = PyDict_SetItemString(retval, "caIssuers", obj);
1661 Py_DECREF(obj);
1662 if (result < 0) {
1663 goto fail1;
1664 }
1665 }
1666
1667 /* CDP (CRL distribution points) */
1668 obj = _get_crl_dp(certificate);
1669 if (obj == NULL) {
1670 goto fail1;
1671 } else if (obj != Py_None) {
1672 result = PyDict_SetItemString(retval, "crlDistributionPoints", obj);
1673 Py_DECREF(obj);
1674 if (result < 0) {
1675 goto fail1;
1676 }
1677 }
1678
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001679 BIO_free(biobuf);
1680 return retval;
Thomas Woutersed03b412007-08-28 21:37:11 +00001681
1682 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001683 if (biobuf != NULL)
1684 BIO_free(biobuf);
Thomas Woutersed03b412007-08-28 21:37:11 +00001685 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001686 Py_XDECREF(retval);
1687 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001688}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001689
Christian Heimes9a5395a2013-06-17 15:44:12 +02001690static PyObject *
Christian Heimes7f1305e2021-04-17 20:06:38 +02001691_certificate_to_der(_sslmodulestate *state, X509 *certificate)
Christian Heimes9a5395a2013-06-17 15:44:12 +02001692{
1693 unsigned char *bytes_buf = NULL;
1694 int len;
1695 PyObject *retval;
1696
1697 bytes_buf = NULL;
1698 len = i2d_X509(certificate, &bytes_buf);
1699 if (len < 0) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02001700 _setSSLError(state, NULL, 0, __FILE__, __LINE__);
Christian Heimes9a5395a2013-06-17 15:44:12 +02001701 return NULL;
1702 }
1703 /* this is actually an immutable bytes sequence */
1704 retval = PyBytes_FromStringAndSize((const char *) bytes_buf, len);
1705 OPENSSL_free(bytes_buf);
1706 return retval;
1707}
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001708
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001709/*[clinic input]
1710_ssl._test_decode_cert
1711 path: object(converter="PyUnicode_FSConverter")
1712 /
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001713
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001714[clinic start generated code]*/
1715
1716static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001717_ssl__test_decode_cert_impl(PyObject *module, PyObject *path)
1718/*[clinic end generated code: output=96becb9abb23c091 input=cdeaaf02d4346628]*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001719{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001720 PyObject *retval = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001721 X509 *x=NULL;
1722 BIO *cert;
Christian Heimes7f1305e2021-04-17 20:06:38 +02001723 _sslmodulestate *state = get_ssl_state(module);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001724
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001725 if ((cert=BIO_new(BIO_s_file())) == NULL) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02001726 PyErr_SetString(state->PySSLErrorObject,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001727 "Can't malloc memory to read file");
1728 goto fail0;
1729 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001730
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001731 if (BIO_read_filename(cert, PyBytes_AsString(path)) <= 0) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02001732 PyErr_SetString(state->PySSLErrorObject,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001733 "Can't open file");
1734 goto fail0;
1735 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001736
Alex Gaynor40dad952019-08-15 08:31:28 -04001737 x = PEM_read_bio_X509(cert, NULL, NULL, NULL);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001738 if (x == NULL) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02001739 PyErr_SetString(state->PySSLErrorObject,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001740 "Error decoding PEM-encoded file");
1741 goto fail0;
1742 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001743
Christian Heimes7f1305e2021-04-17 20:06:38 +02001744 retval = _decode_certificate(state, x);
Mark Dickinsonee55df52010-08-03 18:31:54 +00001745 X509_free(x);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001746
1747 fail0:
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001748 Py_DECREF(path);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001749 if (cert != NULL) BIO_free(cert);
1750 return retval;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001751}
1752
1753
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001754/*[clinic input]
Christian Heimes141c5e82018-02-24 21:10:57 +01001755_ssl._SSLSocket.getpeercert
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001756 der as binary_mode: bool = False
1757 /
1758
1759Returns the certificate for the peer.
1760
1761If no certificate was provided, returns None. If a certificate was
1762provided, but not validated, returns an empty dictionary. Otherwise
1763returns a dict containing information about the peer certificate.
1764
1765If the optional argument is True, returns a DER-encoded copy of the
1766peer certificate, or None if no certificate was provided. This will
1767return the certificate even if it wasn't validated.
1768[clinic start generated code]*/
1769
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001770static PyObject *
Christian Heimes141c5e82018-02-24 21:10:57 +01001771_ssl__SSLSocket_getpeercert_impl(PySSLSocket *self, int binary_mode)
1772/*[clinic end generated code: output=1f0ab66dfb693c88 input=c0fbe802e57629b7]*/
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001773{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001774 int verification;
Christian Heimes66dc33b2017-05-23 16:02:02 -07001775 X509 *peer_cert;
1776 PyObject *result;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001777
Christian Heimes66dc33b2017-05-23 16:02:02 -07001778 if (!SSL_is_init_finished(self->ssl)) {
Antoine Pitrou20b85552013-09-29 19:50:53 +02001779 PyErr_SetString(PyExc_ValueError,
1780 "handshake not done yet");
1781 return NULL;
1782 }
Christian Heimes66dc33b2017-05-23 16:02:02 -07001783 peer_cert = SSL_get_peer_certificate(self->ssl);
1784 if (peer_cert == NULL)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001785 Py_RETURN_NONE;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001786
Antoine Pitrou721738f2012-08-15 23:20:39 +02001787 if (binary_mode) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001788 /* return cert in DER-encoded format */
Christian Heimes7f1305e2021-04-17 20:06:38 +02001789 result = _certificate_to_der(get_state_sock(self), peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001790 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00001791 verification = SSL_CTX_get_verify_mode(SSL_get_SSL_CTX(self->ssl));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001792 if ((verification & SSL_VERIFY_PEER) == 0)
Christian Heimes66dc33b2017-05-23 16:02:02 -07001793 result = PyDict_New();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001794 else
Christian Heimes7f1305e2021-04-17 20:06:38 +02001795 result = _decode_certificate(get_state_sock(self), peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001796 }
Christian Heimes66dc33b2017-05-23 16:02:02 -07001797 X509_free(peer_cert);
1798 return result;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001799}
1800
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001801static PyObject *
1802cipher_to_tuple(const SSL_CIPHER *cipher)
1803{
1804 const char *cipher_name, *cipher_protocol;
1805 PyObject *v, *retval = PyTuple_New(3);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001806 if (retval == NULL)
1807 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001808
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001809 cipher_name = SSL_CIPHER_get_name(cipher);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001810 if (cipher_name == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001811 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001812 PyTuple_SET_ITEM(retval, 0, Py_None);
1813 } else {
1814 v = PyUnicode_FromString(cipher_name);
1815 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001816 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001817 PyTuple_SET_ITEM(retval, 0, v);
1818 }
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001819
1820 cipher_protocol = SSL_CIPHER_get_version(cipher);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001821 if (cipher_protocol == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001822 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001823 PyTuple_SET_ITEM(retval, 1, Py_None);
1824 } else {
1825 v = PyUnicode_FromString(cipher_protocol);
1826 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001827 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001828 PyTuple_SET_ITEM(retval, 1, v);
1829 }
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001830
1831 v = PyLong_FromLong(SSL_CIPHER_get_bits(cipher, NULL));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001832 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001833 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001834 PyTuple_SET_ITEM(retval, 2, v);
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001835
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001836 return retval;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001837
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001838 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001839 Py_DECREF(retval);
1840 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001841}
1842
Christian Heimes25bfcd52016-09-06 00:04:45 +02001843static PyObject *
1844cipher_to_dict(const SSL_CIPHER *cipher)
1845{
1846 const char *cipher_name, *cipher_protocol;
1847
1848 unsigned long cipher_id;
1849 int alg_bits, strength_bits, len;
1850 char buf[512] = {0};
Christian Heimes25bfcd52016-09-06 00:04:45 +02001851 int aead, nid;
1852 const char *skcipher = NULL, *digest = NULL, *kx = NULL, *auth = NULL;
Christian Heimes25bfcd52016-09-06 00:04:45 +02001853
1854 /* can be NULL */
1855 cipher_name = SSL_CIPHER_get_name(cipher);
1856 cipher_protocol = SSL_CIPHER_get_version(cipher);
1857 cipher_id = SSL_CIPHER_get_id(cipher);
1858 SSL_CIPHER_description(cipher, buf, sizeof(buf) - 1);
Segev Finer5cff6372017-07-27 01:19:17 +03001859 /* Downcast to avoid a warning. Safe since buf is always 512 bytes */
1860 len = (int)strlen(buf);
Christian Heimes25bfcd52016-09-06 00:04:45 +02001861 if (len > 1 && buf[len-1] == '\n')
1862 buf[len-1] = '\0';
1863 strength_bits = SSL_CIPHER_get_bits(cipher, &alg_bits);
1864
Christian Heimes25bfcd52016-09-06 00:04:45 +02001865 aead = SSL_CIPHER_is_aead(cipher);
1866 nid = SSL_CIPHER_get_cipher_nid(cipher);
1867 skcipher = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1868 nid = SSL_CIPHER_get_digest_nid(cipher);
1869 digest = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1870 nid = SSL_CIPHER_get_kx_nid(cipher);
1871 kx = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1872 nid = SSL_CIPHER_get_auth_nid(cipher);
1873 auth = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
Christian Heimes25bfcd52016-09-06 00:04:45 +02001874
Victor Stinner410b9882016-09-12 12:00:23 +02001875 return Py_BuildValue(
Christian Heimes25bfcd52016-09-06 00:04:45 +02001876 "{sksssssssisi"
Christian Heimes25bfcd52016-09-06 00:04:45 +02001877 "sOssssssss"
Christian Heimes25bfcd52016-09-06 00:04:45 +02001878 "}",
1879 "id", cipher_id,
1880 "name", cipher_name,
1881 "protocol", cipher_protocol,
1882 "description", buf,
1883 "strength_bits", strength_bits,
1884 "alg_bits", alg_bits
Christian Heimes25bfcd52016-09-06 00:04:45 +02001885 ,"aead", aead ? Py_True : Py_False,
1886 "symmetric", skcipher,
1887 "digest", digest,
1888 "kea", kx,
1889 "auth", auth
Christian Heimes25bfcd52016-09-06 00:04:45 +02001890 );
Christian Heimes25bfcd52016-09-06 00:04:45 +02001891}
Christian Heimes25bfcd52016-09-06 00:04:45 +02001892
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001893/*[clinic input]
1894_ssl._SSLSocket.shared_ciphers
1895[clinic start generated code]*/
1896
1897static PyObject *
1898_ssl__SSLSocket_shared_ciphers_impl(PySSLSocket *self)
1899/*[clinic end generated code: output=3d174ead2e42c4fd input=0bfe149da8fe6306]*/
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001900{
1901 STACK_OF(SSL_CIPHER) *ciphers;
1902 int i;
1903 PyObject *res;
1904
Christian Heimes598894f2016-09-05 23:19:05 +02001905 ciphers = SSL_get_ciphers(self->ssl);
1906 if (!ciphers)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001907 Py_RETURN_NONE;
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001908 res = PyList_New(sk_SSL_CIPHER_num(ciphers));
1909 if (!res)
1910 return NULL;
1911 for (i = 0; i < sk_SSL_CIPHER_num(ciphers); i++) {
1912 PyObject *tup = cipher_to_tuple(sk_SSL_CIPHER_value(ciphers, i));
1913 if (!tup) {
1914 Py_DECREF(res);
1915 return NULL;
1916 }
1917 PyList_SET_ITEM(res, i, tup);
1918 }
1919 return res;
1920}
1921
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001922/*[clinic input]
1923_ssl._SSLSocket.cipher
1924[clinic start generated code]*/
1925
1926static PyObject *
1927_ssl__SSLSocket_cipher_impl(PySSLSocket *self)
1928/*[clinic end generated code: output=376417c16d0e5815 input=548fb0e27243796d]*/
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001929{
1930 const SSL_CIPHER *current;
1931
1932 if (self->ssl == NULL)
1933 Py_RETURN_NONE;
1934 current = SSL_get_current_cipher(self->ssl);
1935 if (current == NULL)
1936 Py_RETURN_NONE;
1937 return cipher_to_tuple(current);
1938}
1939
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001940/*[clinic input]
1941_ssl._SSLSocket.version
1942[clinic start generated code]*/
1943
1944static PyObject *
1945_ssl__SSLSocket_version_impl(PySSLSocket *self)
1946/*[clinic end generated code: output=178aed33193b2cdb input=900186a503436fd6]*/
Antoine Pitrou47e40422014-09-04 21:00:10 +02001947{
1948 const char *version;
1949
1950 if (self->ssl == NULL)
1951 Py_RETURN_NONE;
Christian Heimes68771112017-09-05 21:55:40 -07001952 if (!SSL_is_init_finished(self->ssl)) {
1953 /* handshake not finished */
1954 Py_RETURN_NONE;
1955 }
Antoine Pitrou47e40422014-09-04 21:00:10 +02001956 version = SSL_get_version(self->ssl);
1957 if (!strcmp(version, "unknown"))
1958 Py_RETURN_NONE;
1959 return PyUnicode_FromString(version);
1960}
1961
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001962/*[clinic input]
1963_ssl._SSLSocket.selected_alpn_protocol
1964[clinic start generated code]*/
1965
1966static PyObject *
1967_ssl__SSLSocket_selected_alpn_protocol_impl(PySSLSocket *self)
1968/*[clinic end generated code: output=ec33688b303d250f input=442de30e35bc2913]*/
1969{
Benjamin Petersoncca27322015-01-23 16:35:37 -05001970 const unsigned char *out;
1971 unsigned int outlen;
1972
1973 SSL_get0_alpn_selected(self->ssl, &out, &outlen);
1974
1975 if (out == NULL)
1976 Py_RETURN_NONE;
1977 return PyUnicode_FromStringAndSize((char *)out, outlen);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001978}
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001979
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001980/*[clinic input]
1981_ssl._SSLSocket.compression
1982[clinic start generated code]*/
1983
1984static PyObject *
1985_ssl__SSLSocket_compression_impl(PySSLSocket *self)
1986/*[clinic end generated code: output=bd16cb1bb4646ae7 input=5d059d0a2bbc32c8]*/
1987{
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01001988#ifdef OPENSSL_NO_COMP
1989 Py_RETURN_NONE;
1990#else
1991 const COMP_METHOD *comp_method;
1992 const char *short_name;
1993
1994 if (self->ssl == NULL)
1995 Py_RETURN_NONE;
1996 comp_method = SSL_get_current_compression(self->ssl);
Christian Heimes598894f2016-09-05 23:19:05 +02001997 if (comp_method == NULL || COMP_get_type(comp_method) == NID_undef)
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01001998 Py_RETURN_NONE;
Christian Heimes281e5f82016-09-06 01:10:39 +02001999 short_name = OBJ_nid2sn(COMP_get_type(comp_method));
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01002000 if (short_name == NULL)
2001 Py_RETURN_NONE;
2002 return PyUnicode_DecodeFSDefault(short_name);
2003#endif
2004}
2005
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002006static PySSLContext *PySSL_get_context(PySSLSocket *self, void *closure) {
2007 Py_INCREF(self->ctx);
2008 return self->ctx;
2009}
2010
2011static int PySSL_set_context(PySSLSocket *self, PyObject *value,
2012 void *closure) {
2013
Christian Heimes7f1305e2021-04-17 20:06:38 +02002014 if (PyObject_TypeCheck(value, self->ctx->state->PySSLContext_Type)) {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002015 Py_INCREF(value);
Serhiy Storchaka57a01d32016-04-10 18:05:40 +03002016 Py_SETREF(self->ctx, (PySSLContext *)value);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002017 SSL_set_SSL_CTX(self->ssl, self->ctx->ctx);
Christian Heimes77cde502021-03-21 16:13:09 +01002018 /* Set SSL* internal msg_callback to state of new context's state */
2019 SSL_set_msg_callback(
2020 self->ssl,
2021 self->ctx->msg_cb ? _PySSL_msg_callback : NULL
2022 );
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002023 } else {
Ned Deily4531ec72018-06-11 20:26:28 -04002024 PyErr_SetString(PyExc_TypeError, "The value must be a SSLContext");
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002025 return -1;
2026 }
2027
2028 return 0;
2029}
2030
2031PyDoc_STRVAR(PySSL_set_context_doc,
2032"_setter_context(ctx)\n\
2033\
2034This changes the context associated with the SSLSocket. This is typically\n\
Christian Heimes11a14932018-02-24 02:35:08 +01002035used from within a callback function set by the sni_callback\n\
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002036on the SSLContext to change the certificate information associated with the\n\
2037SSLSocket before the cryptographic exchange handshake messages\n");
2038
2039
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002040static PyObject *
2041PySSL_get_server_side(PySSLSocket *self, void *c)
2042{
2043 return PyBool_FromLong(self->socket_type == PY_SSL_SERVER);
2044}
2045
2046PyDoc_STRVAR(PySSL_get_server_side_doc,
2047"Whether this is a server-side socket.");
2048
2049static PyObject *
2050PySSL_get_server_hostname(PySSLSocket *self, void *c)
2051{
2052 if (self->server_hostname == NULL)
2053 Py_RETURN_NONE;
2054 Py_INCREF(self->server_hostname);
2055 return self->server_hostname;
2056}
2057
2058PyDoc_STRVAR(PySSL_get_server_hostname_doc,
2059"The currently set server hostname (for SNI).");
2060
2061static PyObject *
2062PySSL_get_owner(PySSLSocket *self, void *c)
2063{
2064 PyObject *owner;
2065
2066 if (self->owner == NULL)
2067 Py_RETURN_NONE;
2068
2069 owner = PyWeakref_GetObject(self->owner);
2070 Py_INCREF(owner);
2071 return owner;
2072}
2073
2074static int
2075PySSL_set_owner(PySSLSocket *self, PyObject *value, void *c)
2076{
Serhiy Storchaka48842712016-04-06 09:45:48 +03002077 Py_XSETREF(self->owner, PyWeakref_NewRef(value, NULL));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002078 if (self->owner == NULL)
2079 return -1;
2080 return 0;
2081}
2082
2083PyDoc_STRVAR(PySSL_get_owner_doc,
2084"The Python-level owner of this object.\
2085Passed as \"self\" in servername callback.");
2086
Christian Heimesc7f70692019-05-31 11:44:05 +02002087static int
2088PySSL_traverse(PySSLSocket *self, visitproc visit, void *arg)
2089{
2090 Py_VISIT(self->exc_type);
2091 Py_VISIT(self->exc_value);
2092 Py_VISIT(self->exc_tb);
2093 return 0;
2094}
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002095
Christian Heimesc7f70692019-05-31 11:44:05 +02002096static int
2097PySSL_clear(PySSLSocket *self)
2098{
2099 Py_CLEAR(self->exc_type);
2100 Py_CLEAR(self->exc_value);
2101 Py_CLEAR(self->exc_tb);
2102 return 0;
2103}
2104
2105static void
2106PySSL_dealloc(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002107{
Christian Heimes5c36da72020-11-20 09:40:12 +01002108 PyTypeObject *tp = Py_TYPE(self);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002109 if (self->ssl)
2110 SSL_free(self->ssl);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002111 Py_XDECREF(self->Socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002112 Py_XDECREF(self->ctx);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002113 Py_XDECREF(self->server_hostname);
2114 Py_XDECREF(self->owner);
Victor Stinner32bd68c2020-12-01 10:37:39 +01002115 PyObject_Free(self);
Christian Heimes5c36da72020-11-20 09:40:12 +01002116 Py_DECREF(tp);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002117}
2118
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002119/* If the socket has a timeout, do a select()/poll() on the socket.
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002120 The argument writing indicates the direction.
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00002121 Returns one of the possibilities in the timeout_state enum (above).
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002122 */
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00002123
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002124static int
Victor Stinner14690702015-04-06 22:46:13 +02002125PySSL_select(PySocketSockObject *s, int writing, _PyTime_t timeout)
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002126{
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002127 int rc;
2128#ifdef HAVE_POLL
2129 struct pollfd pollfd;
2130 _PyTime_t ms;
2131#else
2132 int nfds;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002133 fd_set fds;
2134 struct timeval tv;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002135#endif
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002136
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002137 /* Nothing to do unless we're in timeout mode (not non-blocking) */
Victor Stinner14690702015-04-06 22:46:13 +02002138 if ((s == NULL) || (timeout == 0))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002139 return SOCKET_IS_NONBLOCKING;
Victor Stinner14690702015-04-06 22:46:13 +02002140 else if (timeout < 0) {
2141 if (s->sock_timeout > 0)
2142 return SOCKET_HAS_TIMED_OUT;
2143 else
2144 return SOCKET_IS_BLOCKING;
2145 }
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002146
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002147 /* Guard against closed socket */
Victor Stinner524714e2016-07-22 17:43:59 +02002148 if (s->sock_fd == INVALID_SOCKET)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002149 return SOCKET_HAS_BEEN_CLOSED;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002150
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002151 /* Prefer poll, if available, since you can poll() any fd
2152 * which can't be done with select(). */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002153#ifdef HAVE_POLL
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002154 pollfd.fd = s->sock_fd;
2155 pollfd.events = writing ? POLLOUT : POLLIN;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002156
Victor Stinner14690702015-04-06 22:46:13 +02002157 /* timeout is in seconds, poll() uses milliseconds */
2158 ms = (int)_PyTime_AsMilliseconds(timeout, _PyTime_ROUND_CEILING);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002159 assert(ms <= INT_MAX);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002160
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002161 PySSL_BEGIN_ALLOW_THREADS
2162 rc = poll(&pollfd, 1, (int)ms);
2163 PySSL_END_ALLOW_THREADS
2164#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002165 /* Guard against socket too large for select*/
Charles-François Nataliaa26b272011-08-28 17:51:43 +02002166 if (!_PyIsSelectable_fd(s->sock_fd))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002167 return SOCKET_TOO_LARGE_FOR_SELECT;
Neal Norwitz082b2df2006-02-07 07:04:46 +00002168
Victor Stinner14690702015-04-06 22:46:13 +02002169 _PyTime_AsTimeval_noraise(timeout, &tv, _PyTime_ROUND_CEILING);
Victor Stinnere2452312015-03-28 03:00:46 +01002170
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002171 FD_ZERO(&fds);
2172 FD_SET(s->sock_fd, &fds);
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002173
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002174 /* Wait until the socket becomes ready */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002175 PySSL_BEGIN_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002176 nfds = Py_SAFE_DOWNCAST(s->sock_fd+1, SOCKET_T, int);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002177 if (writing)
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002178 rc = select(nfds, NULL, &fds, NULL, &tv);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002179 else
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002180 rc = select(nfds, &fds, NULL, NULL, &tv);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002181 PySSL_END_ALLOW_THREADS
Bill Janssen6e027db2007-11-15 22:23:56 +00002182#endif
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002183
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002184 /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
2185 (when we are able to write or when there's something to read) */
2186 return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002187}
2188
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002189/*[clinic input]
2190_ssl._SSLSocket.write
2191 b: Py_buffer
2192 /
2193
2194Writes the bytes-like object b into the SSL object.
2195
2196Returns the number of bytes written.
2197[clinic start generated code]*/
2198
2199static PyObject *
2200_ssl__SSLSocket_write_impl(PySSLSocket *self, Py_buffer *b)
2201/*[clinic end generated code: output=aa7a6be5527358d8 input=77262d994fe5100a]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002202{
Christian Heimes89d15502021-04-19 06:55:30 +02002203 size_t count = 0;
2204 int retval;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002205 int sockstate;
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002206 _PySSLError err;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002207 int nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002208 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002209 _PyTime_t timeout, deadline = 0;
2210 int has_timeout;
Bill Janssen54cc54c2007-12-14 22:08:56 +00002211
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002212 if (sock != NULL) {
2213 if (((PyObject*)sock) == Py_None) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02002214 _setSSLError(get_state_sock(self),
2215 "Underlying socket connection gone",
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002216 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2217 return NULL;
2218 }
2219 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002220 }
2221
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002222 if (sock != NULL) {
2223 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002224 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002225 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2226 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
2227 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002228
Victor Stinner14690702015-04-06 22:46:13 +02002229 timeout = GET_SOCKET_TIMEOUT(sock);
2230 has_timeout = (timeout > 0);
2231 if (has_timeout)
2232 deadline = _PyTime_GetMonotonicClock() + timeout;
2233
2234 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002235 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Christian Heimes03c8ddd2020-11-20 09:26:07 +01002236 PyErr_SetString(PyExc_TimeoutError,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002237 "The write operation timed out");
2238 goto error;
2239 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02002240 PyErr_SetString(get_state_sock(self)->PySSLErrorObject,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002241 "Underlying socket has been closed.");
2242 goto error;
2243 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02002244 PyErr_SetString(get_state_sock(self)->PySSLErrorObject,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002245 "Underlying socket too large for select().");
2246 goto error;
2247 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002248
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002249 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002250 PySSL_BEGIN_ALLOW_THREADS
Christian Heimes89d15502021-04-19 06:55:30 +02002251 retval = SSL_write_ex(self->ssl, b->buf, (int)b->len, &count);
2252 err = _PySSL_errno(retval == 0, self->ssl, retval);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002253 PySSL_END_ALLOW_THREADS
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002254 self->err = err;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002255
2256 if (PyErr_CheckSignals())
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002257 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002258
Victor Stinner14690702015-04-06 22:46:13 +02002259 if (has_timeout)
2260 timeout = deadline - _PyTime_GetMonotonicClock();
2261
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002262 if (err.ssl == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +02002263 sockstate = PySSL_select(sock, 0, timeout);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002264 } else if (err.ssl == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +02002265 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002266 } else {
2267 sockstate = SOCKET_OPERATION_OK;
2268 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002269
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002270 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Christian Heimes03c8ddd2020-11-20 09:26:07 +01002271 PyErr_SetString(PyExc_TimeoutError,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002272 "The write operation timed out");
2273 goto error;
2274 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02002275 PyErr_SetString(get_state_sock(self)->PySSLErrorObject,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002276 "Underlying socket has been closed.");
2277 goto error;
2278 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
2279 break;
2280 }
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002281 } while (err.ssl == SSL_ERROR_WANT_READ ||
2282 err.ssl == SSL_ERROR_WANT_WRITE);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002283
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002284 Py_XDECREF(sock);
Christian Heimes89d15502021-04-19 06:55:30 +02002285 if (retval == 0)
2286 return PySSL_SetError(self, retval, __FILE__, __LINE__);
Christian Heimesc7f70692019-05-31 11:44:05 +02002287 if (PySSL_ChainExceptions(self) < 0)
2288 return NULL;
Christian Heimes89d15502021-04-19 06:55:30 +02002289 return PyLong_FromSize_t(count);
Antoine Pitrou7d7aede2009-11-25 18:55:32 +00002290error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002291 Py_XDECREF(sock);
Christian Heimesc7f70692019-05-31 11:44:05 +02002292 PySSL_ChainExceptions(self);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002293 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002294}
2295
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002296/*[clinic input]
2297_ssl._SSLSocket.pending
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002298
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002299Returns the number of already decrypted bytes available for read, pending on the connection.
2300[clinic start generated code]*/
2301
2302static PyObject *
2303_ssl__SSLSocket_pending_impl(PySSLSocket *self)
2304/*[clinic end generated code: output=983d9fecdc308a83 input=2b77487d6dfd597f]*/
Bill Janssen6e027db2007-11-15 22:23:56 +00002305{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002306 int count = 0;
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002307 _PySSLError err;
Bill Janssen6e027db2007-11-15 22:23:56 +00002308
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002309 PySSL_BEGIN_ALLOW_THREADS
2310 count = SSL_pending(self->ssl);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002311 err = _PySSL_errno(count < 0, self->ssl, count);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002312 PySSL_END_ALLOW_THREADS
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002313 self->err = err;
2314
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002315 if (count < 0)
2316 return PySSL_SetError(self, count, __FILE__, __LINE__);
2317 else
2318 return PyLong_FromLong(count);
Bill Janssen6e027db2007-11-15 22:23:56 +00002319}
2320
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002321/*[clinic input]
2322_ssl._SSLSocket.read
2323 size as len: int
2324 [
Larry Hastingsdbfdc382015-05-04 06:59:46 -07002325 buffer: Py_buffer(accept={rwbuffer})
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002326 ]
2327 /
Bill Janssen6e027db2007-11-15 22:23:56 +00002328
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002329Read up to size bytes from the SSL socket.
2330[clinic start generated code]*/
2331
2332static PyObject *
2333_ssl__SSLSocket_read_impl(PySSLSocket *self, int len, int group_right_1,
2334 Py_buffer *buffer)
Larry Hastingsdbfdc382015-05-04 06:59:46 -07002335/*[clinic end generated code: output=00097776cec2a0af input=ff157eb918d0905b]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002336{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002337 PyObject *dest = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002338 char *mem;
Christian Heimes89d15502021-04-19 06:55:30 +02002339 size_t count = 0;
2340 int retval;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002341 int sockstate;
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002342 _PySSLError err;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002343 int nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002344 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002345 _PyTime_t timeout, deadline = 0;
2346 int has_timeout;
Bill Janssen54cc54c2007-12-14 22:08:56 +00002347
Martin Panter5503d472016-03-27 05:35:19 +00002348 if (!group_right_1 && len < 0) {
2349 PyErr_SetString(PyExc_ValueError, "size should not be negative");
2350 return NULL;
2351 }
2352
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002353 if (sock != NULL) {
2354 if (((PyObject*)sock) == Py_None) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02002355 _setSSLError(get_state_sock(self),
2356 "Underlying socket connection gone",
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002357 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2358 return NULL;
2359 }
2360 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002361 }
2362
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002363 if (!group_right_1) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002364 dest = PyBytes_FromStringAndSize(NULL, len);
2365 if (dest == NULL)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002366 goto error;
Martin Panterbed7f1a2016-07-11 00:17:13 +00002367 if (len == 0) {
2368 Py_XDECREF(sock);
2369 return dest;
2370 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002371 mem = PyBytes_AS_STRING(dest);
2372 }
2373 else {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002374 mem = buffer->buf;
2375 if (len <= 0 || len > buffer->len) {
2376 len = (int) buffer->len;
2377 if (buffer->len != len) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002378 PyErr_SetString(PyExc_OverflowError,
2379 "maximum length can't fit in a C 'int'");
2380 goto error;
2381 }
Martin Panterbed7f1a2016-07-11 00:17:13 +00002382 if (len == 0) {
2383 count = 0;
2384 goto done;
2385 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002386 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002387 }
2388
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002389 if (sock != NULL) {
2390 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002391 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002392 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2393 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
2394 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002395
Victor Stinner14690702015-04-06 22:46:13 +02002396 timeout = GET_SOCKET_TIMEOUT(sock);
2397 has_timeout = (timeout > 0);
2398 if (has_timeout)
2399 deadline = _PyTime_GetMonotonicClock() + timeout;
2400
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002401 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002402 PySSL_BEGIN_ALLOW_THREADS
Christian Heimes89d15502021-04-19 06:55:30 +02002403 retval = SSL_read_ex(self->ssl, mem, len, &count);
2404 err = _PySSL_errno(retval == 0, self->ssl, retval);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002405 PySSL_END_ALLOW_THREADS
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002406 self->err = err;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002407
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002408 if (PyErr_CheckSignals())
2409 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002410
Victor Stinner14690702015-04-06 22:46:13 +02002411 if (has_timeout)
2412 timeout = deadline - _PyTime_GetMonotonicClock();
2413
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002414 if (err.ssl == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +02002415 sockstate = PySSL_select(sock, 0, timeout);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002416 } else if (err.ssl == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +02002417 sockstate = PySSL_select(sock, 1, timeout);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002418 } else if (err.ssl == SSL_ERROR_ZERO_RETURN &&
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002419 SSL_get_shutdown(self->ssl) == SSL_RECEIVED_SHUTDOWN)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002420 {
2421 count = 0;
2422 goto done;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002423 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002424 else
2425 sockstate = SOCKET_OPERATION_OK;
2426
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002427 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Christian Heimes03c8ddd2020-11-20 09:26:07 +01002428 PyErr_SetString(PyExc_TimeoutError,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002429 "The read operation timed out");
2430 goto error;
2431 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
2432 break;
2433 }
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002434 } while (err.ssl == SSL_ERROR_WANT_READ ||
2435 err.ssl == SSL_ERROR_WANT_WRITE);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002436
Christian Heimes89d15502021-04-19 06:55:30 +02002437 if (retval == 0) {
2438 PySSL_SetError(self, retval, __FILE__, __LINE__);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002439 goto error;
2440 }
Christian Heimesc7f70692019-05-31 11:44:05 +02002441 if (self->exc_type != NULL)
2442 goto error;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002443
2444done:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002445 Py_XDECREF(sock);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002446 if (!group_right_1) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002447 _PyBytes_Resize(&dest, count);
2448 return dest;
2449 }
2450 else {
Christian Heimes89d15502021-04-19 06:55:30 +02002451 return PyLong_FromSize_t(count);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002452 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002453
2454error:
Christian Heimesc7f70692019-05-31 11:44:05 +02002455 PySSL_ChainExceptions(self);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002456 Py_XDECREF(sock);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002457 if (!group_right_1)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002458 Py_XDECREF(dest);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002459 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002460}
2461
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002462/*[clinic input]
2463_ssl._SSLSocket.shutdown
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002464
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002465Does the SSL shutdown handshake with the remote end.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002466[clinic start generated code]*/
2467
2468static PyObject *
2469_ssl__SSLSocket_shutdown_impl(PySSLSocket *self)
Christian Heimes141c5e82018-02-24 21:10:57 +01002470/*[clinic end generated code: output=ca1aa7ed9d25ca42 input=11d39e69b0a2bf4a]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00002471{
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002472 _PySSLError err;
2473 int sockstate, nonblocking, ret;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002474 int zeros = 0;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002475 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002476 _PyTime_t timeout, deadline = 0;
2477 int has_timeout;
Bill Janssen40a0f662008-08-12 16:56:25 +00002478
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002479 if (sock != NULL) {
2480 /* Guard against closed socket */
Victor Stinner524714e2016-07-22 17:43:59 +02002481 if ((((PyObject*)sock) == Py_None) || (sock->sock_fd == INVALID_SOCKET)) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02002482 _setSSLError(get_state_sock(self),
2483 "Underlying socket connection gone",
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002484 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2485 return NULL;
2486 }
2487 Py_INCREF(sock);
2488
2489 /* Just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002490 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002491 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2492 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002493 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002494
Victor Stinner14690702015-04-06 22:46:13 +02002495 timeout = GET_SOCKET_TIMEOUT(sock);
2496 has_timeout = (timeout > 0);
2497 if (has_timeout)
2498 deadline = _PyTime_GetMonotonicClock() + timeout;
2499
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002500 while (1) {
2501 PySSL_BEGIN_ALLOW_THREADS
2502 /* Disable read-ahead so that unwrap can work correctly.
2503 * Otherwise OpenSSL might read in too much data,
2504 * eating clear text data that happens to be
2505 * transmitted after the SSL shutdown.
Ezio Melotti85a86292013-08-17 16:57:41 +03002506 * Should be safe to call repeatedly every time this
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002507 * function is used and the shutdown_seen_zero != 0
2508 * condition is met.
2509 */
2510 if (self->shutdown_seen_zero)
2511 SSL_set_read_ahead(self->ssl, 0);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002512 ret = SSL_shutdown(self->ssl);
2513 err = _PySSL_errno(ret < 0, self->ssl, ret);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002514 PySSL_END_ALLOW_THREADS
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002515 self->err = err;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002516
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002517 /* If err == 1, a secure shutdown with SSL_shutdown() is complete */
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002518 if (ret > 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002519 break;
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002520 if (ret == 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002521 /* Don't loop endlessly; instead preserve legacy
2522 behaviour of trying SSL_shutdown() only twice.
2523 This looks necessary for OpenSSL < 0.9.8m */
2524 if (++zeros > 1)
2525 break;
2526 /* Shutdown was sent, now try receiving */
2527 self->shutdown_seen_zero = 1;
2528 continue;
Bill Janssen40a0f662008-08-12 16:56:25 +00002529 }
2530
Victor Stinner14690702015-04-06 22:46:13 +02002531 if (has_timeout)
2532 timeout = deadline - _PyTime_GetMonotonicClock();
2533
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002534 /* Possibly retry shutdown until timeout or failure */
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002535 if (err.ssl == SSL_ERROR_WANT_READ)
Victor Stinner14690702015-04-06 22:46:13 +02002536 sockstate = PySSL_select(sock, 0, timeout);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002537 else if (err.ssl == SSL_ERROR_WANT_WRITE)
Victor Stinner14690702015-04-06 22:46:13 +02002538 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002539 else
2540 break;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002541
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002542 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002543 if (err.ssl == SSL_ERROR_WANT_READ)
Christian Heimes03c8ddd2020-11-20 09:26:07 +01002544 PyErr_SetString(PyExc_TimeoutError,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002545 "The read operation timed out");
2546 else
Christian Heimes03c8ddd2020-11-20 09:26:07 +01002547 PyErr_SetString(PyExc_TimeoutError,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002548 "The write operation timed out");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002549 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002550 }
2551 else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02002552 PyErr_SetString(get_state_sock(self)->PySSLErrorObject,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002553 "Underlying socket too large for select().");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002554 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002555 }
2556 else if (sockstate != SOCKET_OPERATION_OK)
2557 /* Retain the SSL error code */
2558 break;
2559 }
Nathaniel J. Smithc0da5822018-09-21 21:44:12 -07002560 if (ret < 0) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002561 Py_XDECREF(sock);
Christian Heimesc7f70692019-05-31 11:44:05 +02002562 PySSL_SetError(self, ret, __FILE__, __LINE__);
2563 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002564 }
Christian Heimesc7f70692019-05-31 11:44:05 +02002565 if (self->exc_type != NULL)
2566 goto error;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002567 if (sock)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002568 /* It's already INCREF'ed */
2569 return (PyObject *) sock;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002570 else
2571 Py_RETURN_NONE;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002572
2573error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002574 Py_XDECREF(sock);
Christian Heimesc7f70692019-05-31 11:44:05 +02002575 PySSL_ChainExceptions(self);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002576 return NULL;
Bill Janssen40a0f662008-08-12 16:56:25 +00002577}
2578
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002579/*[clinic input]
Christian Heimes141c5e82018-02-24 21:10:57 +01002580_ssl._SSLSocket.get_channel_binding
2581 cb_type: str = "tls-unique"
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002582
Christian Heimes141c5e82018-02-24 21:10:57 +01002583Get channel binding data for current connection.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002584
Christian Heimes141c5e82018-02-24 21:10:57 +01002585Raise ValueError if the requested `cb_type` is not supported. Return bytes
2586of the data or None if the data is not available (e.g. before the handshake).
2587Only 'tls-unique' channel binding data from RFC 5929 is supported.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002588[clinic start generated code]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00002589
Antoine Pitroud6494802011-07-21 01:11:30 +02002590static PyObject *
Christian Heimes141c5e82018-02-24 21:10:57 +01002591_ssl__SSLSocket_get_channel_binding_impl(PySSLSocket *self,
2592 const char *cb_type)
2593/*[clinic end generated code: output=34bac9acb6a61d31 input=08b7e43b99c17d41]*/
Antoine Pitroud6494802011-07-21 01:11:30 +02002594{
Antoine Pitroud6494802011-07-21 01:11:30 +02002595 char buf[PySSL_CB_MAXLEN];
Victor Stinner9ee02032013-06-23 15:08:23 +02002596 size_t len;
Antoine Pitroud6494802011-07-21 01:11:30 +02002597
Christian Heimes141c5e82018-02-24 21:10:57 +01002598 if (strcmp(cb_type, "tls-unique") == 0) {
2599 if (SSL_session_reused(self->ssl) ^ !self->socket_type) {
2600 /* if session is resumed XOR we are the client */
2601 len = SSL_get_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2602 }
2603 else {
2604 /* if a new session XOR we are the server */
2605 len = SSL_get_peer_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2606 }
Antoine Pitroud6494802011-07-21 01:11:30 +02002607 }
2608 else {
Christian Heimes141c5e82018-02-24 21:10:57 +01002609 PyErr_Format(
2610 PyExc_ValueError,
2611 "'%s' channel binding type not implemented",
2612 cb_type
2613 );
2614 return NULL;
Antoine Pitroud6494802011-07-21 01:11:30 +02002615 }
2616
2617 /* It cannot be negative in current OpenSSL version as of July 2011 */
Antoine Pitroud6494802011-07-21 01:11:30 +02002618 if (len == 0)
2619 Py_RETURN_NONE;
2620
Christian Heimes141c5e82018-02-24 21:10:57 +01002621 return PyBytes_FromStringAndSize(buf, len);
Antoine Pitroud6494802011-07-21 01:11:30 +02002622}
2623
Christian Heimes9fb051f2018-09-23 08:32:31 +02002624/*[clinic input]
2625_ssl._SSLSocket.verify_client_post_handshake
2626
2627Initiate TLS 1.3 post-handshake authentication
2628[clinic start generated code]*/
2629
2630static PyObject *
2631_ssl__SSLSocket_verify_client_post_handshake_impl(PySSLSocket *self)
2632/*[clinic end generated code: output=532147f3b1341425 input=6bfa874810a3d889]*/
2633{
2634#ifdef TLS1_3_VERSION
2635 int err = SSL_verify_client_post_handshake(self->ssl);
2636 if (err == 0)
Christian Heimes7f1305e2021-04-17 20:06:38 +02002637 return _setSSLError(get_state_sock(self), NULL, 0, __FILE__, __LINE__);
Christian Heimes9fb051f2018-09-23 08:32:31 +02002638 else
2639 Py_RETURN_NONE;
2640#else
2641 PyErr_SetString(PyExc_NotImplementedError,
2642 "Post-handshake auth is not supported by your "
2643 "OpenSSL version.");
2644 return NULL;
2645#endif
2646}
2647
Christian Heimes99a65702016-09-10 23:44:53 +02002648static SSL_SESSION*
2649_ssl_session_dup(SSL_SESSION *session) {
2650 SSL_SESSION *newsession = NULL;
2651 int slen;
2652 unsigned char *senc = NULL, *p;
2653 const unsigned char *const_p;
2654
2655 if (session == NULL) {
2656 PyErr_SetString(PyExc_ValueError, "Invalid session");
2657 goto error;
2658 }
2659
2660 /* get length */
2661 slen = i2d_SSL_SESSION(session, NULL);
2662 if (slen == 0 || slen > 0xFF00) {
2663 PyErr_SetString(PyExc_ValueError, "i2d() failed.");
2664 goto error;
2665 }
2666 if ((senc = PyMem_Malloc(slen)) == NULL) {
2667 PyErr_NoMemory();
2668 goto error;
2669 }
2670 p = senc;
2671 if (!i2d_SSL_SESSION(session, &p)) {
2672 PyErr_SetString(PyExc_ValueError, "i2d() failed.");
2673 goto error;
2674 }
2675 const_p = senc;
2676 newsession = d2i_SSL_SESSION(NULL, &const_p, slen);
2677 if (session == NULL) {
2678 goto error;
2679 }
2680 PyMem_Free(senc);
2681 return newsession;
2682 error:
2683 if (senc != NULL) {
2684 PyMem_Free(senc);
2685 }
2686 return NULL;
2687}
Christian Heimes99a65702016-09-10 23:44:53 +02002688
2689static PyObject *
2690PySSL_get_session(PySSLSocket *self, void *closure) {
2691 /* get_session can return sessions from a server-side connection,
2692 * it does not check for handshake done or client socket. */
2693 PySSLSession *pysess;
2694 SSL_SESSION *session;
2695
Christian Heimes99a65702016-09-10 23:44:53 +02002696 /* duplicate session as workaround for session bug in OpenSSL 1.1.0,
2697 * https://github.com/openssl/openssl/issues/1550 */
2698 session = SSL_get0_session(self->ssl); /* borrowed reference */
2699 if (session == NULL) {
2700 Py_RETURN_NONE;
2701 }
2702 if ((session = _ssl_session_dup(session)) == NULL) {
2703 return NULL;
2704 }
Christian Heimes99a65702016-09-10 23:44:53 +02002705 session = SSL_get1_session(self->ssl);
2706 if (session == NULL) {
2707 Py_RETURN_NONE;
2708 }
Christian Heimes7f1305e2021-04-17 20:06:38 +02002709 pysess = PyObject_GC_New(PySSLSession, self->ctx->state->PySSLSession_Type);
Christian Heimes99a65702016-09-10 23:44:53 +02002710 if (pysess == NULL) {
2711 SSL_SESSION_free(session);
2712 return NULL;
2713 }
2714
2715 assert(self->ctx);
2716 pysess->ctx = self->ctx;
2717 Py_INCREF(pysess->ctx);
2718 pysess->session = session;
Christian Heimesa5d07652016-09-24 10:48:05 +02002719 PyObject_GC_Track(pysess);
Christian Heimes99a65702016-09-10 23:44:53 +02002720 return (PyObject *)pysess;
2721}
2722
2723static int PySSL_set_session(PySSLSocket *self, PyObject *value,
2724 void *closure)
2725 {
2726 PySSLSession *pysess;
Christian Heimes99a65702016-09-10 23:44:53 +02002727 SSL_SESSION *session;
Christian Heimes99a65702016-09-10 23:44:53 +02002728 int result;
2729
Christian Heimes7f1305e2021-04-17 20:06:38 +02002730 if (!Py_IS_TYPE(value, get_state_sock(self)->PySSLSession_Type)) {
Ned Deily4531ec72018-06-11 20:26:28 -04002731 PyErr_SetString(PyExc_TypeError, "Value is not a SSLSession.");
Christian Heimes99a65702016-09-10 23:44:53 +02002732 return -1;
2733 }
2734 pysess = (PySSLSession *)value;
2735
2736 if (self->ctx->ctx != pysess->ctx->ctx) {
2737 PyErr_SetString(PyExc_ValueError,
2738 "Session refers to a different SSLContext.");
2739 return -1;
2740 }
2741 if (self->socket_type != PY_SSL_CLIENT) {
2742 PyErr_SetString(PyExc_ValueError,
2743 "Cannot set session for server-side SSLSocket.");
2744 return -1;
2745 }
Christian Heimes66dc33b2017-05-23 16:02:02 -07002746 if (SSL_is_init_finished(self->ssl)) {
Christian Heimes99a65702016-09-10 23:44:53 +02002747 PyErr_SetString(PyExc_ValueError,
2748 "Cannot set session after handshake.");
2749 return -1;
2750 }
Christian Heimes99a65702016-09-10 23:44:53 +02002751 /* duplicate session */
2752 if ((session = _ssl_session_dup(pysess->session)) == NULL) {
2753 return -1;
2754 }
2755 result = SSL_set_session(self->ssl, session);
2756 /* free duplicate, SSL_set_session() bumps ref count */
2757 SSL_SESSION_free(session);
Christian Heimes99a65702016-09-10 23:44:53 +02002758 if (result == 0) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02002759 _setSSLError(get_state_sock(self), NULL, 0, __FILE__, __LINE__);
Christian Heimes99a65702016-09-10 23:44:53 +02002760 return -1;
2761 }
2762 return 0;
2763}
2764
2765PyDoc_STRVAR(PySSL_set_session_doc,
2766"_setter_session(session)\n\
2767\
2768Get / set SSLSession.");
2769
2770static PyObject *
2771PySSL_get_session_reused(PySSLSocket *self, void *closure) {
2772 if (SSL_session_reused(self->ssl)) {
2773 Py_RETURN_TRUE;
2774 } else {
2775 Py_RETURN_FALSE;
2776 }
2777}
2778
2779PyDoc_STRVAR(PySSL_get_session_reused_doc,
2780"Was the client session reused during handshake?");
2781
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002782static PyGetSetDef ssl_getsetlist[] = {
2783 {"context", (getter) PySSL_get_context,
2784 (setter) PySSL_set_context, PySSL_set_context_doc},
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002785 {"server_side", (getter) PySSL_get_server_side, NULL,
2786 PySSL_get_server_side_doc},
2787 {"server_hostname", (getter) PySSL_get_server_hostname, NULL,
2788 PySSL_get_server_hostname_doc},
2789 {"owner", (getter) PySSL_get_owner, (setter) PySSL_set_owner,
2790 PySSL_get_owner_doc},
Christian Heimes99a65702016-09-10 23:44:53 +02002791 {"session", (getter) PySSL_get_session,
2792 (setter) PySSL_set_session, PySSL_set_session_doc},
2793 {"session_reused", (getter) PySSL_get_session_reused, NULL,
2794 PySSL_get_session_reused_doc},
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002795 {NULL}, /* sentinel */
2796};
2797
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002798static PyMethodDef PySSLMethods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002799 _SSL__SSLSOCKET_DO_HANDSHAKE_METHODDEF
2800 _SSL__SSLSOCKET_WRITE_METHODDEF
2801 _SSL__SSLSOCKET_READ_METHODDEF
2802 _SSL__SSLSOCKET_PENDING_METHODDEF
Christian Heimes141c5e82018-02-24 21:10:57 +01002803 _SSL__SSLSOCKET_GETPEERCERT_METHODDEF
2804 _SSL__SSLSOCKET_GET_CHANNEL_BINDING_METHODDEF
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002805 _SSL__SSLSOCKET_CIPHER_METHODDEF
2806 _SSL__SSLSOCKET_SHARED_CIPHERS_METHODDEF
2807 _SSL__SSLSOCKET_VERSION_METHODDEF
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002808 _SSL__SSLSOCKET_SELECTED_ALPN_PROTOCOL_METHODDEF
2809 _SSL__SSLSOCKET_COMPRESSION_METHODDEF
2810 _SSL__SSLSOCKET_SHUTDOWN_METHODDEF
Christian Heimes9fb051f2018-09-23 08:32:31 +02002811 _SSL__SSLSOCKET_VERIFY_CLIENT_POST_HANDSHAKE_METHODDEF
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002812 {NULL, NULL}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002813};
2814
Christian Heimes5c36da72020-11-20 09:40:12 +01002815static PyType_Slot PySSLSocket_slots[] = {
2816 {Py_tp_methods, PySSLMethods},
2817 {Py_tp_getset, ssl_getsetlist},
2818 {Py_tp_dealloc, PySSL_dealloc},
2819 {Py_tp_traverse, PySSL_traverse},
2820 {Py_tp_clear, PySSL_clear},
2821 {0, 0},
2822};
2823
2824static PyType_Spec PySSLSocket_spec = {
2825 "_ssl._SSLSocket",
2826 sizeof(PySSLSocket),
2827 0,
2828 Py_TPFLAGS_DEFAULT,
2829 PySSLSocket_slots,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002830};
2831
Antoine Pitrou152efa22010-05-16 18:19:27 +00002832/*
2833 * _SSLContext objects
2834 */
2835
Christian Heimes5fe668c2016-09-12 00:01:11 +02002836static int
Christian Heimes9fb051f2018-09-23 08:32:31 +02002837_set_verify_mode(PySSLContext *self, enum py_ssl_cert_requirements n)
Christian Heimes5fe668c2016-09-12 00:01:11 +02002838{
2839 int mode;
2840 int (*verify_cb)(int, X509_STORE_CTX *) = NULL;
2841
2842 switch(n) {
2843 case PY_SSL_CERT_NONE:
2844 mode = SSL_VERIFY_NONE;
2845 break;
2846 case PY_SSL_CERT_OPTIONAL:
2847 mode = SSL_VERIFY_PEER;
2848 break;
2849 case PY_SSL_CERT_REQUIRED:
2850 mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
2851 break;
2852 default:
2853 PyErr_SetString(PyExc_ValueError,
2854 "invalid value for verify_mode");
2855 return -1;
2856 }
Christian Heimesf0f59302019-07-01 08:29:17 +02002857
2858 /* bpo-37428: newPySSLSocket() sets SSL_VERIFY_POST_HANDSHAKE flag for
2859 * server sockets and SSL_set_post_handshake_auth() for client. */
2860
Christian Heimes5fe668c2016-09-12 00:01:11 +02002861 /* keep current verify cb */
Christian Heimes9fb051f2018-09-23 08:32:31 +02002862 verify_cb = SSL_CTX_get_verify_callback(self->ctx);
2863 SSL_CTX_set_verify(self->ctx, mode, verify_cb);
Christian Heimes5fe668c2016-09-12 00:01:11 +02002864 return 0;
2865}
2866
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002867/*[clinic input]
2868@classmethod
2869_ssl._SSLContext.__new__
2870 protocol as proto_version: int
2871 /
2872[clinic start generated code]*/
2873
Antoine Pitrou152efa22010-05-16 18:19:27 +00002874static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002875_ssl__SSLContext_impl(PyTypeObject *type, int proto_version)
2876/*[clinic end generated code: output=2cf0d7a0741b6bd1 input=8d58a805b95fc534]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00002877{
Antoine Pitrou152efa22010-05-16 18:19:27 +00002878 PySSLContext *self;
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01002879 long options;
Christian Heimes2875c602021-04-19 07:27:10 +02002880 const SSL_METHOD *method = NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002881 SSL_CTX *ctx = NULL;
Christian Heimes61d478c2018-01-27 15:51:38 +01002882 X509_VERIFY_PARAM *params;
Christian Heimes358cfd42016-09-10 22:43:48 +02002883 int result;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002884
Christian Heimes7f1305e2021-04-17 20:06:38 +02002885 /* slower approach, walk MRO and get borrowed reference to module.
2886 * _PyType_GetModuleByDef is required for SSLContext subclasses */
2887 PyObject *module = _PyType_GetModuleByDef(type, &_sslmodule_def);
2888 if (module == NULL) {
2889 PyErr_SetString(PyExc_RuntimeError,
2890 "Cannot find internal module state");
2891 return NULL;
2892 }
2893
Christian Heimes6e8cda92020-05-16 03:33:05 +02002894 switch(proto_version) {
2895#if defined(SSL3_VERSION) && !defined(OPENSSL_NO_SSL3)
2896 case PY_SSL_VERSION_SSL3:
Christian Heimes2875c602021-04-19 07:27:10 +02002897 PY_SSL_DEPRECATED("PROTOCOL_SSLv3", 2, NULL);
2898 method = SSLv3_method();
Christian Heimes6e8cda92020-05-16 03:33:05 +02002899 break;
Benjamin Petersone32467c2014-12-05 21:59:35 -05002900#endif
Christian Heimesa871f692020-06-01 08:58:14 +02002901#if (defined(TLS1_VERSION) && \
2902 !defined(OPENSSL_NO_TLS1) && \
2903 !defined(OPENSSL_NO_TLS1_METHOD))
Christian Heimes6e8cda92020-05-16 03:33:05 +02002904 case PY_SSL_VERSION_TLS1:
Christian Heimes2875c602021-04-19 07:27:10 +02002905 PY_SSL_DEPRECATED("PROTOCOL_TLSv1", 2, NULL);
2906 method = TLSv1_method();
Christian Heimes6e8cda92020-05-16 03:33:05 +02002907 break;
Victor Stinner3de49192011-05-09 00:42:58 +02002908#endif
Christian Heimesa871f692020-06-01 08:58:14 +02002909#if (defined(TLS1_1_VERSION) && \
2910 !defined(OPENSSL_NO_TLS1_1) && \
2911 !defined(OPENSSL_NO_TLS1_1_METHOD))
Christian Heimes6e8cda92020-05-16 03:33:05 +02002912 case PY_SSL_VERSION_TLS1_1:
Christian Heimes2875c602021-04-19 07:27:10 +02002913 PY_SSL_DEPRECATED("PROTOCOL_TLSv1_1", 2, NULL);
2914 method = TLSv1_1_method();
Christian Heimes6e8cda92020-05-16 03:33:05 +02002915 break;
2916#endif
Christian Heimesa871f692020-06-01 08:58:14 +02002917#if (defined(TLS1_2_VERSION) && \
2918 !defined(OPENSSL_NO_TLS1_2) && \
2919 !defined(OPENSSL_NO_TLS1_2_METHOD))
Christian Heimes6e8cda92020-05-16 03:33:05 +02002920 case PY_SSL_VERSION_TLS1_2:
Christian Heimes2875c602021-04-19 07:27:10 +02002921 PY_SSL_DEPRECATED("PROTOCOL_TLSv1_2", 2, NULL);
2922 method = TLSv1_2_method();
Christian Heimes6e8cda92020-05-16 03:33:05 +02002923 break;
2924#endif
2925 case PY_SSL_VERSION_TLS:
Christian Heimes2875c602021-04-19 07:27:10 +02002926 PY_SSL_DEPRECATED("PROTOCOL_TLS", 2, NULL);
2927 method = TLS_method();
Christian Heimes6e8cda92020-05-16 03:33:05 +02002928 break;
2929 case PY_SSL_VERSION_TLS_CLIENT:
Christian Heimes2875c602021-04-19 07:27:10 +02002930 method = TLS_client_method();
Christian Heimes6e8cda92020-05-16 03:33:05 +02002931 break;
2932 case PY_SSL_VERSION_TLS_SERVER:
Christian Heimes2875c602021-04-19 07:27:10 +02002933 method = TLS_server_method();
Christian Heimes6e8cda92020-05-16 03:33:05 +02002934 break;
2935 default:
Christian Heimes2875c602021-04-19 07:27:10 +02002936 method = NULL;
Christian Heimes6e8cda92020-05-16 03:33:05 +02002937 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002938
Christian Heimes2875c602021-04-19 07:27:10 +02002939 if (method == NULL) {
2940 PyErr_Format(PyExc_ValueError,
2941 "invalid or unsupported protocol version %i",
2942 proto_version);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002943 return NULL;
2944 }
Christian Heimes2875c602021-04-19 07:27:10 +02002945
2946 PySSL_BEGIN_ALLOW_THREADS
2947 ctx = SSL_CTX_new(method);
2948 PySSL_END_ALLOW_THREADS
2949
Antoine Pitrou152efa22010-05-16 18:19:27 +00002950 if (ctx == NULL) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02002951 _setSSLError(get_ssl_state(module), NULL, 0, __FILE__, __LINE__);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002952 return NULL;
2953 }
2954
2955 assert(type != NULL && type->tp_alloc != NULL);
2956 self = (PySSLContext *) type->tp_alloc(type, 0);
2957 if (self == NULL) {
2958 SSL_CTX_free(ctx);
2959 return NULL;
2960 }
2961 self->ctx = ctx;
Christian Heimes61d478c2018-01-27 15:51:38 +01002962 self->hostflags = X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS;
Christian Heimes11a14932018-02-24 02:35:08 +01002963 self->protocol = proto_version;
Christian Heimesc7f70692019-05-31 11:44:05 +02002964 self->msg_cb = NULL;
Christian Heimesc7f70692019-05-31 11:44:05 +02002965 self->keylog_filename = NULL;
2966 self->keylog_bio = NULL;
Benjamin Petersoncca27322015-01-23 16:35:37 -05002967 self->alpn_protocols = NULL;
Christian Heimes11a14932018-02-24 02:35:08 +01002968 self->set_sni_cb = NULL;
Christian Heimes7f1305e2021-04-17 20:06:38 +02002969 self->state = get_ssl_state(module);
2970
Christian Heimes1aa9a752013-12-02 02:41:19 +01002971 /* Don't check host name by default */
Christian Heimes5fe668c2016-09-12 00:01:11 +02002972 if (proto_version == PY_SSL_VERSION_TLS_CLIENT) {
2973 self->check_hostname = 1;
Christian Heimes9fb051f2018-09-23 08:32:31 +02002974 if (_set_verify_mode(self, PY_SSL_CERT_REQUIRED) == -1) {
Christian Heimes5fe668c2016-09-12 00:01:11 +02002975 Py_DECREF(self);
2976 return NULL;
2977 }
2978 } else {
2979 self->check_hostname = 0;
Christian Heimes9fb051f2018-09-23 08:32:31 +02002980 if (_set_verify_mode(self, PY_SSL_CERT_NONE) == -1) {
Christian Heimes5fe668c2016-09-12 00:01:11 +02002981 Py_DECREF(self);
2982 return NULL;
2983 }
2984 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002985 /* Defaults */
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01002986 options = SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
2987 if (proto_version != PY_SSL_VERSION_SSL2)
2988 options |= SSL_OP_NO_SSLv2;
Benjamin Petersona9dcdab2015-11-11 22:38:41 -08002989 if (proto_version != PY_SSL_VERSION_SSL3)
2990 options |= SSL_OP_NO_SSLv3;
Christian Heimes358cfd42016-09-10 22:43:48 +02002991 /* Minimal security flags for server and client side context.
2992 * Client sockets ignore server-side parameters. */
2993#ifdef SSL_OP_NO_COMPRESSION
2994 options |= SSL_OP_NO_COMPRESSION;
2995#endif
2996#ifdef SSL_OP_CIPHER_SERVER_PREFERENCE
2997 options |= SSL_OP_CIPHER_SERVER_PREFERENCE;
2998#endif
2999#ifdef SSL_OP_SINGLE_DH_USE
3000 options |= SSL_OP_SINGLE_DH_USE;
3001#endif
3002#ifdef SSL_OP_SINGLE_ECDH_USE
3003 options |= SSL_OP_SINGLE_ECDH_USE;
3004#endif
Christian Heimes6f37ebc2021-04-09 17:59:21 +02003005#ifdef SSL_OP_IGNORE_UNEXPECTED_EOF
3006 /* Make OpenSSL 3.0.0 behave like 1.1.1 */
3007 options |= SSL_OP_IGNORE_UNEXPECTED_EOF;
3008#endif
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01003009 SSL_CTX_set_options(self->ctx, options);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003010
Semen Zhydenko1295e112017-10-15 21:28:31 +02003011 /* A bare minimum cipher list without completely broken cipher suites.
Christian Heimes358cfd42016-09-10 22:43:48 +02003012 * It's far from perfect but gives users a better head start. */
3013 if (proto_version != PY_SSL_VERSION_SSL2) {
Christian Heimes892d66e2018-01-29 14:10:18 +01003014#if PY_SSL_DEFAULT_CIPHERS == 2
3015 /* stick to OpenSSL's default settings */
3016 result = 1;
3017#else
3018 result = SSL_CTX_set_cipher_list(ctx, PY_SSL_DEFAULT_CIPHER_STRING);
3019#endif
Christian Heimes358cfd42016-09-10 22:43:48 +02003020 } else {
3021 /* SSLv2 needs MD5 */
3022 result = SSL_CTX_set_cipher_list(ctx, "HIGH:!aNULL:!eNULL");
3023 }
3024 if (result == 0) {
3025 Py_DECREF(self);
3026 ERR_clear_error();
Christian Heimes7f1305e2021-04-17 20:06:38 +02003027 PyErr_SetString(get_state_ctx(self)->PySSLErrorObject,
Christian Heimes358cfd42016-09-10 22:43:48 +02003028 "No cipher can be selected.");
3029 return NULL;
3030 }
3031
Benjamin Peterson3b1a8b32016-01-07 21:37:37 -08003032 /* Set SSL_MODE_RELEASE_BUFFERS. This potentially greatly reduces memory
Christian Heimes39258d32021-04-17 11:36:35 +02003033 usage for no cost at all. */
3034 SSL_CTX_set_mode(self->ctx, SSL_MODE_RELEASE_BUFFERS);
Antoine Pitrou0bebbc32014-03-22 18:13:50 +01003035
Antoine Pitroufc113ee2010-10-13 12:46:13 +00003036#define SID_CTX "Python"
3037 SSL_CTX_set_session_id_context(self->ctx, (const unsigned char *) SID_CTX,
3038 sizeof(SID_CTX));
3039#undef SID_CTX
3040
Christian Heimes61d478c2018-01-27 15:51:38 +01003041 params = SSL_CTX_get0_param(self->ctx);
Christian Heimes61d478c2018-01-27 15:51:38 +01003042 /* Improve trust chain building when cross-signed intermediate
3043 certificates are present. See https://bugs.python.org/issue23476. */
3044 X509_VERIFY_PARAM_set_flags(params, X509_V_FLAG_TRUSTED_FIRST);
Christian Heimes61d478c2018-01-27 15:51:38 +01003045 X509_VERIFY_PARAM_set_hostflags(params, self->hostflags);
Benjamin Petersonfdb19712015-03-04 22:11:12 -05003046
Christian Heimes9fb051f2018-09-23 08:32:31 +02003047#ifdef TLS1_3_VERSION
3048 self->post_handshake_auth = 0;
3049 SSL_CTX_set_post_handshake_auth(self->ctx, self->post_handshake_auth);
3050#endif
3051
Antoine Pitrou152efa22010-05-16 18:19:27 +00003052 return (PyObject *)self;
3053}
3054
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003055static int
3056context_traverse(PySSLContext *self, visitproc visit, void *arg)
3057{
Christian Heimes11a14932018-02-24 02:35:08 +01003058 Py_VISIT(self->set_sni_cb);
Christian Heimesc7f70692019-05-31 11:44:05 +02003059 Py_VISIT(self->msg_cb);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003060 return 0;
3061}
3062
3063static int
3064context_clear(PySSLContext *self)
3065{
Christian Heimes11a14932018-02-24 02:35:08 +01003066 Py_CLEAR(self->set_sni_cb);
Christian Heimesc7f70692019-05-31 11:44:05 +02003067 Py_CLEAR(self->msg_cb);
Christian Heimesc7f70692019-05-31 11:44:05 +02003068 Py_CLEAR(self->keylog_filename);
3069 if (self->keylog_bio != NULL) {
3070 PySSL_BEGIN_ALLOW_THREADS
3071 BIO_free_all(self->keylog_bio);
3072 PySSL_END_ALLOW_THREADS
3073 self->keylog_bio = NULL;
3074 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003075 return 0;
3076}
3077
Antoine Pitrou152efa22010-05-16 18:19:27 +00003078static void
3079context_dealloc(PySSLContext *self)
3080{
Christian Heimes5c36da72020-11-20 09:40:12 +01003081 PyTypeObject *tp = Py_TYPE(self);
INADA Naokia6296d32017-08-24 14:55:17 +09003082 /* bpo-31095: UnTrack is needed before calling any callbacks */
3083 PyObject_GC_UnTrack(self);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003084 context_clear(self);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003085 SSL_CTX_free(self->ctx);
Christian Heimes39258d32021-04-17 11:36:35 +02003086 PyMem_FREE(self->alpn_protocols);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003087 Py_TYPE(self)->tp_free(self);
Christian Heimes5c36da72020-11-20 09:40:12 +01003088 Py_DECREF(tp);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003089}
3090
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003091/*[clinic input]
3092_ssl._SSLContext.set_ciphers
3093 cipherlist: str
3094 /
3095[clinic start generated code]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003096
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003097static PyObject *
3098_ssl__SSLContext_set_ciphers_impl(PySSLContext *self, const char *cipherlist)
3099/*[clinic end generated code: output=3a3162f3557c0f3f input=a7ac931b9f3ca7fc]*/
3100{
3101 int ret = SSL_CTX_set_cipher_list(self->ctx, cipherlist);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003102 if (ret == 0) {
Antoine Pitrou65ec8ae2010-05-16 19:56:32 +00003103 /* Clearing the error queue is necessary on some OpenSSL versions,
3104 otherwise the error will be reported again when another SSL call
3105 is done. */
3106 ERR_clear_error();
Christian Heimes7f1305e2021-04-17 20:06:38 +02003107 PyErr_SetString(get_state_ctx(self)->PySSLErrorObject,
Antoine Pitrou152efa22010-05-16 18:19:27 +00003108 "No cipher can be selected.");
3109 return NULL;
3110 }
3111 Py_RETURN_NONE;
3112}
3113
Christian Heimes25bfcd52016-09-06 00:04:45 +02003114/*[clinic input]
3115_ssl._SSLContext.get_ciphers
3116[clinic start generated code]*/
3117
3118static PyObject *
3119_ssl__SSLContext_get_ciphers_impl(PySSLContext *self)
3120/*[clinic end generated code: output=a56e4d68a406dfc4 input=a2aadc9af89b79c5]*/
3121{
3122 SSL *ssl = NULL;
3123 STACK_OF(SSL_CIPHER) *sk = NULL;
Christian Heimes99a65702016-09-10 23:44:53 +02003124 const SSL_CIPHER *cipher;
Christian Heimes25bfcd52016-09-06 00:04:45 +02003125 int i=0;
3126 PyObject *result = NULL, *dct;
3127
3128 ssl = SSL_new(self->ctx);
3129 if (ssl == NULL) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02003130 _setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
Christian Heimes25bfcd52016-09-06 00:04:45 +02003131 goto exit;
3132 }
3133 sk = SSL_get_ciphers(ssl);
3134
3135 result = PyList_New(sk_SSL_CIPHER_num(sk));
3136 if (result == NULL) {
3137 goto exit;
3138 }
3139
3140 for (i = 0; i < sk_SSL_CIPHER_num(sk); i++) {
3141 cipher = sk_SSL_CIPHER_value(sk, i);
3142 dct = cipher_to_dict(cipher);
3143 if (dct == NULL) {
3144 Py_CLEAR(result);
3145 goto exit;
3146 }
3147 PyList_SET_ITEM(result, i, dct);
3148 }
3149
3150 exit:
3151 if (ssl != NULL)
3152 SSL_free(ssl);
3153 return result;
3154
3155}
Christian Heimes25bfcd52016-09-06 00:04:45 +02003156
3157
Benjamin Petersoncca27322015-01-23 16:35:37 -05003158static int
Benjamin Peterson88615022015-01-23 17:30:26 -05003159do_protocol_selection(int alpn, unsigned char **out, unsigned char *outlen,
3160 const unsigned char *server_protocols, unsigned int server_protocols_len,
3161 const unsigned char *client_protocols, unsigned int client_protocols_len)
Benjamin Petersoncca27322015-01-23 16:35:37 -05003162{
Benjamin Peterson88615022015-01-23 17:30:26 -05003163 int ret;
3164 if (client_protocols == NULL) {
3165 client_protocols = (unsigned char *)"";
3166 client_protocols_len = 0;
3167 }
3168 if (server_protocols == NULL) {
3169 server_protocols = (unsigned char *)"";
3170 server_protocols_len = 0;
Benjamin Petersoncca27322015-01-23 16:35:37 -05003171 }
3172
Benjamin Peterson88615022015-01-23 17:30:26 -05003173 ret = SSL_select_next_proto(out, outlen,
3174 server_protocols, server_protocols_len,
3175 client_protocols, client_protocols_len);
3176 if (alpn && ret != OPENSSL_NPN_NEGOTIATED)
3177 return SSL_TLSEXT_ERR_NOACK;
Benjamin Petersoncca27322015-01-23 16:35:37 -05003178
3179 return SSL_TLSEXT_ERR_OK;
3180}
3181
Benjamin Petersoncca27322015-01-23 16:35:37 -05003182static int
3183_selectALPN_cb(SSL *s,
3184 const unsigned char **out, unsigned char *outlen,
3185 const unsigned char *client_protocols, unsigned int client_protocols_len,
3186 void *args)
3187{
3188 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Peterson88615022015-01-23 17:30:26 -05003189 return do_protocol_selection(1, (unsigned char **)out, outlen,
3190 ctx->alpn_protocols, ctx->alpn_protocols_len,
3191 client_protocols, client_protocols_len);
Benjamin Petersoncca27322015-01-23 16:35:37 -05003192}
Benjamin Petersoncca27322015-01-23 16:35:37 -05003193
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003194/*[clinic input]
3195_ssl._SSLContext._set_alpn_protocols
3196 protos: Py_buffer
3197 /
3198[clinic start generated code]*/
3199
Benjamin Petersoncca27322015-01-23 16:35:37 -05003200static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003201_ssl__SSLContext__set_alpn_protocols_impl(PySSLContext *self,
3202 Py_buffer *protos)
3203/*[clinic end generated code: output=87599a7f76651a9b input=9bba964595d519be]*/
Benjamin Petersoncca27322015-01-23 16:35:37 -05003204{
Victor Stinner5a615592017-09-14 01:10:30 -07003205 if ((size_t)protos->len > UINT_MAX) {
Segev Finer5cff6372017-07-27 01:19:17 +03003206 PyErr_Format(PyExc_OverflowError,
Serhiy Storchakad53fe5f2019-03-13 22:59:55 +02003207 "protocols longer than %u bytes", UINT_MAX);
Segev Finer5cff6372017-07-27 01:19:17 +03003208 return NULL;
3209 }
3210
Victor Stinner00d7abd2020-12-01 09:56:42 +01003211 PyMem_Free(self->alpn_protocols);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003212 self->alpn_protocols = PyMem_Malloc(protos->len);
Benjamin Petersoncca27322015-01-23 16:35:37 -05003213 if (!self->alpn_protocols)
3214 return PyErr_NoMemory();
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003215 memcpy(self->alpn_protocols, protos->buf, protos->len);
Segev Finer5cff6372017-07-27 01:19:17 +03003216 self->alpn_protocols_len = (unsigned int)protos->len;
Benjamin Petersoncca27322015-01-23 16:35:37 -05003217
3218 if (SSL_CTX_set_alpn_protos(self->ctx, self->alpn_protocols, self->alpn_protocols_len))
3219 return PyErr_NoMemory();
3220 SSL_CTX_set_alpn_select_cb(self->ctx, _selectALPN_cb, self);
3221
Benjamin Petersoncca27322015-01-23 16:35:37 -05003222 Py_RETURN_NONE;
Benjamin Petersoncca27322015-01-23 16:35:37 -05003223}
3224
Antoine Pitrou152efa22010-05-16 18:19:27 +00003225static PyObject *
3226get_verify_mode(PySSLContext *self, void *c)
3227{
Christian Heimes9fb051f2018-09-23 08:32:31 +02003228 /* ignore SSL_VERIFY_CLIENT_ONCE and SSL_VERIFY_POST_HANDSHAKE */
3229 int mask = (SSL_VERIFY_NONE | SSL_VERIFY_PEER |
3230 SSL_VERIFY_FAIL_IF_NO_PEER_CERT);
3231 switch (SSL_CTX_get_verify_mode(self->ctx) & mask) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003232 case SSL_VERIFY_NONE:
3233 return PyLong_FromLong(PY_SSL_CERT_NONE);
3234 case SSL_VERIFY_PEER:
3235 return PyLong_FromLong(PY_SSL_CERT_OPTIONAL);
3236 case SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT:
3237 return PyLong_FromLong(PY_SSL_CERT_REQUIRED);
3238 }
Christian Heimes7f1305e2021-04-17 20:06:38 +02003239 PyErr_SetString(get_state_ctx(self)->PySSLErrorObject,
Antoine Pitrou152efa22010-05-16 18:19:27 +00003240 "invalid return value from SSL_CTX_get_verify_mode");
3241 return NULL;
3242}
3243
3244static int
3245set_verify_mode(PySSLContext *self, PyObject *arg, void *c)
3246{
Christian Heimes5fe668c2016-09-12 00:01:11 +02003247 int n;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003248 if (!PyArg_Parse(arg, "i", &n))
3249 return -1;
Christian Heimes5fe668c2016-09-12 00:01:11 +02003250 if (n == PY_SSL_CERT_NONE && self->check_hostname) {
Christian Heimes1aa9a752013-12-02 02:41:19 +01003251 PyErr_SetString(PyExc_ValueError,
3252 "Cannot set verify_mode to CERT_NONE when "
3253 "check_hostname is enabled.");
3254 return -1;
3255 }
Christian Heimes9fb051f2018-09-23 08:32:31 +02003256 return _set_verify_mode(self, n);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003257}
3258
3259static PyObject *
Christian Heimes22587792013-11-21 23:56:13 +01003260get_verify_flags(PySSLContext *self, void *c)
3261{
Christian Heimes598894f2016-09-05 23:19:05 +02003262 X509_VERIFY_PARAM *param;
Christian Heimes22587792013-11-21 23:56:13 +01003263 unsigned long flags;
3264
Christian Heimes61d478c2018-01-27 15:51:38 +01003265 param = SSL_CTX_get0_param(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02003266 flags = X509_VERIFY_PARAM_get_flags(param);
Christian Heimes22587792013-11-21 23:56:13 +01003267 return PyLong_FromUnsignedLong(flags);
3268}
3269
3270static int
3271set_verify_flags(PySSLContext *self, PyObject *arg, void *c)
3272{
Christian Heimes598894f2016-09-05 23:19:05 +02003273 X509_VERIFY_PARAM *param;
Christian Heimes22587792013-11-21 23:56:13 +01003274 unsigned long new_flags, flags, set, clear;
3275
3276 if (!PyArg_Parse(arg, "k", &new_flags))
3277 return -1;
Christian Heimes61d478c2018-01-27 15:51:38 +01003278 param = SSL_CTX_get0_param(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02003279 flags = X509_VERIFY_PARAM_get_flags(param);
Christian Heimes22587792013-11-21 23:56:13 +01003280 clear = flags & ~new_flags;
3281 set = ~flags & new_flags;
3282 if (clear) {
Christian Heimes598894f2016-09-05 23:19:05 +02003283 if (!X509_VERIFY_PARAM_clear_flags(param, clear)) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02003284 _setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
Christian Heimes22587792013-11-21 23:56:13 +01003285 return -1;
3286 }
3287 }
3288 if (set) {
Christian Heimes598894f2016-09-05 23:19:05 +02003289 if (!X509_VERIFY_PARAM_set_flags(param, set)) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02003290 _setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
Christian Heimes22587792013-11-21 23:56:13 +01003291 return -1;
3292 }
3293 }
3294 return 0;
3295}
3296
Christian Heimes698dde12018-02-27 11:54:43 +01003297/* Getter and setter for protocol version */
Christian Heimes698dde12018-02-27 11:54:43 +01003298static int
3299set_min_max_proto_version(PySSLContext *self, PyObject *arg, int what)
3300{
3301 long v;
3302 int result;
3303
3304 if (!PyArg_Parse(arg, "l", &v))
3305 return -1;
3306 if (v > INT_MAX) {
3307 PyErr_SetString(PyExc_OverflowError, "Option is too long");
3308 return -1;
3309 }
3310
3311 switch(self->protocol) {
3312 case PY_SSL_VERSION_TLS_CLIENT: /* fall through */
3313 case PY_SSL_VERSION_TLS_SERVER: /* fall through */
3314 case PY_SSL_VERSION_TLS:
3315 break;
3316 default:
3317 PyErr_SetString(
3318 PyExc_ValueError,
3319 "The context's protocol doesn't support modification of "
3320 "highest and lowest version."
3321 );
3322 return -1;
3323 }
3324
Christian Heimes2875c602021-04-19 07:27:10 +02003325 /* check for deprecations and supported values */
3326 switch(v) {
3327 case PY_PROTO_SSLv3:
3328 PY_SSL_DEPRECATED("TLSVersion.SSLv3", 2, -1);
3329 break;
3330 case PY_PROTO_TLSv1:
3331 PY_SSL_DEPRECATED("TLSVersion.TLSv1", 2, -1);
3332 break;
3333 case PY_PROTO_TLSv1_1:
3334 PY_SSL_DEPRECATED("TLSVersion.TLSv1_1", 2, -1);
3335 break;
3336 case PY_PROTO_MINIMUM_SUPPORTED:
3337 case PY_PROTO_MAXIMUM_SUPPORTED:
3338 case PY_PROTO_TLSv1_2:
3339 case PY_PROTO_TLSv1_3:
3340 /* ok */
3341 break;
3342 default:
3343 PyErr_Format(PyExc_ValueError,
3344 "Unsupported TLS/SSL version 0x%x", v);
3345 return -1;
3346 }
3347
Christian Heimes698dde12018-02-27 11:54:43 +01003348 if (what == 0) {
3349 switch(v) {
3350 case PY_PROTO_MINIMUM_SUPPORTED:
3351 v = 0;
3352 break;
3353 case PY_PROTO_MAXIMUM_SUPPORTED:
3354 /* Emulate max for set_min_proto_version */
3355 v = PY_PROTO_MAXIMUM_AVAILABLE;
3356 break;
3357 default:
3358 break;
3359 }
3360 result = SSL_CTX_set_min_proto_version(self->ctx, v);
3361 }
3362 else {
3363 switch(v) {
3364 case PY_PROTO_MAXIMUM_SUPPORTED:
3365 v = 0;
3366 break;
3367 case PY_PROTO_MINIMUM_SUPPORTED:
3368 /* Emulate max for set_min_proto_version */
3369 v = PY_PROTO_MINIMUM_AVAILABLE;
3370 break;
3371 default:
3372 break;
3373 }
3374 result = SSL_CTX_set_max_proto_version(self->ctx, v);
3375 }
3376 if (result == 0) {
3377 PyErr_Format(PyExc_ValueError,
3378 "Unsupported protocol version 0x%x", v);
3379 return -1;
3380 }
3381 return 0;
3382}
3383
3384static PyObject *
3385get_minimum_version(PySSLContext *self, void *c)
3386{
3387 int v = SSL_CTX_ctrl(self->ctx, SSL_CTRL_GET_MIN_PROTO_VERSION, 0, NULL);
3388 if (v == 0) {
3389 v = PY_PROTO_MINIMUM_SUPPORTED;
3390 }
3391 return PyLong_FromLong(v);
3392}
3393
3394static int
3395set_minimum_version(PySSLContext *self, PyObject *arg, void *c)
3396{
3397 return set_min_max_proto_version(self, arg, 0);
3398}
3399
3400static PyObject *
3401get_maximum_version(PySSLContext *self, void *c)
3402{
3403 int v = SSL_CTX_ctrl(self->ctx, SSL_CTRL_GET_MAX_PROTO_VERSION, 0, NULL);
3404 if (v == 0) {
3405 v = PY_PROTO_MAXIMUM_SUPPORTED;
3406 }
3407 return PyLong_FromLong(v);
3408}
3409
3410static int
3411set_maximum_version(PySSLContext *self, PyObject *arg, void *c)
3412{
3413 return set_min_max_proto_version(self, arg, 1);
3414}
Christian Heimes698dde12018-02-27 11:54:43 +01003415
Christian Heimes39258d32021-04-17 11:36:35 +02003416#ifdef TLS1_3_VERSION
Christian Heimes78c7d522019-06-03 21:00:10 +02003417static PyObject *
3418get_num_tickets(PySSLContext *self, void *c)
3419{
Victor Stinner76611c72019-07-09 13:30:52 +02003420 return PyLong_FromSize_t(SSL_CTX_get_num_tickets(self->ctx));
Christian Heimes78c7d522019-06-03 21:00:10 +02003421}
3422
3423static int
3424set_num_tickets(PySSLContext *self, PyObject *arg, void *c)
3425{
3426 long num;
3427 if (!PyArg_Parse(arg, "l", &num))
3428 return -1;
3429 if (num < 0) {
3430 PyErr_SetString(PyExc_ValueError, "value must be non-negative");
3431 return -1;
3432 }
3433 if (self->protocol != PY_SSL_VERSION_TLS_SERVER) {
3434 PyErr_SetString(PyExc_ValueError,
3435 "SSLContext is not a server context.");
3436 return -1;
3437 }
3438 if (SSL_CTX_set_num_tickets(self->ctx, num) != 1) {
3439 PyErr_SetString(PyExc_ValueError, "failed to set num tickets.");
3440 return -1;
3441 }
3442 return 0;
3443}
3444
3445PyDoc_STRVAR(PySSLContext_num_tickets_doc,
3446"Control the number of TLSv1.3 session tickets");
Christian Heimes39258d32021-04-17 11:36:35 +02003447#endif /* TLS1_3_VERSION */
Christian Heimes78c7d522019-06-03 21:00:10 +02003448
matthewhughes9348e836bb2020-07-17 09:59:15 +01003449static PyObject *
3450get_security_level(PySSLContext *self, void *c)
3451{
3452 return PyLong_FromLong(SSL_CTX_get_security_level(self->ctx));
3453}
3454PyDoc_STRVAR(PySSLContext_security_level_doc, "The current security level");
matthewhughes9348e836bb2020-07-17 09:59:15 +01003455
Christian Heimes22587792013-11-21 23:56:13 +01003456static PyObject *
Antoine Pitroub5218772010-05-21 09:56:06 +00003457get_options(PySSLContext *self, void *c)
3458{
3459 return PyLong_FromLong(SSL_CTX_get_options(self->ctx));
3460}
3461
3462static int
3463set_options(PySSLContext *self, PyObject *arg, void *c)
3464{
3465 long new_opts, opts, set, clear;
Christian Heimes2875c602021-04-19 07:27:10 +02003466 long opt_no = (
3467 SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1 |
3468 SSL_OP_NO_TLSv1_1 | SSL_OP_NO_TLSv1_2 | SSL_OP_NO_TLSv1_2
3469 );
3470
Antoine Pitroub5218772010-05-21 09:56:06 +00003471 if (!PyArg_Parse(arg, "l", &new_opts))
3472 return -1;
3473 opts = SSL_CTX_get_options(self->ctx);
3474 clear = opts & ~new_opts;
3475 set = ~opts & new_opts;
Christian Heimes2875c602021-04-19 07:27:10 +02003476
3477 if ((set & opt_no) != 0) {
3478 if (_ssl_deprecated("Setting OP_NO_SSL* or SSL_NO_TLS* options is "
3479 "deprecated", 2) < 0) {
3480 return -1;
3481 }
3482 }
Antoine Pitroub5218772010-05-21 09:56:06 +00003483 if (clear) {
Antoine Pitroub5218772010-05-21 09:56:06 +00003484 SSL_CTX_clear_options(self->ctx, clear);
Antoine Pitroub5218772010-05-21 09:56:06 +00003485 }
3486 if (set)
3487 SSL_CTX_set_options(self->ctx, set);
3488 return 0;
3489}
3490
Christian Heimes1aa9a752013-12-02 02:41:19 +01003491static PyObject *
Christian Heimes61d478c2018-01-27 15:51:38 +01003492get_host_flags(PySSLContext *self, void *c)
3493{
3494 return PyLong_FromUnsignedLong(self->hostflags);
3495}
3496
3497static int
3498set_host_flags(PySSLContext *self, PyObject *arg, void *c)
3499{
3500 X509_VERIFY_PARAM *param;
3501 unsigned int new_flags = 0;
3502
3503 if (!PyArg_Parse(arg, "I", &new_flags))
3504 return -1;
3505
3506 param = SSL_CTX_get0_param(self->ctx);
3507 self->hostflags = new_flags;
3508 X509_VERIFY_PARAM_set_hostflags(param, new_flags);
3509 return 0;
3510}
3511
3512static PyObject *
Christian Heimes1aa9a752013-12-02 02:41:19 +01003513get_check_hostname(PySSLContext *self, void *c)
3514{
3515 return PyBool_FromLong(self->check_hostname);
3516}
3517
3518static int
3519set_check_hostname(PySSLContext *self, PyObject *arg, void *c)
3520{
3521 int check_hostname;
3522 if (!PyArg_Parse(arg, "p", &check_hostname))
3523 return -1;
3524 if (check_hostname &&
3525 SSL_CTX_get_verify_mode(self->ctx) == SSL_VERIFY_NONE) {
Christian Heimese82c0342017-09-15 20:29:57 +02003526 /* check_hostname = True sets verify_mode = CERT_REQUIRED */
Christian Heimes9fb051f2018-09-23 08:32:31 +02003527 if (_set_verify_mode(self, PY_SSL_CERT_REQUIRED) == -1) {
Christian Heimese82c0342017-09-15 20:29:57 +02003528 return -1;
3529 }
Christian Heimes1aa9a752013-12-02 02:41:19 +01003530 }
3531 self->check_hostname = check_hostname;
3532 return 0;
3533}
3534
Christian Heimes11a14932018-02-24 02:35:08 +01003535static PyObject *
Christian Heimes9fb051f2018-09-23 08:32:31 +02003536get_post_handshake_auth(PySSLContext *self, void *c) {
3537#if TLS1_3_VERSION
3538 return PyBool_FromLong(self->post_handshake_auth);
3539#else
3540 Py_RETURN_NONE;
3541#endif
3542}
3543
3544#if TLS1_3_VERSION
3545static int
3546set_post_handshake_auth(PySSLContext *self, PyObject *arg, void *c) {
Zackery Spytz842acaa2018-12-17 07:52:45 -07003547 if (arg == NULL) {
3548 PyErr_SetString(PyExc_AttributeError, "cannot delete attribute");
3549 return -1;
3550 }
Christian Heimes9fb051f2018-09-23 08:32:31 +02003551 int pha = PyObject_IsTrue(arg);
3552
3553 if (pha == -1) {
3554 return -1;
3555 }
3556 self->post_handshake_auth = pha;
3557
Christian Heimesf0f59302019-07-01 08:29:17 +02003558 /* bpo-37428: newPySSLSocket() sets SSL_VERIFY_POST_HANDSHAKE flag for
3559 * server sockets and SSL_set_post_handshake_auth() for client. */
Christian Heimes9fb051f2018-09-23 08:32:31 +02003560
3561 return 0;
3562}
3563#endif
3564
3565static PyObject *
Christian Heimes11a14932018-02-24 02:35:08 +01003566get_protocol(PySSLContext *self, void *c) {
3567 return PyLong_FromLong(self->protocol);
3568}
Christian Heimes1aa9a752013-12-02 02:41:19 +01003569
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003570typedef struct {
3571 PyThreadState *thread_state;
3572 PyObject *callable;
3573 char *password;
Victor Stinner9ee02032013-06-23 15:08:23 +02003574 int size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003575 int error;
3576} _PySSLPasswordInfo;
3577
3578static int
3579_pwinfo_set(_PySSLPasswordInfo *pw_info, PyObject* password,
3580 const char *bad_type_error)
3581{
3582 /* Set the password and size fields of a _PySSLPasswordInfo struct
3583 from a unicode, bytes, or byte array object.
3584 The password field will be dynamically allocated and must be freed
3585 by the caller */
3586 PyObject *password_bytes = NULL;
3587 const char *data = NULL;
3588 Py_ssize_t size;
3589
3590 if (PyUnicode_Check(password)) {
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03003591 password_bytes = PyUnicode_AsUTF8String(password);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003592 if (!password_bytes) {
3593 goto error;
3594 }
3595 data = PyBytes_AS_STRING(password_bytes);
3596 size = PyBytes_GET_SIZE(password_bytes);
3597 } else if (PyBytes_Check(password)) {
3598 data = PyBytes_AS_STRING(password);
3599 size = PyBytes_GET_SIZE(password);
3600 } else if (PyByteArray_Check(password)) {
3601 data = PyByteArray_AS_STRING(password);
3602 size = PyByteArray_GET_SIZE(password);
3603 } else {
3604 PyErr_SetString(PyExc_TypeError, bad_type_error);
3605 goto error;
3606 }
3607
Victor Stinner9ee02032013-06-23 15:08:23 +02003608 if (size > (Py_ssize_t)INT_MAX) {
3609 PyErr_Format(PyExc_ValueError,
3610 "password cannot be longer than %d bytes", INT_MAX);
3611 goto error;
3612 }
3613
Victor Stinner11ebff22013-07-07 17:07:52 +02003614 PyMem_Free(pw_info->password);
3615 pw_info->password = PyMem_Malloc(size);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003616 if (!pw_info->password) {
3617 PyErr_SetString(PyExc_MemoryError,
3618 "unable to allocate password buffer");
3619 goto error;
3620 }
3621 memcpy(pw_info->password, data, size);
Victor Stinner9ee02032013-06-23 15:08:23 +02003622 pw_info->size = (int)size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003623
3624 Py_XDECREF(password_bytes);
3625 return 1;
3626
3627error:
3628 Py_XDECREF(password_bytes);
3629 return 0;
3630}
3631
3632static int
3633_password_callback(char *buf, int size, int rwflag, void *userdata)
3634{
3635 _PySSLPasswordInfo *pw_info = (_PySSLPasswordInfo*) userdata;
3636 PyObject *fn_ret = NULL;
3637
3638 PySSL_END_ALLOW_THREADS_S(pw_info->thread_state);
3639
Christian Heimesd3b73f32021-04-09 15:23:38 +02003640 if (pw_info->error) {
3641 /* already failed previously. OpenSSL 3.0.0-alpha14 invokes the
3642 * callback multiple times which can lead to fatal Python error in
3643 * exception check. */
3644 goto error;
3645 }
3646
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003647 if (pw_info->callable) {
Victor Stinnerf17c3de2016-12-06 18:46:19 +01003648 fn_ret = _PyObject_CallNoArg(pw_info->callable);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003649 if (!fn_ret) {
3650 /* TODO: It would be nice to move _ctypes_add_traceback() into the
3651 core python API, so we could use it to add a frame here */
3652 goto error;
3653 }
3654
3655 if (!_pwinfo_set(pw_info, fn_ret,
3656 "password callback must return a string")) {
3657 goto error;
3658 }
3659 Py_CLEAR(fn_ret);
3660 }
3661
3662 if (pw_info->size > size) {
3663 PyErr_Format(PyExc_ValueError,
3664 "password cannot be longer than %d bytes", size);
3665 goto error;
3666 }
3667
3668 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
3669 memcpy(buf, pw_info->password, pw_info->size);
3670 return pw_info->size;
3671
3672error:
3673 Py_XDECREF(fn_ret);
3674 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
3675 pw_info->error = 1;
3676 return -1;
3677}
3678
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003679/*[clinic input]
3680_ssl._SSLContext.load_cert_chain
3681 certfile: object
Serhiy Storchaka279f4462019-09-14 12:24:05 +03003682 keyfile: object = None
3683 password: object = None
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003684
3685[clinic start generated code]*/
3686
Antoine Pitroub5218772010-05-21 09:56:06 +00003687static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003688_ssl__SSLContext_load_cert_chain_impl(PySSLContext *self, PyObject *certfile,
3689 PyObject *keyfile, PyObject *password)
Serhiy Storchaka279f4462019-09-14 12:24:05 +03003690/*[clinic end generated code: output=9480bc1c380e2095 input=30bc7e967ea01a58]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003691{
Antoine Pitrou152efa22010-05-16 18:19:27 +00003692 PyObject *certfile_bytes = NULL, *keyfile_bytes = NULL;
Christian Heimes598894f2016-09-05 23:19:05 +02003693 pem_password_cb *orig_passwd_cb = SSL_CTX_get_default_passwd_cb(self->ctx);
3694 void *orig_passwd_userdata = SSL_CTX_get_default_passwd_cb_userdata(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003695 _PySSLPasswordInfo pw_info = { NULL, NULL, NULL, 0, 0 };
Antoine Pitrou152efa22010-05-16 18:19:27 +00003696 int r;
3697
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003698 errno = 0;
Antoine Pitrou67e8e562010-09-01 20:55:41 +00003699 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00003700 if (keyfile == Py_None)
3701 keyfile = NULL;
3702 if (!PyUnicode_FSConverter(certfile, &certfile_bytes)) {
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03003703 if (PyErr_ExceptionMatches(PyExc_TypeError)) {
3704 PyErr_SetString(PyExc_TypeError,
3705 "certfile should be a valid filesystem path");
3706 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003707 return NULL;
3708 }
3709 if (keyfile && !PyUnicode_FSConverter(keyfile, &keyfile_bytes)) {
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03003710 if (PyErr_ExceptionMatches(PyExc_TypeError)) {
3711 PyErr_SetString(PyExc_TypeError,
3712 "keyfile should be a valid filesystem path");
3713 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003714 goto error;
3715 }
Serhiy Storchaka279f4462019-09-14 12:24:05 +03003716 if (password != Py_None) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003717 if (PyCallable_Check(password)) {
3718 pw_info.callable = password;
3719 } else if (!_pwinfo_set(&pw_info, password,
3720 "password should be a string or callable")) {
3721 goto error;
3722 }
3723 SSL_CTX_set_default_passwd_cb(self->ctx, _password_callback);
3724 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, &pw_info);
3725 }
3726 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003727 r = SSL_CTX_use_certificate_chain_file(self->ctx,
3728 PyBytes_AS_STRING(certfile_bytes));
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003729 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003730 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003731 if (pw_info.error) {
3732 ERR_clear_error();
3733 /* the password callback has already set the error information */
3734 }
3735 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00003736 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03003737 PyErr_SetFromErrno(PyExc_OSError);
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003738 }
3739 else {
Christian Heimes7f1305e2021-04-17 20:06:38 +02003740 _setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003741 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003742 goto error;
3743 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003744 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou9c254862011-04-03 18:15:34 +02003745 r = SSL_CTX_use_PrivateKey_file(self->ctx,
Antoine Pitrou152efa22010-05-16 18:19:27 +00003746 PyBytes_AS_STRING(keyfile ? keyfile_bytes : certfile_bytes),
3747 SSL_FILETYPE_PEM);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003748 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
3749 Py_CLEAR(keyfile_bytes);
3750 Py_CLEAR(certfile_bytes);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003751 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003752 if (pw_info.error) {
3753 ERR_clear_error();
3754 /* the password callback has already set the error information */
3755 }
3756 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00003757 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03003758 PyErr_SetFromErrno(PyExc_OSError);
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003759 }
3760 else {
Christian Heimes7f1305e2021-04-17 20:06:38 +02003761 _setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003762 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003763 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003764 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003765 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003766 r = SSL_CTX_check_private_key(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003767 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003768 if (r != 1) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02003769 _setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003770 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003771 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003772 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
3773 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02003774 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003775 Py_RETURN_NONE;
3776
3777error:
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003778 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
3779 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02003780 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003781 Py_XDECREF(keyfile_bytes);
3782 Py_XDECREF(certfile_bytes);
3783 return NULL;
3784}
3785
Christian Heimesefff7062013-11-21 03:35:02 +01003786/* internal helper function, returns -1 on error
3787 */
3788static int
Serhiy Storchaka8f87eef2020-04-12 14:58:27 +03003789_add_ca_certs(PySSLContext *self, const void *data, Py_ssize_t len,
Christian Heimesefff7062013-11-21 03:35:02 +01003790 int filetype)
3791{
3792 BIO *biobuf = NULL;
3793 X509_STORE *store;
Christian Heimesb9ad88b2021-04-23 13:51:40 +02003794 int retval = -1, err, loaded = 0;
Christian Heimesefff7062013-11-21 03:35:02 +01003795
3796 assert(filetype == SSL_FILETYPE_ASN1 || filetype == SSL_FILETYPE_PEM);
3797
3798 if (len <= 0) {
3799 PyErr_SetString(PyExc_ValueError,
3800 "Empty certificate data");
3801 return -1;
3802 } else if (len > INT_MAX) {
3803 PyErr_SetString(PyExc_OverflowError,
3804 "Certificate data is too long.");
3805 return -1;
3806 }
3807
Christian Heimes1dbf61f2013-11-22 00:34:18 +01003808 biobuf = BIO_new_mem_buf(data, (int)len);
Christian Heimesefff7062013-11-21 03:35:02 +01003809 if (biobuf == NULL) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02003810 _setSSLError(get_state_ctx(self), "Can't allocate buffer", 0, __FILE__, __LINE__);
Christian Heimesefff7062013-11-21 03:35:02 +01003811 return -1;
3812 }
3813
3814 store = SSL_CTX_get_cert_store(self->ctx);
3815 assert(store != NULL);
3816
3817 while (1) {
3818 X509 *cert = NULL;
3819 int r;
3820
3821 if (filetype == SSL_FILETYPE_ASN1) {
3822 cert = d2i_X509_bio(biobuf, NULL);
3823 } else {
3824 cert = PEM_read_bio_X509(biobuf, NULL,
Christian Heimes598894f2016-09-05 23:19:05 +02003825 SSL_CTX_get_default_passwd_cb(self->ctx),
3826 SSL_CTX_get_default_passwd_cb_userdata(self->ctx)
3827 );
Christian Heimesefff7062013-11-21 03:35:02 +01003828 }
3829 if (cert == NULL) {
3830 break;
3831 }
3832 r = X509_STORE_add_cert(store, cert);
3833 X509_free(cert);
3834 if (!r) {
3835 err = ERR_peek_last_error();
3836 if ((ERR_GET_LIB(err) == ERR_LIB_X509) &&
3837 (ERR_GET_REASON(err) == X509_R_CERT_ALREADY_IN_HASH_TABLE)) {
3838 /* cert already in hash table, not an error */
3839 ERR_clear_error();
3840 } else {
3841 break;
3842 }
3843 }
3844 loaded++;
3845 }
3846
3847 err = ERR_peek_last_error();
Christian Heimesb9ad88b2021-04-23 13:51:40 +02003848 if (loaded == 0) {
3849 const char *msg = NULL;
3850 if (filetype == SSL_FILETYPE_PEM) {
3851 msg = "no start line: cadata does not contain a certificate";
3852 } else {
3853 msg = "not enough data: cadata does not contain a certificate";
3854 }
3855 _setSSLError(get_state_ctx(self), msg, 0, __FILE__, __LINE__);
3856 retval = -1;
3857 } else if ((filetype == SSL_FILETYPE_ASN1) &&
3858 (ERR_GET_LIB(err) == ERR_LIB_ASN1) &&
3859 (ERR_GET_REASON(err) == ASN1_R_HEADER_TOO_LONG)) {
Christian Heimesefff7062013-11-21 03:35:02 +01003860 /* EOF ASN1 file, not an error */
3861 ERR_clear_error();
3862 retval = 0;
3863 } else if ((filetype == SSL_FILETYPE_PEM) &&
Christian Heimesefff7062013-11-21 03:35:02 +01003864 (ERR_GET_LIB(err) == ERR_LIB_PEM) &&
3865 (ERR_GET_REASON(err) == PEM_R_NO_START_LINE)) {
3866 /* EOF PEM file, not an error */
3867 ERR_clear_error();
3868 retval = 0;
Christian Heimesb9ad88b2021-04-23 13:51:40 +02003869 } else if (err != 0) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02003870 _setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
Christian Heimesefff7062013-11-21 03:35:02 +01003871 retval = -1;
Christian Heimesb9ad88b2021-04-23 13:51:40 +02003872 } else {
3873 retval = 0;
Christian Heimesefff7062013-11-21 03:35:02 +01003874 }
3875
3876 BIO_free(biobuf);
3877 return retval;
3878}
3879
3880
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003881/*[clinic input]
3882_ssl._SSLContext.load_verify_locations
Serhiy Storchaka279f4462019-09-14 12:24:05 +03003883 cafile: object = None
3884 capath: object = None
3885 cadata: object = None
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003886
3887[clinic start generated code]*/
3888
Antoine Pitrou152efa22010-05-16 18:19:27 +00003889static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003890_ssl__SSLContext_load_verify_locations_impl(PySSLContext *self,
3891 PyObject *cafile,
3892 PyObject *capath,
3893 PyObject *cadata)
Serhiy Storchaka279f4462019-09-14 12:24:05 +03003894/*[clinic end generated code: output=454c7e41230ca551 input=42ecfe258233e194]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003895{
Antoine Pitrou152efa22010-05-16 18:19:27 +00003896 PyObject *cafile_bytes = NULL, *capath_bytes = NULL;
3897 const char *cafile_buf = NULL, *capath_buf = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01003898 int r = 0, ok = 1;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003899
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003900 errno = 0;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003901 if (cafile == Py_None)
3902 cafile = NULL;
3903 if (capath == Py_None)
3904 capath = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01003905 if (cadata == Py_None)
3906 cadata = NULL;
3907
3908 if (cafile == NULL && capath == NULL && cadata == NULL) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003909 PyErr_SetString(PyExc_TypeError,
Christian Heimesefff7062013-11-21 03:35:02 +01003910 "cafile, capath and cadata cannot be all omitted");
3911 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003912 }
3913 if (cafile && !PyUnicode_FSConverter(cafile, &cafile_bytes)) {
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03003914 if (PyErr_ExceptionMatches(PyExc_TypeError)) {
3915 PyErr_SetString(PyExc_TypeError,
3916 "cafile should be a valid filesystem path");
3917 }
Christian Heimesefff7062013-11-21 03:35:02 +01003918 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003919 }
3920 if (capath && !PyUnicode_FSConverter(capath, &capath_bytes)) {
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03003921 if (PyErr_ExceptionMatches(PyExc_TypeError)) {
3922 PyErr_SetString(PyExc_TypeError,
3923 "capath should be a valid filesystem path");
3924 }
Christian Heimesefff7062013-11-21 03:35:02 +01003925 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003926 }
Christian Heimesefff7062013-11-21 03:35:02 +01003927
3928 /* validata cadata type and load cadata */
3929 if (cadata) {
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03003930 if (PyUnicode_Check(cadata)) {
3931 PyObject *cadata_ascii = PyUnicode_AsASCIIString(cadata);
3932 if (cadata_ascii == NULL) {
3933 if (PyErr_ExceptionMatches(PyExc_UnicodeEncodeError)) {
3934 goto invalid_cadata;
3935 }
3936 goto error;
3937 }
3938 r = _add_ca_certs(self,
3939 PyBytes_AS_STRING(cadata_ascii),
3940 PyBytes_GET_SIZE(cadata_ascii),
3941 SSL_FILETYPE_PEM);
3942 Py_DECREF(cadata_ascii);
3943 if (r == -1) {
3944 goto error;
3945 }
3946 }
3947 else if (PyObject_CheckBuffer(cadata)) {
3948 Py_buffer buf;
3949 if (PyObject_GetBuffer(cadata, &buf, PyBUF_SIMPLE)) {
3950 goto error;
3951 }
Christian Heimesefff7062013-11-21 03:35:02 +01003952 if (!PyBuffer_IsContiguous(&buf, 'C') || buf.ndim > 1) {
3953 PyBuffer_Release(&buf);
3954 PyErr_SetString(PyExc_TypeError,
3955 "cadata should be a contiguous buffer with "
3956 "a single dimension");
3957 goto error;
3958 }
3959 r = _add_ca_certs(self, buf.buf, buf.len, SSL_FILETYPE_ASN1);
3960 PyBuffer_Release(&buf);
3961 if (r == -1) {
3962 goto error;
3963 }
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03003964 }
3965 else {
3966 invalid_cadata:
3967 PyErr_SetString(PyExc_TypeError,
3968 "cadata should be an ASCII string or a "
3969 "bytes-like object");
3970 goto error;
Christian Heimesefff7062013-11-21 03:35:02 +01003971 }
3972 }
3973
3974 /* load cafile or capath */
3975 if (cafile || capath) {
3976 if (cafile)
3977 cafile_buf = PyBytes_AS_STRING(cafile_bytes);
3978 if (capath)
3979 capath_buf = PyBytes_AS_STRING(capath_bytes);
3980 PySSL_BEGIN_ALLOW_THREADS
3981 r = SSL_CTX_load_verify_locations(self->ctx, cafile_buf, capath_buf);
3982 PySSL_END_ALLOW_THREADS
3983 if (r != 1) {
Christian Heimesefff7062013-11-21 03:35:02 +01003984 if (errno != 0) {
3985 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03003986 PyErr_SetFromErrno(PyExc_OSError);
Christian Heimesefff7062013-11-21 03:35:02 +01003987 }
3988 else {
Christian Heimes7f1305e2021-04-17 20:06:38 +02003989 _setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
Christian Heimesefff7062013-11-21 03:35:02 +01003990 }
3991 goto error;
3992 }
3993 }
3994 goto end;
3995
3996 error:
3997 ok = 0;
3998 end:
Antoine Pitrou152efa22010-05-16 18:19:27 +00003999 Py_XDECREF(cafile_bytes);
4000 Py_XDECREF(capath_bytes);
Christian Heimesefff7062013-11-21 03:35:02 +01004001 if (ok) {
4002 Py_RETURN_NONE;
4003 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00004004 return NULL;
4005 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00004006}
4007
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004008/*[clinic input]
4009_ssl._SSLContext.load_dh_params
4010 path as filepath: object
4011 /
4012
4013[clinic start generated code]*/
4014
Antoine Pitrou152efa22010-05-16 18:19:27 +00004015static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004016_ssl__SSLContext_load_dh_params(PySSLContext *self, PyObject *filepath)
4017/*[clinic end generated code: output=1c8e57a38e055af0 input=c8871f3c796ae1d6]*/
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004018{
4019 FILE *f;
4020 DH *dh;
4021
Victor Stinnerdaf45552013-08-28 00:53:59 +02004022 f = _Py_fopen_obj(filepath, "rb");
Victor Stinnere42ccd22015-03-18 01:39:23 +01004023 if (f == NULL)
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004024 return NULL;
Victor Stinnere42ccd22015-03-18 01:39:23 +01004025
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004026 errno = 0;
4027 PySSL_BEGIN_ALLOW_THREADS
4028 dh = PEM_read_DHparams(f, NULL, NULL, NULL);
Antoine Pitrou457a2292013-01-12 21:43:45 +01004029 fclose(f);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004030 PySSL_END_ALLOW_THREADS
4031 if (dh == NULL) {
4032 if (errno != 0) {
4033 ERR_clear_error();
4034 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
4035 }
4036 else {
Christian Heimes7f1305e2021-04-17 20:06:38 +02004037 _setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004038 }
4039 return NULL;
4040 }
Zackery Spytzaebc0492020-07-07 22:21:58 -06004041 if (!SSL_CTX_set_tmp_dh(self->ctx, dh)) {
4042 DH_free(dh);
Christian Heimes7f1305e2021-04-17 20:06:38 +02004043 return _setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
Zackery Spytzaebc0492020-07-07 22:21:58 -06004044 }
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004045 DH_free(dh);
4046 Py_RETURN_NONE;
4047}
4048
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004049/*[clinic input]
4050_ssl._SSLContext._wrap_socket
Christian Heimes7f1305e2021-04-17 20:06:38 +02004051 sock: object(subclass_of="get_state_ctx(self)->Sock_Type")
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004052 server_side: int
4053 server_hostname as hostname_obj: object = None
Christian Heimes141c5e82018-02-24 21:10:57 +01004054 *
4055 owner: object = None
4056 session: object = None
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004057
4058[clinic start generated code]*/
4059
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004060static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004061_ssl__SSLContext__wrap_socket_impl(PySSLContext *self, PyObject *sock,
Christian Heimes141c5e82018-02-24 21:10:57 +01004062 int server_side, PyObject *hostname_obj,
4063 PyObject *owner, PyObject *session)
Christian Heimes7f1305e2021-04-17 20:06:38 +02004064/*[clinic end generated code: output=f103f238633940b4 input=f5916eadbc6eae81]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004065{
Antoine Pitroud5323212010-10-22 18:19:07 +00004066 char *hostname = NULL;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004067 PyObject *res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004068
Antoine Pitroud5323212010-10-22 18:19:07 +00004069 /* server_hostname is either None (or absent), or to be encoded
Christian Heimesd02ac252018-03-25 12:36:13 +02004070 as IDN A-label (ASCII str) without NULL bytes. */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004071 if (hostname_obj != Py_None) {
Christian Heimes11a14932018-02-24 02:35:08 +01004072 if (!PyArg_Parse(hostname_obj, "es", "ascii", &hostname))
Antoine Pitroud5323212010-10-22 18:19:07 +00004073 return NULL;
Antoine Pitroud5323212010-10-22 18:19:07 +00004074 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00004075
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004076 res = (PyObject *) newPySSLSocket(self, (PySocketSockObject *)sock,
4077 server_side, hostname,
Christian Heimes141c5e82018-02-24 21:10:57 +01004078 owner, session,
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004079 NULL, NULL);
Antoine Pitroud5323212010-10-22 18:19:07 +00004080 if (hostname != NULL)
4081 PyMem_Free(hostname);
4082 return res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004083}
4084
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004085/*[clinic input]
4086_ssl._SSLContext._wrap_bio
Christian Heimes7f1305e2021-04-17 20:06:38 +02004087 incoming: object(subclass_of="get_state_ctx(self)->PySSLMemoryBIO_Type", type="PySSLMemoryBIO *")
4088 outgoing: object(subclass_of="get_state_ctx(self)->PySSLMemoryBIO_Type", type="PySSLMemoryBIO *")
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004089 server_side: int
4090 server_hostname as hostname_obj: object = None
Christian Heimes141c5e82018-02-24 21:10:57 +01004091 *
4092 owner: object = None
4093 session: object = None
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004094
4095[clinic start generated code]*/
4096
Antoine Pitroub0182c82010-10-12 20:09:02 +00004097static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004098_ssl__SSLContext__wrap_bio_impl(PySSLContext *self, PySSLMemoryBIO *incoming,
4099 PySSLMemoryBIO *outgoing, int server_side,
Christian Heimes141c5e82018-02-24 21:10:57 +01004100 PyObject *hostname_obj, PyObject *owner,
4101 PyObject *session)
Christian Heimes7f1305e2021-04-17 20:06:38 +02004102/*[clinic end generated code: output=5c5d6d9b41f99332 input=331edeec9c738382]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004103{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004104 char *hostname = NULL;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004105 PyObject *res;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004106
4107 /* server_hostname is either None (or absent), or to be encoded
Christian Heimesd02ac252018-03-25 12:36:13 +02004108 as IDN A-label (ASCII str) without NULL bytes. */
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004109 if (hostname_obj != Py_None) {
Christian Heimes11a14932018-02-24 02:35:08 +01004110 if (!PyArg_Parse(hostname_obj, "es", "ascii", &hostname))
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004111 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004112 }
4113
4114 res = (PyObject *) newPySSLSocket(self, NULL, server_side, hostname,
Christian Heimes141c5e82018-02-24 21:10:57 +01004115 owner, session,
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004116 incoming, outgoing);
4117
4118 PyMem_Free(hostname);
4119 return res;
4120}
4121
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004122/*[clinic input]
4123_ssl._SSLContext.session_stats
4124[clinic start generated code]*/
4125
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004126static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004127_ssl__SSLContext_session_stats_impl(PySSLContext *self)
4128/*[clinic end generated code: output=0d96411c42893bfb input=7e0a81fb11102c8b]*/
Antoine Pitroub0182c82010-10-12 20:09:02 +00004129{
4130 int r;
4131 PyObject *value, *stats = PyDict_New();
4132 if (!stats)
4133 return NULL;
4134
4135#define ADD_STATS(SSL_NAME, KEY_NAME) \
4136 value = PyLong_FromLong(SSL_CTX_sess_ ## SSL_NAME (self->ctx)); \
4137 if (value == NULL) \
4138 goto error; \
4139 r = PyDict_SetItemString(stats, KEY_NAME, value); \
4140 Py_DECREF(value); \
4141 if (r < 0) \
4142 goto error;
4143
4144 ADD_STATS(number, "number");
4145 ADD_STATS(connect, "connect");
4146 ADD_STATS(connect_good, "connect_good");
4147 ADD_STATS(connect_renegotiate, "connect_renegotiate");
4148 ADD_STATS(accept, "accept");
4149 ADD_STATS(accept_good, "accept_good");
4150 ADD_STATS(accept_renegotiate, "accept_renegotiate");
4151 ADD_STATS(accept, "accept");
4152 ADD_STATS(hits, "hits");
4153 ADD_STATS(misses, "misses");
4154 ADD_STATS(timeouts, "timeouts");
4155 ADD_STATS(cache_full, "cache_full");
4156
4157#undef ADD_STATS
4158
4159 return stats;
4160
4161error:
4162 Py_DECREF(stats);
4163 return NULL;
4164}
4165
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004166/*[clinic input]
4167_ssl._SSLContext.set_default_verify_paths
4168[clinic start generated code]*/
4169
Antoine Pitrou664c2d12010-11-17 20:29:42 +00004170static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004171_ssl__SSLContext_set_default_verify_paths_impl(PySSLContext *self)
4172/*[clinic end generated code: output=0bee74e6e09deaaa input=35f3408021463d74]*/
Antoine Pitrou664c2d12010-11-17 20:29:42 +00004173{
4174 if (!SSL_CTX_set_default_verify_paths(self->ctx)) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02004175 _setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
Antoine Pitrou664c2d12010-11-17 20:29:42 +00004176 return NULL;
4177 }
4178 Py_RETURN_NONE;
4179}
4180
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004181/*[clinic input]
4182_ssl._SSLContext.set_ecdh_curve
4183 name: object
4184 /
4185
4186[clinic start generated code]*/
4187
Antoine Pitrou923df6f2011-12-19 17:16:51 +01004188static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004189_ssl__SSLContext_set_ecdh_curve(PySSLContext *self, PyObject *name)
4190/*[clinic end generated code: output=23022c196e40d7d2 input=c2bafb6f6e34726b]*/
Antoine Pitrou923df6f2011-12-19 17:16:51 +01004191{
4192 PyObject *name_bytes;
4193 int nid;
4194 EC_KEY *key;
4195
4196 if (!PyUnicode_FSConverter(name, &name_bytes))
4197 return NULL;
4198 assert(PyBytes_Check(name_bytes));
4199 nid = OBJ_sn2nid(PyBytes_AS_STRING(name_bytes));
4200 Py_DECREF(name_bytes);
4201 if (nid == 0) {
4202 PyErr_Format(PyExc_ValueError,
4203 "unknown elliptic curve name %R", name);
4204 return NULL;
4205 }
4206 key = EC_KEY_new_by_curve_name(nid);
4207 if (key == NULL) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02004208 _setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
Antoine Pitrou923df6f2011-12-19 17:16:51 +01004209 return NULL;
4210 }
4211 SSL_CTX_set_tmp_ecdh(self->ctx, key);
4212 EC_KEY_free(key);
4213 Py_RETURN_NONE;
4214}
4215
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004216static int
4217_servername_callback(SSL *s, int *al, void *args)
4218{
4219 int ret;
Christian Heimes7f1305e2021-04-17 20:06:38 +02004220 PySSLContext *sslctx = (PySSLContext *) args;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004221 PySSLSocket *ssl;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004222 PyObject *result;
4223 /* The high-level ssl.SSLSocket object */
4224 PyObject *ssl_socket;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004225 const char *servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
Stefan Krah20d60802013-01-17 17:07:17 +01004226 PyGILState_STATE gstate = PyGILState_Ensure();
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004227
Christian Heimes7f1305e2021-04-17 20:06:38 +02004228 if (sslctx->set_sni_cb == NULL) {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004229 /* remove race condition in this the call back while if removing the
4230 * callback is in progress */
4231 PyGILState_Release(gstate);
Antoine Pitrou5dd12a52013-01-06 15:25:36 +01004232 return SSL_TLSEXT_ERR_OK;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004233 }
4234
4235 ssl = SSL_get_app_data(s);
Christian Heimes7f1305e2021-04-17 20:06:38 +02004236 assert(Py_IS_TYPE(ssl, get_state_ctx(sslctx)->PySSLSocket_Type));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004237
Serhiy Storchakaf51d7152015-11-02 14:40:41 +02004238 /* The servername callback expects an argument that represents the current
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004239 * SSL connection and that has a .context attribute that can be changed to
4240 * identify the requested hostname. Since the official API is the Python
4241 * level API we want to pass the callback a Python level object rather than
4242 * a _ssl.SSLSocket instance. If there's an "owner" (typically an
4243 * SSLObject) that will be passed. Otherwise if there's a socket then that
4244 * will be passed. If both do not exist only then the C-level object is
4245 * passed. */
4246 if (ssl->owner)
4247 ssl_socket = PyWeakref_GetObject(ssl->owner);
4248 else if (ssl->Socket)
4249 ssl_socket = PyWeakref_GetObject(ssl->Socket);
4250 else
4251 ssl_socket = (PyObject *) ssl;
4252
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004253 Py_INCREF(ssl_socket);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004254 if (ssl_socket == Py_None)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004255 goto error;
Victor Stinner7e001512013-06-25 00:44:31 +02004256
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004257 if (servername == NULL) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02004258 result = PyObject_CallFunctionObjArgs(sslctx->set_sni_cb, ssl_socket,
4259 Py_None, sslctx, NULL);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004260 }
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004261 else {
Christian Heimes11a14932018-02-24 02:35:08 +01004262 PyObject *servername_bytes;
4263 PyObject *servername_str;
4264
4265 servername_bytes = PyBytes_FromString(servername);
4266 if (servername_bytes == NULL) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02004267 PyErr_WriteUnraisable((PyObject *) sslctx);
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004268 goto error;
4269 }
Christian Heimes11a14932018-02-24 02:35:08 +01004270 /* server_hostname was encoded to an A-label by our caller; put it
4271 * back into a str object, but still as an A-label (bpo-28414)
4272 */
4273 servername_str = PyUnicode_FromEncodedObject(servername_bytes, "ascii", NULL);
Christian Heimes11a14932018-02-24 02:35:08 +01004274 if (servername_str == NULL) {
4275 PyErr_WriteUnraisable(servername_bytes);
Zackery Spytzee96f322020-07-09 04:00:21 -06004276 Py_DECREF(servername_bytes);
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004277 goto error;
4278 }
Zackery Spytzee96f322020-07-09 04:00:21 -06004279 Py_DECREF(servername_bytes);
Christian Heimes11a14932018-02-24 02:35:08 +01004280 result = PyObject_CallFunctionObjArgs(
Christian Heimes7f1305e2021-04-17 20:06:38 +02004281 sslctx->set_sni_cb, ssl_socket, servername_str,
4282 sslctx, NULL);
Christian Heimes11a14932018-02-24 02:35:08 +01004283 Py_DECREF(servername_str);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004284 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004285 Py_DECREF(ssl_socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004286
4287 if (result == NULL) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02004288 PyErr_WriteUnraisable(sslctx->set_sni_cb);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004289 *al = SSL_AD_HANDSHAKE_FAILURE;
4290 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
4291 }
4292 else {
Christian Heimes11a14932018-02-24 02:35:08 +01004293 /* Result may be None, a SSLContext or an integer
4294 * None and SSLContext are OK, integer or other values are an error.
4295 */
4296 if (result == Py_None) {
4297 ret = SSL_TLSEXT_ERR_OK;
4298 } else {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004299 *al = (int) PyLong_AsLong(result);
4300 if (PyErr_Occurred()) {
4301 PyErr_WriteUnraisable(result);
4302 *al = SSL_AD_INTERNAL_ERROR;
4303 }
4304 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
4305 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004306 Py_DECREF(result);
4307 }
4308
4309 PyGILState_Release(gstate);
4310 return ret;
4311
4312error:
4313 Py_DECREF(ssl_socket);
4314 *al = SSL_AD_INTERNAL_ERROR;
4315 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
4316 PyGILState_Release(gstate);
4317 return ret;
4318}
4319
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004320static PyObject *
Christian Heimes11a14932018-02-24 02:35:08 +01004321get_sni_callback(PySSLContext *self, void *c)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004322{
Christian Heimes11a14932018-02-24 02:35:08 +01004323 PyObject *cb = self->set_sni_cb;
4324 if (cb == NULL) {
4325 Py_RETURN_NONE;
4326 }
4327 Py_INCREF(cb);
4328 return cb;
4329}
4330
4331static int
4332set_sni_callback(PySSLContext *self, PyObject *arg, void *c)
4333{
4334 if (self->protocol == PY_SSL_VERSION_TLS_CLIENT) {
4335 PyErr_SetString(PyExc_ValueError,
4336 "sni_callback cannot be set on TLS_CLIENT context");
4337 return -1;
4338 }
Christian Heimes11a14932018-02-24 02:35:08 +01004339 Py_CLEAR(self->set_sni_cb);
4340 if (arg == Py_None) {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004341 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
4342 }
4343 else {
Christian Heimes11a14932018-02-24 02:35:08 +01004344 if (!PyCallable_Check(arg)) {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004345 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
4346 PyErr_SetString(PyExc_TypeError,
4347 "not a callable object");
Christian Heimes11a14932018-02-24 02:35:08 +01004348 return -1;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004349 }
Christian Heimes11a14932018-02-24 02:35:08 +01004350 Py_INCREF(arg);
4351 self->set_sni_cb = arg;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004352 SSL_CTX_set_tlsext_servername_callback(self->ctx, _servername_callback);
4353 SSL_CTX_set_tlsext_servername_arg(self->ctx, self);
4354 }
Christian Heimes11a14932018-02-24 02:35:08 +01004355 return 0;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004356}
4357
Christian Heimes11a14932018-02-24 02:35:08 +01004358PyDoc_STRVAR(PySSLContext_sni_callback_doc,
4359"Set a callback that will be called when a server name is provided by the SSL/TLS client in the SNI extension.\n\
4360\n\
4361If the argument is None then the callback is disabled. The method is called\n\
4362with the SSLSocket, the server name as a string, and the SSLContext object.\n\
4363See RFC 6066 for details of the SNI extension.");
4364
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004365/*[clinic input]
4366_ssl._SSLContext.cert_store_stats
4367
4368Returns quantities of loaded X.509 certificates.
4369
4370X.509 certificates with a CA extension and certificate revocation lists
4371inside the context's cert store.
4372
4373NOTE: Certificates in a capath directory aren't loaded unless they have
4374been used at least once.
4375[clinic start generated code]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004376
4377static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004378_ssl__SSLContext_cert_store_stats_impl(PySSLContext *self)
4379/*[clinic end generated code: output=5f356f4d9cca874d input=eb40dd0f6d0e40cf]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004380{
4381 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02004382 STACK_OF(X509_OBJECT) *objs;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004383 X509_OBJECT *obj;
Christian Heimes598894f2016-09-05 23:19:05 +02004384 int x509 = 0, crl = 0, ca = 0, i;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004385
4386 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02004387 objs = X509_STORE_get0_objects(store);
4388 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
4389 obj = sk_X509_OBJECT_value(objs, i);
4390 switch (X509_OBJECT_get_type(obj)) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004391 case X509_LU_X509:
4392 x509++;
Christian Heimes598894f2016-09-05 23:19:05 +02004393 if (X509_check_ca(X509_OBJECT_get0_X509(obj))) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004394 ca++;
4395 }
4396 break;
4397 case X509_LU_CRL:
4398 crl++;
4399 break;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004400 default:
4401 /* Ignore X509_LU_FAIL, X509_LU_RETRY, X509_LU_PKEY.
4402 * As far as I can tell they are internal states and never
4403 * stored in a cert store */
4404 break;
4405 }
4406 }
4407 return Py_BuildValue("{sisisi}", "x509", x509, "crl", crl,
4408 "x509_ca", ca);
4409}
4410
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004411/*[clinic input]
4412_ssl._SSLContext.get_ca_certs
4413 binary_form: bool = False
4414
4415Returns a list of dicts with information of loaded CA certs.
4416
4417If the optional argument is True, returns a DER-encoded copy of the CA
4418certificate.
4419
4420NOTE: Certificates in a capath directory aren't loaded unless they have
4421been used at least once.
4422[clinic start generated code]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004423
4424static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004425_ssl__SSLContext_get_ca_certs_impl(PySSLContext *self, int binary_form)
4426/*[clinic end generated code: output=0d58f148f37e2938 input=6887b5a09b7f9076]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004427{
4428 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02004429 STACK_OF(X509_OBJECT) *objs;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004430 PyObject *ci = NULL, *rlist = NULL;
4431 int i;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004432
4433 if ((rlist = PyList_New(0)) == NULL) {
4434 return NULL;
4435 }
4436
4437 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02004438 objs = X509_STORE_get0_objects(store);
4439 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004440 X509_OBJECT *obj;
4441 X509 *cert;
4442
Christian Heimes598894f2016-09-05 23:19:05 +02004443 obj = sk_X509_OBJECT_value(objs, i);
4444 if (X509_OBJECT_get_type(obj) != X509_LU_X509) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004445 /* not a x509 cert */
4446 continue;
4447 }
4448 /* CA for any purpose */
Christian Heimes598894f2016-09-05 23:19:05 +02004449 cert = X509_OBJECT_get0_X509(obj);
Christian Heimes9a5395a2013-06-17 15:44:12 +02004450 if (!X509_check_ca(cert)) {
4451 continue;
4452 }
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004453 if (binary_form) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02004454 ci = _certificate_to_der(get_state_ctx(self), cert);
Christian Heimes9a5395a2013-06-17 15:44:12 +02004455 } else {
Christian Heimes7f1305e2021-04-17 20:06:38 +02004456 ci = _decode_certificate(get_state_ctx(self), cert);
Christian Heimes9a5395a2013-06-17 15:44:12 +02004457 }
4458 if (ci == NULL) {
4459 goto error;
4460 }
4461 if (PyList_Append(rlist, ci) == -1) {
4462 goto error;
4463 }
4464 Py_CLEAR(ci);
4465 }
4466 return rlist;
4467
4468 error:
4469 Py_XDECREF(ci);
4470 Py_XDECREF(rlist);
4471 return NULL;
4472}
4473
4474
Antoine Pitrou152efa22010-05-16 18:19:27 +00004475static PyGetSetDef context_getsetlist[] = {
Christian Heimes1aa9a752013-12-02 02:41:19 +01004476 {"check_hostname", (getter) get_check_hostname,
4477 (setter) set_check_hostname, NULL},
Christian Heimes61d478c2018-01-27 15:51:38 +01004478 {"_host_flags", (getter) get_host_flags,
4479 (setter) set_host_flags, NULL},
Christian Heimes698dde12018-02-27 11:54:43 +01004480 {"minimum_version", (getter) get_minimum_version,
4481 (setter) set_minimum_version, NULL},
4482 {"maximum_version", (getter) get_maximum_version,
4483 (setter) set_maximum_version, NULL},
Christian Heimesc7f70692019-05-31 11:44:05 +02004484 {"keylog_filename", (getter) _PySSLContext_get_keylog_filename,
4485 (setter) _PySSLContext_set_keylog_filename, NULL},
Christian Heimesc7f70692019-05-31 11:44:05 +02004486 {"_msg_callback", (getter) _PySSLContext_get_msg_callback,
4487 (setter) _PySSLContext_set_msg_callback, NULL},
Christian Heimes11a14932018-02-24 02:35:08 +01004488 {"sni_callback", (getter) get_sni_callback,
Christian Heimes698dde12018-02-27 11:54:43 +01004489 (setter) set_sni_callback, PySSLContext_sni_callback_doc},
Christian Heimes39258d32021-04-17 11:36:35 +02004490#ifdef TLS1_3_VERSION
Christian Heimes78c7d522019-06-03 21:00:10 +02004491 {"num_tickets", (getter) get_num_tickets,
4492 (setter) set_num_tickets, PySSLContext_num_tickets_doc},
4493#endif
Antoine Pitroub5218772010-05-21 09:56:06 +00004494 {"options", (getter) get_options,
4495 (setter) set_options, NULL},
Christian Heimes9fb051f2018-09-23 08:32:31 +02004496 {"post_handshake_auth", (getter) get_post_handshake_auth,
4497#ifdef TLS1_3_VERSION
4498 (setter) set_post_handshake_auth,
4499#else
4500 NULL,
4501#endif
4502 NULL},
Christian Heimes11a14932018-02-24 02:35:08 +01004503 {"protocol", (getter) get_protocol,
4504 NULL, NULL},
Christian Heimes22587792013-11-21 23:56:13 +01004505 {"verify_flags", (getter) get_verify_flags,
4506 (setter) set_verify_flags, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00004507 {"verify_mode", (getter) get_verify_mode,
4508 (setter) set_verify_mode, NULL},
matthewhughes9348e836bb2020-07-17 09:59:15 +01004509 {"security_level", (getter) get_security_level,
4510 NULL, PySSLContext_security_level_doc},
Antoine Pitrou152efa22010-05-16 18:19:27 +00004511 {NULL}, /* sentinel */
4512};
4513
4514static struct PyMethodDef context_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004515 _SSL__SSLCONTEXT__WRAP_SOCKET_METHODDEF
4516 _SSL__SSLCONTEXT__WRAP_BIO_METHODDEF
4517 _SSL__SSLCONTEXT_SET_CIPHERS_METHODDEF
4518 _SSL__SSLCONTEXT__SET_ALPN_PROTOCOLS_METHODDEF
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004519 _SSL__SSLCONTEXT_LOAD_CERT_CHAIN_METHODDEF
4520 _SSL__SSLCONTEXT_LOAD_DH_PARAMS_METHODDEF
4521 _SSL__SSLCONTEXT_LOAD_VERIFY_LOCATIONS_METHODDEF
4522 _SSL__SSLCONTEXT_SESSION_STATS_METHODDEF
4523 _SSL__SSLCONTEXT_SET_DEFAULT_VERIFY_PATHS_METHODDEF
4524 _SSL__SSLCONTEXT_SET_ECDH_CURVE_METHODDEF
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004525 _SSL__SSLCONTEXT_CERT_STORE_STATS_METHODDEF
4526 _SSL__SSLCONTEXT_GET_CA_CERTS_METHODDEF
Christian Heimes25bfcd52016-09-06 00:04:45 +02004527 _SSL__SSLCONTEXT_GET_CIPHERS_METHODDEF
Antoine Pitrou152efa22010-05-16 18:19:27 +00004528 {NULL, NULL} /* sentinel */
4529};
4530
Christian Heimes5c36da72020-11-20 09:40:12 +01004531static PyType_Slot PySSLContext_slots[] = {
4532 {Py_tp_methods, context_methods},
4533 {Py_tp_getset, context_getsetlist},
4534 {Py_tp_new, _ssl__SSLContext},
4535 {Py_tp_dealloc, context_dealloc},
4536 {Py_tp_traverse, context_traverse},
4537 {Py_tp_clear, context_clear},
4538 {0, 0},
4539};
4540
4541static PyType_Spec PySSLContext_spec = {
4542 "_ssl._SSLContext",
4543 sizeof(PySSLContext),
4544 0,
4545 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
4546 PySSLContext_slots,
Antoine Pitrou152efa22010-05-16 18:19:27 +00004547};
4548
4549
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004550/*
4551 * MemoryBIO objects
4552 */
4553
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004554/*[clinic input]
4555@classmethod
4556_ssl.MemoryBIO.__new__
4557
4558[clinic start generated code]*/
4559
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004560static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004561_ssl_MemoryBIO_impl(PyTypeObject *type)
4562/*[clinic end generated code: output=8820a58db78330ac input=26d22e4909ecb1b5]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004563{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004564 BIO *bio;
4565 PySSLMemoryBIO *self;
4566
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004567 bio = BIO_new(BIO_s_mem());
4568 if (bio == NULL) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02004569 PyErr_SetString(PyExc_MemoryError, "failed to allocate BIO");
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004570 return NULL;
4571 }
4572 /* Since our BIO is non-blocking an empty read() does not indicate EOF,
4573 * just that no data is currently available. The SSL routines should retry
4574 * the read, which we can achieve by calling BIO_set_retry_read(). */
4575 BIO_set_retry_read(bio);
4576 BIO_set_mem_eof_return(bio, -1);
4577
4578 assert(type != NULL && type->tp_alloc != NULL);
4579 self = (PySSLMemoryBIO *) type->tp_alloc(type, 0);
4580 if (self == NULL) {
4581 BIO_free(bio);
4582 return NULL;
4583 }
4584 self->bio = bio;
4585 self->eof_written = 0;
4586
4587 return (PyObject *) self;
4588}
4589
4590static void
4591memory_bio_dealloc(PySSLMemoryBIO *self)
4592{
Christian Heimes5c36da72020-11-20 09:40:12 +01004593 PyTypeObject *tp = Py_TYPE(self);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004594 BIO_free(self->bio);
4595 Py_TYPE(self)->tp_free(self);
Christian Heimes5c36da72020-11-20 09:40:12 +01004596 Py_DECREF(tp);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004597}
4598
4599static PyObject *
4600memory_bio_get_pending(PySSLMemoryBIO *self, void *c)
4601{
Segev Finer5cff6372017-07-27 01:19:17 +03004602 return PyLong_FromSize_t(BIO_ctrl_pending(self->bio));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004603}
4604
4605PyDoc_STRVAR(PySSL_memory_bio_pending_doc,
4606"The number of bytes pending in the memory BIO.");
4607
4608static PyObject *
4609memory_bio_get_eof(PySSLMemoryBIO *self, void *c)
4610{
4611 return PyBool_FromLong((BIO_ctrl_pending(self->bio) == 0)
4612 && self->eof_written);
4613}
4614
4615PyDoc_STRVAR(PySSL_memory_bio_eof_doc,
4616"Whether the memory BIO is at EOF.");
4617
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004618/*[clinic input]
4619_ssl.MemoryBIO.read
4620 size as len: int = -1
4621 /
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004622
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004623Read up to size bytes from the memory BIO.
4624
4625If size is not specified, read the entire buffer.
4626If the return value is an empty bytes instance, this means either
4627EOF or that no data is available. Use the "eof" property to
4628distinguish between the two.
4629[clinic start generated code]*/
4630
4631static PyObject *
4632_ssl_MemoryBIO_read_impl(PySSLMemoryBIO *self, int len)
4633/*[clinic end generated code: output=a657aa1e79cd01b3 input=574d7be06a902366]*/
4634{
4635 int avail, nbytes;
4636 PyObject *result;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004637
Segev Finer5cff6372017-07-27 01:19:17 +03004638 avail = (int)Py_MIN(BIO_ctrl_pending(self->bio), INT_MAX);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004639 if ((len < 0) || (len > avail))
4640 len = avail;
4641
4642 result = PyBytes_FromStringAndSize(NULL, len);
4643 if ((result == NULL) || (len == 0))
4644 return result;
4645
4646 nbytes = BIO_read(self->bio, PyBytes_AS_STRING(result), len);
Zackery Spytz365ad2e2018-10-06 11:41:45 -06004647 if (nbytes < 0) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02004648 _sslmodulestate *state = get_state_mbio(self);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004649 Py_DECREF(result);
Christian Heimes7f1305e2021-04-17 20:06:38 +02004650 _setSSLError(state, NULL, 0, __FILE__, __LINE__);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004651 return NULL;
4652 }
4653
Zackery Spytz365ad2e2018-10-06 11:41:45 -06004654 /* There should never be any short reads but check anyway. */
4655 if (nbytes < len) {
4656 _PyBytes_Resize(&result, nbytes);
4657 }
4658
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004659 return result;
4660}
4661
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004662/*[clinic input]
4663_ssl.MemoryBIO.write
4664 b: Py_buffer
4665 /
4666
4667Writes the bytes b into the memory BIO.
4668
4669Returns the number of bytes written.
4670[clinic start generated code]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004671
4672static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004673_ssl_MemoryBIO_write_impl(PySSLMemoryBIO *self, Py_buffer *b)
4674/*[clinic end generated code: output=156ec59110d75935 input=e45757b3e17c4808]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004675{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004676 int nbytes;
4677
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004678 if (b->len > INT_MAX) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004679 PyErr_Format(PyExc_OverflowError,
4680 "string longer than %d bytes", INT_MAX);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004681 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004682 }
4683
4684 if (self->eof_written) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02004685 PyObject *module = PyType_GetModule(Py_TYPE(self));
4686 if (module == NULL)
4687 return NULL;
4688 PyErr_SetString(get_ssl_state(module)->PySSLErrorObject,
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004689 "cannot write() after write_eof()");
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004690 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004691 }
4692
Segev Finer5cff6372017-07-27 01:19:17 +03004693 nbytes = BIO_write(self->bio, b->buf, (int)b->len);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004694 if (nbytes < 0) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02004695 _sslmodulestate *state = get_state_mbio(self);
4696 _setSSLError(state, NULL, 0, __FILE__, __LINE__);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004697 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004698 }
4699
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004700 return PyLong_FromLong(nbytes);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004701}
4702
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004703/*[clinic input]
4704_ssl.MemoryBIO.write_eof
4705
4706Write an EOF marker to the memory BIO.
4707
4708When all data has been read, the "eof" property will be True.
4709[clinic start generated code]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004710
4711static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004712_ssl_MemoryBIO_write_eof_impl(PySSLMemoryBIO *self)
4713/*[clinic end generated code: output=d4106276ccd1ed34 input=56a945f1d29e8bd6]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004714{
4715 self->eof_written = 1;
4716 /* After an EOF is written, a zero return from read() should be a real EOF
4717 * i.e. it should not be retried. Clear the SHOULD_RETRY flag. */
4718 BIO_clear_retry_flags(self->bio);
4719 BIO_set_mem_eof_return(self->bio, 0);
4720
4721 Py_RETURN_NONE;
4722}
4723
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004724static PyGetSetDef memory_bio_getsetlist[] = {
4725 {"pending", (getter) memory_bio_get_pending, NULL,
4726 PySSL_memory_bio_pending_doc},
4727 {"eof", (getter) memory_bio_get_eof, NULL,
4728 PySSL_memory_bio_eof_doc},
4729 {NULL}, /* sentinel */
4730};
4731
4732static struct PyMethodDef memory_bio_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004733 _SSL_MEMORYBIO_READ_METHODDEF
4734 _SSL_MEMORYBIO_WRITE_METHODDEF
4735 _SSL_MEMORYBIO_WRITE_EOF_METHODDEF
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004736 {NULL, NULL} /* sentinel */
4737};
4738
Christian Heimes5c36da72020-11-20 09:40:12 +01004739static PyType_Slot PySSLMemoryBIO_slots[] = {
4740 {Py_tp_methods, memory_bio_methods},
4741 {Py_tp_getset, memory_bio_getsetlist},
4742 {Py_tp_new, _ssl_MemoryBIO},
4743 {Py_tp_dealloc, memory_bio_dealloc},
4744 {0, 0},
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004745};
4746
Christian Heimes5c36da72020-11-20 09:40:12 +01004747static PyType_Spec PySSLMemoryBIO_spec = {
4748 "_ssl.MemoryBIO",
4749 sizeof(PySSLMemoryBIO),
4750 0,
4751 Py_TPFLAGS_DEFAULT,
4752 PySSLMemoryBIO_slots,
4753};
Antoine Pitrou152efa22010-05-16 18:19:27 +00004754
Christian Heimes99a65702016-09-10 23:44:53 +02004755/*
4756 * SSL Session object
4757 */
4758
4759static void
4760PySSLSession_dealloc(PySSLSession *self)
4761{
Christian Heimes5c36da72020-11-20 09:40:12 +01004762 PyTypeObject *tp = Py_TYPE(self);
INADA Naokia6296d32017-08-24 14:55:17 +09004763 /* bpo-31095: UnTrack is needed before calling any callbacks */
Christian Heimesa5d07652016-09-24 10:48:05 +02004764 PyObject_GC_UnTrack(self);
Christian Heimes99a65702016-09-10 23:44:53 +02004765 Py_XDECREF(self->ctx);
4766 if (self->session != NULL) {
4767 SSL_SESSION_free(self->session);
4768 }
Christian Heimesa5d07652016-09-24 10:48:05 +02004769 PyObject_GC_Del(self);
Christian Heimes5c36da72020-11-20 09:40:12 +01004770 Py_DECREF(tp);
Christian Heimes99a65702016-09-10 23:44:53 +02004771}
4772
4773static PyObject *
4774PySSLSession_richcompare(PyObject *left, PyObject *right, int op)
4775{
4776 int result;
Christian Heimes7f1305e2021-04-17 20:06:38 +02004777 PyTypeObject *sesstype = ((PySSLSession*)left)->ctx->state->PySSLSession_Type;
Christian Heimes99a65702016-09-10 23:44:53 +02004778
4779 if (left == NULL || right == NULL) {
4780 PyErr_BadInternalCall();
4781 return NULL;
4782 }
4783
Christian Heimes7f1305e2021-04-17 20:06:38 +02004784 if (!Py_IS_TYPE(left, sesstype) || !Py_IS_TYPE(right, sesstype)) {
Christian Heimes99a65702016-09-10 23:44:53 +02004785 Py_RETURN_NOTIMPLEMENTED;
4786 }
4787
4788 if (left == right) {
4789 result = 0;
4790 } else {
4791 const unsigned char *left_id, *right_id;
4792 unsigned int left_len, right_len;
4793 left_id = SSL_SESSION_get_id(((PySSLSession *)left)->session,
4794 &left_len);
4795 right_id = SSL_SESSION_get_id(((PySSLSession *)right)->session,
4796 &right_len);
4797 if (left_len == right_len) {
4798 result = memcmp(left_id, right_id, left_len);
4799 } else {
4800 result = 1;
4801 }
4802 }
4803
4804 switch (op) {
4805 case Py_EQ:
4806 if (result == 0) {
4807 Py_RETURN_TRUE;
4808 } else {
4809 Py_RETURN_FALSE;
4810 }
4811 break;
4812 case Py_NE:
4813 if (result != 0) {
4814 Py_RETURN_TRUE;
4815 } else {
4816 Py_RETURN_FALSE;
4817 }
4818 break;
4819 case Py_LT:
4820 case Py_LE:
4821 case Py_GT:
4822 case Py_GE:
4823 Py_RETURN_NOTIMPLEMENTED;
4824 break;
4825 default:
4826 PyErr_BadArgument();
4827 return NULL;
4828 }
4829}
4830
4831static int
4832PySSLSession_traverse(PySSLSession *self, visitproc visit, void *arg)
4833{
4834 Py_VISIT(self->ctx);
4835 return 0;
4836}
4837
4838static int
4839PySSLSession_clear(PySSLSession *self)
4840{
4841 Py_CLEAR(self->ctx);
4842 return 0;
4843}
4844
4845
4846static PyObject *
4847PySSLSession_get_time(PySSLSession *self, void *closure) {
4848 return PyLong_FromLong(SSL_SESSION_get_time(self->session));
4849}
4850
4851PyDoc_STRVAR(PySSLSession_get_time_doc,
4852"Session creation time (seconds since epoch).");
4853
4854
4855static PyObject *
4856PySSLSession_get_timeout(PySSLSession *self, void *closure) {
4857 return PyLong_FromLong(SSL_SESSION_get_timeout(self->session));
4858}
4859
4860PyDoc_STRVAR(PySSLSession_get_timeout_doc,
4861"Session timeout (delta in seconds).");
4862
4863
4864static PyObject *
4865PySSLSession_get_ticket_lifetime_hint(PySSLSession *self, void *closure) {
4866 unsigned long hint = SSL_SESSION_get_ticket_lifetime_hint(self->session);
4867 return PyLong_FromUnsignedLong(hint);
4868}
4869
4870PyDoc_STRVAR(PySSLSession_get_ticket_lifetime_hint_doc,
4871"Ticket life time hint.");
4872
4873
4874static PyObject *
4875PySSLSession_get_session_id(PySSLSession *self, void *closure) {
4876 const unsigned char *id;
4877 unsigned int len;
4878 id = SSL_SESSION_get_id(self->session, &len);
4879 return PyBytes_FromStringAndSize((const char *)id, len);
4880}
4881
4882PyDoc_STRVAR(PySSLSession_get_session_id_doc,
4883"Session id");
4884
4885
4886static PyObject *
4887PySSLSession_get_has_ticket(PySSLSession *self, void *closure) {
4888 if (SSL_SESSION_has_ticket(self->session)) {
4889 Py_RETURN_TRUE;
4890 } else {
4891 Py_RETURN_FALSE;
4892 }
4893}
4894
4895PyDoc_STRVAR(PySSLSession_get_has_ticket_doc,
4896"Does the session contain a ticket?");
4897
4898
4899static PyGetSetDef PySSLSession_getsetlist[] = {
4900 {"has_ticket", (getter) PySSLSession_get_has_ticket, NULL,
4901 PySSLSession_get_has_ticket_doc},
4902 {"id", (getter) PySSLSession_get_session_id, NULL,
4903 PySSLSession_get_session_id_doc},
4904 {"ticket_lifetime_hint", (getter) PySSLSession_get_ticket_lifetime_hint,
4905 NULL, PySSLSession_get_ticket_lifetime_hint_doc},
4906 {"time", (getter) PySSLSession_get_time, NULL,
4907 PySSLSession_get_time_doc},
4908 {"timeout", (getter) PySSLSession_get_timeout, NULL,
4909 PySSLSession_get_timeout_doc},
4910 {NULL}, /* sentinel */
4911};
4912
Christian Heimes5c36da72020-11-20 09:40:12 +01004913static PyType_Slot PySSLSession_slots[] = {
4914 {Py_tp_getset,PySSLSession_getsetlist},
4915 {Py_tp_richcompare, PySSLSession_richcompare},
4916 {Py_tp_dealloc, PySSLSession_dealloc},
4917 {Py_tp_traverse, PySSLSession_traverse},
4918 {Py_tp_clear, PySSLSession_clear},
4919 {0, 0},
4920};
4921
4922static PyType_Spec PySSLSession_spec = {
4923 "_ssl.SSLSession",
4924 sizeof(PySSLSession),
4925 0,
4926 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,
4927 PySSLSession_slots,
Christian Heimes99a65702016-09-10 23:44:53 +02004928};
4929
4930
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004931/* helper routines for seeding the SSL PRNG */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004932/*[clinic input]
4933_ssl.RAND_add
Larry Hastingsdbfdc382015-05-04 06:59:46 -07004934 string as view: Py_buffer(accept={str, buffer})
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004935 entropy: double
4936 /
4937
4938Mix string into the OpenSSL PRNG state.
4939
4940entropy (a float) is a lower bound on the entropy contained in
Chandan Kumar63c2c8a2017-06-09 15:13:58 +05304941string. See RFC 4086.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004942[clinic start generated code]*/
4943
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004944static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004945_ssl_RAND_add_impl(PyObject *module, Py_buffer *view, double entropy)
Serhiy Storchaka5f31d5c2017-06-10 13:13:51 +03004946/*[clinic end generated code: output=e6dd48df9c9024e9 input=5c33017422828f5c]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004947{
Serhiy Storchaka8490f5a2015-03-20 09:00:36 +02004948 const char *buf;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02004949 Py_ssize_t len, written;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004950
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004951 buf = (const char *)view->buf;
4952 len = view->len;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02004953 do {
4954 written = Py_MIN(len, INT_MAX);
4955 RAND_add(buf, (int)written, entropy);
4956 buf += written;
4957 len -= written;
4958 } while (len);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02004959 Py_RETURN_NONE;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004960}
4961
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004962static PyObject *
Christian Heimes7f1305e2021-04-17 20:06:38 +02004963PySSL_RAND(PyObject *module, int len, int pseudo)
Victor Stinner99c8b162011-05-24 12:05:19 +02004964{
4965 int ok;
4966 PyObject *bytes;
4967 unsigned long err;
4968 const char *errstr;
4969 PyObject *v;
4970
Victor Stinner1e81a392013-12-19 16:47:04 +01004971 if (len < 0) {
4972 PyErr_SetString(PyExc_ValueError, "num must be positive");
4973 return NULL;
4974 }
4975
Victor Stinner99c8b162011-05-24 12:05:19 +02004976 bytes = PyBytes_FromStringAndSize(NULL, len);
4977 if (bytes == NULL)
4978 return NULL;
4979 if (pseudo) {
Christian Heimesa871f692020-06-01 08:58:14 +02004980 ok = RAND_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
Victor Stinner99c8b162011-05-24 12:05:19 +02004981 if (ok == 0 || ok == 1)
4982 return Py_BuildValue("NO", bytes, ok == 1 ? Py_True : Py_False);
4983 }
4984 else {
4985 ok = RAND_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
4986 if (ok == 1)
4987 return bytes;
4988 }
4989 Py_DECREF(bytes);
4990
4991 err = ERR_get_error();
4992 errstr = ERR_reason_error_string(err);
4993 v = Py_BuildValue("(ks)", err, errstr);
4994 if (v != NULL) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02004995 PyErr_SetObject(get_ssl_state(module)->PySSLErrorObject, v);
Victor Stinner99c8b162011-05-24 12:05:19 +02004996 Py_DECREF(v);
4997 }
4998 return NULL;
4999}
5000
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005001/*[clinic input]
5002_ssl.RAND_bytes
5003 n: int
5004 /
5005
5006Generate n cryptographically strong pseudo-random bytes.
5007[clinic start generated code]*/
5008
Victor Stinner99c8b162011-05-24 12:05:19 +02005009static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005010_ssl_RAND_bytes_impl(PyObject *module, int n)
5011/*[clinic end generated code: output=977da635e4838bc7 input=678ddf2872dfebfc]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02005012{
Christian Heimes7f1305e2021-04-17 20:06:38 +02005013 return PySSL_RAND(module, n, 0);
Victor Stinner99c8b162011-05-24 12:05:19 +02005014}
5015
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005016/*[clinic input]
5017_ssl.RAND_pseudo_bytes
5018 n: int
5019 /
5020
5021Generate n pseudo-random bytes.
5022
5023Return a pair (bytes, is_cryptographic). is_cryptographic is True
5024if the bytes generated are cryptographically strong.
5025[clinic start generated code]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02005026
5027static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005028_ssl_RAND_pseudo_bytes_impl(PyObject *module, int n)
5029/*[clinic end generated code: output=b1509e937000e52d input=58312bd53f9bbdd0]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02005030{
Christian Heimes2875c602021-04-19 07:27:10 +02005031 PY_SSL_DEPRECATED("RAND_pseudo_bytes", 1, NULL);
Christian Heimes7f1305e2021-04-17 20:06:38 +02005032 return PySSL_RAND(module, n, 1);
Victor Stinner99c8b162011-05-24 12:05:19 +02005033}
5034
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005035/*[clinic input]
5036_ssl.RAND_status
5037
5038Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.
5039
5040It is necessary to seed the PRNG with RAND_add() on some platforms before
5041using the ssl() function.
5042[clinic start generated code]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02005043
5044static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005045_ssl_RAND_status_impl(PyObject *module)
5046/*[clinic end generated code: output=7e0aaa2d39fdc1ad input=8a774b02d1dc81f3]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005047{
Christian Heimes217cfd12007-12-02 14:31:20 +00005048 return PyLong_FromLong(RAND_status());
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005049}
5050
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005051/*[clinic input]
5052_ssl.get_default_verify_paths
5053
5054Return search paths and environment vars that are used by SSLContext's set_default_verify_paths() to load default CAs.
5055
5056The values are 'cert_file_env', 'cert_file', 'cert_dir_env', 'cert_dir'.
5057[clinic start generated code]*/
Christian Heimes6d7ad132013-06-09 18:02:55 +02005058
5059static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005060_ssl_get_default_verify_paths_impl(PyObject *module)
5061/*[clinic end generated code: output=e5b62a466271928b input=5210c953d98c3eb5]*/
Christian Heimes6d7ad132013-06-09 18:02:55 +02005062{
5063 PyObject *ofile_env = NULL;
5064 PyObject *ofile = NULL;
5065 PyObject *odir_env = NULL;
5066 PyObject *odir = NULL;
5067
Benjamin Petersond113c962015-07-18 10:59:13 -07005068#define CONVERT(info, target) { \
Christian Heimes6d7ad132013-06-09 18:02:55 +02005069 const char *tmp = (info); \
5070 target = NULL; \
5071 if (!tmp) { Py_INCREF(Py_None); target = Py_None; } \
5072 else if ((target = PyUnicode_DecodeFSDefault(tmp)) == NULL) { \
5073 target = PyBytes_FromString(tmp); } \
5074 if (!target) goto error; \
Benjamin Peterson025a1fd2015-11-14 15:12:38 -08005075 }
Christian Heimes6d7ad132013-06-09 18:02:55 +02005076
Benjamin Petersond113c962015-07-18 10:59:13 -07005077 CONVERT(X509_get_default_cert_file_env(), ofile_env);
5078 CONVERT(X509_get_default_cert_file(), ofile);
5079 CONVERT(X509_get_default_cert_dir_env(), odir_env);
5080 CONVERT(X509_get_default_cert_dir(), odir);
5081#undef CONVERT
Christian Heimes6d7ad132013-06-09 18:02:55 +02005082
Christian Heimes200bb1b2013-06-14 15:14:29 +02005083 return Py_BuildValue("NNNN", ofile_env, ofile, odir_env, odir);
Christian Heimes6d7ad132013-06-09 18:02:55 +02005084
5085 error:
5086 Py_XDECREF(ofile_env);
5087 Py_XDECREF(ofile);
5088 Py_XDECREF(odir_env);
5089 Py_XDECREF(odir);
5090 return NULL;
5091}
5092
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005093static PyObject*
Christian Heimes7f1305e2021-04-17 20:06:38 +02005094asn1obj2py(_sslmodulestate *state, ASN1_OBJECT *obj)
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005095{
5096 int nid;
5097 const char *ln, *sn;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005098
5099 nid = OBJ_obj2nid(obj);
5100 if (nid == NID_undef) {
5101 PyErr_Format(PyExc_ValueError, "Unknown object");
5102 return NULL;
5103 }
5104 sn = OBJ_nid2sn(nid);
5105 ln = OBJ_nid2ln(nid);
Christian Heimes7f1305e2021-04-17 20:06:38 +02005106 return Py_BuildValue("issN", nid, sn, ln, _asn1obj2py(state, obj, 1));
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005107}
5108
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005109/*[clinic input]
5110_ssl.txt2obj
5111 txt: str
5112 name: bool = False
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005113
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005114Lookup NID, short name, long name and OID of an ASN1_OBJECT.
5115
5116By default objects are looked up by OID. With name=True short and
5117long name are also matched.
5118[clinic start generated code]*/
5119
5120static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005121_ssl_txt2obj_impl(PyObject *module, const char *txt, int name)
5122/*[clinic end generated code: output=c38e3991347079c1 input=1c1e7d0aa7c48602]*/
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005123{
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005124 PyObject *result = NULL;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005125 ASN1_OBJECT *obj;
5126
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005127 obj = OBJ_txt2obj(txt, name ? 0 : 1);
5128 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01005129 PyErr_Format(PyExc_ValueError, "unknown object '%.100s'", txt);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005130 return NULL;
5131 }
Christian Heimes7f1305e2021-04-17 20:06:38 +02005132 result = asn1obj2py(get_ssl_state(module), obj);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005133 ASN1_OBJECT_free(obj);
5134 return result;
5135}
5136
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005137/*[clinic input]
5138_ssl.nid2obj
5139 nid: int
5140 /
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005141
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005142Lookup NID, short name, long name and OID of an ASN1_OBJECT by NID.
5143[clinic start generated code]*/
5144
5145static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005146_ssl_nid2obj_impl(PyObject *module, int nid)
5147/*[clinic end generated code: output=4a98ab691cd4f84a input=51787a3bee7d8f98]*/
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005148{
5149 PyObject *result = NULL;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005150 ASN1_OBJECT *obj;
5151
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005152 if (nid < NID_undef) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01005153 PyErr_SetString(PyExc_ValueError, "NID must be positive.");
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005154 return NULL;
5155 }
5156 obj = OBJ_nid2obj(nid);
5157 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01005158 PyErr_Format(PyExc_ValueError, "unknown NID %i", nid);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005159 return NULL;
5160 }
Christian Heimes7f1305e2021-04-17 20:06:38 +02005161 result = asn1obj2py(get_ssl_state(module), obj);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005162 ASN1_OBJECT_free(obj);
5163 return result;
5164}
5165
Christian Heimes46bebee2013-06-09 19:03:31 +02005166#ifdef _MSC_VER
Christian Heimes44109d72013-11-22 01:51:30 +01005167
5168static PyObject*
5169certEncodingType(DWORD encodingType)
5170{
5171 static PyObject *x509_asn = NULL;
5172 static PyObject *pkcs_7_asn = NULL;
5173
5174 if (x509_asn == NULL) {
5175 x509_asn = PyUnicode_InternFromString("x509_asn");
5176 if (x509_asn == NULL)
5177 return NULL;
5178 }
5179 if (pkcs_7_asn == NULL) {
5180 pkcs_7_asn = PyUnicode_InternFromString("pkcs_7_asn");
5181 if (pkcs_7_asn == NULL)
5182 return NULL;
5183 }
5184 switch(encodingType) {
5185 case X509_ASN_ENCODING:
5186 Py_INCREF(x509_asn);
5187 return x509_asn;
5188 case PKCS_7_ASN_ENCODING:
5189 Py_INCREF(pkcs_7_asn);
5190 return pkcs_7_asn;
5191 default:
5192 return PyLong_FromLong(encodingType);
5193 }
5194}
5195
5196static PyObject*
5197parseKeyUsage(PCCERT_CONTEXT pCertCtx, DWORD flags)
5198{
5199 CERT_ENHKEY_USAGE *usage;
5200 DWORD size, error, i;
5201 PyObject *retval;
5202
5203 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, NULL, &size)) {
5204 error = GetLastError();
5205 if (error == CRYPT_E_NOT_FOUND) {
5206 Py_RETURN_TRUE;
5207 }
5208 return PyErr_SetFromWindowsErr(error);
5209 }
5210
5211 usage = (CERT_ENHKEY_USAGE*)PyMem_Malloc(size);
5212 if (usage == NULL) {
5213 return PyErr_NoMemory();
5214 }
5215
5216 /* Now get the actual enhanced usage property */
5217 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, usage, &size)) {
5218 PyMem_Free(usage);
5219 error = GetLastError();
5220 if (error == CRYPT_E_NOT_FOUND) {
5221 Py_RETURN_TRUE;
5222 }
5223 return PyErr_SetFromWindowsErr(error);
5224 }
Christian Heimes915cd3f2019-09-09 18:06:55 +02005225 retval = PyFrozenSet_New(NULL);
Christian Heimes44109d72013-11-22 01:51:30 +01005226 if (retval == NULL) {
5227 goto error;
5228 }
5229 for (i = 0; i < usage->cUsageIdentifier; ++i) {
5230 if (usage->rgpszUsageIdentifier[i]) {
5231 PyObject *oid;
5232 int err;
5233 oid = PyUnicode_FromString(usage->rgpszUsageIdentifier[i]);
5234 if (oid == NULL) {
5235 Py_CLEAR(retval);
5236 goto error;
5237 }
5238 err = PySet_Add(retval, oid);
5239 Py_DECREF(oid);
5240 if (err == -1) {
5241 Py_CLEAR(retval);
5242 goto error;
5243 }
5244 }
5245 }
5246 error:
5247 PyMem_Free(usage);
5248 return retval;
5249}
5250
kctherookied93fbbf2019-03-29 00:59:06 +07005251static HCERTSTORE
5252ssl_collect_certificates(const char *store_name)
5253{
5254/* this function collects the system certificate stores listed in
5255 * system_stores into a collection certificate store for being
5256 * enumerated. The store must be readable to be added to the
5257 * store collection.
5258 */
5259
5260 HCERTSTORE hCollectionStore = NULL, hSystemStore = NULL;
5261 static DWORD system_stores[] = {
5262 CERT_SYSTEM_STORE_LOCAL_MACHINE,
5263 CERT_SYSTEM_STORE_LOCAL_MACHINE_ENTERPRISE,
5264 CERT_SYSTEM_STORE_LOCAL_MACHINE_GROUP_POLICY,
5265 CERT_SYSTEM_STORE_CURRENT_USER,
5266 CERT_SYSTEM_STORE_CURRENT_USER_GROUP_POLICY,
5267 CERT_SYSTEM_STORE_SERVICES,
5268 CERT_SYSTEM_STORE_USERS};
5269 size_t i, storesAdded;
5270 BOOL result;
5271
5272 hCollectionStore = CertOpenStore(CERT_STORE_PROV_COLLECTION, 0,
5273 (HCRYPTPROV)NULL, 0, NULL);
5274 if (!hCollectionStore) {
5275 return NULL;
5276 }
5277 storesAdded = 0;
5278 for (i = 0; i < sizeof(system_stores) / sizeof(DWORD); i++) {
5279 hSystemStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0,
5280 (HCRYPTPROV)NULL,
5281 CERT_STORE_READONLY_FLAG |
5282 system_stores[i], store_name);
5283 if (hSystemStore) {
5284 result = CertAddStoreToCollection(hCollectionStore, hSystemStore,
5285 CERT_PHYSICAL_STORE_ADD_ENABLE_FLAG, 0);
5286 if (result) {
5287 ++storesAdded;
5288 }
neoneneed701292019-09-09 21:33:43 +09005289 CertCloseStore(hSystemStore, 0); /* flag must be 0 */
kctherookied93fbbf2019-03-29 00:59:06 +07005290 }
5291 }
5292 if (storesAdded == 0) {
5293 CertCloseStore(hCollectionStore, CERT_CLOSE_STORE_FORCE_FLAG);
5294 return NULL;
5295 }
5296
5297 return hCollectionStore;
5298}
5299
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005300/*[clinic input]
5301_ssl.enum_certificates
5302 store_name: str
5303
5304Retrieve certificates from Windows' cert store.
5305
5306store_name may be one of 'CA', 'ROOT' or 'MY'. The system may provide
5307more cert storages, too. The function returns a list of (bytes,
5308encoding_type, trust) tuples. The encoding_type flag can be interpreted
5309with X509_ASN_ENCODING or PKCS_7_ASN_ENCODING. The trust setting is either
5310a set of OIDs or the boolean True.
5311[clinic start generated code]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00005312
Christian Heimes46bebee2013-06-09 19:03:31 +02005313static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005314_ssl_enum_certificates_impl(PyObject *module, const char *store_name)
5315/*[clinic end generated code: output=5134dc8bb3a3c893 input=915f60d70461ea4e]*/
Christian Heimes46bebee2013-06-09 19:03:31 +02005316{
kctherookied93fbbf2019-03-29 00:59:06 +07005317 HCERTSTORE hCollectionStore = NULL;
Christian Heimes44109d72013-11-22 01:51:30 +01005318 PCCERT_CONTEXT pCertCtx = NULL;
5319 PyObject *keyusage = NULL, *cert = NULL, *enc = NULL, *tup = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02005320 PyObject *result = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02005321
Christian Heimes915cd3f2019-09-09 18:06:55 +02005322 result = PySet_New(NULL);
Christian Heimes44109d72013-11-22 01:51:30 +01005323 if (result == NULL) {
5324 return NULL;
5325 }
kctherookied93fbbf2019-03-29 00:59:06 +07005326 hCollectionStore = ssl_collect_certificates(store_name);
5327 if (hCollectionStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02005328 Py_DECREF(result);
5329 return PyErr_SetFromWindowsErr(GetLastError());
5330 }
5331
kctherookied93fbbf2019-03-29 00:59:06 +07005332 while (pCertCtx = CertEnumCertificatesInStore(hCollectionStore, pCertCtx)) {
Christian Heimes44109d72013-11-22 01:51:30 +01005333 cert = PyBytes_FromStringAndSize((const char*)pCertCtx->pbCertEncoded,
5334 pCertCtx->cbCertEncoded);
5335 if (!cert) {
5336 Py_CLEAR(result);
5337 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02005338 }
Christian Heimes44109d72013-11-22 01:51:30 +01005339 if ((enc = certEncodingType(pCertCtx->dwCertEncodingType)) == NULL) {
5340 Py_CLEAR(result);
5341 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02005342 }
Christian Heimes44109d72013-11-22 01:51:30 +01005343 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG);
5344 if (keyusage == Py_True) {
5345 Py_DECREF(keyusage);
5346 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_EXT_ONLY_ENHKEY_USAGE_FLAG);
Christian Heimes46bebee2013-06-09 19:03:31 +02005347 }
Christian Heimes44109d72013-11-22 01:51:30 +01005348 if (keyusage == NULL) {
5349 Py_CLEAR(result);
5350 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02005351 }
Christian Heimes44109d72013-11-22 01:51:30 +01005352 if ((tup = PyTuple_New(3)) == NULL) {
5353 Py_CLEAR(result);
5354 break;
5355 }
5356 PyTuple_SET_ITEM(tup, 0, cert);
5357 cert = NULL;
5358 PyTuple_SET_ITEM(tup, 1, enc);
5359 enc = NULL;
5360 PyTuple_SET_ITEM(tup, 2, keyusage);
5361 keyusage = NULL;
Christian Heimes915cd3f2019-09-09 18:06:55 +02005362 if (PySet_Add(result, tup) == -1) {
5363 Py_CLEAR(result);
5364 Py_CLEAR(tup);
5365 break;
Christian Heimes44109d72013-11-22 01:51:30 +01005366 }
5367 Py_CLEAR(tup);
5368 }
5369 if (pCertCtx) {
5370 /* loop ended with an error, need to clean up context manually */
5371 CertFreeCertificateContext(pCertCtx);
Christian Heimes46bebee2013-06-09 19:03:31 +02005372 }
5373
5374 /* In error cases cert, enc and tup may not be NULL */
5375 Py_XDECREF(cert);
5376 Py_XDECREF(enc);
Christian Heimes44109d72013-11-22 01:51:30 +01005377 Py_XDECREF(keyusage);
Christian Heimes46bebee2013-06-09 19:03:31 +02005378 Py_XDECREF(tup);
5379
kctherookied93fbbf2019-03-29 00:59:06 +07005380 /* CERT_CLOSE_STORE_FORCE_FLAG forces freeing of memory for all contexts
5381 associated with the store, in this case our collection store and the
5382 associated system stores. */
5383 if (!CertCloseStore(hCollectionStore, CERT_CLOSE_STORE_FORCE_FLAG)) {
Christian Heimes46bebee2013-06-09 19:03:31 +02005384 /* This error case might shadow another exception.*/
Christian Heimes44109d72013-11-22 01:51:30 +01005385 Py_XDECREF(result);
5386 return PyErr_SetFromWindowsErr(GetLastError());
5387 }
kctherookied93fbbf2019-03-29 00:59:06 +07005388
Christian Heimes915cd3f2019-09-09 18:06:55 +02005389 /* convert set to list */
5390 if (result == NULL) {
5391 return NULL;
5392 } else {
5393 PyObject *lst = PySequence_List(result);
5394 Py_DECREF(result);
5395 return lst;
5396 }
Christian Heimes44109d72013-11-22 01:51:30 +01005397}
5398
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005399/*[clinic input]
5400_ssl.enum_crls
5401 store_name: str
5402
5403Retrieve CRLs from Windows' cert store.
5404
5405store_name may be one of 'CA', 'ROOT' or 'MY'. The system may provide
5406more cert storages, too. The function returns a list of (bytes,
5407encoding_type) tuples. The encoding_type flag can be interpreted with
5408X509_ASN_ENCODING or PKCS_7_ASN_ENCODING.
5409[clinic start generated code]*/
Christian Heimes44109d72013-11-22 01:51:30 +01005410
5411static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005412_ssl_enum_crls_impl(PyObject *module, const char *store_name)
5413/*[clinic end generated code: output=bce467f60ccd03b6 input=a1f1d7629f1c5d3d]*/
Christian Heimes44109d72013-11-22 01:51:30 +01005414{
kctherookied93fbbf2019-03-29 00:59:06 +07005415 HCERTSTORE hCollectionStore = NULL;
Christian Heimes44109d72013-11-22 01:51:30 +01005416 PCCRL_CONTEXT pCrlCtx = NULL;
5417 PyObject *crl = NULL, *enc = NULL, *tup = NULL;
5418 PyObject *result = NULL;
5419
Christian Heimes915cd3f2019-09-09 18:06:55 +02005420 result = PySet_New(NULL);
Christian Heimes44109d72013-11-22 01:51:30 +01005421 if (result == NULL) {
5422 return NULL;
5423 }
kctherookied93fbbf2019-03-29 00:59:06 +07005424 hCollectionStore = ssl_collect_certificates(store_name);
5425 if (hCollectionStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02005426 Py_DECREF(result);
5427 return PyErr_SetFromWindowsErr(GetLastError());
5428 }
Christian Heimes44109d72013-11-22 01:51:30 +01005429
kctherookied93fbbf2019-03-29 00:59:06 +07005430 while (pCrlCtx = CertEnumCRLsInStore(hCollectionStore, pCrlCtx)) {
Christian Heimes44109d72013-11-22 01:51:30 +01005431 crl = PyBytes_FromStringAndSize((const char*)pCrlCtx->pbCrlEncoded,
5432 pCrlCtx->cbCrlEncoded);
5433 if (!crl) {
5434 Py_CLEAR(result);
5435 break;
5436 }
5437 if ((enc = certEncodingType(pCrlCtx->dwCertEncodingType)) == NULL) {
5438 Py_CLEAR(result);
5439 break;
5440 }
5441 if ((tup = PyTuple_New(2)) == NULL) {
5442 Py_CLEAR(result);
5443 break;
5444 }
5445 PyTuple_SET_ITEM(tup, 0, crl);
5446 crl = NULL;
5447 PyTuple_SET_ITEM(tup, 1, enc);
5448 enc = NULL;
5449
Christian Heimes915cd3f2019-09-09 18:06:55 +02005450 if (PySet_Add(result, tup) == -1) {
5451 Py_CLEAR(result);
5452 Py_CLEAR(tup);
5453 break;
Christian Heimes44109d72013-11-22 01:51:30 +01005454 }
5455 Py_CLEAR(tup);
Christian Heimes46bebee2013-06-09 19:03:31 +02005456 }
Christian Heimes44109d72013-11-22 01:51:30 +01005457 if (pCrlCtx) {
5458 /* loop ended with an error, need to clean up context manually */
5459 CertFreeCRLContext(pCrlCtx);
5460 }
5461
5462 /* In error cases cert, enc and tup may not be NULL */
5463 Py_XDECREF(crl);
5464 Py_XDECREF(enc);
5465 Py_XDECREF(tup);
5466
kctherookied93fbbf2019-03-29 00:59:06 +07005467 /* CERT_CLOSE_STORE_FORCE_FLAG forces freeing of memory for all contexts
5468 associated with the store, in this case our collection store and the
5469 associated system stores. */
5470 if (!CertCloseStore(hCollectionStore, CERT_CLOSE_STORE_FORCE_FLAG)) {
Christian Heimes44109d72013-11-22 01:51:30 +01005471 /* This error case might shadow another exception.*/
5472 Py_XDECREF(result);
5473 return PyErr_SetFromWindowsErr(GetLastError());
5474 }
Christian Heimes915cd3f2019-09-09 18:06:55 +02005475 /* convert set to list */
5476 if (result == NULL) {
5477 return NULL;
5478 } else {
5479 PyObject *lst = PySequence_List(result);
5480 Py_DECREF(result);
5481 return lst;
5482 }
Christian Heimes46bebee2013-06-09 19:03:31 +02005483}
Christian Heimes44109d72013-11-22 01:51:30 +01005484
5485#endif /* _MSC_VER */
Bill Janssen40a0f662008-08-12 16:56:25 +00005486
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005487/* List of functions exported by this module. */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005488static PyMethodDef PySSL_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005489 _SSL__TEST_DECODE_CERT_METHODDEF
5490 _SSL_RAND_ADD_METHODDEF
5491 _SSL_RAND_BYTES_METHODDEF
5492 _SSL_RAND_PSEUDO_BYTES_METHODDEF
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005493 _SSL_RAND_STATUS_METHODDEF
5494 _SSL_GET_DEFAULT_VERIFY_PATHS_METHODDEF
5495 _SSL_ENUM_CERTIFICATES_METHODDEF
5496 _SSL_ENUM_CRLS_METHODDEF
5497 _SSL_TXT2OBJ_METHODDEF
5498 _SSL_NID2OBJ_METHODDEF
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005499 {NULL, NULL} /* Sentinel */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005500};
5501
5502
Christian Heimes7f1305e2021-04-17 20:06:38 +02005503PyDoc_STRVAR(module_doc,
5504"Implementation module for SSL socket operations. See the socket module\n\
5505for documentation.");
Christian Heimes5c36da72020-11-20 09:40:12 +01005506
5507static int
5508sslmodule_init_exceptions(PyObject *module)
5509{
Christian Heimes7f1305e2021-04-17 20:06:38 +02005510 _sslmodulestate *state = get_ssl_state(module);
Christian Heimes5c36da72020-11-20 09:40:12 +01005511 PyObject *bases = NULL;
5512
Christian Heimes7f1305e2021-04-17 20:06:38 +02005513#define add_exception(exc, name, doc, base) \
5514do { \
5515 (exc) = PyErr_NewExceptionWithDoc("ssl." name, (doc), (base), NULL); \
5516 if ((state) == NULL) goto error; \
5517 if (PyModule_AddObjectRef(module, name, exc) < 0) goto error; \
Christian Heimes5c36da72020-11-20 09:40:12 +01005518} while(0)
5519
Christian Heimes7f1305e2021-04-17 20:06:38 +02005520 state->PySSLErrorObject = PyType_FromSpecWithBases(
5521 &sslerror_type_spec, PyExc_OSError);
5522 if (state->PySSLErrorObject == NULL) {
Christian Heimes5c36da72020-11-20 09:40:12 +01005523 goto error;
5524 }
Christian Heimes7f1305e2021-04-17 20:06:38 +02005525 if (PyModule_AddObjectRef(module, "SSLError", state->PySSLErrorObject) < 0) {
Christian Heimes5c36da72020-11-20 09:40:12 +01005526 goto error;
5527 }
5528
5529 /* ssl.CertificateError used to be a subclass of ValueError */
Christian Heimes7f1305e2021-04-17 20:06:38 +02005530 bases = PyTuple_Pack(2, state->PySSLErrorObject, PyExc_ValueError);
Christian Heimes5c36da72020-11-20 09:40:12 +01005531 if (bases == NULL) {
5532 goto error;
5533 }
5534 add_exception(
Christian Heimes7f1305e2021-04-17 20:06:38 +02005535 state->PySSLCertVerificationErrorObject,
Christian Heimes5c36da72020-11-20 09:40:12 +01005536 "SSLCertVerificationError",
5537 SSLCertVerificationError_doc,
5538 bases
5539 );
5540 Py_CLEAR(bases);
5541
5542 add_exception(
Christian Heimes7f1305e2021-04-17 20:06:38 +02005543 state->PySSLZeroReturnErrorObject,
Christian Heimes5c36da72020-11-20 09:40:12 +01005544 "SSLZeroReturnError",
5545 SSLZeroReturnError_doc,
Christian Heimes7f1305e2021-04-17 20:06:38 +02005546 state->PySSLErrorObject
Christian Heimes5c36da72020-11-20 09:40:12 +01005547 );
5548
5549 add_exception(
Christian Heimes7f1305e2021-04-17 20:06:38 +02005550 state->PySSLWantWriteErrorObject,
Christian Heimes5c36da72020-11-20 09:40:12 +01005551 "SSLWantWriteError",
5552 SSLWantWriteError_doc,
Christian Heimes7f1305e2021-04-17 20:06:38 +02005553 state->PySSLErrorObject
Christian Heimes5c36da72020-11-20 09:40:12 +01005554 );
5555
5556 add_exception(
Christian Heimes7f1305e2021-04-17 20:06:38 +02005557 state->PySSLWantReadErrorObject,
Christian Heimes5c36da72020-11-20 09:40:12 +01005558 "SSLWantReadError",
5559 SSLWantReadError_doc,
Christian Heimes7f1305e2021-04-17 20:06:38 +02005560 state->PySSLErrorObject
Christian Heimes5c36da72020-11-20 09:40:12 +01005561 );
5562
5563 add_exception(
Christian Heimes7f1305e2021-04-17 20:06:38 +02005564 state->PySSLSyscallErrorObject,
Christian Heimes5c36da72020-11-20 09:40:12 +01005565 "SSLSyscallError",
5566 SSLSyscallError_doc,
Christian Heimes7f1305e2021-04-17 20:06:38 +02005567 state->PySSLErrorObject
Christian Heimes5c36da72020-11-20 09:40:12 +01005568 );
5569
5570 add_exception(
Christian Heimes7f1305e2021-04-17 20:06:38 +02005571 state->PySSLEOFErrorObject,
Christian Heimes5c36da72020-11-20 09:40:12 +01005572 "SSLEOFError",
5573 SSLEOFError_doc,
Christian Heimes7f1305e2021-04-17 20:06:38 +02005574 state->PySSLErrorObject
Christian Heimes5c36da72020-11-20 09:40:12 +01005575 );
5576#undef add_exception
5577
5578 return 0;
5579 error:
5580 Py_XDECREF(bases);
5581 return -1;
5582}
5583
5584static int
5585sslmodule_init_socketapi(PyObject *module)
5586{
Christian Heimes7f1305e2021-04-17 20:06:38 +02005587 _sslmodulestate *state = get_ssl_state(module);
5588 PySocketModule_APIObject *sockmod = PySocketModule_ImportModuleAndAPI();
Christian Heimes5c36da72020-11-20 09:40:12 +01005589
Christian Heimes7f1305e2021-04-17 20:06:38 +02005590 if ((sockmod == NULL) || (sockmod->Sock_Type == NULL)) {
Christian Heimes5c36da72020-11-20 09:40:12 +01005591 return -1;
Christian Heimes5c36da72020-11-20 09:40:12 +01005592 }
Christian Heimes7f1305e2021-04-17 20:06:38 +02005593 state->Sock_Type = sockmod->Sock_Type;
5594 Py_INCREF(state->Sock_Type);
Christian Heimes5c36da72020-11-20 09:40:12 +01005595 return 0;
5596}
Christian Heimesc941e622017-09-05 15:47:11 +02005597
Christian Heimes5c36da72020-11-20 09:40:12 +01005598static int
5599sslmodule_init_constants(PyObject *m)
5600{
Christian Heimes7f1305e2021-04-17 20:06:38 +02005601
Christian Heimes892d66e2018-01-29 14:10:18 +01005602 PyModule_AddStringConstant(m, "_DEFAULT_CIPHERS",
5603 PY_SSL_DEFAULT_CIPHER_STRING);
5604
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005605 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
5606 PY_SSL_ERROR_ZERO_RETURN);
5607 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
5608 PY_SSL_ERROR_WANT_READ);
5609 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
5610 PY_SSL_ERROR_WANT_WRITE);
5611 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
5612 PY_SSL_ERROR_WANT_X509_LOOKUP);
5613 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
5614 PY_SSL_ERROR_SYSCALL);
5615 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
5616 PY_SSL_ERROR_SSL);
5617 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
5618 PY_SSL_ERROR_WANT_CONNECT);
5619 /* non ssl.h errorcodes */
5620 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
5621 PY_SSL_ERROR_EOF);
5622 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
5623 PY_SSL_ERROR_INVALID_ERROR_CODE);
5624 /* cert requirements */
5625 PyModule_AddIntConstant(m, "CERT_NONE",
5626 PY_SSL_CERT_NONE);
5627 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
5628 PY_SSL_CERT_OPTIONAL);
5629 PyModule_AddIntConstant(m, "CERT_REQUIRED",
5630 PY_SSL_CERT_REQUIRED);
Christian Heimes22587792013-11-21 23:56:13 +01005631 /* CRL verification for verification_flags */
5632 PyModule_AddIntConstant(m, "VERIFY_DEFAULT",
5633 0);
5634 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_LEAF",
5635 X509_V_FLAG_CRL_CHECK);
5636 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_CHAIN",
5637 X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
5638 PyModule_AddIntConstant(m, "VERIFY_X509_STRICT",
5639 X509_V_FLAG_X509_STRICT);
Chris Burre0b4aa02021-03-18 09:24:01 +01005640 PyModule_AddIntConstant(m, "VERIFY_ALLOW_PROXY_CERTS",
5641 X509_V_FLAG_ALLOW_PROXY_CERTS);
Benjamin Peterson990fcaa2015-03-04 22:49:41 -05005642 PyModule_AddIntConstant(m, "VERIFY_X509_TRUSTED_FIRST",
5643 X509_V_FLAG_TRUSTED_FIRST);
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00005644
l0x64d97522021-04-19 13:51:18 +02005645#ifdef X509_V_FLAG_PARTIAL_CHAIN
5646 PyModule_AddIntConstant(m, "VERIFY_X509_PARTIAL_CHAIN",
5647 X509_V_FLAG_PARTIAL_CHAIN);
5648#endif
5649
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01005650 /* Alert Descriptions from ssl.h */
5651 /* note RESERVED constants no longer intended for use have been removed */
5652 /* http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-6 */
5653
5654#define ADD_AD_CONSTANT(s) \
5655 PyModule_AddIntConstant(m, "ALERT_DESCRIPTION_"#s, \
5656 SSL_AD_##s)
5657
5658 ADD_AD_CONSTANT(CLOSE_NOTIFY);
5659 ADD_AD_CONSTANT(UNEXPECTED_MESSAGE);
5660 ADD_AD_CONSTANT(BAD_RECORD_MAC);
5661 ADD_AD_CONSTANT(RECORD_OVERFLOW);
5662 ADD_AD_CONSTANT(DECOMPRESSION_FAILURE);
5663 ADD_AD_CONSTANT(HANDSHAKE_FAILURE);
5664 ADD_AD_CONSTANT(BAD_CERTIFICATE);
5665 ADD_AD_CONSTANT(UNSUPPORTED_CERTIFICATE);
5666 ADD_AD_CONSTANT(CERTIFICATE_REVOKED);
5667 ADD_AD_CONSTANT(CERTIFICATE_EXPIRED);
5668 ADD_AD_CONSTANT(CERTIFICATE_UNKNOWN);
5669 ADD_AD_CONSTANT(ILLEGAL_PARAMETER);
5670 ADD_AD_CONSTANT(UNKNOWN_CA);
5671 ADD_AD_CONSTANT(ACCESS_DENIED);
5672 ADD_AD_CONSTANT(DECODE_ERROR);
5673 ADD_AD_CONSTANT(DECRYPT_ERROR);
5674 ADD_AD_CONSTANT(PROTOCOL_VERSION);
5675 ADD_AD_CONSTANT(INSUFFICIENT_SECURITY);
5676 ADD_AD_CONSTANT(INTERNAL_ERROR);
5677 ADD_AD_CONSTANT(USER_CANCELLED);
5678 ADD_AD_CONSTANT(NO_RENEGOTIATION);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01005679 /* Not all constants are in old OpenSSL versions */
Antoine Pitrou912fbff2013-03-30 16:29:32 +01005680#ifdef SSL_AD_UNSUPPORTED_EXTENSION
5681 ADD_AD_CONSTANT(UNSUPPORTED_EXTENSION);
5682#endif
5683#ifdef SSL_AD_CERTIFICATE_UNOBTAINABLE
5684 ADD_AD_CONSTANT(CERTIFICATE_UNOBTAINABLE);
5685#endif
5686#ifdef SSL_AD_UNRECOGNIZED_NAME
5687 ADD_AD_CONSTANT(UNRECOGNIZED_NAME);
5688#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01005689#ifdef SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE
5690 ADD_AD_CONSTANT(BAD_CERTIFICATE_STATUS_RESPONSE);
5691#endif
5692#ifdef SSL_AD_BAD_CERTIFICATE_HASH_VALUE
5693 ADD_AD_CONSTANT(BAD_CERTIFICATE_HASH_VALUE);
5694#endif
5695#ifdef SSL_AD_UNKNOWN_PSK_IDENTITY
5696 ADD_AD_CONSTANT(UNKNOWN_PSK_IDENTITY);
5697#endif
5698
5699#undef ADD_AD_CONSTANT
5700
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005701 /* protocol versions */
Victor Stinner3de49192011-05-09 00:42:58 +02005702#ifndef OPENSSL_NO_SSL2
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005703 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
5704 PY_SSL_VERSION_SSL2);
Victor Stinner3de49192011-05-09 00:42:58 +02005705#endif
Benjamin Petersone32467c2014-12-05 21:59:35 -05005706#ifndef OPENSSL_NO_SSL3
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005707 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
5708 PY_SSL_VERSION_SSL3);
Benjamin Petersone32467c2014-12-05 21:59:35 -05005709#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005710 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
Christian Heimes598894f2016-09-05 23:19:05 +02005711 PY_SSL_VERSION_TLS);
5712 PyModule_AddIntConstant(m, "PROTOCOL_TLS",
5713 PY_SSL_VERSION_TLS);
Christian Heimes5fe668c2016-09-12 00:01:11 +02005714 PyModule_AddIntConstant(m, "PROTOCOL_TLS_CLIENT",
5715 PY_SSL_VERSION_TLS_CLIENT);
5716 PyModule_AddIntConstant(m, "PROTOCOL_TLS_SERVER",
5717 PY_SSL_VERSION_TLS_SERVER);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005718 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
5719 PY_SSL_VERSION_TLS1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01005720 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_1",
5721 PY_SSL_VERSION_TLS1_1);
5722 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_2",
5723 PY_SSL_VERSION_TLS1_2);
Antoine Pitrou04f6a322010-04-05 21:40:07 +00005724
Antoine Pitroub5218772010-05-21 09:56:06 +00005725 /* protocol options */
Antoine Pitrou3f366312012-01-27 09:50:45 +01005726 PyModule_AddIntConstant(m, "OP_ALL",
5727 SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
Antoine Pitroub5218772010-05-21 09:56:06 +00005728 PyModule_AddIntConstant(m, "OP_NO_SSLv2", SSL_OP_NO_SSLv2);
5729 PyModule_AddIntConstant(m, "OP_NO_SSLv3", SSL_OP_NO_SSLv3);
5730 PyModule_AddIntConstant(m, "OP_NO_TLSv1", SSL_OP_NO_TLSv1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01005731 PyModule_AddIntConstant(m, "OP_NO_TLSv1_1", SSL_OP_NO_TLSv1_1);
5732 PyModule_AddIntConstant(m, "OP_NO_TLSv1_2", SSL_OP_NO_TLSv1_2);
Christian Heimescb5b68a2017-09-07 18:07:00 -07005733#ifdef SSL_OP_NO_TLSv1_3
5734 PyModule_AddIntConstant(m, "OP_NO_TLSv1_3", SSL_OP_NO_TLSv1_3);
5735#else
5736 PyModule_AddIntConstant(m, "OP_NO_TLSv1_3", 0);
5737#endif
Antoine Pitrou6db49442011-12-19 13:27:11 +01005738 PyModule_AddIntConstant(m, "OP_CIPHER_SERVER_PREFERENCE",
5739 SSL_OP_CIPHER_SERVER_PREFERENCE);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01005740 PyModule_AddIntConstant(m, "OP_SINGLE_DH_USE", SSL_OP_SINGLE_DH_USE);
Christian Heimes99a65702016-09-10 23:44:53 +02005741 PyModule_AddIntConstant(m, "OP_NO_TICKET", SSL_OP_NO_TICKET);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01005742#ifdef SSL_OP_SINGLE_ECDH_USE
Antoine Pitrou923df6f2011-12-19 17:16:51 +01005743 PyModule_AddIntConstant(m, "OP_SINGLE_ECDH_USE", SSL_OP_SINGLE_ECDH_USE);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01005744#endif
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01005745#ifdef SSL_OP_NO_COMPRESSION
5746 PyModule_AddIntConstant(m, "OP_NO_COMPRESSION",
5747 SSL_OP_NO_COMPRESSION);
5748#endif
Christian Heimes05d9fe32018-02-27 08:55:39 +01005749#ifdef SSL_OP_ENABLE_MIDDLEBOX_COMPAT
5750 PyModule_AddIntConstant(m, "OP_ENABLE_MIDDLEBOX_COMPAT",
5751 SSL_OP_ENABLE_MIDDLEBOX_COMPAT);
5752#endif
Christian Heimes67c48012018-05-15 16:25:40 -04005753#ifdef SSL_OP_NO_RENEGOTIATION
5754 PyModule_AddIntConstant(m, "OP_NO_RENEGOTIATION",
5755 SSL_OP_NO_RENEGOTIATION);
5756#endif
Christian Heimes6f37ebc2021-04-09 17:59:21 +02005757#ifdef SSL_OP_IGNORE_UNEXPECTED_EOF
5758 PyModule_AddIntConstant(m, "OP_IGNORE_UNEXPECTED_EOF",
5759 SSL_OP_IGNORE_UNEXPECTED_EOF);
5760#endif
Antoine Pitroub5218772010-05-21 09:56:06 +00005761
Christian Heimes61d478c2018-01-27 15:51:38 +01005762#ifdef X509_CHECK_FLAG_ALWAYS_CHECK_SUBJECT
5763 PyModule_AddIntConstant(m, "HOSTFLAG_ALWAYS_CHECK_SUBJECT",
5764 X509_CHECK_FLAG_ALWAYS_CHECK_SUBJECT);
5765#endif
5766#ifdef X509_CHECK_FLAG_NEVER_CHECK_SUBJECT
5767 PyModule_AddIntConstant(m, "HOSTFLAG_NEVER_CHECK_SUBJECT",
5768 X509_CHECK_FLAG_NEVER_CHECK_SUBJECT);
5769#endif
5770#ifdef X509_CHECK_FLAG_NO_WILDCARDS
5771 PyModule_AddIntConstant(m, "HOSTFLAG_NO_WILDCARDS",
5772 X509_CHECK_FLAG_NO_WILDCARDS);
5773#endif
5774#ifdef X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS
5775 PyModule_AddIntConstant(m, "HOSTFLAG_NO_PARTIAL_WILDCARDS",
5776 X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS);
5777#endif
5778#ifdef X509_CHECK_FLAG_MULTI_LABEL_WILDCARDS
5779 PyModule_AddIntConstant(m, "HOSTFLAG_MULTI_LABEL_WILDCARDS",
5780 X509_CHECK_FLAG_MULTI_LABEL_WILDCARDS);
5781#endif
5782#ifdef X509_CHECK_FLAG_SINGLE_LABEL_SUBDOMAINS
5783 PyModule_AddIntConstant(m, "HOSTFLAG_SINGLE_LABEL_SUBDOMAINS",
5784 X509_CHECK_FLAG_SINGLE_LABEL_SUBDOMAINS);
5785#endif
5786
Christian Heimes698dde12018-02-27 11:54:43 +01005787 /* protocol versions */
5788 PyModule_AddIntConstant(m, "PROTO_MINIMUM_SUPPORTED",
5789 PY_PROTO_MINIMUM_SUPPORTED);
5790 PyModule_AddIntConstant(m, "PROTO_MAXIMUM_SUPPORTED",
5791 PY_PROTO_MAXIMUM_SUPPORTED);
5792 PyModule_AddIntConstant(m, "PROTO_SSLv3", PY_PROTO_SSLv3);
5793 PyModule_AddIntConstant(m, "PROTO_TLSv1", PY_PROTO_TLSv1);
5794 PyModule_AddIntConstant(m, "PROTO_TLSv1_1", PY_PROTO_TLSv1_1);
5795 PyModule_AddIntConstant(m, "PROTO_TLSv1_2", PY_PROTO_TLSv1_2);
5796 PyModule_AddIntConstant(m, "PROTO_TLSv1_3", PY_PROTO_TLSv1_3);
Antoine Pitroud5323212010-10-22 18:19:07 +00005797
Victor Stinnerb37672d2018-11-22 03:37:50 +01005798#define addbool(m, key, value) \
5799 do { \
5800 PyObject *bool_obj = (value) ? Py_True : Py_False; \
5801 Py_INCREF(bool_obj); \
5802 PyModule_AddObject((m), (key), bool_obj); \
5803 } while (0)
Christian Heimes698dde12018-02-27 11:54:43 +01005804
Christian Heimes698dde12018-02-27 11:54:43 +01005805 addbool(m, "HAS_SNI", 1);
Christian Heimes698dde12018-02-27 11:54:43 +01005806 addbool(m, "HAS_TLS_UNIQUE", 1);
Christian Heimes698dde12018-02-27 11:54:43 +01005807 addbool(m, "HAS_ECDH", 1);
Christian Heimes698dde12018-02-27 11:54:43 +01005808 addbool(m, "HAS_NPN", 0);
Christian Heimes698dde12018-02-27 11:54:43 +01005809 addbool(m, "HAS_ALPN", 1);
Christian Heimes698dde12018-02-27 11:54:43 +01005810
5811#if defined(SSL2_VERSION) && !defined(OPENSSL_NO_SSL2)
5812 addbool(m, "HAS_SSLv2", 1);
5813#else
5814 addbool(m, "HAS_SSLv2", 0);
5815#endif
5816
5817#if defined(SSL3_VERSION) && !defined(OPENSSL_NO_SSL3)
5818 addbool(m, "HAS_SSLv3", 1);
5819#else
5820 addbool(m, "HAS_SSLv3", 0);
5821#endif
5822
5823#if defined(TLS1_VERSION) && !defined(OPENSSL_NO_TLS1)
5824 addbool(m, "HAS_TLSv1", 1);
5825#else
5826 addbool(m, "HAS_TLSv1", 0);
5827#endif
5828
5829#if defined(TLS1_1_VERSION) && !defined(OPENSSL_NO_TLS1_1)
5830 addbool(m, "HAS_TLSv1_1", 1);
5831#else
5832 addbool(m, "HAS_TLSv1_1", 0);
5833#endif
5834
5835#if defined(TLS1_2_VERSION) && !defined(OPENSSL_NO_TLS1_2)
5836 addbool(m, "HAS_TLSv1_2", 1);
5837#else
5838 addbool(m, "HAS_TLSv1_2", 0);
5839#endif
Benjamin Petersoncca27322015-01-23 16:35:37 -05005840
Christian Heimescb5b68a2017-09-07 18:07:00 -07005841#if defined(TLS1_3_VERSION) && !defined(OPENSSL_NO_TLS1_3)
Christian Heimes698dde12018-02-27 11:54:43 +01005842 addbool(m, "HAS_TLSv1_3", 1);
Christian Heimescb5b68a2017-09-07 18:07:00 -07005843#else
Christian Heimes698dde12018-02-27 11:54:43 +01005844 addbool(m, "HAS_TLSv1_3", 0);
Christian Heimescb5b68a2017-09-07 18:07:00 -07005845#endif
Christian Heimescb5b68a2017-09-07 18:07:00 -07005846
Christian Heimes5c36da72020-11-20 09:40:12 +01005847 return 0;
5848}
5849
Christian Heimes7f1305e2021-04-17 20:06:38 +02005850static int
5851sslmodule_init_errorcodes(PyObject *module)
5852{
5853 _sslmodulestate *state = get_ssl_state(module);
Christian Heimes5c36da72020-11-20 09:40:12 +01005854
Christian Heimes7f1305e2021-04-17 20:06:38 +02005855 struct py_ssl_error_code *errcode;
5856 struct py_ssl_library_code *libcode;
Christian Heimes5c36da72020-11-20 09:40:12 +01005857
Christian Heimes7f1305e2021-04-17 20:06:38 +02005858 /* Mappings for error codes */
5859 state->err_codes_to_names = PyDict_New();
5860 if (state->err_codes_to_names == NULL)
5861 return -1;
5862 state->err_names_to_codes = PyDict_New();
5863 if (state->err_names_to_codes == NULL)
5864 return -1;
5865 state->lib_codes_to_names = PyDict_New();
5866 if (state->lib_codes_to_names == NULL)
5867 return -1;
5868
5869 errcode = error_codes;
5870 while (errcode->mnemonic != NULL) {
5871 PyObject *mnemo, *key;
5872 mnemo = PyUnicode_FromString(errcode->mnemonic);
5873 key = Py_BuildValue("ii", errcode->library, errcode->reason);
5874 if (mnemo == NULL || key == NULL)
5875 return -1;
5876 if (PyDict_SetItem(state->err_codes_to_names, key, mnemo))
5877 return -1;
5878 if (PyDict_SetItem(state->err_names_to_codes, mnemo, key))
5879 return -1;
5880 Py_DECREF(key);
5881 Py_DECREF(mnemo);
5882 errcode++;
5883 }
5884
5885 libcode = library_codes;
5886 while (libcode->library != NULL) {
5887 PyObject *mnemo, *key;
5888 key = PyLong_FromLong(libcode->code);
5889 mnemo = PyUnicode_FromString(libcode->library);
5890 if (key == NULL || mnemo == NULL)
5891 return -1;
5892 if (PyDict_SetItem(state->lib_codes_to_names, key, mnemo))
5893 return -1;
5894 Py_DECREF(key);
5895 Py_DECREF(mnemo);
5896 libcode++;
5897 }
5898
5899 if (PyModule_AddObjectRef(module, "err_codes_to_names", state->err_codes_to_names))
5900 return -1;
5901 if (PyModule_AddObjectRef(module, "err_names_to_codes", state->err_names_to_codes))
5902 return -1;
5903 if (PyModule_AddObjectRef(module, "lib_codes_to_names", state->lib_codes_to_names))
5904 return -1;
5905
5906 return 0;
5907}
5908
5909static void
5910parse_openssl_version(unsigned long libver,
5911 unsigned int *major, unsigned int *minor,
5912 unsigned int *fix, unsigned int *patch,
5913 unsigned int *status)
5914{
5915 *status = libver & 0xF;
5916 libver >>= 4;
5917 *patch = libver & 0xFF;
5918 libver >>= 8;
5919 *fix = libver & 0xFF;
5920 libver >>= 8;
5921 *minor = libver & 0xFF;
5922 libver >>= 8;
5923 *major = libver & 0xFF;
5924}
5925
5926static int
5927sslmodule_init_versioninfo(PyObject *m)
5928{
5929 PyObject *r;
5930 unsigned long libver;
5931 unsigned int major, minor, fix, patch, status;
5932
5933 /* OpenSSL version */
5934 /* SSLeay() gives us the version of the library linked against,
5935 which could be different from the headers version.
5936 */
5937 libver = OpenSSL_version_num();
5938 r = PyLong_FromUnsignedLong(libver);
5939 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r))
5940 return -1;
5941
5942 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
5943 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
5944 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r))
5945 return -1;
5946
5947 r = PyUnicode_FromString(OpenSSL_version(OPENSSL_VERSION));
5948 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r))
5949 return -1;
5950
5951 libver = OPENSSL_VERSION_NUMBER;
5952 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
5953 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
5954 if (r == NULL || PyModule_AddObject(m, "_OPENSSL_API_VERSION", r))
5955 return -1;
5956
5957 return 0;
5958}
5959
5960static int
5961sslmodule_init_types(PyObject *module)
5962{
5963 _sslmodulestate *state = get_ssl_state(module);
5964
5965 state->PySSLContext_Type = (PyTypeObject *)PyType_FromModuleAndSpec(
5966 module, &PySSLContext_spec, NULL
5967 );
5968 if (state->PySSLContext_Type == NULL)
5969 return -1;
5970
5971 state->PySSLSocket_Type = (PyTypeObject *)PyType_FromModuleAndSpec(
5972 module, &PySSLSocket_spec, NULL
5973 );
5974 if (state->PySSLSocket_Type == NULL)
5975 return -1;
5976
5977 state->PySSLMemoryBIO_Type = (PyTypeObject *)PyType_FromModuleAndSpec(
5978 module, &PySSLMemoryBIO_spec, NULL
5979 );
5980 if (state->PySSLMemoryBIO_Type == NULL)
5981 return -1;
5982
5983 state->PySSLSession_Type = (PyTypeObject *)PyType_FromModuleAndSpec(
5984 module, &PySSLSession_spec, NULL
5985 );
5986 if (state->PySSLSession_Type == NULL)
5987 return -1;
5988
5989 if (PyModule_AddType(module, state->PySSLContext_Type))
5990 return -1;
5991 if (PyModule_AddType(module, state->PySSLSocket_Type))
5992 return -1;
5993 if (PyModule_AddType(module, state->PySSLMemoryBIO_Type))
5994 return -1;
5995 if (PyModule_AddType(module, state->PySSLSession_Type))
5996 return -1;
5997
5998 return 0;
5999}
6000
6001static PyModuleDef_Slot sslmodule_slots[] = {
6002 {Py_mod_exec, sslmodule_init_types},
6003 {Py_mod_exec, sslmodule_init_exceptions},
6004 {Py_mod_exec, sslmodule_init_socketapi},
6005 {Py_mod_exec, sslmodule_init_errorcodes},
6006 {Py_mod_exec, sslmodule_init_constants},
6007 {Py_mod_exec, sslmodule_init_versioninfo},
6008 {0, NULL}
6009};
6010
6011static int
6012sslmodule_traverse(PyObject *m, visitproc visit, void *arg)
6013{
6014 _sslmodulestate *state = get_ssl_state(m);
6015
6016 Py_VISIT(state->PySSLContext_Type);
6017 Py_VISIT(state->PySSLSocket_Type);
6018 Py_VISIT(state->PySSLMemoryBIO_Type);
6019 Py_VISIT(state->PySSLSession_Type);
6020 Py_VISIT(state->PySSLErrorObject);
6021 Py_VISIT(state->PySSLCertVerificationErrorObject);
6022 Py_VISIT(state->PySSLZeroReturnErrorObject);
6023 Py_VISIT(state->PySSLWantReadErrorObject);
6024 Py_VISIT(state->PySSLWantWriteErrorObject);
6025 Py_VISIT(state->PySSLSyscallErrorObject);
6026 Py_VISIT(state->PySSLEOFErrorObject);
6027 Py_VISIT(state->err_codes_to_names);
6028 Py_VISIT(state->err_names_to_codes);
6029 Py_VISIT(state->lib_codes_to_names);
6030 Py_VISIT(state->Sock_Type);
6031
6032 return 0;
6033}
6034
6035static int
6036sslmodule_clear(PyObject *m)
6037{
6038 _sslmodulestate *state = get_ssl_state(m);
6039
6040 Py_CLEAR(state->PySSLContext_Type);
6041 Py_CLEAR(state->PySSLSocket_Type);
6042 Py_CLEAR(state->PySSLMemoryBIO_Type);
6043 Py_CLEAR(state->PySSLSession_Type);
6044 Py_CLEAR(state->PySSLErrorObject);
6045 Py_CLEAR(state->PySSLCertVerificationErrorObject);
6046 Py_CLEAR(state->PySSLZeroReturnErrorObject);
6047 Py_CLEAR(state->PySSLWantReadErrorObject);
6048 Py_CLEAR(state->PySSLWantWriteErrorObject);
6049 Py_CLEAR(state->PySSLSyscallErrorObject);
6050 Py_CLEAR(state->PySSLEOFErrorObject);
6051 Py_CLEAR(state->err_codes_to_names);
6052 Py_CLEAR(state->err_names_to_codes);
6053 Py_CLEAR(state->lib_codes_to_names);
6054 Py_CLEAR(state->Sock_Type);
6055
6056 return 0;
6057}
6058
6059static void
6060sslmodule_free(void *m)
6061{
6062 sslmodule_clear((PyObject *)m);
6063}
6064
6065static struct PyModuleDef _sslmodule_def = {
Christian Heimes5c36da72020-11-20 09:40:12 +01006066 PyModuleDef_HEAD_INIT,
Christian Heimes7f1305e2021-04-17 20:06:38 +02006067 .m_name = "_ssl",
6068 .m_doc = module_doc,
6069 .m_size = sizeof(_sslmodulestate),
6070 .m_methods = PySSL_methods,
6071 .m_slots = sslmodule_slots,
6072 .m_traverse = sslmodule_traverse,
6073 .m_clear = sslmodule_clear,
6074 .m_free = sslmodule_free
Christian Heimes5c36da72020-11-20 09:40:12 +01006075};
6076
6077PyMODINIT_FUNC
6078PyInit__ssl(void)
6079{
Christian Heimes7f1305e2021-04-17 20:06:38 +02006080 return PyModuleDef_Init(&_sslmodule_def);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00006081}