blob: e28c1286784a45371fbd9151976ecadaaf6a4c09 [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;
3794 int retval = 0, err, loaded = 0;
3795
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();
3848 if ((filetype == SSL_FILETYPE_ASN1) &&
3849 (loaded > 0) &&
3850 (ERR_GET_LIB(err) == ERR_LIB_ASN1) &&
3851 (ERR_GET_REASON(err) == ASN1_R_HEADER_TOO_LONG)) {
3852 /* EOF ASN1 file, not an error */
3853 ERR_clear_error();
3854 retval = 0;
3855 } else if ((filetype == SSL_FILETYPE_PEM) &&
3856 (loaded > 0) &&
3857 (ERR_GET_LIB(err) == ERR_LIB_PEM) &&
3858 (ERR_GET_REASON(err) == PEM_R_NO_START_LINE)) {
3859 /* EOF PEM file, not an error */
3860 ERR_clear_error();
3861 retval = 0;
3862 } else {
Christian Heimes7f1305e2021-04-17 20:06:38 +02003863 _setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
Christian Heimesefff7062013-11-21 03:35:02 +01003864 retval = -1;
3865 }
3866
3867 BIO_free(biobuf);
3868 return retval;
3869}
3870
3871
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003872/*[clinic input]
3873_ssl._SSLContext.load_verify_locations
Serhiy Storchaka279f4462019-09-14 12:24:05 +03003874 cafile: object = None
3875 capath: object = None
3876 cadata: object = None
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003877
3878[clinic start generated code]*/
3879
Antoine Pitrou152efa22010-05-16 18:19:27 +00003880static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003881_ssl__SSLContext_load_verify_locations_impl(PySSLContext *self,
3882 PyObject *cafile,
3883 PyObject *capath,
3884 PyObject *cadata)
Serhiy Storchaka279f4462019-09-14 12:24:05 +03003885/*[clinic end generated code: output=454c7e41230ca551 input=42ecfe258233e194]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003886{
Antoine Pitrou152efa22010-05-16 18:19:27 +00003887 PyObject *cafile_bytes = NULL, *capath_bytes = NULL;
3888 const char *cafile_buf = NULL, *capath_buf = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01003889 int r = 0, ok = 1;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003890
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003891 errno = 0;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003892 if (cafile == Py_None)
3893 cafile = NULL;
3894 if (capath == Py_None)
3895 capath = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01003896 if (cadata == Py_None)
3897 cadata = NULL;
3898
3899 if (cafile == NULL && capath == NULL && cadata == NULL) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003900 PyErr_SetString(PyExc_TypeError,
Christian Heimesefff7062013-11-21 03:35:02 +01003901 "cafile, capath and cadata cannot be all omitted");
3902 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003903 }
3904 if (cafile && !PyUnicode_FSConverter(cafile, &cafile_bytes)) {
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03003905 if (PyErr_ExceptionMatches(PyExc_TypeError)) {
3906 PyErr_SetString(PyExc_TypeError,
3907 "cafile should be a valid filesystem path");
3908 }
Christian Heimesefff7062013-11-21 03:35:02 +01003909 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003910 }
3911 if (capath && !PyUnicode_FSConverter(capath, &capath_bytes)) {
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03003912 if (PyErr_ExceptionMatches(PyExc_TypeError)) {
3913 PyErr_SetString(PyExc_TypeError,
3914 "capath should be a valid filesystem path");
3915 }
Christian Heimesefff7062013-11-21 03:35:02 +01003916 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003917 }
Christian Heimesefff7062013-11-21 03:35:02 +01003918
3919 /* validata cadata type and load cadata */
3920 if (cadata) {
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03003921 if (PyUnicode_Check(cadata)) {
3922 PyObject *cadata_ascii = PyUnicode_AsASCIIString(cadata);
3923 if (cadata_ascii == NULL) {
3924 if (PyErr_ExceptionMatches(PyExc_UnicodeEncodeError)) {
3925 goto invalid_cadata;
3926 }
3927 goto error;
3928 }
3929 r = _add_ca_certs(self,
3930 PyBytes_AS_STRING(cadata_ascii),
3931 PyBytes_GET_SIZE(cadata_ascii),
3932 SSL_FILETYPE_PEM);
3933 Py_DECREF(cadata_ascii);
3934 if (r == -1) {
3935 goto error;
3936 }
3937 }
3938 else if (PyObject_CheckBuffer(cadata)) {
3939 Py_buffer buf;
3940 if (PyObject_GetBuffer(cadata, &buf, PyBUF_SIMPLE)) {
3941 goto error;
3942 }
Christian Heimesefff7062013-11-21 03:35:02 +01003943 if (!PyBuffer_IsContiguous(&buf, 'C') || buf.ndim > 1) {
3944 PyBuffer_Release(&buf);
3945 PyErr_SetString(PyExc_TypeError,
3946 "cadata should be a contiguous buffer with "
3947 "a single dimension");
3948 goto error;
3949 }
3950 r = _add_ca_certs(self, buf.buf, buf.len, SSL_FILETYPE_ASN1);
3951 PyBuffer_Release(&buf);
3952 if (r == -1) {
3953 goto error;
3954 }
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03003955 }
3956 else {
3957 invalid_cadata:
3958 PyErr_SetString(PyExc_TypeError,
3959 "cadata should be an ASCII string or a "
3960 "bytes-like object");
3961 goto error;
Christian Heimesefff7062013-11-21 03:35:02 +01003962 }
3963 }
3964
3965 /* load cafile or capath */
3966 if (cafile || capath) {
3967 if (cafile)
3968 cafile_buf = PyBytes_AS_STRING(cafile_bytes);
3969 if (capath)
3970 capath_buf = PyBytes_AS_STRING(capath_bytes);
3971 PySSL_BEGIN_ALLOW_THREADS
3972 r = SSL_CTX_load_verify_locations(self->ctx, cafile_buf, capath_buf);
3973 PySSL_END_ALLOW_THREADS
3974 if (r != 1) {
Christian Heimesefff7062013-11-21 03:35:02 +01003975 if (errno != 0) {
3976 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03003977 PyErr_SetFromErrno(PyExc_OSError);
Christian Heimesefff7062013-11-21 03:35:02 +01003978 }
3979 else {
Christian Heimes7f1305e2021-04-17 20:06:38 +02003980 _setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
Christian Heimesefff7062013-11-21 03:35:02 +01003981 }
3982 goto error;
3983 }
3984 }
3985 goto end;
3986
3987 error:
3988 ok = 0;
3989 end:
Antoine Pitrou152efa22010-05-16 18:19:27 +00003990 Py_XDECREF(cafile_bytes);
3991 Py_XDECREF(capath_bytes);
Christian Heimesefff7062013-11-21 03:35:02 +01003992 if (ok) {
3993 Py_RETURN_NONE;
3994 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003995 return NULL;
3996 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003997}
3998
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003999/*[clinic input]
4000_ssl._SSLContext.load_dh_params
4001 path as filepath: object
4002 /
4003
4004[clinic start generated code]*/
4005
Antoine Pitrou152efa22010-05-16 18:19:27 +00004006static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004007_ssl__SSLContext_load_dh_params(PySSLContext *self, PyObject *filepath)
4008/*[clinic end generated code: output=1c8e57a38e055af0 input=c8871f3c796ae1d6]*/
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004009{
4010 FILE *f;
4011 DH *dh;
4012
Victor Stinnerdaf45552013-08-28 00:53:59 +02004013 f = _Py_fopen_obj(filepath, "rb");
Victor Stinnere42ccd22015-03-18 01:39:23 +01004014 if (f == NULL)
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004015 return NULL;
Victor Stinnere42ccd22015-03-18 01:39:23 +01004016
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004017 errno = 0;
4018 PySSL_BEGIN_ALLOW_THREADS
4019 dh = PEM_read_DHparams(f, NULL, NULL, NULL);
Antoine Pitrou457a2292013-01-12 21:43:45 +01004020 fclose(f);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004021 PySSL_END_ALLOW_THREADS
4022 if (dh == NULL) {
4023 if (errno != 0) {
4024 ERR_clear_error();
4025 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
4026 }
4027 else {
Christian Heimes7f1305e2021-04-17 20:06:38 +02004028 _setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004029 }
4030 return NULL;
4031 }
Zackery Spytzaebc0492020-07-07 22:21:58 -06004032 if (!SSL_CTX_set_tmp_dh(self->ctx, dh)) {
4033 DH_free(dh);
Christian Heimes7f1305e2021-04-17 20:06:38 +02004034 return _setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
Zackery Spytzaebc0492020-07-07 22:21:58 -06004035 }
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004036 DH_free(dh);
4037 Py_RETURN_NONE;
4038}
4039
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004040/*[clinic input]
4041_ssl._SSLContext._wrap_socket
Christian Heimes7f1305e2021-04-17 20:06:38 +02004042 sock: object(subclass_of="get_state_ctx(self)->Sock_Type")
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004043 server_side: int
4044 server_hostname as hostname_obj: object = None
Christian Heimes141c5e82018-02-24 21:10:57 +01004045 *
4046 owner: object = None
4047 session: object = None
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004048
4049[clinic start generated code]*/
4050
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004051static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004052_ssl__SSLContext__wrap_socket_impl(PySSLContext *self, PyObject *sock,
Christian Heimes141c5e82018-02-24 21:10:57 +01004053 int server_side, PyObject *hostname_obj,
4054 PyObject *owner, PyObject *session)
Christian Heimes7f1305e2021-04-17 20:06:38 +02004055/*[clinic end generated code: output=f103f238633940b4 input=f5916eadbc6eae81]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004056{
Antoine Pitroud5323212010-10-22 18:19:07 +00004057 char *hostname = NULL;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004058 PyObject *res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004059
Antoine Pitroud5323212010-10-22 18:19:07 +00004060 /* server_hostname is either None (or absent), or to be encoded
Christian Heimesd02ac252018-03-25 12:36:13 +02004061 as IDN A-label (ASCII str) without NULL bytes. */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004062 if (hostname_obj != Py_None) {
Christian Heimes11a14932018-02-24 02:35:08 +01004063 if (!PyArg_Parse(hostname_obj, "es", "ascii", &hostname))
Antoine Pitroud5323212010-10-22 18:19:07 +00004064 return NULL;
Antoine Pitroud5323212010-10-22 18:19:07 +00004065 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00004066
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004067 res = (PyObject *) newPySSLSocket(self, (PySocketSockObject *)sock,
4068 server_side, hostname,
Christian Heimes141c5e82018-02-24 21:10:57 +01004069 owner, session,
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004070 NULL, NULL);
Antoine Pitroud5323212010-10-22 18:19:07 +00004071 if (hostname != NULL)
4072 PyMem_Free(hostname);
4073 return res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004074}
4075
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004076/*[clinic input]
4077_ssl._SSLContext._wrap_bio
Christian Heimes7f1305e2021-04-17 20:06:38 +02004078 incoming: object(subclass_of="get_state_ctx(self)->PySSLMemoryBIO_Type", type="PySSLMemoryBIO *")
4079 outgoing: object(subclass_of="get_state_ctx(self)->PySSLMemoryBIO_Type", type="PySSLMemoryBIO *")
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004080 server_side: int
4081 server_hostname as hostname_obj: object = None
Christian Heimes141c5e82018-02-24 21:10:57 +01004082 *
4083 owner: object = None
4084 session: object = None
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004085
4086[clinic start generated code]*/
4087
Antoine Pitroub0182c82010-10-12 20:09:02 +00004088static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004089_ssl__SSLContext__wrap_bio_impl(PySSLContext *self, PySSLMemoryBIO *incoming,
4090 PySSLMemoryBIO *outgoing, int server_side,
Christian Heimes141c5e82018-02-24 21:10:57 +01004091 PyObject *hostname_obj, PyObject *owner,
4092 PyObject *session)
Christian Heimes7f1305e2021-04-17 20:06:38 +02004093/*[clinic end generated code: output=5c5d6d9b41f99332 input=331edeec9c738382]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004094{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004095 char *hostname = NULL;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004096 PyObject *res;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004097
4098 /* server_hostname is either None (or absent), or to be encoded
Christian Heimesd02ac252018-03-25 12:36:13 +02004099 as IDN A-label (ASCII str) without NULL bytes. */
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004100 if (hostname_obj != Py_None) {
Christian Heimes11a14932018-02-24 02:35:08 +01004101 if (!PyArg_Parse(hostname_obj, "es", "ascii", &hostname))
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004102 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004103 }
4104
4105 res = (PyObject *) newPySSLSocket(self, NULL, server_side, hostname,
Christian Heimes141c5e82018-02-24 21:10:57 +01004106 owner, session,
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004107 incoming, outgoing);
4108
4109 PyMem_Free(hostname);
4110 return res;
4111}
4112
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004113/*[clinic input]
4114_ssl._SSLContext.session_stats
4115[clinic start generated code]*/
4116
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004117static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004118_ssl__SSLContext_session_stats_impl(PySSLContext *self)
4119/*[clinic end generated code: output=0d96411c42893bfb input=7e0a81fb11102c8b]*/
Antoine Pitroub0182c82010-10-12 20:09:02 +00004120{
4121 int r;
4122 PyObject *value, *stats = PyDict_New();
4123 if (!stats)
4124 return NULL;
4125
4126#define ADD_STATS(SSL_NAME, KEY_NAME) \
4127 value = PyLong_FromLong(SSL_CTX_sess_ ## SSL_NAME (self->ctx)); \
4128 if (value == NULL) \
4129 goto error; \
4130 r = PyDict_SetItemString(stats, KEY_NAME, value); \
4131 Py_DECREF(value); \
4132 if (r < 0) \
4133 goto error;
4134
4135 ADD_STATS(number, "number");
4136 ADD_STATS(connect, "connect");
4137 ADD_STATS(connect_good, "connect_good");
4138 ADD_STATS(connect_renegotiate, "connect_renegotiate");
4139 ADD_STATS(accept, "accept");
4140 ADD_STATS(accept_good, "accept_good");
4141 ADD_STATS(accept_renegotiate, "accept_renegotiate");
4142 ADD_STATS(accept, "accept");
4143 ADD_STATS(hits, "hits");
4144 ADD_STATS(misses, "misses");
4145 ADD_STATS(timeouts, "timeouts");
4146 ADD_STATS(cache_full, "cache_full");
4147
4148#undef ADD_STATS
4149
4150 return stats;
4151
4152error:
4153 Py_DECREF(stats);
4154 return NULL;
4155}
4156
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004157/*[clinic input]
4158_ssl._SSLContext.set_default_verify_paths
4159[clinic start generated code]*/
4160
Antoine Pitrou664c2d12010-11-17 20:29:42 +00004161static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004162_ssl__SSLContext_set_default_verify_paths_impl(PySSLContext *self)
4163/*[clinic end generated code: output=0bee74e6e09deaaa input=35f3408021463d74]*/
Antoine Pitrou664c2d12010-11-17 20:29:42 +00004164{
4165 if (!SSL_CTX_set_default_verify_paths(self->ctx)) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02004166 _setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
Antoine Pitrou664c2d12010-11-17 20:29:42 +00004167 return NULL;
4168 }
4169 Py_RETURN_NONE;
4170}
4171
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004172/*[clinic input]
4173_ssl._SSLContext.set_ecdh_curve
4174 name: object
4175 /
4176
4177[clinic start generated code]*/
4178
Antoine Pitrou923df6f2011-12-19 17:16:51 +01004179static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004180_ssl__SSLContext_set_ecdh_curve(PySSLContext *self, PyObject *name)
4181/*[clinic end generated code: output=23022c196e40d7d2 input=c2bafb6f6e34726b]*/
Antoine Pitrou923df6f2011-12-19 17:16:51 +01004182{
4183 PyObject *name_bytes;
4184 int nid;
4185 EC_KEY *key;
4186
4187 if (!PyUnicode_FSConverter(name, &name_bytes))
4188 return NULL;
4189 assert(PyBytes_Check(name_bytes));
4190 nid = OBJ_sn2nid(PyBytes_AS_STRING(name_bytes));
4191 Py_DECREF(name_bytes);
4192 if (nid == 0) {
4193 PyErr_Format(PyExc_ValueError,
4194 "unknown elliptic curve name %R", name);
4195 return NULL;
4196 }
4197 key = EC_KEY_new_by_curve_name(nid);
4198 if (key == NULL) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02004199 _setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
Antoine Pitrou923df6f2011-12-19 17:16:51 +01004200 return NULL;
4201 }
4202 SSL_CTX_set_tmp_ecdh(self->ctx, key);
4203 EC_KEY_free(key);
4204 Py_RETURN_NONE;
4205}
4206
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004207static int
4208_servername_callback(SSL *s, int *al, void *args)
4209{
4210 int ret;
Christian Heimes7f1305e2021-04-17 20:06:38 +02004211 PySSLContext *sslctx = (PySSLContext *) args;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004212 PySSLSocket *ssl;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004213 PyObject *result;
4214 /* The high-level ssl.SSLSocket object */
4215 PyObject *ssl_socket;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004216 const char *servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
Stefan Krah20d60802013-01-17 17:07:17 +01004217 PyGILState_STATE gstate = PyGILState_Ensure();
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004218
Christian Heimes7f1305e2021-04-17 20:06:38 +02004219 if (sslctx->set_sni_cb == NULL) {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004220 /* remove race condition in this the call back while if removing the
4221 * callback is in progress */
4222 PyGILState_Release(gstate);
Antoine Pitrou5dd12a52013-01-06 15:25:36 +01004223 return SSL_TLSEXT_ERR_OK;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004224 }
4225
4226 ssl = SSL_get_app_data(s);
Christian Heimes7f1305e2021-04-17 20:06:38 +02004227 assert(Py_IS_TYPE(ssl, get_state_ctx(sslctx)->PySSLSocket_Type));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004228
Serhiy Storchakaf51d7152015-11-02 14:40:41 +02004229 /* The servername callback expects an argument that represents the current
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004230 * SSL connection and that has a .context attribute that can be changed to
4231 * identify the requested hostname. Since the official API is the Python
4232 * level API we want to pass the callback a Python level object rather than
4233 * a _ssl.SSLSocket instance. If there's an "owner" (typically an
4234 * SSLObject) that will be passed. Otherwise if there's a socket then that
4235 * will be passed. If both do not exist only then the C-level object is
4236 * passed. */
4237 if (ssl->owner)
4238 ssl_socket = PyWeakref_GetObject(ssl->owner);
4239 else if (ssl->Socket)
4240 ssl_socket = PyWeakref_GetObject(ssl->Socket);
4241 else
4242 ssl_socket = (PyObject *) ssl;
4243
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004244 Py_INCREF(ssl_socket);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004245 if (ssl_socket == Py_None)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004246 goto error;
Victor Stinner7e001512013-06-25 00:44:31 +02004247
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004248 if (servername == NULL) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02004249 result = PyObject_CallFunctionObjArgs(sslctx->set_sni_cb, ssl_socket,
4250 Py_None, sslctx, NULL);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004251 }
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004252 else {
Christian Heimes11a14932018-02-24 02:35:08 +01004253 PyObject *servername_bytes;
4254 PyObject *servername_str;
4255
4256 servername_bytes = PyBytes_FromString(servername);
4257 if (servername_bytes == NULL) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02004258 PyErr_WriteUnraisable((PyObject *) sslctx);
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004259 goto error;
4260 }
Christian Heimes11a14932018-02-24 02:35:08 +01004261 /* server_hostname was encoded to an A-label by our caller; put it
4262 * back into a str object, but still as an A-label (bpo-28414)
4263 */
4264 servername_str = PyUnicode_FromEncodedObject(servername_bytes, "ascii", NULL);
Christian Heimes11a14932018-02-24 02:35:08 +01004265 if (servername_str == NULL) {
4266 PyErr_WriteUnraisable(servername_bytes);
Zackery Spytzee96f322020-07-09 04:00:21 -06004267 Py_DECREF(servername_bytes);
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004268 goto error;
4269 }
Zackery Spytzee96f322020-07-09 04:00:21 -06004270 Py_DECREF(servername_bytes);
Christian Heimes11a14932018-02-24 02:35:08 +01004271 result = PyObject_CallFunctionObjArgs(
Christian Heimes7f1305e2021-04-17 20:06:38 +02004272 sslctx->set_sni_cb, ssl_socket, servername_str,
4273 sslctx, NULL);
Christian Heimes11a14932018-02-24 02:35:08 +01004274 Py_DECREF(servername_str);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004275 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004276 Py_DECREF(ssl_socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004277
4278 if (result == NULL) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02004279 PyErr_WriteUnraisable(sslctx->set_sni_cb);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004280 *al = SSL_AD_HANDSHAKE_FAILURE;
4281 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
4282 }
4283 else {
Christian Heimes11a14932018-02-24 02:35:08 +01004284 /* Result may be None, a SSLContext or an integer
4285 * None and SSLContext are OK, integer or other values are an error.
4286 */
4287 if (result == Py_None) {
4288 ret = SSL_TLSEXT_ERR_OK;
4289 } else {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004290 *al = (int) PyLong_AsLong(result);
4291 if (PyErr_Occurred()) {
4292 PyErr_WriteUnraisable(result);
4293 *al = SSL_AD_INTERNAL_ERROR;
4294 }
4295 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
4296 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004297 Py_DECREF(result);
4298 }
4299
4300 PyGILState_Release(gstate);
4301 return ret;
4302
4303error:
4304 Py_DECREF(ssl_socket);
4305 *al = SSL_AD_INTERNAL_ERROR;
4306 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
4307 PyGILState_Release(gstate);
4308 return ret;
4309}
4310
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004311static PyObject *
Christian Heimes11a14932018-02-24 02:35:08 +01004312get_sni_callback(PySSLContext *self, void *c)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004313{
Christian Heimes11a14932018-02-24 02:35:08 +01004314 PyObject *cb = self->set_sni_cb;
4315 if (cb == NULL) {
4316 Py_RETURN_NONE;
4317 }
4318 Py_INCREF(cb);
4319 return cb;
4320}
4321
4322static int
4323set_sni_callback(PySSLContext *self, PyObject *arg, void *c)
4324{
4325 if (self->protocol == PY_SSL_VERSION_TLS_CLIENT) {
4326 PyErr_SetString(PyExc_ValueError,
4327 "sni_callback cannot be set on TLS_CLIENT context");
4328 return -1;
4329 }
Christian Heimes11a14932018-02-24 02:35:08 +01004330 Py_CLEAR(self->set_sni_cb);
4331 if (arg == Py_None) {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004332 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
4333 }
4334 else {
Christian Heimes11a14932018-02-24 02:35:08 +01004335 if (!PyCallable_Check(arg)) {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004336 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
4337 PyErr_SetString(PyExc_TypeError,
4338 "not a callable object");
Christian Heimes11a14932018-02-24 02:35:08 +01004339 return -1;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004340 }
Christian Heimes11a14932018-02-24 02:35:08 +01004341 Py_INCREF(arg);
4342 self->set_sni_cb = arg;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004343 SSL_CTX_set_tlsext_servername_callback(self->ctx, _servername_callback);
4344 SSL_CTX_set_tlsext_servername_arg(self->ctx, self);
4345 }
Christian Heimes11a14932018-02-24 02:35:08 +01004346 return 0;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004347}
4348
Christian Heimes11a14932018-02-24 02:35:08 +01004349PyDoc_STRVAR(PySSLContext_sni_callback_doc,
4350"Set a callback that will be called when a server name is provided by the SSL/TLS client in the SNI extension.\n\
4351\n\
4352If the argument is None then the callback is disabled. The method is called\n\
4353with the SSLSocket, the server name as a string, and the SSLContext object.\n\
4354See RFC 6066 for details of the SNI extension.");
4355
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004356/*[clinic input]
4357_ssl._SSLContext.cert_store_stats
4358
4359Returns quantities of loaded X.509 certificates.
4360
4361X.509 certificates with a CA extension and certificate revocation lists
4362inside the context's cert store.
4363
4364NOTE: Certificates in a capath directory aren't loaded unless they have
4365been used at least once.
4366[clinic start generated code]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004367
4368static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004369_ssl__SSLContext_cert_store_stats_impl(PySSLContext *self)
4370/*[clinic end generated code: output=5f356f4d9cca874d input=eb40dd0f6d0e40cf]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004371{
4372 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02004373 STACK_OF(X509_OBJECT) *objs;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004374 X509_OBJECT *obj;
Christian Heimes598894f2016-09-05 23:19:05 +02004375 int x509 = 0, crl = 0, ca = 0, i;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004376
4377 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02004378 objs = X509_STORE_get0_objects(store);
4379 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
4380 obj = sk_X509_OBJECT_value(objs, i);
4381 switch (X509_OBJECT_get_type(obj)) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004382 case X509_LU_X509:
4383 x509++;
Christian Heimes598894f2016-09-05 23:19:05 +02004384 if (X509_check_ca(X509_OBJECT_get0_X509(obj))) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004385 ca++;
4386 }
4387 break;
4388 case X509_LU_CRL:
4389 crl++;
4390 break;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004391 default:
4392 /* Ignore X509_LU_FAIL, X509_LU_RETRY, X509_LU_PKEY.
4393 * As far as I can tell they are internal states and never
4394 * stored in a cert store */
4395 break;
4396 }
4397 }
4398 return Py_BuildValue("{sisisi}", "x509", x509, "crl", crl,
4399 "x509_ca", ca);
4400}
4401
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004402/*[clinic input]
4403_ssl._SSLContext.get_ca_certs
4404 binary_form: bool = False
4405
4406Returns a list of dicts with information of loaded CA certs.
4407
4408If the optional argument is True, returns a DER-encoded copy of the CA
4409certificate.
4410
4411NOTE: Certificates in a capath directory aren't loaded unless they have
4412been used at least once.
4413[clinic start generated code]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004414
4415static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004416_ssl__SSLContext_get_ca_certs_impl(PySSLContext *self, int binary_form)
4417/*[clinic end generated code: output=0d58f148f37e2938 input=6887b5a09b7f9076]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004418{
4419 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02004420 STACK_OF(X509_OBJECT) *objs;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004421 PyObject *ci = NULL, *rlist = NULL;
4422 int i;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004423
4424 if ((rlist = PyList_New(0)) == NULL) {
4425 return NULL;
4426 }
4427
4428 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02004429 objs = X509_STORE_get0_objects(store);
4430 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004431 X509_OBJECT *obj;
4432 X509 *cert;
4433
Christian Heimes598894f2016-09-05 23:19:05 +02004434 obj = sk_X509_OBJECT_value(objs, i);
4435 if (X509_OBJECT_get_type(obj) != X509_LU_X509) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004436 /* not a x509 cert */
4437 continue;
4438 }
4439 /* CA for any purpose */
Christian Heimes598894f2016-09-05 23:19:05 +02004440 cert = X509_OBJECT_get0_X509(obj);
Christian Heimes9a5395a2013-06-17 15:44:12 +02004441 if (!X509_check_ca(cert)) {
4442 continue;
4443 }
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004444 if (binary_form) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02004445 ci = _certificate_to_der(get_state_ctx(self), cert);
Christian Heimes9a5395a2013-06-17 15:44:12 +02004446 } else {
Christian Heimes7f1305e2021-04-17 20:06:38 +02004447 ci = _decode_certificate(get_state_ctx(self), cert);
Christian Heimes9a5395a2013-06-17 15:44:12 +02004448 }
4449 if (ci == NULL) {
4450 goto error;
4451 }
4452 if (PyList_Append(rlist, ci) == -1) {
4453 goto error;
4454 }
4455 Py_CLEAR(ci);
4456 }
4457 return rlist;
4458
4459 error:
4460 Py_XDECREF(ci);
4461 Py_XDECREF(rlist);
4462 return NULL;
4463}
4464
4465
Antoine Pitrou152efa22010-05-16 18:19:27 +00004466static PyGetSetDef context_getsetlist[] = {
Christian Heimes1aa9a752013-12-02 02:41:19 +01004467 {"check_hostname", (getter) get_check_hostname,
4468 (setter) set_check_hostname, NULL},
Christian Heimes61d478c2018-01-27 15:51:38 +01004469 {"_host_flags", (getter) get_host_flags,
4470 (setter) set_host_flags, NULL},
Christian Heimes698dde12018-02-27 11:54:43 +01004471 {"minimum_version", (getter) get_minimum_version,
4472 (setter) set_minimum_version, NULL},
4473 {"maximum_version", (getter) get_maximum_version,
4474 (setter) set_maximum_version, NULL},
Christian Heimesc7f70692019-05-31 11:44:05 +02004475 {"keylog_filename", (getter) _PySSLContext_get_keylog_filename,
4476 (setter) _PySSLContext_set_keylog_filename, NULL},
Christian Heimesc7f70692019-05-31 11:44:05 +02004477 {"_msg_callback", (getter) _PySSLContext_get_msg_callback,
4478 (setter) _PySSLContext_set_msg_callback, NULL},
Christian Heimes11a14932018-02-24 02:35:08 +01004479 {"sni_callback", (getter) get_sni_callback,
Christian Heimes698dde12018-02-27 11:54:43 +01004480 (setter) set_sni_callback, PySSLContext_sni_callback_doc},
Christian Heimes39258d32021-04-17 11:36:35 +02004481#ifdef TLS1_3_VERSION
Christian Heimes78c7d522019-06-03 21:00:10 +02004482 {"num_tickets", (getter) get_num_tickets,
4483 (setter) set_num_tickets, PySSLContext_num_tickets_doc},
4484#endif
Antoine Pitroub5218772010-05-21 09:56:06 +00004485 {"options", (getter) get_options,
4486 (setter) set_options, NULL},
Christian Heimes9fb051f2018-09-23 08:32:31 +02004487 {"post_handshake_auth", (getter) get_post_handshake_auth,
4488#ifdef TLS1_3_VERSION
4489 (setter) set_post_handshake_auth,
4490#else
4491 NULL,
4492#endif
4493 NULL},
Christian Heimes11a14932018-02-24 02:35:08 +01004494 {"protocol", (getter) get_protocol,
4495 NULL, NULL},
Christian Heimes22587792013-11-21 23:56:13 +01004496 {"verify_flags", (getter) get_verify_flags,
4497 (setter) set_verify_flags, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00004498 {"verify_mode", (getter) get_verify_mode,
4499 (setter) set_verify_mode, NULL},
matthewhughes9348e836bb2020-07-17 09:59:15 +01004500 {"security_level", (getter) get_security_level,
4501 NULL, PySSLContext_security_level_doc},
Antoine Pitrou152efa22010-05-16 18:19:27 +00004502 {NULL}, /* sentinel */
4503};
4504
4505static struct PyMethodDef context_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004506 _SSL__SSLCONTEXT__WRAP_SOCKET_METHODDEF
4507 _SSL__SSLCONTEXT__WRAP_BIO_METHODDEF
4508 _SSL__SSLCONTEXT_SET_CIPHERS_METHODDEF
4509 _SSL__SSLCONTEXT__SET_ALPN_PROTOCOLS_METHODDEF
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004510 _SSL__SSLCONTEXT_LOAD_CERT_CHAIN_METHODDEF
4511 _SSL__SSLCONTEXT_LOAD_DH_PARAMS_METHODDEF
4512 _SSL__SSLCONTEXT_LOAD_VERIFY_LOCATIONS_METHODDEF
4513 _SSL__SSLCONTEXT_SESSION_STATS_METHODDEF
4514 _SSL__SSLCONTEXT_SET_DEFAULT_VERIFY_PATHS_METHODDEF
4515 _SSL__SSLCONTEXT_SET_ECDH_CURVE_METHODDEF
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004516 _SSL__SSLCONTEXT_CERT_STORE_STATS_METHODDEF
4517 _SSL__SSLCONTEXT_GET_CA_CERTS_METHODDEF
Christian Heimes25bfcd52016-09-06 00:04:45 +02004518 _SSL__SSLCONTEXT_GET_CIPHERS_METHODDEF
Antoine Pitrou152efa22010-05-16 18:19:27 +00004519 {NULL, NULL} /* sentinel */
4520};
4521
Christian Heimes5c36da72020-11-20 09:40:12 +01004522static PyType_Slot PySSLContext_slots[] = {
4523 {Py_tp_methods, context_methods},
4524 {Py_tp_getset, context_getsetlist},
4525 {Py_tp_new, _ssl__SSLContext},
4526 {Py_tp_dealloc, context_dealloc},
4527 {Py_tp_traverse, context_traverse},
4528 {Py_tp_clear, context_clear},
4529 {0, 0},
4530};
4531
4532static PyType_Spec PySSLContext_spec = {
4533 "_ssl._SSLContext",
4534 sizeof(PySSLContext),
4535 0,
4536 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
4537 PySSLContext_slots,
Antoine Pitrou152efa22010-05-16 18:19:27 +00004538};
4539
4540
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004541/*
4542 * MemoryBIO objects
4543 */
4544
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004545/*[clinic input]
4546@classmethod
4547_ssl.MemoryBIO.__new__
4548
4549[clinic start generated code]*/
4550
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004551static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004552_ssl_MemoryBIO_impl(PyTypeObject *type)
4553/*[clinic end generated code: output=8820a58db78330ac input=26d22e4909ecb1b5]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004554{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004555 BIO *bio;
4556 PySSLMemoryBIO *self;
4557
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004558 bio = BIO_new(BIO_s_mem());
4559 if (bio == NULL) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02004560 PyErr_SetString(PyExc_MemoryError, "failed to allocate BIO");
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004561 return NULL;
4562 }
4563 /* Since our BIO is non-blocking an empty read() does not indicate EOF,
4564 * just that no data is currently available. The SSL routines should retry
4565 * the read, which we can achieve by calling BIO_set_retry_read(). */
4566 BIO_set_retry_read(bio);
4567 BIO_set_mem_eof_return(bio, -1);
4568
4569 assert(type != NULL && type->tp_alloc != NULL);
4570 self = (PySSLMemoryBIO *) type->tp_alloc(type, 0);
4571 if (self == NULL) {
4572 BIO_free(bio);
4573 return NULL;
4574 }
4575 self->bio = bio;
4576 self->eof_written = 0;
4577
4578 return (PyObject *) self;
4579}
4580
4581static void
4582memory_bio_dealloc(PySSLMemoryBIO *self)
4583{
Christian Heimes5c36da72020-11-20 09:40:12 +01004584 PyTypeObject *tp = Py_TYPE(self);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004585 BIO_free(self->bio);
4586 Py_TYPE(self)->tp_free(self);
Christian Heimes5c36da72020-11-20 09:40:12 +01004587 Py_DECREF(tp);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004588}
4589
4590static PyObject *
4591memory_bio_get_pending(PySSLMemoryBIO *self, void *c)
4592{
Segev Finer5cff6372017-07-27 01:19:17 +03004593 return PyLong_FromSize_t(BIO_ctrl_pending(self->bio));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004594}
4595
4596PyDoc_STRVAR(PySSL_memory_bio_pending_doc,
4597"The number of bytes pending in the memory BIO.");
4598
4599static PyObject *
4600memory_bio_get_eof(PySSLMemoryBIO *self, void *c)
4601{
4602 return PyBool_FromLong((BIO_ctrl_pending(self->bio) == 0)
4603 && self->eof_written);
4604}
4605
4606PyDoc_STRVAR(PySSL_memory_bio_eof_doc,
4607"Whether the memory BIO is at EOF.");
4608
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004609/*[clinic input]
4610_ssl.MemoryBIO.read
4611 size as len: int = -1
4612 /
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004613
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004614Read up to size bytes from the memory BIO.
4615
4616If size is not specified, read the entire buffer.
4617If the return value is an empty bytes instance, this means either
4618EOF or that no data is available. Use the "eof" property to
4619distinguish between the two.
4620[clinic start generated code]*/
4621
4622static PyObject *
4623_ssl_MemoryBIO_read_impl(PySSLMemoryBIO *self, int len)
4624/*[clinic end generated code: output=a657aa1e79cd01b3 input=574d7be06a902366]*/
4625{
4626 int avail, nbytes;
4627 PyObject *result;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004628
Segev Finer5cff6372017-07-27 01:19:17 +03004629 avail = (int)Py_MIN(BIO_ctrl_pending(self->bio), INT_MAX);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004630 if ((len < 0) || (len > avail))
4631 len = avail;
4632
4633 result = PyBytes_FromStringAndSize(NULL, len);
4634 if ((result == NULL) || (len == 0))
4635 return result;
4636
4637 nbytes = BIO_read(self->bio, PyBytes_AS_STRING(result), len);
Zackery Spytz365ad2e2018-10-06 11:41:45 -06004638 if (nbytes < 0) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02004639 _sslmodulestate *state = get_state_mbio(self);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004640 Py_DECREF(result);
Christian Heimes7f1305e2021-04-17 20:06:38 +02004641 _setSSLError(state, NULL, 0, __FILE__, __LINE__);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004642 return NULL;
4643 }
4644
Zackery Spytz365ad2e2018-10-06 11:41:45 -06004645 /* There should never be any short reads but check anyway. */
4646 if (nbytes < len) {
4647 _PyBytes_Resize(&result, nbytes);
4648 }
4649
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004650 return result;
4651}
4652
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004653/*[clinic input]
4654_ssl.MemoryBIO.write
4655 b: Py_buffer
4656 /
4657
4658Writes the bytes b into the memory BIO.
4659
4660Returns the number of bytes written.
4661[clinic start generated code]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004662
4663static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004664_ssl_MemoryBIO_write_impl(PySSLMemoryBIO *self, Py_buffer *b)
4665/*[clinic end generated code: output=156ec59110d75935 input=e45757b3e17c4808]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004666{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004667 int nbytes;
4668
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004669 if (b->len > INT_MAX) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004670 PyErr_Format(PyExc_OverflowError,
4671 "string longer than %d bytes", INT_MAX);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004672 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004673 }
4674
4675 if (self->eof_written) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02004676 PyObject *module = PyType_GetModule(Py_TYPE(self));
4677 if (module == NULL)
4678 return NULL;
4679 PyErr_SetString(get_ssl_state(module)->PySSLErrorObject,
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004680 "cannot write() after write_eof()");
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004681 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004682 }
4683
Segev Finer5cff6372017-07-27 01:19:17 +03004684 nbytes = BIO_write(self->bio, b->buf, (int)b->len);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004685 if (nbytes < 0) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02004686 _sslmodulestate *state = get_state_mbio(self);
4687 _setSSLError(state, NULL, 0, __FILE__, __LINE__);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004688 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004689 }
4690
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004691 return PyLong_FromLong(nbytes);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004692}
4693
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004694/*[clinic input]
4695_ssl.MemoryBIO.write_eof
4696
4697Write an EOF marker to the memory BIO.
4698
4699When all data has been read, the "eof" property will be True.
4700[clinic start generated code]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004701
4702static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004703_ssl_MemoryBIO_write_eof_impl(PySSLMemoryBIO *self)
4704/*[clinic end generated code: output=d4106276ccd1ed34 input=56a945f1d29e8bd6]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004705{
4706 self->eof_written = 1;
4707 /* After an EOF is written, a zero return from read() should be a real EOF
4708 * i.e. it should not be retried. Clear the SHOULD_RETRY flag. */
4709 BIO_clear_retry_flags(self->bio);
4710 BIO_set_mem_eof_return(self->bio, 0);
4711
4712 Py_RETURN_NONE;
4713}
4714
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004715static PyGetSetDef memory_bio_getsetlist[] = {
4716 {"pending", (getter) memory_bio_get_pending, NULL,
4717 PySSL_memory_bio_pending_doc},
4718 {"eof", (getter) memory_bio_get_eof, NULL,
4719 PySSL_memory_bio_eof_doc},
4720 {NULL}, /* sentinel */
4721};
4722
4723static struct PyMethodDef memory_bio_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004724 _SSL_MEMORYBIO_READ_METHODDEF
4725 _SSL_MEMORYBIO_WRITE_METHODDEF
4726 _SSL_MEMORYBIO_WRITE_EOF_METHODDEF
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004727 {NULL, NULL} /* sentinel */
4728};
4729
Christian Heimes5c36da72020-11-20 09:40:12 +01004730static PyType_Slot PySSLMemoryBIO_slots[] = {
4731 {Py_tp_methods, memory_bio_methods},
4732 {Py_tp_getset, memory_bio_getsetlist},
4733 {Py_tp_new, _ssl_MemoryBIO},
4734 {Py_tp_dealloc, memory_bio_dealloc},
4735 {0, 0},
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004736};
4737
Christian Heimes5c36da72020-11-20 09:40:12 +01004738static PyType_Spec PySSLMemoryBIO_spec = {
4739 "_ssl.MemoryBIO",
4740 sizeof(PySSLMemoryBIO),
4741 0,
4742 Py_TPFLAGS_DEFAULT,
4743 PySSLMemoryBIO_slots,
4744};
Antoine Pitrou152efa22010-05-16 18:19:27 +00004745
Christian Heimes99a65702016-09-10 23:44:53 +02004746/*
4747 * SSL Session object
4748 */
4749
4750static void
4751PySSLSession_dealloc(PySSLSession *self)
4752{
Christian Heimes5c36da72020-11-20 09:40:12 +01004753 PyTypeObject *tp = Py_TYPE(self);
INADA Naokia6296d32017-08-24 14:55:17 +09004754 /* bpo-31095: UnTrack is needed before calling any callbacks */
Christian Heimesa5d07652016-09-24 10:48:05 +02004755 PyObject_GC_UnTrack(self);
Christian Heimes99a65702016-09-10 23:44:53 +02004756 Py_XDECREF(self->ctx);
4757 if (self->session != NULL) {
4758 SSL_SESSION_free(self->session);
4759 }
Christian Heimesa5d07652016-09-24 10:48:05 +02004760 PyObject_GC_Del(self);
Christian Heimes5c36da72020-11-20 09:40:12 +01004761 Py_DECREF(tp);
Christian Heimes99a65702016-09-10 23:44:53 +02004762}
4763
4764static PyObject *
4765PySSLSession_richcompare(PyObject *left, PyObject *right, int op)
4766{
4767 int result;
Christian Heimes7f1305e2021-04-17 20:06:38 +02004768 PyTypeObject *sesstype = ((PySSLSession*)left)->ctx->state->PySSLSession_Type;
Christian Heimes99a65702016-09-10 23:44:53 +02004769
4770 if (left == NULL || right == NULL) {
4771 PyErr_BadInternalCall();
4772 return NULL;
4773 }
4774
Christian Heimes7f1305e2021-04-17 20:06:38 +02004775 if (!Py_IS_TYPE(left, sesstype) || !Py_IS_TYPE(right, sesstype)) {
Christian Heimes99a65702016-09-10 23:44:53 +02004776 Py_RETURN_NOTIMPLEMENTED;
4777 }
4778
4779 if (left == right) {
4780 result = 0;
4781 } else {
4782 const unsigned char *left_id, *right_id;
4783 unsigned int left_len, right_len;
4784 left_id = SSL_SESSION_get_id(((PySSLSession *)left)->session,
4785 &left_len);
4786 right_id = SSL_SESSION_get_id(((PySSLSession *)right)->session,
4787 &right_len);
4788 if (left_len == right_len) {
4789 result = memcmp(left_id, right_id, left_len);
4790 } else {
4791 result = 1;
4792 }
4793 }
4794
4795 switch (op) {
4796 case Py_EQ:
4797 if (result == 0) {
4798 Py_RETURN_TRUE;
4799 } else {
4800 Py_RETURN_FALSE;
4801 }
4802 break;
4803 case Py_NE:
4804 if (result != 0) {
4805 Py_RETURN_TRUE;
4806 } else {
4807 Py_RETURN_FALSE;
4808 }
4809 break;
4810 case Py_LT:
4811 case Py_LE:
4812 case Py_GT:
4813 case Py_GE:
4814 Py_RETURN_NOTIMPLEMENTED;
4815 break;
4816 default:
4817 PyErr_BadArgument();
4818 return NULL;
4819 }
4820}
4821
4822static int
4823PySSLSession_traverse(PySSLSession *self, visitproc visit, void *arg)
4824{
4825 Py_VISIT(self->ctx);
4826 return 0;
4827}
4828
4829static int
4830PySSLSession_clear(PySSLSession *self)
4831{
4832 Py_CLEAR(self->ctx);
4833 return 0;
4834}
4835
4836
4837static PyObject *
4838PySSLSession_get_time(PySSLSession *self, void *closure) {
4839 return PyLong_FromLong(SSL_SESSION_get_time(self->session));
4840}
4841
4842PyDoc_STRVAR(PySSLSession_get_time_doc,
4843"Session creation time (seconds since epoch).");
4844
4845
4846static PyObject *
4847PySSLSession_get_timeout(PySSLSession *self, void *closure) {
4848 return PyLong_FromLong(SSL_SESSION_get_timeout(self->session));
4849}
4850
4851PyDoc_STRVAR(PySSLSession_get_timeout_doc,
4852"Session timeout (delta in seconds).");
4853
4854
4855static PyObject *
4856PySSLSession_get_ticket_lifetime_hint(PySSLSession *self, void *closure) {
4857 unsigned long hint = SSL_SESSION_get_ticket_lifetime_hint(self->session);
4858 return PyLong_FromUnsignedLong(hint);
4859}
4860
4861PyDoc_STRVAR(PySSLSession_get_ticket_lifetime_hint_doc,
4862"Ticket life time hint.");
4863
4864
4865static PyObject *
4866PySSLSession_get_session_id(PySSLSession *self, void *closure) {
4867 const unsigned char *id;
4868 unsigned int len;
4869 id = SSL_SESSION_get_id(self->session, &len);
4870 return PyBytes_FromStringAndSize((const char *)id, len);
4871}
4872
4873PyDoc_STRVAR(PySSLSession_get_session_id_doc,
4874"Session id");
4875
4876
4877static PyObject *
4878PySSLSession_get_has_ticket(PySSLSession *self, void *closure) {
4879 if (SSL_SESSION_has_ticket(self->session)) {
4880 Py_RETURN_TRUE;
4881 } else {
4882 Py_RETURN_FALSE;
4883 }
4884}
4885
4886PyDoc_STRVAR(PySSLSession_get_has_ticket_doc,
4887"Does the session contain a ticket?");
4888
4889
4890static PyGetSetDef PySSLSession_getsetlist[] = {
4891 {"has_ticket", (getter) PySSLSession_get_has_ticket, NULL,
4892 PySSLSession_get_has_ticket_doc},
4893 {"id", (getter) PySSLSession_get_session_id, NULL,
4894 PySSLSession_get_session_id_doc},
4895 {"ticket_lifetime_hint", (getter) PySSLSession_get_ticket_lifetime_hint,
4896 NULL, PySSLSession_get_ticket_lifetime_hint_doc},
4897 {"time", (getter) PySSLSession_get_time, NULL,
4898 PySSLSession_get_time_doc},
4899 {"timeout", (getter) PySSLSession_get_timeout, NULL,
4900 PySSLSession_get_timeout_doc},
4901 {NULL}, /* sentinel */
4902};
4903
Christian Heimes5c36da72020-11-20 09:40:12 +01004904static PyType_Slot PySSLSession_slots[] = {
4905 {Py_tp_getset,PySSLSession_getsetlist},
4906 {Py_tp_richcompare, PySSLSession_richcompare},
4907 {Py_tp_dealloc, PySSLSession_dealloc},
4908 {Py_tp_traverse, PySSLSession_traverse},
4909 {Py_tp_clear, PySSLSession_clear},
4910 {0, 0},
4911};
4912
4913static PyType_Spec PySSLSession_spec = {
4914 "_ssl.SSLSession",
4915 sizeof(PySSLSession),
4916 0,
4917 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,
4918 PySSLSession_slots,
Christian Heimes99a65702016-09-10 23:44:53 +02004919};
4920
4921
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004922/* helper routines for seeding the SSL PRNG */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004923/*[clinic input]
4924_ssl.RAND_add
Larry Hastingsdbfdc382015-05-04 06:59:46 -07004925 string as view: Py_buffer(accept={str, buffer})
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004926 entropy: double
4927 /
4928
4929Mix string into the OpenSSL PRNG state.
4930
4931entropy (a float) is a lower bound on the entropy contained in
Chandan Kumar63c2c8a2017-06-09 15:13:58 +05304932string. See RFC 4086.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004933[clinic start generated code]*/
4934
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004935static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004936_ssl_RAND_add_impl(PyObject *module, Py_buffer *view, double entropy)
Serhiy Storchaka5f31d5c2017-06-10 13:13:51 +03004937/*[clinic end generated code: output=e6dd48df9c9024e9 input=5c33017422828f5c]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004938{
Serhiy Storchaka8490f5a2015-03-20 09:00:36 +02004939 const char *buf;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02004940 Py_ssize_t len, written;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004941
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004942 buf = (const char *)view->buf;
4943 len = view->len;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02004944 do {
4945 written = Py_MIN(len, INT_MAX);
4946 RAND_add(buf, (int)written, entropy);
4947 buf += written;
4948 len -= written;
4949 } while (len);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02004950 Py_RETURN_NONE;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004951}
4952
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004953static PyObject *
Christian Heimes7f1305e2021-04-17 20:06:38 +02004954PySSL_RAND(PyObject *module, int len, int pseudo)
Victor Stinner99c8b162011-05-24 12:05:19 +02004955{
4956 int ok;
4957 PyObject *bytes;
4958 unsigned long err;
4959 const char *errstr;
4960 PyObject *v;
4961
Victor Stinner1e81a392013-12-19 16:47:04 +01004962 if (len < 0) {
4963 PyErr_SetString(PyExc_ValueError, "num must be positive");
4964 return NULL;
4965 }
4966
Victor Stinner99c8b162011-05-24 12:05:19 +02004967 bytes = PyBytes_FromStringAndSize(NULL, len);
4968 if (bytes == NULL)
4969 return NULL;
4970 if (pseudo) {
Christian Heimesa871f692020-06-01 08:58:14 +02004971 ok = RAND_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
Victor Stinner99c8b162011-05-24 12:05:19 +02004972 if (ok == 0 || ok == 1)
4973 return Py_BuildValue("NO", bytes, ok == 1 ? Py_True : Py_False);
4974 }
4975 else {
4976 ok = RAND_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
4977 if (ok == 1)
4978 return bytes;
4979 }
4980 Py_DECREF(bytes);
4981
4982 err = ERR_get_error();
4983 errstr = ERR_reason_error_string(err);
4984 v = Py_BuildValue("(ks)", err, errstr);
4985 if (v != NULL) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02004986 PyErr_SetObject(get_ssl_state(module)->PySSLErrorObject, v);
Victor Stinner99c8b162011-05-24 12:05:19 +02004987 Py_DECREF(v);
4988 }
4989 return NULL;
4990}
4991
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004992/*[clinic input]
4993_ssl.RAND_bytes
4994 n: int
4995 /
4996
4997Generate n cryptographically strong pseudo-random bytes.
4998[clinic start generated code]*/
4999
Victor Stinner99c8b162011-05-24 12:05:19 +02005000static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005001_ssl_RAND_bytes_impl(PyObject *module, int n)
5002/*[clinic end generated code: output=977da635e4838bc7 input=678ddf2872dfebfc]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02005003{
Christian Heimes7f1305e2021-04-17 20:06:38 +02005004 return PySSL_RAND(module, n, 0);
Victor Stinner99c8b162011-05-24 12:05:19 +02005005}
5006
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005007/*[clinic input]
5008_ssl.RAND_pseudo_bytes
5009 n: int
5010 /
5011
5012Generate n pseudo-random bytes.
5013
5014Return a pair (bytes, is_cryptographic). is_cryptographic is True
5015if the bytes generated are cryptographically strong.
5016[clinic start generated code]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02005017
5018static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005019_ssl_RAND_pseudo_bytes_impl(PyObject *module, int n)
5020/*[clinic end generated code: output=b1509e937000e52d input=58312bd53f9bbdd0]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02005021{
Christian Heimes2875c602021-04-19 07:27:10 +02005022 PY_SSL_DEPRECATED("RAND_pseudo_bytes", 1, NULL);
Christian Heimes7f1305e2021-04-17 20:06:38 +02005023 return PySSL_RAND(module, n, 1);
Victor Stinner99c8b162011-05-24 12:05:19 +02005024}
5025
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005026/*[clinic input]
5027_ssl.RAND_status
5028
5029Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.
5030
5031It is necessary to seed the PRNG with RAND_add() on some platforms before
5032using the ssl() function.
5033[clinic start generated code]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02005034
5035static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005036_ssl_RAND_status_impl(PyObject *module)
5037/*[clinic end generated code: output=7e0aaa2d39fdc1ad input=8a774b02d1dc81f3]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005038{
Christian Heimes217cfd12007-12-02 14:31:20 +00005039 return PyLong_FromLong(RAND_status());
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005040}
5041
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005042/*[clinic input]
5043_ssl.get_default_verify_paths
5044
5045Return search paths and environment vars that are used by SSLContext's set_default_verify_paths() to load default CAs.
5046
5047The values are 'cert_file_env', 'cert_file', 'cert_dir_env', 'cert_dir'.
5048[clinic start generated code]*/
Christian Heimes6d7ad132013-06-09 18:02:55 +02005049
5050static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005051_ssl_get_default_verify_paths_impl(PyObject *module)
5052/*[clinic end generated code: output=e5b62a466271928b input=5210c953d98c3eb5]*/
Christian Heimes6d7ad132013-06-09 18:02:55 +02005053{
5054 PyObject *ofile_env = NULL;
5055 PyObject *ofile = NULL;
5056 PyObject *odir_env = NULL;
5057 PyObject *odir = NULL;
5058
Benjamin Petersond113c962015-07-18 10:59:13 -07005059#define CONVERT(info, target) { \
Christian Heimes6d7ad132013-06-09 18:02:55 +02005060 const char *tmp = (info); \
5061 target = NULL; \
5062 if (!tmp) { Py_INCREF(Py_None); target = Py_None; } \
5063 else if ((target = PyUnicode_DecodeFSDefault(tmp)) == NULL) { \
5064 target = PyBytes_FromString(tmp); } \
5065 if (!target) goto error; \
Benjamin Peterson025a1fd2015-11-14 15:12:38 -08005066 }
Christian Heimes6d7ad132013-06-09 18:02:55 +02005067
Benjamin Petersond113c962015-07-18 10:59:13 -07005068 CONVERT(X509_get_default_cert_file_env(), ofile_env);
5069 CONVERT(X509_get_default_cert_file(), ofile);
5070 CONVERT(X509_get_default_cert_dir_env(), odir_env);
5071 CONVERT(X509_get_default_cert_dir(), odir);
5072#undef CONVERT
Christian Heimes6d7ad132013-06-09 18:02:55 +02005073
Christian Heimes200bb1b2013-06-14 15:14:29 +02005074 return Py_BuildValue("NNNN", ofile_env, ofile, odir_env, odir);
Christian Heimes6d7ad132013-06-09 18:02:55 +02005075
5076 error:
5077 Py_XDECREF(ofile_env);
5078 Py_XDECREF(ofile);
5079 Py_XDECREF(odir_env);
5080 Py_XDECREF(odir);
5081 return NULL;
5082}
5083
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005084static PyObject*
Christian Heimes7f1305e2021-04-17 20:06:38 +02005085asn1obj2py(_sslmodulestate *state, ASN1_OBJECT *obj)
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005086{
5087 int nid;
5088 const char *ln, *sn;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005089
5090 nid = OBJ_obj2nid(obj);
5091 if (nid == NID_undef) {
5092 PyErr_Format(PyExc_ValueError, "Unknown object");
5093 return NULL;
5094 }
5095 sn = OBJ_nid2sn(nid);
5096 ln = OBJ_nid2ln(nid);
Christian Heimes7f1305e2021-04-17 20:06:38 +02005097 return Py_BuildValue("issN", nid, sn, ln, _asn1obj2py(state, obj, 1));
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005098}
5099
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005100/*[clinic input]
5101_ssl.txt2obj
5102 txt: str
5103 name: bool = False
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005104
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005105Lookup NID, short name, long name and OID of an ASN1_OBJECT.
5106
5107By default objects are looked up by OID. With name=True short and
5108long name are also matched.
5109[clinic start generated code]*/
5110
5111static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005112_ssl_txt2obj_impl(PyObject *module, const char *txt, int name)
5113/*[clinic end generated code: output=c38e3991347079c1 input=1c1e7d0aa7c48602]*/
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005114{
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005115 PyObject *result = NULL;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005116 ASN1_OBJECT *obj;
5117
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005118 obj = OBJ_txt2obj(txt, name ? 0 : 1);
5119 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01005120 PyErr_Format(PyExc_ValueError, "unknown object '%.100s'", txt);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005121 return NULL;
5122 }
Christian Heimes7f1305e2021-04-17 20:06:38 +02005123 result = asn1obj2py(get_ssl_state(module), obj);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005124 ASN1_OBJECT_free(obj);
5125 return result;
5126}
5127
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005128/*[clinic input]
5129_ssl.nid2obj
5130 nid: int
5131 /
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005132
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005133Lookup NID, short name, long name and OID of an ASN1_OBJECT by NID.
5134[clinic start generated code]*/
5135
5136static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005137_ssl_nid2obj_impl(PyObject *module, int nid)
5138/*[clinic end generated code: output=4a98ab691cd4f84a input=51787a3bee7d8f98]*/
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005139{
5140 PyObject *result = NULL;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005141 ASN1_OBJECT *obj;
5142
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005143 if (nid < NID_undef) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01005144 PyErr_SetString(PyExc_ValueError, "NID must be positive.");
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005145 return NULL;
5146 }
5147 obj = OBJ_nid2obj(nid);
5148 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01005149 PyErr_Format(PyExc_ValueError, "unknown NID %i", nid);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005150 return NULL;
5151 }
Christian Heimes7f1305e2021-04-17 20:06:38 +02005152 result = asn1obj2py(get_ssl_state(module), obj);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005153 ASN1_OBJECT_free(obj);
5154 return result;
5155}
5156
Christian Heimes46bebee2013-06-09 19:03:31 +02005157#ifdef _MSC_VER
Christian Heimes44109d72013-11-22 01:51:30 +01005158
5159static PyObject*
5160certEncodingType(DWORD encodingType)
5161{
5162 static PyObject *x509_asn = NULL;
5163 static PyObject *pkcs_7_asn = NULL;
5164
5165 if (x509_asn == NULL) {
5166 x509_asn = PyUnicode_InternFromString("x509_asn");
5167 if (x509_asn == NULL)
5168 return NULL;
5169 }
5170 if (pkcs_7_asn == NULL) {
5171 pkcs_7_asn = PyUnicode_InternFromString("pkcs_7_asn");
5172 if (pkcs_7_asn == NULL)
5173 return NULL;
5174 }
5175 switch(encodingType) {
5176 case X509_ASN_ENCODING:
5177 Py_INCREF(x509_asn);
5178 return x509_asn;
5179 case PKCS_7_ASN_ENCODING:
5180 Py_INCREF(pkcs_7_asn);
5181 return pkcs_7_asn;
5182 default:
5183 return PyLong_FromLong(encodingType);
5184 }
5185}
5186
5187static PyObject*
5188parseKeyUsage(PCCERT_CONTEXT pCertCtx, DWORD flags)
5189{
5190 CERT_ENHKEY_USAGE *usage;
5191 DWORD size, error, i;
5192 PyObject *retval;
5193
5194 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, NULL, &size)) {
5195 error = GetLastError();
5196 if (error == CRYPT_E_NOT_FOUND) {
5197 Py_RETURN_TRUE;
5198 }
5199 return PyErr_SetFromWindowsErr(error);
5200 }
5201
5202 usage = (CERT_ENHKEY_USAGE*)PyMem_Malloc(size);
5203 if (usage == NULL) {
5204 return PyErr_NoMemory();
5205 }
5206
5207 /* Now get the actual enhanced usage property */
5208 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, usage, &size)) {
5209 PyMem_Free(usage);
5210 error = GetLastError();
5211 if (error == CRYPT_E_NOT_FOUND) {
5212 Py_RETURN_TRUE;
5213 }
5214 return PyErr_SetFromWindowsErr(error);
5215 }
Christian Heimes915cd3f2019-09-09 18:06:55 +02005216 retval = PyFrozenSet_New(NULL);
Christian Heimes44109d72013-11-22 01:51:30 +01005217 if (retval == NULL) {
5218 goto error;
5219 }
5220 for (i = 0; i < usage->cUsageIdentifier; ++i) {
5221 if (usage->rgpszUsageIdentifier[i]) {
5222 PyObject *oid;
5223 int err;
5224 oid = PyUnicode_FromString(usage->rgpszUsageIdentifier[i]);
5225 if (oid == NULL) {
5226 Py_CLEAR(retval);
5227 goto error;
5228 }
5229 err = PySet_Add(retval, oid);
5230 Py_DECREF(oid);
5231 if (err == -1) {
5232 Py_CLEAR(retval);
5233 goto error;
5234 }
5235 }
5236 }
5237 error:
5238 PyMem_Free(usage);
5239 return retval;
5240}
5241
kctherookied93fbbf2019-03-29 00:59:06 +07005242static HCERTSTORE
5243ssl_collect_certificates(const char *store_name)
5244{
5245/* this function collects the system certificate stores listed in
5246 * system_stores into a collection certificate store for being
5247 * enumerated. The store must be readable to be added to the
5248 * store collection.
5249 */
5250
5251 HCERTSTORE hCollectionStore = NULL, hSystemStore = NULL;
5252 static DWORD system_stores[] = {
5253 CERT_SYSTEM_STORE_LOCAL_MACHINE,
5254 CERT_SYSTEM_STORE_LOCAL_MACHINE_ENTERPRISE,
5255 CERT_SYSTEM_STORE_LOCAL_MACHINE_GROUP_POLICY,
5256 CERT_SYSTEM_STORE_CURRENT_USER,
5257 CERT_SYSTEM_STORE_CURRENT_USER_GROUP_POLICY,
5258 CERT_SYSTEM_STORE_SERVICES,
5259 CERT_SYSTEM_STORE_USERS};
5260 size_t i, storesAdded;
5261 BOOL result;
5262
5263 hCollectionStore = CertOpenStore(CERT_STORE_PROV_COLLECTION, 0,
5264 (HCRYPTPROV)NULL, 0, NULL);
5265 if (!hCollectionStore) {
5266 return NULL;
5267 }
5268 storesAdded = 0;
5269 for (i = 0; i < sizeof(system_stores) / sizeof(DWORD); i++) {
5270 hSystemStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0,
5271 (HCRYPTPROV)NULL,
5272 CERT_STORE_READONLY_FLAG |
5273 system_stores[i], store_name);
5274 if (hSystemStore) {
5275 result = CertAddStoreToCollection(hCollectionStore, hSystemStore,
5276 CERT_PHYSICAL_STORE_ADD_ENABLE_FLAG, 0);
5277 if (result) {
5278 ++storesAdded;
5279 }
neoneneed701292019-09-09 21:33:43 +09005280 CertCloseStore(hSystemStore, 0); /* flag must be 0 */
kctherookied93fbbf2019-03-29 00:59:06 +07005281 }
5282 }
5283 if (storesAdded == 0) {
5284 CertCloseStore(hCollectionStore, CERT_CLOSE_STORE_FORCE_FLAG);
5285 return NULL;
5286 }
5287
5288 return hCollectionStore;
5289}
5290
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005291/*[clinic input]
5292_ssl.enum_certificates
5293 store_name: str
5294
5295Retrieve certificates from Windows' cert store.
5296
5297store_name may be one of 'CA', 'ROOT' or 'MY'. The system may provide
5298more cert storages, too. The function returns a list of (bytes,
5299encoding_type, trust) tuples. The encoding_type flag can be interpreted
5300with X509_ASN_ENCODING or PKCS_7_ASN_ENCODING. The trust setting is either
5301a set of OIDs or the boolean True.
5302[clinic start generated code]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00005303
Christian Heimes46bebee2013-06-09 19:03:31 +02005304static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005305_ssl_enum_certificates_impl(PyObject *module, const char *store_name)
5306/*[clinic end generated code: output=5134dc8bb3a3c893 input=915f60d70461ea4e]*/
Christian Heimes46bebee2013-06-09 19:03:31 +02005307{
kctherookied93fbbf2019-03-29 00:59:06 +07005308 HCERTSTORE hCollectionStore = NULL;
Christian Heimes44109d72013-11-22 01:51:30 +01005309 PCCERT_CONTEXT pCertCtx = NULL;
5310 PyObject *keyusage = NULL, *cert = NULL, *enc = NULL, *tup = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02005311 PyObject *result = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02005312
Christian Heimes915cd3f2019-09-09 18:06:55 +02005313 result = PySet_New(NULL);
Christian Heimes44109d72013-11-22 01:51:30 +01005314 if (result == NULL) {
5315 return NULL;
5316 }
kctherookied93fbbf2019-03-29 00:59:06 +07005317 hCollectionStore = ssl_collect_certificates(store_name);
5318 if (hCollectionStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02005319 Py_DECREF(result);
5320 return PyErr_SetFromWindowsErr(GetLastError());
5321 }
5322
kctherookied93fbbf2019-03-29 00:59:06 +07005323 while (pCertCtx = CertEnumCertificatesInStore(hCollectionStore, pCertCtx)) {
Christian Heimes44109d72013-11-22 01:51:30 +01005324 cert = PyBytes_FromStringAndSize((const char*)pCertCtx->pbCertEncoded,
5325 pCertCtx->cbCertEncoded);
5326 if (!cert) {
5327 Py_CLEAR(result);
5328 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02005329 }
Christian Heimes44109d72013-11-22 01:51:30 +01005330 if ((enc = certEncodingType(pCertCtx->dwCertEncodingType)) == NULL) {
5331 Py_CLEAR(result);
5332 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02005333 }
Christian Heimes44109d72013-11-22 01:51:30 +01005334 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG);
5335 if (keyusage == Py_True) {
5336 Py_DECREF(keyusage);
5337 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_EXT_ONLY_ENHKEY_USAGE_FLAG);
Christian Heimes46bebee2013-06-09 19:03:31 +02005338 }
Christian Heimes44109d72013-11-22 01:51:30 +01005339 if (keyusage == NULL) {
5340 Py_CLEAR(result);
5341 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02005342 }
Christian Heimes44109d72013-11-22 01:51:30 +01005343 if ((tup = PyTuple_New(3)) == NULL) {
5344 Py_CLEAR(result);
5345 break;
5346 }
5347 PyTuple_SET_ITEM(tup, 0, cert);
5348 cert = NULL;
5349 PyTuple_SET_ITEM(tup, 1, enc);
5350 enc = NULL;
5351 PyTuple_SET_ITEM(tup, 2, keyusage);
5352 keyusage = NULL;
Christian Heimes915cd3f2019-09-09 18:06:55 +02005353 if (PySet_Add(result, tup) == -1) {
5354 Py_CLEAR(result);
5355 Py_CLEAR(tup);
5356 break;
Christian Heimes44109d72013-11-22 01:51:30 +01005357 }
5358 Py_CLEAR(tup);
5359 }
5360 if (pCertCtx) {
5361 /* loop ended with an error, need to clean up context manually */
5362 CertFreeCertificateContext(pCertCtx);
Christian Heimes46bebee2013-06-09 19:03:31 +02005363 }
5364
5365 /* In error cases cert, enc and tup may not be NULL */
5366 Py_XDECREF(cert);
5367 Py_XDECREF(enc);
Christian Heimes44109d72013-11-22 01:51:30 +01005368 Py_XDECREF(keyusage);
Christian Heimes46bebee2013-06-09 19:03:31 +02005369 Py_XDECREF(tup);
5370
kctherookied93fbbf2019-03-29 00:59:06 +07005371 /* CERT_CLOSE_STORE_FORCE_FLAG forces freeing of memory for all contexts
5372 associated with the store, in this case our collection store and the
5373 associated system stores. */
5374 if (!CertCloseStore(hCollectionStore, CERT_CLOSE_STORE_FORCE_FLAG)) {
Christian Heimes46bebee2013-06-09 19:03:31 +02005375 /* This error case might shadow another exception.*/
Christian Heimes44109d72013-11-22 01:51:30 +01005376 Py_XDECREF(result);
5377 return PyErr_SetFromWindowsErr(GetLastError());
5378 }
kctherookied93fbbf2019-03-29 00:59:06 +07005379
Christian Heimes915cd3f2019-09-09 18:06:55 +02005380 /* convert set to list */
5381 if (result == NULL) {
5382 return NULL;
5383 } else {
5384 PyObject *lst = PySequence_List(result);
5385 Py_DECREF(result);
5386 return lst;
5387 }
Christian Heimes44109d72013-11-22 01:51:30 +01005388}
5389
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005390/*[clinic input]
5391_ssl.enum_crls
5392 store_name: str
5393
5394Retrieve CRLs from Windows' cert store.
5395
5396store_name may be one of 'CA', 'ROOT' or 'MY'. The system may provide
5397more cert storages, too. The function returns a list of (bytes,
5398encoding_type) tuples. The encoding_type flag can be interpreted with
5399X509_ASN_ENCODING or PKCS_7_ASN_ENCODING.
5400[clinic start generated code]*/
Christian Heimes44109d72013-11-22 01:51:30 +01005401
5402static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005403_ssl_enum_crls_impl(PyObject *module, const char *store_name)
5404/*[clinic end generated code: output=bce467f60ccd03b6 input=a1f1d7629f1c5d3d]*/
Christian Heimes44109d72013-11-22 01:51:30 +01005405{
kctherookied93fbbf2019-03-29 00:59:06 +07005406 HCERTSTORE hCollectionStore = NULL;
Christian Heimes44109d72013-11-22 01:51:30 +01005407 PCCRL_CONTEXT pCrlCtx = NULL;
5408 PyObject *crl = NULL, *enc = NULL, *tup = NULL;
5409 PyObject *result = NULL;
5410
Christian Heimes915cd3f2019-09-09 18:06:55 +02005411 result = PySet_New(NULL);
Christian Heimes44109d72013-11-22 01:51:30 +01005412 if (result == NULL) {
5413 return NULL;
5414 }
kctherookied93fbbf2019-03-29 00:59:06 +07005415 hCollectionStore = ssl_collect_certificates(store_name);
5416 if (hCollectionStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02005417 Py_DECREF(result);
5418 return PyErr_SetFromWindowsErr(GetLastError());
5419 }
Christian Heimes44109d72013-11-22 01:51:30 +01005420
kctherookied93fbbf2019-03-29 00:59:06 +07005421 while (pCrlCtx = CertEnumCRLsInStore(hCollectionStore, pCrlCtx)) {
Christian Heimes44109d72013-11-22 01:51:30 +01005422 crl = PyBytes_FromStringAndSize((const char*)pCrlCtx->pbCrlEncoded,
5423 pCrlCtx->cbCrlEncoded);
5424 if (!crl) {
5425 Py_CLEAR(result);
5426 break;
5427 }
5428 if ((enc = certEncodingType(pCrlCtx->dwCertEncodingType)) == NULL) {
5429 Py_CLEAR(result);
5430 break;
5431 }
5432 if ((tup = PyTuple_New(2)) == NULL) {
5433 Py_CLEAR(result);
5434 break;
5435 }
5436 PyTuple_SET_ITEM(tup, 0, crl);
5437 crl = NULL;
5438 PyTuple_SET_ITEM(tup, 1, enc);
5439 enc = NULL;
5440
Christian Heimes915cd3f2019-09-09 18:06:55 +02005441 if (PySet_Add(result, tup) == -1) {
5442 Py_CLEAR(result);
5443 Py_CLEAR(tup);
5444 break;
Christian Heimes44109d72013-11-22 01:51:30 +01005445 }
5446 Py_CLEAR(tup);
Christian Heimes46bebee2013-06-09 19:03:31 +02005447 }
Christian Heimes44109d72013-11-22 01:51:30 +01005448 if (pCrlCtx) {
5449 /* loop ended with an error, need to clean up context manually */
5450 CertFreeCRLContext(pCrlCtx);
5451 }
5452
5453 /* In error cases cert, enc and tup may not be NULL */
5454 Py_XDECREF(crl);
5455 Py_XDECREF(enc);
5456 Py_XDECREF(tup);
5457
kctherookied93fbbf2019-03-29 00:59:06 +07005458 /* CERT_CLOSE_STORE_FORCE_FLAG forces freeing of memory for all contexts
5459 associated with the store, in this case our collection store and the
5460 associated system stores. */
5461 if (!CertCloseStore(hCollectionStore, CERT_CLOSE_STORE_FORCE_FLAG)) {
Christian Heimes44109d72013-11-22 01:51:30 +01005462 /* This error case might shadow another exception.*/
5463 Py_XDECREF(result);
5464 return PyErr_SetFromWindowsErr(GetLastError());
5465 }
Christian Heimes915cd3f2019-09-09 18:06:55 +02005466 /* convert set to list */
5467 if (result == NULL) {
5468 return NULL;
5469 } else {
5470 PyObject *lst = PySequence_List(result);
5471 Py_DECREF(result);
5472 return lst;
5473 }
Christian Heimes46bebee2013-06-09 19:03:31 +02005474}
Christian Heimes44109d72013-11-22 01:51:30 +01005475
5476#endif /* _MSC_VER */
Bill Janssen40a0f662008-08-12 16:56:25 +00005477
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005478/* List of functions exported by this module. */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005479static PyMethodDef PySSL_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005480 _SSL__TEST_DECODE_CERT_METHODDEF
5481 _SSL_RAND_ADD_METHODDEF
5482 _SSL_RAND_BYTES_METHODDEF
5483 _SSL_RAND_PSEUDO_BYTES_METHODDEF
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005484 _SSL_RAND_STATUS_METHODDEF
5485 _SSL_GET_DEFAULT_VERIFY_PATHS_METHODDEF
5486 _SSL_ENUM_CERTIFICATES_METHODDEF
5487 _SSL_ENUM_CRLS_METHODDEF
5488 _SSL_TXT2OBJ_METHODDEF
5489 _SSL_NID2OBJ_METHODDEF
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005490 {NULL, NULL} /* Sentinel */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005491};
5492
5493
Christian Heimes7f1305e2021-04-17 20:06:38 +02005494PyDoc_STRVAR(module_doc,
5495"Implementation module for SSL socket operations. See the socket module\n\
5496for documentation.");
Christian Heimes5c36da72020-11-20 09:40:12 +01005497
5498static int
5499sslmodule_init_exceptions(PyObject *module)
5500{
Christian Heimes7f1305e2021-04-17 20:06:38 +02005501 _sslmodulestate *state = get_ssl_state(module);
Christian Heimes5c36da72020-11-20 09:40:12 +01005502 PyObject *bases = NULL;
5503
Christian Heimes7f1305e2021-04-17 20:06:38 +02005504#define add_exception(exc, name, doc, base) \
5505do { \
5506 (exc) = PyErr_NewExceptionWithDoc("ssl." name, (doc), (base), NULL); \
5507 if ((state) == NULL) goto error; \
5508 if (PyModule_AddObjectRef(module, name, exc) < 0) goto error; \
Christian Heimes5c36da72020-11-20 09:40:12 +01005509} while(0)
5510
Christian Heimes7f1305e2021-04-17 20:06:38 +02005511 state->PySSLErrorObject = PyType_FromSpecWithBases(
5512 &sslerror_type_spec, PyExc_OSError);
5513 if (state->PySSLErrorObject == NULL) {
Christian Heimes5c36da72020-11-20 09:40:12 +01005514 goto error;
5515 }
Christian Heimes7f1305e2021-04-17 20:06:38 +02005516 if (PyModule_AddObjectRef(module, "SSLError", state->PySSLErrorObject) < 0) {
Christian Heimes5c36da72020-11-20 09:40:12 +01005517 goto error;
5518 }
5519
5520 /* ssl.CertificateError used to be a subclass of ValueError */
Christian Heimes7f1305e2021-04-17 20:06:38 +02005521 bases = PyTuple_Pack(2, state->PySSLErrorObject, PyExc_ValueError);
Christian Heimes5c36da72020-11-20 09:40:12 +01005522 if (bases == NULL) {
5523 goto error;
5524 }
5525 add_exception(
Christian Heimes7f1305e2021-04-17 20:06:38 +02005526 state->PySSLCertVerificationErrorObject,
Christian Heimes5c36da72020-11-20 09:40:12 +01005527 "SSLCertVerificationError",
5528 SSLCertVerificationError_doc,
5529 bases
5530 );
5531 Py_CLEAR(bases);
5532
5533 add_exception(
Christian Heimes7f1305e2021-04-17 20:06:38 +02005534 state->PySSLZeroReturnErrorObject,
Christian Heimes5c36da72020-11-20 09:40:12 +01005535 "SSLZeroReturnError",
5536 SSLZeroReturnError_doc,
Christian Heimes7f1305e2021-04-17 20:06:38 +02005537 state->PySSLErrorObject
Christian Heimes5c36da72020-11-20 09:40:12 +01005538 );
5539
5540 add_exception(
Christian Heimes7f1305e2021-04-17 20:06:38 +02005541 state->PySSLWantWriteErrorObject,
Christian Heimes5c36da72020-11-20 09:40:12 +01005542 "SSLWantWriteError",
5543 SSLWantWriteError_doc,
Christian Heimes7f1305e2021-04-17 20:06:38 +02005544 state->PySSLErrorObject
Christian Heimes5c36da72020-11-20 09:40:12 +01005545 );
5546
5547 add_exception(
Christian Heimes7f1305e2021-04-17 20:06:38 +02005548 state->PySSLWantReadErrorObject,
Christian Heimes5c36da72020-11-20 09:40:12 +01005549 "SSLWantReadError",
5550 SSLWantReadError_doc,
Christian Heimes7f1305e2021-04-17 20:06:38 +02005551 state->PySSLErrorObject
Christian Heimes5c36da72020-11-20 09:40:12 +01005552 );
5553
5554 add_exception(
Christian Heimes7f1305e2021-04-17 20:06:38 +02005555 state->PySSLSyscallErrorObject,
Christian Heimes5c36da72020-11-20 09:40:12 +01005556 "SSLSyscallError",
5557 SSLSyscallError_doc,
Christian Heimes7f1305e2021-04-17 20:06:38 +02005558 state->PySSLErrorObject
Christian Heimes5c36da72020-11-20 09:40:12 +01005559 );
5560
5561 add_exception(
Christian Heimes7f1305e2021-04-17 20:06:38 +02005562 state->PySSLEOFErrorObject,
Christian Heimes5c36da72020-11-20 09:40:12 +01005563 "SSLEOFError",
5564 SSLEOFError_doc,
Christian Heimes7f1305e2021-04-17 20:06:38 +02005565 state->PySSLErrorObject
Christian Heimes5c36da72020-11-20 09:40:12 +01005566 );
5567#undef add_exception
5568
5569 return 0;
5570 error:
5571 Py_XDECREF(bases);
5572 return -1;
5573}
5574
5575static int
5576sslmodule_init_socketapi(PyObject *module)
5577{
Christian Heimes7f1305e2021-04-17 20:06:38 +02005578 _sslmodulestate *state = get_ssl_state(module);
5579 PySocketModule_APIObject *sockmod = PySocketModule_ImportModuleAndAPI();
Christian Heimes5c36da72020-11-20 09:40:12 +01005580
Christian Heimes7f1305e2021-04-17 20:06:38 +02005581 if ((sockmod == NULL) || (sockmod->Sock_Type == NULL)) {
Christian Heimes5c36da72020-11-20 09:40:12 +01005582 return -1;
Christian Heimes5c36da72020-11-20 09:40:12 +01005583 }
Christian Heimes7f1305e2021-04-17 20:06:38 +02005584 state->Sock_Type = sockmod->Sock_Type;
5585 Py_INCREF(state->Sock_Type);
Christian Heimes5c36da72020-11-20 09:40:12 +01005586 return 0;
5587}
Christian Heimesc941e622017-09-05 15:47:11 +02005588
Christian Heimes5c36da72020-11-20 09:40:12 +01005589static int
5590sslmodule_init_constants(PyObject *m)
5591{
Christian Heimes7f1305e2021-04-17 20:06:38 +02005592
Christian Heimes892d66e2018-01-29 14:10:18 +01005593 PyModule_AddStringConstant(m, "_DEFAULT_CIPHERS",
5594 PY_SSL_DEFAULT_CIPHER_STRING);
5595
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005596 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
5597 PY_SSL_ERROR_ZERO_RETURN);
5598 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
5599 PY_SSL_ERROR_WANT_READ);
5600 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
5601 PY_SSL_ERROR_WANT_WRITE);
5602 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
5603 PY_SSL_ERROR_WANT_X509_LOOKUP);
5604 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
5605 PY_SSL_ERROR_SYSCALL);
5606 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
5607 PY_SSL_ERROR_SSL);
5608 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
5609 PY_SSL_ERROR_WANT_CONNECT);
5610 /* non ssl.h errorcodes */
5611 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
5612 PY_SSL_ERROR_EOF);
5613 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
5614 PY_SSL_ERROR_INVALID_ERROR_CODE);
5615 /* cert requirements */
5616 PyModule_AddIntConstant(m, "CERT_NONE",
5617 PY_SSL_CERT_NONE);
5618 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
5619 PY_SSL_CERT_OPTIONAL);
5620 PyModule_AddIntConstant(m, "CERT_REQUIRED",
5621 PY_SSL_CERT_REQUIRED);
Christian Heimes22587792013-11-21 23:56:13 +01005622 /* CRL verification for verification_flags */
5623 PyModule_AddIntConstant(m, "VERIFY_DEFAULT",
5624 0);
5625 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_LEAF",
5626 X509_V_FLAG_CRL_CHECK);
5627 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_CHAIN",
5628 X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
5629 PyModule_AddIntConstant(m, "VERIFY_X509_STRICT",
5630 X509_V_FLAG_X509_STRICT);
Chris Burre0b4aa02021-03-18 09:24:01 +01005631 PyModule_AddIntConstant(m, "VERIFY_ALLOW_PROXY_CERTS",
5632 X509_V_FLAG_ALLOW_PROXY_CERTS);
Benjamin Peterson990fcaa2015-03-04 22:49:41 -05005633 PyModule_AddIntConstant(m, "VERIFY_X509_TRUSTED_FIRST",
5634 X509_V_FLAG_TRUSTED_FIRST);
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00005635
l0x64d97522021-04-19 13:51:18 +02005636#ifdef X509_V_FLAG_PARTIAL_CHAIN
5637 PyModule_AddIntConstant(m, "VERIFY_X509_PARTIAL_CHAIN",
5638 X509_V_FLAG_PARTIAL_CHAIN);
5639#endif
5640
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01005641 /* Alert Descriptions from ssl.h */
5642 /* note RESERVED constants no longer intended for use have been removed */
5643 /* http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-6 */
5644
5645#define ADD_AD_CONSTANT(s) \
5646 PyModule_AddIntConstant(m, "ALERT_DESCRIPTION_"#s, \
5647 SSL_AD_##s)
5648
5649 ADD_AD_CONSTANT(CLOSE_NOTIFY);
5650 ADD_AD_CONSTANT(UNEXPECTED_MESSAGE);
5651 ADD_AD_CONSTANT(BAD_RECORD_MAC);
5652 ADD_AD_CONSTANT(RECORD_OVERFLOW);
5653 ADD_AD_CONSTANT(DECOMPRESSION_FAILURE);
5654 ADD_AD_CONSTANT(HANDSHAKE_FAILURE);
5655 ADD_AD_CONSTANT(BAD_CERTIFICATE);
5656 ADD_AD_CONSTANT(UNSUPPORTED_CERTIFICATE);
5657 ADD_AD_CONSTANT(CERTIFICATE_REVOKED);
5658 ADD_AD_CONSTANT(CERTIFICATE_EXPIRED);
5659 ADD_AD_CONSTANT(CERTIFICATE_UNKNOWN);
5660 ADD_AD_CONSTANT(ILLEGAL_PARAMETER);
5661 ADD_AD_CONSTANT(UNKNOWN_CA);
5662 ADD_AD_CONSTANT(ACCESS_DENIED);
5663 ADD_AD_CONSTANT(DECODE_ERROR);
5664 ADD_AD_CONSTANT(DECRYPT_ERROR);
5665 ADD_AD_CONSTANT(PROTOCOL_VERSION);
5666 ADD_AD_CONSTANT(INSUFFICIENT_SECURITY);
5667 ADD_AD_CONSTANT(INTERNAL_ERROR);
5668 ADD_AD_CONSTANT(USER_CANCELLED);
5669 ADD_AD_CONSTANT(NO_RENEGOTIATION);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01005670 /* Not all constants are in old OpenSSL versions */
Antoine Pitrou912fbff2013-03-30 16:29:32 +01005671#ifdef SSL_AD_UNSUPPORTED_EXTENSION
5672 ADD_AD_CONSTANT(UNSUPPORTED_EXTENSION);
5673#endif
5674#ifdef SSL_AD_CERTIFICATE_UNOBTAINABLE
5675 ADD_AD_CONSTANT(CERTIFICATE_UNOBTAINABLE);
5676#endif
5677#ifdef SSL_AD_UNRECOGNIZED_NAME
5678 ADD_AD_CONSTANT(UNRECOGNIZED_NAME);
5679#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01005680#ifdef SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE
5681 ADD_AD_CONSTANT(BAD_CERTIFICATE_STATUS_RESPONSE);
5682#endif
5683#ifdef SSL_AD_BAD_CERTIFICATE_HASH_VALUE
5684 ADD_AD_CONSTANT(BAD_CERTIFICATE_HASH_VALUE);
5685#endif
5686#ifdef SSL_AD_UNKNOWN_PSK_IDENTITY
5687 ADD_AD_CONSTANT(UNKNOWN_PSK_IDENTITY);
5688#endif
5689
5690#undef ADD_AD_CONSTANT
5691
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005692 /* protocol versions */
Victor Stinner3de49192011-05-09 00:42:58 +02005693#ifndef OPENSSL_NO_SSL2
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005694 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
5695 PY_SSL_VERSION_SSL2);
Victor Stinner3de49192011-05-09 00:42:58 +02005696#endif
Benjamin Petersone32467c2014-12-05 21:59:35 -05005697#ifndef OPENSSL_NO_SSL3
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005698 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
5699 PY_SSL_VERSION_SSL3);
Benjamin Petersone32467c2014-12-05 21:59:35 -05005700#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005701 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
Christian Heimes598894f2016-09-05 23:19:05 +02005702 PY_SSL_VERSION_TLS);
5703 PyModule_AddIntConstant(m, "PROTOCOL_TLS",
5704 PY_SSL_VERSION_TLS);
Christian Heimes5fe668c2016-09-12 00:01:11 +02005705 PyModule_AddIntConstant(m, "PROTOCOL_TLS_CLIENT",
5706 PY_SSL_VERSION_TLS_CLIENT);
5707 PyModule_AddIntConstant(m, "PROTOCOL_TLS_SERVER",
5708 PY_SSL_VERSION_TLS_SERVER);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005709 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
5710 PY_SSL_VERSION_TLS1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01005711 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_1",
5712 PY_SSL_VERSION_TLS1_1);
5713 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_2",
5714 PY_SSL_VERSION_TLS1_2);
Antoine Pitrou04f6a322010-04-05 21:40:07 +00005715
Antoine Pitroub5218772010-05-21 09:56:06 +00005716 /* protocol options */
Antoine Pitrou3f366312012-01-27 09:50:45 +01005717 PyModule_AddIntConstant(m, "OP_ALL",
5718 SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
Antoine Pitroub5218772010-05-21 09:56:06 +00005719 PyModule_AddIntConstant(m, "OP_NO_SSLv2", SSL_OP_NO_SSLv2);
5720 PyModule_AddIntConstant(m, "OP_NO_SSLv3", SSL_OP_NO_SSLv3);
5721 PyModule_AddIntConstant(m, "OP_NO_TLSv1", SSL_OP_NO_TLSv1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01005722 PyModule_AddIntConstant(m, "OP_NO_TLSv1_1", SSL_OP_NO_TLSv1_1);
5723 PyModule_AddIntConstant(m, "OP_NO_TLSv1_2", SSL_OP_NO_TLSv1_2);
Christian Heimescb5b68a2017-09-07 18:07:00 -07005724#ifdef SSL_OP_NO_TLSv1_3
5725 PyModule_AddIntConstant(m, "OP_NO_TLSv1_3", SSL_OP_NO_TLSv1_3);
5726#else
5727 PyModule_AddIntConstant(m, "OP_NO_TLSv1_3", 0);
5728#endif
Antoine Pitrou6db49442011-12-19 13:27:11 +01005729 PyModule_AddIntConstant(m, "OP_CIPHER_SERVER_PREFERENCE",
5730 SSL_OP_CIPHER_SERVER_PREFERENCE);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01005731 PyModule_AddIntConstant(m, "OP_SINGLE_DH_USE", SSL_OP_SINGLE_DH_USE);
Christian Heimes99a65702016-09-10 23:44:53 +02005732 PyModule_AddIntConstant(m, "OP_NO_TICKET", SSL_OP_NO_TICKET);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01005733#ifdef SSL_OP_SINGLE_ECDH_USE
Antoine Pitrou923df6f2011-12-19 17:16:51 +01005734 PyModule_AddIntConstant(m, "OP_SINGLE_ECDH_USE", SSL_OP_SINGLE_ECDH_USE);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01005735#endif
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01005736#ifdef SSL_OP_NO_COMPRESSION
5737 PyModule_AddIntConstant(m, "OP_NO_COMPRESSION",
5738 SSL_OP_NO_COMPRESSION);
5739#endif
Christian Heimes05d9fe32018-02-27 08:55:39 +01005740#ifdef SSL_OP_ENABLE_MIDDLEBOX_COMPAT
5741 PyModule_AddIntConstant(m, "OP_ENABLE_MIDDLEBOX_COMPAT",
5742 SSL_OP_ENABLE_MIDDLEBOX_COMPAT);
5743#endif
Christian Heimes67c48012018-05-15 16:25:40 -04005744#ifdef SSL_OP_NO_RENEGOTIATION
5745 PyModule_AddIntConstant(m, "OP_NO_RENEGOTIATION",
5746 SSL_OP_NO_RENEGOTIATION);
5747#endif
Christian Heimes6f37ebc2021-04-09 17:59:21 +02005748#ifdef SSL_OP_IGNORE_UNEXPECTED_EOF
5749 PyModule_AddIntConstant(m, "OP_IGNORE_UNEXPECTED_EOF",
5750 SSL_OP_IGNORE_UNEXPECTED_EOF);
5751#endif
Antoine Pitroub5218772010-05-21 09:56:06 +00005752
Christian Heimes61d478c2018-01-27 15:51:38 +01005753#ifdef X509_CHECK_FLAG_ALWAYS_CHECK_SUBJECT
5754 PyModule_AddIntConstant(m, "HOSTFLAG_ALWAYS_CHECK_SUBJECT",
5755 X509_CHECK_FLAG_ALWAYS_CHECK_SUBJECT);
5756#endif
5757#ifdef X509_CHECK_FLAG_NEVER_CHECK_SUBJECT
5758 PyModule_AddIntConstant(m, "HOSTFLAG_NEVER_CHECK_SUBJECT",
5759 X509_CHECK_FLAG_NEVER_CHECK_SUBJECT);
5760#endif
5761#ifdef X509_CHECK_FLAG_NO_WILDCARDS
5762 PyModule_AddIntConstant(m, "HOSTFLAG_NO_WILDCARDS",
5763 X509_CHECK_FLAG_NO_WILDCARDS);
5764#endif
5765#ifdef X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS
5766 PyModule_AddIntConstant(m, "HOSTFLAG_NO_PARTIAL_WILDCARDS",
5767 X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS);
5768#endif
5769#ifdef X509_CHECK_FLAG_MULTI_LABEL_WILDCARDS
5770 PyModule_AddIntConstant(m, "HOSTFLAG_MULTI_LABEL_WILDCARDS",
5771 X509_CHECK_FLAG_MULTI_LABEL_WILDCARDS);
5772#endif
5773#ifdef X509_CHECK_FLAG_SINGLE_LABEL_SUBDOMAINS
5774 PyModule_AddIntConstant(m, "HOSTFLAG_SINGLE_LABEL_SUBDOMAINS",
5775 X509_CHECK_FLAG_SINGLE_LABEL_SUBDOMAINS);
5776#endif
5777
Christian Heimes698dde12018-02-27 11:54:43 +01005778 /* protocol versions */
5779 PyModule_AddIntConstant(m, "PROTO_MINIMUM_SUPPORTED",
5780 PY_PROTO_MINIMUM_SUPPORTED);
5781 PyModule_AddIntConstant(m, "PROTO_MAXIMUM_SUPPORTED",
5782 PY_PROTO_MAXIMUM_SUPPORTED);
5783 PyModule_AddIntConstant(m, "PROTO_SSLv3", PY_PROTO_SSLv3);
5784 PyModule_AddIntConstant(m, "PROTO_TLSv1", PY_PROTO_TLSv1);
5785 PyModule_AddIntConstant(m, "PROTO_TLSv1_1", PY_PROTO_TLSv1_1);
5786 PyModule_AddIntConstant(m, "PROTO_TLSv1_2", PY_PROTO_TLSv1_2);
5787 PyModule_AddIntConstant(m, "PROTO_TLSv1_3", PY_PROTO_TLSv1_3);
Antoine Pitroud5323212010-10-22 18:19:07 +00005788
Victor Stinnerb37672d2018-11-22 03:37:50 +01005789#define addbool(m, key, value) \
5790 do { \
5791 PyObject *bool_obj = (value) ? Py_True : Py_False; \
5792 Py_INCREF(bool_obj); \
5793 PyModule_AddObject((m), (key), bool_obj); \
5794 } while (0)
Christian Heimes698dde12018-02-27 11:54:43 +01005795
Christian Heimes698dde12018-02-27 11:54:43 +01005796 addbool(m, "HAS_SNI", 1);
Christian Heimes698dde12018-02-27 11:54:43 +01005797 addbool(m, "HAS_TLS_UNIQUE", 1);
Christian Heimes698dde12018-02-27 11:54:43 +01005798 addbool(m, "HAS_ECDH", 1);
Christian Heimes698dde12018-02-27 11:54:43 +01005799 addbool(m, "HAS_NPN", 0);
Christian Heimes698dde12018-02-27 11:54:43 +01005800 addbool(m, "HAS_ALPN", 1);
Christian Heimes698dde12018-02-27 11:54:43 +01005801
5802#if defined(SSL2_VERSION) && !defined(OPENSSL_NO_SSL2)
5803 addbool(m, "HAS_SSLv2", 1);
5804#else
5805 addbool(m, "HAS_SSLv2", 0);
5806#endif
5807
5808#if defined(SSL3_VERSION) && !defined(OPENSSL_NO_SSL3)
5809 addbool(m, "HAS_SSLv3", 1);
5810#else
5811 addbool(m, "HAS_SSLv3", 0);
5812#endif
5813
5814#if defined(TLS1_VERSION) && !defined(OPENSSL_NO_TLS1)
5815 addbool(m, "HAS_TLSv1", 1);
5816#else
5817 addbool(m, "HAS_TLSv1", 0);
5818#endif
5819
5820#if defined(TLS1_1_VERSION) && !defined(OPENSSL_NO_TLS1_1)
5821 addbool(m, "HAS_TLSv1_1", 1);
5822#else
5823 addbool(m, "HAS_TLSv1_1", 0);
5824#endif
5825
5826#if defined(TLS1_2_VERSION) && !defined(OPENSSL_NO_TLS1_2)
5827 addbool(m, "HAS_TLSv1_2", 1);
5828#else
5829 addbool(m, "HAS_TLSv1_2", 0);
5830#endif
Benjamin Petersoncca27322015-01-23 16:35:37 -05005831
Christian Heimescb5b68a2017-09-07 18:07:00 -07005832#if defined(TLS1_3_VERSION) && !defined(OPENSSL_NO_TLS1_3)
Christian Heimes698dde12018-02-27 11:54:43 +01005833 addbool(m, "HAS_TLSv1_3", 1);
Christian Heimescb5b68a2017-09-07 18:07:00 -07005834#else
Christian Heimes698dde12018-02-27 11:54:43 +01005835 addbool(m, "HAS_TLSv1_3", 0);
Christian Heimescb5b68a2017-09-07 18:07:00 -07005836#endif
Christian Heimescb5b68a2017-09-07 18:07:00 -07005837
Christian Heimes5c36da72020-11-20 09:40:12 +01005838 return 0;
5839}
5840
Christian Heimes7f1305e2021-04-17 20:06:38 +02005841static int
5842sslmodule_init_errorcodes(PyObject *module)
5843{
5844 _sslmodulestate *state = get_ssl_state(module);
Christian Heimes5c36da72020-11-20 09:40:12 +01005845
Christian Heimes7f1305e2021-04-17 20:06:38 +02005846 struct py_ssl_error_code *errcode;
5847 struct py_ssl_library_code *libcode;
Christian Heimes5c36da72020-11-20 09:40:12 +01005848
Christian Heimes7f1305e2021-04-17 20:06:38 +02005849 /* Mappings for error codes */
5850 state->err_codes_to_names = PyDict_New();
5851 if (state->err_codes_to_names == NULL)
5852 return -1;
5853 state->err_names_to_codes = PyDict_New();
5854 if (state->err_names_to_codes == NULL)
5855 return -1;
5856 state->lib_codes_to_names = PyDict_New();
5857 if (state->lib_codes_to_names == NULL)
5858 return -1;
5859
5860 errcode = error_codes;
5861 while (errcode->mnemonic != NULL) {
5862 PyObject *mnemo, *key;
5863 mnemo = PyUnicode_FromString(errcode->mnemonic);
5864 key = Py_BuildValue("ii", errcode->library, errcode->reason);
5865 if (mnemo == NULL || key == NULL)
5866 return -1;
5867 if (PyDict_SetItem(state->err_codes_to_names, key, mnemo))
5868 return -1;
5869 if (PyDict_SetItem(state->err_names_to_codes, mnemo, key))
5870 return -1;
5871 Py_DECREF(key);
5872 Py_DECREF(mnemo);
5873 errcode++;
5874 }
5875
5876 libcode = library_codes;
5877 while (libcode->library != NULL) {
5878 PyObject *mnemo, *key;
5879 key = PyLong_FromLong(libcode->code);
5880 mnemo = PyUnicode_FromString(libcode->library);
5881 if (key == NULL || mnemo == NULL)
5882 return -1;
5883 if (PyDict_SetItem(state->lib_codes_to_names, key, mnemo))
5884 return -1;
5885 Py_DECREF(key);
5886 Py_DECREF(mnemo);
5887 libcode++;
5888 }
5889
5890 if (PyModule_AddObjectRef(module, "err_codes_to_names", state->err_codes_to_names))
5891 return -1;
5892 if (PyModule_AddObjectRef(module, "err_names_to_codes", state->err_names_to_codes))
5893 return -1;
5894 if (PyModule_AddObjectRef(module, "lib_codes_to_names", state->lib_codes_to_names))
5895 return -1;
5896
5897 return 0;
5898}
5899
5900static void
5901parse_openssl_version(unsigned long libver,
5902 unsigned int *major, unsigned int *minor,
5903 unsigned int *fix, unsigned int *patch,
5904 unsigned int *status)
5905{
5906 *status = libver & 0xF;
5907 libver >>= 4;
5908 *patch = libver & 0xFF;
5909 libver >>= 8;
5910 *fix = libver & 0xFF;
5911 libver >>= 8;
5912 *minor = libver & 0xFF;
5913 libver >>= 8;
5914 *major = libver & 0xFF;
5915}
5916
5917static int
5918sslmodule_init_versioninfo(PyObject *m)
5919{
5920 PyObject *r;
5921 unsigned long libver;
5922 unsigned int major, minor, fix, patch, status;
5923
5924 /* OpenSSL version */
5925 /* SSLeay() gives us the version of the library linked against,
5926 which could be different from the headers version.
5927 */
5928 libver = OpenSSL_version_num();
5929 r = PyLong_FromUnsignedLong(libver);
5930 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r))
5931 return -1;
5932
5933 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
5934 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
5935 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r))
5936 return -1;
5937
5938 r = PyUnicode_FromString(OpenSSL_version(OPENSSL_VERSION));
5939 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r))
5940 return -1;
5941
5942 libver = OPENSSL_VERSION_NUMBER;
5943 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
5944 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
5945 if (r == NULL || PyModule_AddObject(m, "_OPENSSL_API_VERSION", r))
5946 return -1;
5947
5948 return 0;
5949}
5950
5951static int
5952sslmodule_init_types(PyObject *module)
5953{
5954 _sslmodulestate *state = get_ssl_state(module);
5955
5956 state->PySSLContext_Type = (PyTypeObject *)PyType_FromModuleAndSpec(
5957 module, &PySSLContext_spec, NULL
5958 );
5959 if (state->PySSLContext_Type == NULL)
5960 return -1;
5961
5962 state->PySSLSocket_Type = (PyTypeObject *)PyType_FromModuleAndSpec(
5963 module, &PySSLSocket_spec, NULL
5964 );
5965 if (state->PySSLSocket_Type == NULL)
5966 return -1;
5967
5968 state->PySSLMemoryBIO_Type = (PyTypeObject *)PyType_FromModuleAndSpec(
5969 module, &PySSLMemoryBIO_spec, NULL
5970 );
5971 if (state->PySSLMemoryBIO_Type == NULL)
5972 return -1;
5973
5974 state->PySSLSession_Type = (PyTypeObject *)PyType_FromModuleAndSpec(
5975 module, &PySSLSession_spec, NULL
5976 );
5977 if (state->PySSLSession_Type == NULL)
5978 return -1;
5979
5980 if (PyModule_AddType(module, state->PySSLContext_Type))
5981 return -1;
5982 if (PyModule_AddType(module, state->PySSLSocket_Type))
5983 return -1;
5984 if (PyModule_AddType(module, state->PySSLMemoryBIO_Type))
5985 return -1;
5986 if (PyModule_AddType(module, state->PySSLSession_Type))
5987 return -1;
5988
5989 return 0;
5990}
5991
5992static PyModuleDef_Slot sslmodule_slots[] = {
5993 {Py_mod_exec, sslmodule_init_types},
5994 {Py_mod_exec, sslmodule_init_exceptions},
5995 {Py_mod_exec, sslmodule_init_socketapi},
5996 {Py_mod_exec, sslmodule_init_errorcodes},
5997 {Py_mod_exec, sslmodule_init_constants},
5998 {Py_mod_exec, sslmodule_init_versioninfo},
5999 {0, NULL}
6000};
6001
6002static int
6003sslmodule_traverse(PyObject *m, visitproc visit, void *arg)
6004{
6005 _sslmodulestate *state = get_ssl_state(m);
6006
6007 Py_VISIT(state->PySSLContext_Type);
6008 Py_VISIT(state->PySSLSocket_Type);
6009 Py_VISIT(state->PySSLMemoryBIO_Type);
6010 Py_VISIT(state->PySSLSession_Type);
6011 Py_VISIT(state->PySSLErrorObject);
6012 Py_VISIT(state->PySSLCertVerificationErrorObject);
6013 Py_VISIT(state->PySSLZeroReturnErrorObject);
6014 Py_VISIT(state->PySSLWantReadErrorObject);
6015 Py_VISIT(state->PySSLWantWriteErrorObject);
6016 Py_VISIT(state->PySSLSyscallErrorObject);
6017 Py_VISIT(state->PySSLEOFErrorObject);
6018 Py_VISIT(state->err_codes_to_names);
6019 Py_VISIT(state->err_names_to_codes);
6020 Py_VISIT(state->lib_codes_to_names);
6021 Py_VISIT(state->Sock_Type);
6022
6023 return 0;
6024}
6025
6026static int
6027sslmodule_clear(PyObject *m)
6028{
6029 _sslmodulestate *state = get_ssl_state(m);
6030
6031 Py_CLEAR(state->PySSLContext_Type);
6032 Py_CLEAR(state->PySSLSocket_Type);
6033 Py_CLEAR(state->PySSLMemoryBIO_Type);
6034 Py_CLEAR(state->PySSLSession_Type);
6035 Py_CLEAR(state->PySSLErrorObject);
6036 Py_CLEAR(state->PySSLCertVerificationErrorObject);
6037 Py_CLEAR(state->PySSLZeroReturnErrorObject);
6038 Py_CLEAR(state->PySSLWantReadErrorObject);
6039 Py_CLEAR(state->PySSLWantWriteErrorObject);
6040 Py_CLEAR(state->PySSLSyscallErrorObject);
6041 Py_CLEAR(state->PySSLEOFErrorObject);
6042 Py_CLEAR(state->err_codes_to_names);
6043 Py_CLEAR(state->err_names_to_codes);
6044 Py_CLEAR(state->lib_codes_to_names);
6045 Py_CLEAR(state->Sock_Type);
6046
6047 return 0;
6048}
6049
6050static void
6051sslmodule_free(void *m)
6052{
6053 sslmodule_clear((PyObject *)m);
6054}
6055
6056static struct PyModuleDef _sslmodule_def = {
Christian Heimes5c36da72020-11-20 09:40:12 +01006057 PyModuleDef_HEAD_INIT,
Christian Heimes7f1305e2021-04-17 20:06:38 +02006058 .m_name = "_ssl",
6059 .m_doc = module_doc,
6060 .m_size = sizeof(_sslmodulestate),
6061 .m_methods = PySSL_methods,
6062 .m_slots = sslmodule_slots,
6063 .m_traverse = sslmodule_traverse,
6064 .m_clear = sslmodule_clear,
6065 .m_free = sslmodule_free
Christian Heimes5c36da72020-11-20 09:40:12 +01006066};
6067
6068PyMODINIT_FUNC
6069PyInit__ssl(void)
6070{
Christian Heimes7f1305e2021-04-17 20:06:38 +02006071 return PyModuleDef_Init(&_sslmodule_def);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00006072}