blob: 65370c58a38b5dde20762fd10c2db44626118722 [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
Christian Heimes666991f2021-04-26 15:01:40 +02001709#include "_ssl/misc.c"
1710#include "_ssl/cert.c"
1711
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001712/*[clinic input]
1713_ssl._test_decode_cert
1714 path: object(converter="PyUnicode_FSConverter")
1715 /
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001716
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001717[clinic start generated code]*/
1718
1719static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001720_ssl__test_decode_cert_impl(PyObject *module, PyObject *path)
1721/*[clinic end generated code: output=96becb9abb23c091 input=cdeaaf02d4346628]*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001722{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001723 PyObject *retval = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001724 X509 *x=NULL;
1725 BIO *cert;
Christian Heimes7f1305e2021-04-17 20:06:38 +02001726 _sslmodulestate *state = get_ssl_state(module);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001727
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001728 if ((cert=BIO_new(BIO_s_file())) == NULL) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02001729 PyErr_SetString(state->PySSLErrorObject,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001730 "Can't malloc memory to read file");
1731 goto fail0;
1732 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001733
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001734 if (BIO_read_filename(cert, PyBytes_AsString(path)) <= 0) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02001735 PyErr_SetString(state->PySSLErrorObject,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001736 "Can't open file");
1737 goto fail0;
1738 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001739
Alex Gaynor40dad952019-08-15 08:31:28 -04001740 x = PEM_read_bio_X509(cert, NULL, NULL, NULL);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001741 if (x == NULL) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02001742 PyErr_SetString(state->PySSLErrorObject,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001743 "Error decoding PEM-encoded file");
1744 goto fail0;
1745 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001746
Christian Heimes7f1305e2021-04-17 20:06:38 +02001747 retval = _decode_certificate(state, x);
Mark Dickinsonee55df52010-08-03 18:31:54 +00001748 X509_free(x);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001749
1750 fail0:
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001751 Py_DECREF(path);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001752 if (cert != NULL) BIO_free(cert);
1753 return retval;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001754}
1755
1756
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001757/*[clinic input]
Christian Heimes141c5e82018-02-24 21:10:57 +01001758_ssl._SSLSocket.getpeercert
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001759 der as binary_mode: bool = False
1760 /
1761
1762Returns the certificate for the peer.
1763
1764If no certificate was provided, returns None. If a certificate was
1765provided, but not validated, returns an empty dictionary. Otherwise
1766returns a dict containing information about the peer certificate.
1767
1768If the optional argument is True, returns a DER-encoded copy of the
1769peer certificate, or None if no certificate was provided. This will
1770return the certificate even if it wasn't validated.
1771[clinic start generated code]*/
1772
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001773static PyObject *
Christian Heimes141c5e82018-02-24 21:10:57 +01001774_ssl__SSLSocket_getpeercert_impl(PySSLSocket *self, int binary_mode)
1775/*[clinic end generated code: output=1f0ab66dfb693c88 input=c0fbe802e57629b7]*/
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001776{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001777 int verification;
Christian Heimes66dc33b2017-05-23 16:02:02 -07001778 X509 *peer_cert;
1779 PyObject *result;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001780
Christian Heimes66dc33b2017-05-23 16:02:02 -07001781 if (!SSL_is_init_finished(self->ssl)) {
Antoine Pitrou20b85552013-09-29 19:50:53 +02001782 PyErr_SetString(PyExc_ValueError,
1783 "handshake not done yet");
1784 return NULL;
1785 }
Christian Heimes66dc33b2017-05-23 16:02:02 -07001786 peer_cert = SSL_get_peer_certificate(self->ssl);
1787 if (peer_cert == NULL)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001788 Py_RETURN_NONE;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001789
Antoine Pitrou721738f2012-08-15 23:20:39 +02001790 if (binary_mode) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001791 /* return cert in DER-encoded format */
Christian Heimes7f1305e2021-04-17 20:06:38 +02001792 result = _certificate_to_der(get_state_sock(self), peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001793 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00001794 verification = SSL_CTX_get_verify_mode(SSL_get_SSL_CTX(self->ssl));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001795 if ((verification & SSL_VERIFY_PEER) == 0)
Christian Heimes66dc33b2017-05-23 16:02:02 -07001796 result = PyDict_New();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001797 else
Christian Heimes7f1305e2021-04-17 20:06:38 +02001798 result = _decode_certificate(get_state_sock(self), peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001799 }
Christian Heimes66dc33b2017-05-23 16:02:02 -07001800 X509_free(peer_cert);
1801 return result;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001802}
1803
Christian Heimes666991f2021-04-26 15:01:40 +02001804/*[clinic input]
1805_ssl._SSLSocket.get_verified_chain
1806
1807[clinic start generated code]*/
1808
1809static PyObject *
1810_ssl__SSLSocket_get_verified_chain_impl(PySSLSocket *self)
1811/*[clinic end generated code: output=802421163cdc3110 input=5fb0714f77e2bd51]*/
1812{
1813 /* borrowed reference */
1814 STACK_OF(X509) *chain = SSL_get0_verified_chain(self->ssl);
1815 if (chain == NULL) {
1816 Py_RETURN_NONE;
1817 }
1818 return _PySSL_CertificateFromX509Stack(self->ctx->state, chain, 1);
1819}
1820
1821/*[clinic input]
1822_ssl._SSLSocket.get_unverified_chain
1823
1824[clinic start generated code]*/
1825
1826static PyObject *
1827_ssl__SSLSocket_get_unverified_chain_impl(PySSLSocket *self)
1828/*[clinic end generated code: output=5acdae414e13f913 input=78c33c360c635cb5]*/
1829{
1830 PyObject *retval;
1831 /* borrowed reference */
1832 /* TODO: include SSL_get_peer_certificate() for server-side sockets */
1833 STACK_OF(X509) *chain = SSL_get_peer_cert_chain(self->ssl);
1834 if (chain == NULL) {
1835 Py_RETURN_NONE;
1836 }
1837 retval = _PySSL_CertificateFromX509Stack(self->ctx->state, chain, 1);
1838 if (retval == NULL) {
1839 return NULL;
1840 }
1841 /* OpenSSL does not include peer cert for server side connections */
1842 if (self->socket_type == PY_SSL_SERVER) {
1843 PyObject *peerobj = NULL;
1844 X509 *peer = SSL_get_peer_certificate(self->ssl);
1845
1846 if (peer == NULL) {
1847 peerobj = Py_None;
1848 Py_INCREF(peerobj);
1849 } else {
1850 /* consume X509 reference on success */
1851 peerobj = _PySSL_CertificateFromX509(self->ctx->state, peer, 0);
1852 if (peerobj == NULL) {
1853 X509_free(peer);
1854 Py_DECREF(retval);
1855 return NULL;
1856 }
1857 }
1858 int res = PyList_Insert(retval, 0, peerobj);
1859 Py_DECREF(peerobj);
1860 if (res < 0) {
1861 Py_DECREF(retval);
1862 return NULL;
1863 }
1864 }
1865 return retval;
1866}
1867
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001868static PyObject *
1869cipher_to_tuple(const SSL_CIPHER *cipher)
1870{
1871 const char *cipher_name, *cipher_protocol;
1872 PyObject *v, *retval = PyTuple_New(3);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001873 if (retval == NULL)
1874 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001875
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001876 cipher_name = SSL_CIPHER_get_name(cipher);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001877 if (cipher_name == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001878 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001879 PyTuple_SET_ITEM(retval, 0, Py_None);
1880 } else {
1881 v = PyUnicode_FromString(cipher_name);
1882 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001883 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001884 PyTuple_SET_ITEM(retval, 0, v);
1885 }
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001886
1887 cipher_protocol = SSL_CIPHER_get_version(cipher);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001888 if (cipher_protocol == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001889 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001890 PyTuple_SET_ITEM(retval, 1, Py_None);
1891 } else {
1892 v = PyUnicode_FromString(cipher_protocol);
1893 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001894 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001895 PyTuple_SET_ITEM(retval, 1, v);
1896 }
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001897
1898 v = PyLong_FromLong(SSL_CIPHER_get_bits(cipher, NULL));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001899 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001900 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001901 PyTuple_SET_ITEM(retval, 2, v);
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001902
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001903 return retval;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001904
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001905 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001906 Py_DECREF(retval);
1907 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001908}
1909
Christian Heimes25bfcd52016-09-06 00:04:45 +02001910static PyObject *
1911cipher_to_dict(const SSL_CIPHER *cipher)
1912{
1913 const char *cipher_name, *cipher_protocol;
1914
1915 unsigned long cipher_id;
1916 int alg_bits, strength_bits, len;
1917 char buf[512] = {0};
Christian Heimes25bfcd52016-09-06 00:04:45 +02001918 int aead, nid;
1919 const char *skcipher = NULL, *digest = NULL, *kx = NULL, *auth = NULL;
Christian Heimes25bfcd52016-09-06 00:04:45 +02001920
1921 /* can be NULL */
1922 cipher_name = SSL_CIPHER_get_name(cipher);
1923 cipher_protocol = SSL_CIPHER_get_version(cipher);
1924 cipher_id = SSL_CIPHER_get_id(cipher);
1925 SSL_CIPHER_description(cipher, buf, sizeof(buf) - 1);
Segev Finer5cff6372017-07-27 01:19:17 +03001926 /* Downcast to avoid a warning. Safe since buf is always 512 bytes */
1927 len = (int)strlen(buf);
Christian Heimes25bfcd52016-09-06 00:04:45 +02001928 if (len > 1 && buf[len-1] == '\n')
1929 buf[len-1] = '\0';
1930 strength_bits = SSL_CIPHER_get_bits(cipher, &alg_bits);
1931
Christian Heimes25bfcd52016-09-06 00:04:45 +02001932 aead = SSL_CIPHER_is_aead(cipher);
1933 nid = SSL_CIPHER_get_cipher_nid(cipher);
1934 skcipher = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1935 nid = SSL_CIPHER_get_digest_nid(cipher);
1936 digest = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1937 nid = SSL_CIPHER_get_kx_nid(cipher);
1938 kx = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1939 nid = SSL_CIPHER_get_auth_nid(cipher);
1940 auth = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
Christian Heimes25bfcd52016-09-06 00:04:45 +02001941
Victor Stinner410b9882016-09-12 12:00:23 +02001942 return Py_BuildValue(
Christian Heimes25bfcd52016-09-06 00:04:45 +02001943 "{sksssssssisi"
Christian Heimes25bfcd52016-09-06 00:04:45 +02001944 "sOssssssss"
Christian Heimes25bfcd52016-09-06 00:04:45 +02001945 "}",
1946 "id", cipher_id,
1947 "name", cipher_name,
1948 "protocol", cipher_protocol,
1949 "description", buf,
1950 "strength_bits", strength_bits,
1951 "alg_bits", alg_bits
Christian Heimes25bfcd52016-09-06 00:04:45 +02001952 ,"aead", aead ? Py_True : Py_False,
1953 "symmetric", skcipher,
1954 "digest", digest,
1955 "kea", kx,
1956 "auth", auth
Christian Heimes25bfcd52016-09-06 00:04:45 +02001957 );
Christian Heimes25bfcd52016-09-06 00:04:45 +02001958}
Christian Heimes25bfcd52016-09-06 00:04:45 +02001959
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001960/*[clinic input]
1961_ssl._SSLSocket.shared_ciphers
1962[clinic start generated code]*/
1963
1964static PyObject *
1965_ssl__SSLSocket_shared_ciphers_impl(PySSLSocket *self)
1966/*[clinic end generated code: output=3d174ead2e42c4fd input=0bfe149da8fe6306]*/
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001967{
1968 STACK_OF(SSL_CIPHER) *ciphers;
1969 int i;
1970 PyObject *res;
1971
Christian Heimes598894f2016-09-05 23:19:05 +02001972 ciphers = SSL_get_ciphers(self->ssl);
1973 if (!ciphers)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001974 Py_RETURN_NONE;
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001975 res = PyList_New(sk_SSL_CIPHER_num(ciphers));
1976 if (!res)
1977 return NULL;
1978 for (i = 0; i < sk_SSL_CIPHER_num(ciphers); i++) {
1979 PyObject *tup = cipher_to_tuple(sk_SSL_CIPHER_value(ciphers, i));
1980 if (!tup) {
1981 Py_DECREF(res);
1982 return NULL;
1983 }
1984 PyList_SET_ITEM(res, i, tup);
1985 }
1986 return res;
1987}
1988
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001989/*[clinic input]
1990_ssl._SSLSocket.cipher
1991[clinic start generated code]*/
1992
1993static PyObject *
1994_ssl__SSLSocket_cipher_impl(PySSLSocket *self)
1995/*[clinic end generated code: output=376417c16d0e5815 input=548fb0e27243796d]*/
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001996{
1997 const SSL_CIPHER *current;
1998
1999 if (self->ssl == NULL)
2000 Py_RETURN_NONE;
2001 current = SSL_get_current_cipher(self->ssl);
2002 if (current == NULL)
2003 Py_RETURN_NONE;
2004 return cipher_to_tuple(current);
2005}
2006
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002007/*[clinic input]
2008_ssl._SSLSocket.version
2009[clinic start generated code]*/
2010
2011static PyObject *
2012_ssl__SSLSocket_version_impl(PySSLSocket *self)
2013/*[clinic end generated code: output=178aed33193b2cdb input=900186a503436fd6]*/
Antoine Pitrou47e40422014-09-04 21:00:10 +02002014{
2015 const char *version;
2016
2017 if (self->ssl == NULL)
2018 Py_RETURN_NONE;
Christian Heimes68771112017-09-05 21:55:40 -07002019 if (!SSL_is_init_finished(self->ssl)) {
2020 /* handshake not finished */
2021 Py_RETURN_NONE;
2022 }
Antoine Pitrou47e40422014-09-04 21:00:10 +02002023 version = SSL_get_version(self->ssl);
2024 if (!strcmp(version, "unknown"))
2025 Py_RETURN_NONE;
2026 return PyUnicode_FromString(version);
2027}
2028
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002029/*[clinic input]
2030_ssl._SSLSocket.selected_alpn_protocol
2031[clinic start generated code]*/
2032
2033static PyObject *
2034_ssl__SSLSocket_selected_alpn_protocol_impl(PySSLSocket *self)
2035/*[clinic end generated code: output=ec33688b303d250f input=442de30e35bc2913]*/
2036{
Benjamin Petersoncca27322015-01-23 16:35:37 -05002037 const unsigned char *out;
2038 unsigned int outlen;
2039
2040 SSL_get0_alpn_selected(self->ssl, &out, &outlen);
2041
2042 if (out == NULL)
2043 Py_RETURN_NONE;
2044 return PyUnicode_FromStringAndSize((char *)out, outlen);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002045}
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002046
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002047/*[clinic input]
2048_ssl._SSLSocket.compression
2049[clinic start generated code]*/
2050
2051static PyObject *
2052_ssl__SSLSocket_compression_impl(PySSLSocket *self)
2053/*[clinic end generated code: output=bd16cb1bb4646ae7 input=5d059d0a2bbc32c8]*/
2054{
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01002055#ifdef OPENSSL_NO_COMP
2056 Py_RETURN_NONE;
2057#else
2058 const COMP_METHOD *comp_method;
2059 const char *short_name;
2060
2061 if (self->ssl == NULL)
2062 Py_RETURN_NONE;
2063 comp_method = SSL_get_current_compression(self->ssl);
Christian Heimes598894f2016-09-05 23:19:05 +02002064 if (comp_method == NULL || COMP_get_type(comp_method) == NID_undef)
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01002065 Py_RETURN_NONE;
Christian Heimes281e5f82016-09-06 01:10:39 +02002066 short_name = OBJ_nid2sn(COMP_get_type(comp_method));
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01002067 if (short_name == NULL)
2068 Py_RETURN_NONE;
2069 return PyUnicode_DecodeFSDefault(short_name);
2070#endif
2071}
2072
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002073static PySSLContext *PySSL_get_context(PySSLSocket *self, void *closure) {
2074 Py_INCREF(self->ctx);
2075 return self->ctx;
2076}
2077
2078static int PySSL_set_context(PySSLSocket *self, PyObject *value,
2079 void *closure) {
2080
Christian Heimes7f1305e2021-04-17 20:06:38 +02002081 if (PyObject_TypeCheck(value, self->ctx->state->PySSLContext_Type)) {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002082 Py_INCREF(value);
Serhiy Storchaka57a01d32016-04-10 18:05:40 +03002083 Py_SETREF(self->ctx, (PySSLContext *)value);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002084 SSL_set_SSL_CTX(self->ssl, self->ctx->ctx);
Christian Heimes77cde502021-03-21 16:13:09 +01002085 /* Set SSL* internal msg_callback to state of new context's state */
2086 SSL_set_msg_callback(
2087 self->ssl,
2088 self->ctx->msg_cb ? _PySSL_msg_callback : NULL
2089 );
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002090 } else {
Ned Deily4531ec72018-06-11 20:26:28 -04002091 PyErr_SetString(PyExc_TypeError, "The value must be a SSLContext");
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002092 return -1;
2093 }
2094
2095 return 0;
2096}
2097
2098PyDoc_STRVAR(PySSL_set_context_doc,
2099"_setter_context(ctx)\n\
2100\
2101This changes the context associated with the SSLSocket. This is typically\n\
Christian Heimes11a14932018-02-24 02:35:08 +01002102used from within a callback function set by the sni_callback\n\
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002103on the SSLContext to change the certificate information associated with the\n\
2104SSLSocket before the cryptographic exchange handshake messages\n");
2105
2106
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002107static PyObject *
2108PySSL_get_server_side(PySSLSocket *self, void *c)
2109{
2110 return PyBool_FromLong(self->socket_type == PY_SSL_SERVER);
2111}
2112
2113PyDoc_STRVAR(PySSL_get_server_side_doc,
2114"Whether this is a server-side socket.");
2115
2116static PyObject *
2117PySSL_get_server_hostname(PySSLSocket *self, void *c)
2118{
2119 if (self->server_hostname == NULL)
2120 Py_RETURN_NONE;
2121 Py_INCREF(self->server_hostname);
2122 return self->server_hostname;
2123}
2124
2125PyDoc_STRVAR(PySSL_get_server_hostname_doc,
2126"The currently set server hostname (for SNI).");
2127
2128static PyObject *
2129PySSL_get_owner(PySSLSocket *self, void *c)
2130{
2131 PyObject *owner;
2132
2133 if (self->owner == NULL)
2134 Py_RETURN_NONE;
2135
2136 owner = PyWeakref_GetObject(self->owner);
2137 Py_INCREF(owner);
2138 return owner;
2139}
2140
2141static int
2142PySSL_set_owner(PySSLSocket *self, PyObject *value, void *c)
2143{
Serhiy Storchaka48842712016-04-06 09:45:48 +03002144 Py_XSETREF(self->owner, PyWeakref_NewRef(value, NULL));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002145 if (self->owner == NULL)
2146 return -1;
2147 return 0;
2148}
2149
2150PyDoc_STRVAR(PySSL_get_owner_doc,
2151"The Python-level owner of this object.\
2152Passed as \"self\" in servername callback.");
2153
Christian Heimesc7f70692019-05-31 11:44:05 +02002154static int
2155PySSL_traverse(PySSLSocket *self, visitproc visit, void *arg)
2156{
2157 Py_VISIT(self->exc_type);
2158 Py_VISIT(self->exc_value);
2159 Py_VISIT(self->exc_tb);
2160 return 0;
2161}
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002162
Christian Heimesc7f70692019-05-31 11:44:05 +02002163static int
2164PySSL_clear(PySSLSocket *self)
2165{
2166 Py_CLEAR(self->exc_type);
2167 Py_CLEAR(self->exc_value);
2168 Py_CLEAR(self->exc_tb);
2169 return 0;
2170}
2171
2172static void
2173PySSL_dealloc(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002174{
Christian Heimes5c36da72020-11-20 09:40:12 +01002175 PyTypeObject *tp = Py_TYPE(self);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002176 if (self->ssl)
2177 SSL_free(self->ssl);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002178 Py_XDECREF(self->Socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002179 Py_XDECREF(self->ctx);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002180 Py_XDECREF(self->server_hostname);
2181 Py_XDECREF(self->owner);
Victor Stinner32bd68c2020-12-01 10:37:39 +01002182 PyObject_Free(self);
Christian Heimes5c36da72020-11-20 09:40:12 +01002183 Py_DECREF(tp);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002184}
2185
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002186/* If the socket has a timeout, do a select()/poll() on the socket.
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002187 The argument writing indicates the direction.
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00002188 Returns one of the possibilities in the timeout_state enum (above).
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002189 */
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00002190
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002191static int
Victor Stinner14690702015-04-06 22:46:13 +02002192PySSL_select(PySocketSockObject *s, int writing, _PyTime_t timeout)
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002193{
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002194 int rc;
2195#ifdef HAVE_POLL
2196 struct pollfd pollfd;
2197 _PyTime_t ms;
2198#else
2199 int nfds;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002200 fd_set fds;
2201 struct timeval tv;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002202#endif
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002203
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002204 /* Nothing to do unless we're in timeout mode (not non-blocking) */
Victor Stinner14690702015-04-06 22:46:13 +02002205 if ((s == NULL) || (timeout == 0))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002206 return SOCKET_IS_NONBLOCKING;
Victor Stinner14690702015-04-06 22:46:13 +02002207 else if (timeout < 0) {
2208 if (s->sock_timeout > 0)
2209 return SOCKET_HAS_TIMED_OUT;
2210 else
2211 return SOCKET_IS_BLOCKING;
2212 }
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002213
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002214 /* Guard against closed socket */
Victor Stinner524714e2016-07-22 17:43:59 +02002215 if (s->sock_fd == INVALID_SOCKET)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002216 return SOCKET_HAS_BEEN_CLOSED;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002217
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002218 /* Prefer poll, if available, since you can poll() any fd
2219 * which can't be done with select(). */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002220#ifdef HAVE_POLL
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002221 pollfd.fd = s->sock_fd;
2222 pollfd.events = writing ? POLLOUT : POLLIN;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002223
Victor Stinner14690702015-04-06 22:46:13 +02002224 /* timeout is in seconds, poll() uses milliseconds */
2225 ms = (int)_PyTime_AsMilliseconds(timeout, _PyTime_ROUND_CEILING);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002226 assert(ms <= INT_MAX);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002227
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002228 PySSL_BEGIN_ALLOW_THREADS
2229 rc = poll(&pollfd, 1, (int)ms);
2230 PySSL_END_ALLOW_THREADS
2231#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002232 /* Guard against socket too large for select*/
Charles-François Nataliaa26b272011-08-28 17:51:43 +02002233 if (!_PyIsSelectable_fd(s->sock_fd))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002234 return SOCKET_TOO_LARGE_FOR_SELECT;
Neal Norwitz082b2df2006-02-07 07:04:46 +00002235
Victor Stinner14690702015-04-06 22:46:13 +02002236 _PyTime_AsTimeval_noraise(timeout, &tv, _PyTime_ROUND_CEILING);
Victor Stinnere2452312015-03-28 03:00:46 +01002237
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002238 FD_ZERO(&fds);
2239 FD_SET(s->sock_fd, &fds);
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002240
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002241 /* Wait until the socket becomes ready */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002242 PySSL_BEGIN_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002243 nfds = Py_SAFE_DOWNCAST(s->sock_fd+1, SOCKET_T, int);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002244 if (writing)
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002245 rc = select(nfds, NULL, &fds, NULL, &tv);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002246 else
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002247 rc = select(nfds, &fds, NULL, NULL, &tv);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002248 PySSL_END_ALLOW_THREADS
Bill Janssen6e027db2007-11-15 22:23:56 +00002249#endif
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002250
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002251 /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
2252 (when we are able to write or when there's something to read) */
2253 return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002254}
2255
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002256/*[clinic input]
2257_ssl._SSLSocket.write
2258 b: Py_buffer
2259 /
2260
2261Writes the bytes-like object b into the SSL object.
2262
2263Returns the number of bytes written.
2264[clinic start generated code]*/
2265
2266static PyObject *
2267_ssl__SSLSocket_write_impl(PySSLSocket *self, Py_buffer *b)
2268/*[clinic end generated code: output=aa7a6be5527358d8 input=77262d994fe5100a]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002269{
Christian Heimes89d15502021-04-19 06:55:30 +02002270 size_t count = 0;
2271 int retval;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002272 int sockstate;
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002273 _PySSLError err;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002274 int nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002275 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002276 _PyTime_t timeout, deadline = 0;
2277 int has_timeout;
Bill Janssen54cc54c2007-12-14 22:08:56 +00002278
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002279 if (sock != NULL) {
2280 if (((PyObject*)sock) == Py_None) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02002281 _setSSLError(get_state_sock(self),
2282 "Underlying socket connection gone",
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002283 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2284 return NULL;
2285 }
2286 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002287 }
2288
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002289 if (sock != NULL) {
2290 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002291 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002292 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2293 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
2294 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002295
Victor Stinner14690702015-04-06 22:46:13 +02002296 timeout = GET_SOCKET_TIMEOUT(sock);
2297 has_timeout = (timeout > 0);
2298 if (has_timeout)
2299 deadline = _PyTime_GetMonotonicClock() + timeout;
2300
2301 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002302 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Christian Heimes03c8ddd2020-11-20 09:26:07 +01002303 PyErr_SetString(PyExc_TimeoutError,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002304 "The write operation timed out");
2305 goto error;
2306 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02002307 PyErr_SetString(get_state_sock(self)->PySSLErrorObject,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002308 "Underlying socket has been closed.");
2309 goto error;
2310 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02002311 PyErr_SetString(get_state_sock(self)->PySSLErrorObject,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002312 "Underlying socket too large for select().");
2313 goto error;
2314 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002315
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002316 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002317 PySSL_BEGIN_ALLOW_THREADS
Christian Heimes89d15502021-04-19 06:55:30 +02002318 retval = SSL_write_ex(self->ssl, b->buf, (int)b->len, &count);
2319 err = _PySSL_errno(retval == 0, self->ssl, retval);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002320 PySSL_END_ALLOW_THREADS
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002321 self->err = err;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002322
2323 if (PyErr_CheckSignals())
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002324 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002325
Victor Stinner14690702015-04-06 22:46:13 +02002326 if (has_timeout)
2327 timeout = deadline - _PyTime_GetMonotonicClock();
2328
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002329 if (err.ssl == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +02002330 sockstate = PySSL_select(sock, 0, timeout);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002331 } else if (err.ssl == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +02002332 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002333 } else {
2334 sockstate = SOCKET_OPERATION_OK;
2335 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002336
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002337 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Christian Heimes03c8ddd2020-11-20 09:26:07 +01002338 PyErr_SetString(PyExc_TimeoutError,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002339 "The write operation timed out");
2340 goto error;
2341 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02002342 PyErr_SetString(get_state_sock(self)->PySSLErrorObject,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002343 "Underlying socket has been closed.");
2344 goto error;
2345 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
2346 break;
2347 }
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002348 } while (err.ssl == SSL_ERROR_WANT_READ ||
2349 err.ssl == SSL_ERROR_WANT_WRITE);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002350
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002351 Py_XDECREF(sock);
Christian Heimes89d15502021-04-19 06:55:30 +02002352 if (retval == 0)
2353 return PySSL_SetError(self, retval, __FILE__, __LINE__);
Christian Heimesc7f70692019-05-31 11:44:05 +02002354 if (PySSL_ChainExceptions(self) < 0)
2355 return NULL;
Christian Heimes89d15502021-04-19 06:55:30 +02002356 return PyLong_FromSize_t(count);
Antoine Pitrou7d7aede2009-11-25 18:55:32 +00002357error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002358 Py_XDECREF(sock);
Christian Heimesc7f70692019-05-31 11:44:05 +02002359 PySSL_ChainExceptions(self);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002360 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002361}
2362
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002363/*[clinic input]
2364_ssl._SSLSocket.pending
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002365
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002366Returns the number of already decrypted bytes available for read, pending on the connection.
2367[clinic start generated code]*/
2368
2369static PyObject *
2370_ssl__SSLSocket_pending_impl(PySSLSocket *self)
2371/*[clinic end generated code: output=983d9fecdc308a83 input=2b77487d6dfd597f]*/
Bill Janssen6e027db2007-11-15 22:23:56 +00002372{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002373 int count = 0;
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002374 _PySSLError err;
Bill Janssen6e027db2007-11-15 22:23:56 +00002375
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002376 PySSL_BEGIN_ALLOW_THREADS
2377 count = SSL_pending(self->ssl);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002378 err = _PySSL_errno(count < 0, self->ssl, count);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002379 PySSL_END_ALLOW_THREADS
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002380 self->err = err;
2381
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002382 if (count < 0)
2383 return PySSL_SetError(self, count, __FILE__, __LINE__);
2384 else
2385 return PyLong_FromLong(count);
Bill Janssen6e027db2007-11-15 22:23:56 +00002386}
2387
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002388/*[clinic input]
2389_ssl._SSLSocket.read
2390 size as len: int
2391 [
Larry Hastingsdbfdc382015-05-04 06:59:46 -07002392 buffer: Py_buffer(accept={rwbuffer})
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002393 ]
2394 /
Bill Janssen6e027db2007-11-15 22:23:56 +00002395
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002396Read up to size bytes from the SSL socket.
2397[clinic start generated code]*/
2398
2399static PyObject *
2400_ssl__SSLSocket_read_impl(PySSLSocket *self, int len, int group_right_1,
2401 Py_buffer *buffer)
Larry Hastingsdbfdc382015-05-04 06:59:46 -07002402/*[clinic end generated code: output=00097776cec2a0af input=ff157eb918d0905b]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002403{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002404 PyObject *dest = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002405 char *mem;
Christian Heimes89d15502021-04-19 06:55:30 +02002406 size_t count = 0;
2407 int retval;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002408 int sockstate;
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002409 _PySSLError err;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002410 int nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002411 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002412 _PyTime_t timeout, deadline = 0;
2413 int has_timeout;
Bill Janssen54cc54c2007-12-14 22:08:56 +00002414
Martin Panter5503d472016-03-27 05:35:19 +00002415 if (!group_right_1 && len < 0) {
2416 PyErr_SetString(PyExc_ValueError, "size should not be negative");
2417 return NULL;
2418 }
2419
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002420 if (sock != NULL) {
2421 if (((PyObject*)sock) == Py_None) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02002422 _setSSLError(get_state_sock(self),
2423 "Underlying socket connection gone",
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002424 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2425 return NULL;
2426 }
2427 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002428 }
2429
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002430 if (!group_right_1) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002431 dest = PyBytes_FromStringAndSize(NULL, len);
2432 if (dest == NULL)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002433 goto error;
Martin Panterbed7f1a2016-07-11 00:17:13 +00002434 if (len == 0) {
2435 Py_XDECREF(sock);
2436 return dest;
2437 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002438 mem = PyBytes_AS_STRING(dest);
2439 }
2440 else {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002441 mem = buffer->buf;
2442 if (len <= 0 || len > buffer->len) {
2443 len = (int) buffer->len;
2444 if (buffer->len != len) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002445 PyErr_SetString(PyExc_OverflowError,
2446 "maximum length can't fit in a C 'int'");
2447 goto error;
2448 }
Martin Panterbed7f1a2016-07-11 00:17:13 +00002449 if (len == 0) {
2450 count = 0;
2451 goto done;
2452 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002453 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002454 }
2455
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002456 if (sock != NULL) {
2457 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002458 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002459 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2460 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
2461 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002462
Victor Stinner14690702015-04-06 22:46:13 +02002463 timeout = GET_SOCKET_TIMEOUT(sock);
2464 has_timeout = (timeout > 0);
2465 if (has_timeout)
2466 deadline = _PyTime_GetMonotonicClock() + timeout;
2467
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002468 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002469 PySSL_BEGIN_ALLOW_THREADS
Christian Heimes89d15502021-04-19 06:55:30 +02002470 retval = SSL_read_ex(self->ssl, mem, len, &count);
2471 err = _PySSL_errno(retval == 0, self->ssl, retval);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002472 PySSL_END_ALLOW_THREADS
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002473 self->err = err;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002474
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002475 if (PyErr_CheckSignals())
2476 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002477
Victor Stinner14690702015-04-06 22:46:13 +02002478 if (has_timeout)
2479 timeout = deadline - _PyTime_GetMonotonicClock();
2480
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002481 if (err.ssl == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +02002482 sockstate = PySSL_select(sock, 0, timeout);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002483 } else if (err.ssl == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +02002484 sockstate = PySSL_select(sock, 1, timeout);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002485 } else if (err.ssl == SSL_ERROR_ZERO_RETURN &&
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002486 SSL_get_shutdown(self->ssl) == SSL_RECEIVED_SHUTDOWN)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002487 {
2488 count = 0;
2489 goto done;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002490 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002491 else
2492 sockstate = SOCKET_OPERATION_OK;
2493
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002494 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Christian Heimes03c8ddd2020-11-20 09:26:07 +01002495 PyErr_SetString(PyExc_TimeoutError,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002496 "The read operation timed out");
2497 goto error;
2498 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
2499 break;
2500 }
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002501 } while (err.ssl == SSL_ERROR_WANT_READ ||
2502 err.ssl == SSL_ERROR_WANT_WRITE);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002503
Christian Heimes89d15502021-04-19 06:55:30 +02002504 if (retval == 0) {
2505 PySSL_SetError(self, retval, __FILE__, __LINE__);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002506 goto error;
2507 }
Christian Heimesc7f70692019-05-31 11:44:05 +02002508 if (self->exc_type != NULL)
2509 goto error;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002510
2511done:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002512 Py_XDECREF(sock);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002513 if (!group_right_1) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002514 _PyBytes_Resize(&dest, count);
2515 return dest;
2516 }
2517 else {
Christian Heimes89d15502021-04-19 06:55:30 +02002518 return PyLong_FromSize_t(count);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002519 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002520
2521error:
Christian Heimesc7f70692019-05-31 11:44:05 +02002522 PySSL_ChainExceptions(self);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002523 Py_XDECREF(sock);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002524 if (!group_right_1)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002525 Py_XDECREF(dest);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002526 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002527}
2528
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002529/*[clinic input]
2530_ssl._SSLSocket.shutdown
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002531
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002532Does the SSL shutdown handshake with the remote end.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002533[clinic start generated code]*/
2534
2535static PyObject *
2536_ssl__SSLSocket_shutdown_impl(PySSLSocket *self)
Christian Heimes141c5e82018-02-24 21:10:57 +01002537/*[clinic end generated code: output=ca1aa7ed9d25ca42 input=11d39e69b0a2bf4a]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00002538{
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002539 _PySSLError err;
2540 int sockstate, nonblocking, ret;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002541 int zeros = 0;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002542 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002543 _PyTime_t timeout, deadline = 0;
2544 int has_timeout;
Bill Janssen40a0f662008-08-12 16:56:25 +00002545
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002546 if (sock != NULL) {
2547 /* Guard against closed socket */
Victor Stinner524714e2016-07-22 17:43:59 +02002548 if ((((PyObject*)sock) == Py_None) || (sock->sock_fd == INVALID_SOCKET)) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02002549 _setSSLError(get_state_sock(self),
2550 "Underlying socket connection gone",
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002551 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2552 return NULL;
2553 }
2554 Py_INCREF(sock);
2555
2556 /* Just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002557 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002558 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2559 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002560 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002561
Victor Stinner14690702015-04-06 22:46:13 +02002562 timeout = GET_SOCKET_TIMEOUT(sock);
2563 has_timeout = (timeout > 0);
2564 if (has_timeout)
2565 deadline = _PyTime_GetMonotonicClock() + timeout;
2566
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002567 while (1) {
2568 PySSL_BEGIN_ALLOW_THREADS
2569 /* Disable read-ahead so that unwrap can work correctly.
2570 * Otherwise OpenSSL might read in too much data,
2571 * eating clear text data that happens to be
2572 * transmitted after the SSL shutdown.
Ezio Melotti85a86292013-08-17 16:57:41 +03002573 * Should be safe to call repeatedly every time this
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002574 * function is used and the shutdown_seen_zero != 0
2575 * condition is met.
2576 */
2577 if (self->shutdown_seen_zero)
2578 SSL_set_read_ahead(self->ssl, 0);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002579 ret = SSL_shutdown(self->ssl);
2580 err = _PySSL_errno(ret < 0, self->ssl, ret);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002581 PySSL_END_ALLOW_THREADS
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002582 self->err = err;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002583
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002584 /* If err == 1, a secure shutdown with SSL_shutdown() is complete */
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002585 if (ret > 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002586 break;
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002587 if (ret == 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002588 /* Don't loop endlessly; instead preserve legacy
2589 behaviour of trying SSL_shutdown() only twice.
2590 This looks necessary for OpenSSL < 0.9.8m */
2591 if (++zeros > 1)
2592 break;
2593 /* Shutdown was sent, now try receiving */
2594 self->shutdown_seen_zero = 1;
2595 continue;
Bill Janssen40a0f662008-08-12 16:56:25 +00002596 }
2597
Victor Stinner14690702015-04-06 22:46:13 +02002598 if (has_timeout)
2599 timeout = deadline - _PyTime_GetMonotonicClock();
2600
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002601 /* Possibly retry shutdown until timeout or failure */
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002602 if (err.ssl == SSL_ERROR_WANT_READ)
Victor Stinner14690702015-04-06 22:46:13 +02002603 sockstate = PySSL_select(sock, 0, timeout);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002604 else if (err.ssl == SSL_ERROR_WANT_WRITE)
Victor Stinner14690702015-04-06 22:46:13 +02002605 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002606 else
2607 break;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002608
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002609 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002610 if (err.ssl == SSL_ERROR_WANT_READ)
Christian Heimes03c8ddd2020-11-20 09:26:07 +01002611 PyErr_SetString(PyExc_TimeoutError,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002612 "The read operation timed out");
2613 else
Christian Heimes03c8ddd2020-11-20 09:26:07 +01002614 PyErr_SetString(PyExc_TimeoutError,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002615 "The write operation timed out");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002616 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002617 }
2618 else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02002619 PyErr_SetString(get_state_sock(self)->PySSLErrorObject,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002620 "Underlying socket too large for select().");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002621 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002622 }
2623 else if (sockstate != SOCKET_OPERATION_OK)
2624 /* Retain the SSL error code */
2625 break;
2626 }
Nathaniel J. Smithc0da5822018-09-21 21:44:12 -07002627 if (ret < 0) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002628 Py_XDECREF(sock);
Christian Heimesc7f70692019-05-31 11:44:05 +02002629 PySSL_SetError(self, ret, __FILE__, __LINE__);
2630 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002631 }
Christian Heimesc7f70692019-05-31 11:44:05 +02002632 if (self->exc_type != NULL)
2633 goto error;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002634 if (sock)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002635 /* It's already INCREF'ed */
2636 return (PyObject *) sock;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002637 else
2638 Py_RETURN_NONE;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002639
2640error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002641 Py_XDECREF(sock);
Christian Heimesc7f70692019-05-31 11:44:05 +02002642 PySSL_ChainExceptions(self);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002643 return NULL;
Bill Janssen40a0f662008-08-12 16:56:25 +00002644}
2645
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002646/*[clinic input]
Christian Heimes141c5e82018-02-24 21:10:57 +01002647_ssl._SSLSocket.get_channel_binding
2648 cb_type: str = "tls-unique"
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002649
Christian Heimes141c5e82018-02-24 21:10:57 +01002650Get channel binding data for current connection.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002651
Christian Heimes141c5e82018-02-24 21:10:57 +01002652Raise ValueError if the requested `cb_type` is not supported. Return bytes
2653of the data or None if the data is not available (e.g. before the handshake).
2654Only 'tls-unique' channel binding data from RFC 5929 is supported.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002655[clinic start generated code]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00002656
Antoine Pitroud6494802011-07-21 01:11:30 +02002657static PyObject *
Christian Heimes141c5e82018-02-24 21:10:57 +01002658_ssl__SSLSocket_get_channel_binding_impl(PySSLSocket *self,
2659 const char *cb_type)
2660/*[clinic end generated code: output=34bac9acb6a61d31 input=08b7e43b99c17d41]*/
Antoine Pitroud6494802011-07-21 01:11:30 +02002661{
Antoine Pitroud6494802011-07-21 01:11:30 +02002662 char buf[PySSL_CB_MAXLEN];
Victor Stinner9ee02032013-06-23 15:08:23 +02002663 size_t len;
Antoine Pitroud6494802011-07-21 01:11:30 +02002664
Christian Heimes141c5e82018-02-24 21:10:57 +01002665 if (strcmp(cb_type, "tls-unique") == 0) {
2666 if (SSL_session_reused(self->ssl) ^ !self->socket_type) {
2667 /* if session is resumed XOR we are the client */
2668 len = SSL_get_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2669 }
2670 else {
2671 /* if a new session XOR we are the server */
2672 len = SSL_get_peer_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2673 }
Antoine Pitroud6494802011-07-21 01:11:30 +02002674 }
2675 else {
Christian Heimes141c5e82018-02-24 21:10:57 +01002676 PyErr_Format(
2677 PyExc_ValueError,
2678 "'%s' channel binding type not implemented",
2679 cb_type
2680 );
2681 return NULL;
Antoine Pitroud6494802011-07-21 01:11:30 +02002682 }
2683
2684 /* It cannot be negative in current OpenSSL version as of July 2011 */
Antoine Pitroud6494802011-07-21 01:11:30 +02002685 if (len == 0)
2686 Py_RETURN_NONE;
2687
Christian Heimes141c5e82018-02-24 21:10:57 +01002688 return PyBytes_FromStringAndSize(buf, len);
Antoine Pitroud6494802011-07-21 01:11:30 +02002689}
2690
Christian Heimes9fb051f2018-09-23 08:32:31 +02002691/*[clinic input]
2692_ssl._SSLSocket.verify_client_post_handshake
2693
2694Initiate TLS 1.3 post-handshake authentication
2695[clinic start generated code]*/
2696
2697static PyObject *
2698_ssl__SSLSocket_verify_client_post_handshake_impl(PySSLSocket *self)
2699/*[clinic end generated code: output=532147f3b1341425 input=6bfa874810a3d889]*/
2700{
2701#ifdef TLS1_3_VERSION
2702 int err = SSL_verify_client_post_handshake(self->ssl);
2703 if (err == 0)
Christian Heimes7f1305e2021-04-17 20:06:38 +02002704 return _setSSLError(get_state_sock(self), NULL, 0, __FILE__, __LINE__);
Christian Heimes9fb051f2018-09-23 08:32:31 +02002705 else
2706 Py_RETURN_NONE;
2707#else
2708 PyErr_SetString(PyExc_NotImplementedError,
2709 "Post-handshake auth is not supported by your "
2710 "OpenSSL version.");
2711 return NULL;
2712#endif
2713}
2714
Christian Heimes99a65702016-09-10 23:44:53 +02002715static SSL_SESSION*
2716_ssl_session_dup(SSL_SESSION *session) {
2717 SSL_SESSION *newsession = NULL;
2718 int slen;
2719 unsigned char *senc = NULL, *p;
2720 const unsigned char *const_p;
2721
2722 if (session == NULL) {
2723 PyErr_SetString(PyExc_ValueError, "Invalid session");
2724 goto error;
2725 }
2726
2727 /* get length */
2728 slen = i2d_SSL_SESSION(session, NULL);
2729 if (slen == 0 || slen > 0xFF00) {
2730 PyErr_SetString(PyExc_ValueError, "i2d() failed.");
2731 goto error;
2732 }
2733 if ((senc = PyMem_Malloc(slen)) == NULL) {
2734 PyErr_NoMemory();
2735 goto error;
2736 }
2737 p = senc;
2738 if (!i2d_SSL_SESSION(session, &p)) {
2739 PyErr_SetString(PyExc_ValueError, "i2d() failed.");
2740 goto error;
2741 }
2742 const_p = senc;
2743 newsession = d2i_SSL_SESSION(NULL, &const_p, slen);
2744 if (session == NULL) {
2745 goto error;
2746 }
2747 PyMem_Free(senc);
2748 return newsession;
2749 error:
2750 if (senc != NULL) {
2751 PyMem_Free(senc);
2752 }
2753 return NULL;
2754}
Christian Heimes99a65702016-09-10 23:44:53 +02002755
2756static PyObject *
2757PySSL_get_session(PySSLSocket *self, void *closure) {
2758 /* get_session can return sessions from a server-side connection,
2759 * it does not check for handshake done or client socket. */
2760 PySSLSession *pysess;
2761 SSL_SESSION *session;
2762
Christian Heimes99a65702016-09-10 23:44:53 +02002763 /* duplicate session as workaround for session bug in OpenSSL 1.1.0,
2764 * https://github.com/openssl/openssl/issues/1550 */
2765 session = SSL_get0_session(self->ssl); /* borrowed reference */
2766 if (session == NULL) {
2767 Py_RETURN_NONE;
2768 }
2769 if ((session = _ssl_session_dup(session)) == NULL) {
2770 return NULL;
2771 }
Christian Heimes99a65702016-09-10 23:44:53 +02002772 session = SSL_get1_session(self->ssl);
2773 if (session == NULL) {
2774 Py_RETURN_NONE;
2775 }
Christian Heimes7f1305e2021-04-17 20:06:38 +02002776 pysess = PyObject_GC_New(PySSLSession, self->ctx->state->PySSLSession_Type);
Christian Heimes99a65702016-09-10 23:44:53 +02002777 if (pysess == NULL) {
2778 SSL_SESSION_free(session);
2779 return NULL;
2780 }
2781
2782 assert(self->ctx);
2783 pysess->ctx = self->ctx;
2784 Py_INCREF(pysess->ctx);
2785 pysess->session = session;
Christian Heimesa5d07652016-09-24 10:48:05 +02002786 PyObject_GC_Track(pysess);
Christian Heimes99a65702016-09-10 23:44:53 +02002787 return (PyObject *)pysess;
2788}
2789
2790static int PySSL_set_session(PySSLSocket *self, PyObject *value,
2791 void *closure)
2792 {
2793 PySSLSession *pysess;
Christian Heimes99a65702016-09-10 23:44:53 +02002794 SSL_SESSION *session;
Christian Heimes99a65702016-09-10 23:44:53 +02002795 int result;
2796
Christian Heimes7f1305e2021-04-17 20:06:38 +02002797 if (!Py_IS_TYPE(value, get_state_sock(self)->PySSLSession_Type)) {
Ned Deily4531ec72018-06-11 20:26:28 -04002798 PyErr_SetString(PyExc_TypeError, "Value is not a SSLSession.");
Christian Heimes99a65702016-09-10 23:44:53 +02002799 return -1;
2800 }
2801 pysess = (PySSLSession *)value;
2802
2803 if (self->ctx->ctx != pysess->ctx->ctx) {
2804 PyErr_SetString(PyExc_ValueError,
2805 "Session refers to a different SSLContext.");
2806 return -1;
2807 }
2808 if (self->socket_type != PY_SSL_CLIENT) {
2809 PyErr_SetString(PyExc_ValueError,
2810 "Cannot set session for server-side SSLSocket.");
2811 return -1;
2812 }
Christian Heimes66dc33b2017-05-23 16:02:02 -07002813 if (SSL_is_init_finished(self->ssl)) {
Christian Heimes99a65702016-09-10 23:44:53 +02002814 PyErr_SetString(PyExc_ValueError,
2815 "Cannot set session after handshake.");
2816 return -1;
2817 }
Christian Heimes99a65702016-09-10 23:44:53 +02002818 /* duplicate session */
2819 if ((session = _ssl_session_dup(pysess->session)) == NULL) {
2820 return -1;
2821 }
2822 result = SSL_set_session(self->ssl, session);
2823 /* free duplicate, SSL_set_session() bumps ref count */
2824 SSL_SESSION_free(session);
Christian Heimes99a65702016-09-10 23:44:53 +02002825 if (result == 0) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02002826 _setSSLError(get_state_sock(self), NULL, 0, __FILE__, __LINE__);
Christian Heimes99a65702016-09-10 23:44:53 +02002827 return -1;
2828 }
2829 return 0;
2830}
2831
2832PyDoc_STRVAR(PySSL_set_session_doc,
2833"_setter_session(session)\n\
2834\
2835Get / set SSLSession.");
2836
2837static PyObject *
2838PySSL_get_session_reused(PySSLSocket *self, void *closure) {
2839 if (SSL_session_reused(self->ssl)) {
2840 Py_RETURN_TRUE;
2841 } else {
2842 Py_RETURN_FALSE;
2843 }
2844}
2845
2846PyDoc_STRVAR(PySSL_get_session_reused_doc,
2847"Was the client session reused during handshake?");
2848
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002849static PyGetSetDef ssl_getsetlist[] = {
2850 {"context", (getter) PySSL_get_context,
2851 (setter) PySSL_set_context, PySSL_set_context_doc},
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002852 {"server_side", (getter) PySSL_get_server_side, NULL,
2853 PySSL_get_server_side_doc},
2854 {"server_hostname", (getter) PySSL_get_server_hostname, NULL,
2855 PySSL_get_server_hostname_doc},
2856 {"owner", (getter) PySSL_get_owner, (setter) PySSL_set_owner,
2857 PySSL_get_owner_doc},
Christian Heimes99a65702016-09-10 23:44:53 +02002858 {"session", (getter) PySSL_get_session,
2859 (setter) PySSL_set_session, PySSL_set_session_doc},
2860 {"session_reused", (getter) PySSL_get_session_reused, NULL,
2861 PySSL_get_session_reused_doc},
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002862 {NULL}, /* sentinel */
2863};
2864
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002865static PyMethodDef PySSLMethods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002866 _SSL__SSLSOCKET_DO_HANDSHAKE_METHODDEF
2867 _SSL__SSLSOCKET_WRITE_METHODDEF
2868 _SSL__SSLSOCKET_READ_METHODDEF
2869 _SSL__SSLSOCKET_PENDING_METHODDEF
Christian Heimes141c5e82018-02-24 21:10:57 +01002870 _SSL__SSLSOCKET_GETPEERCERT_METHODDEF
2871 _SSL__SSLSOCKET_GET_CHANNEL_BINDING_METHODDEF
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002872 _SSL__SSLSOCKET_CIPHER_METHODDEF
2873 _SSL__SSLSOCKET_SHARED_CIPHERS_METHODDEF
2874 _SSL__SSLSOCKET_VERSION_METHODDEF
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002875 _SSL__SSLSOCKET_SELECTED_ALPN_PROTOCOL_METHODDEF
2876 _SSL__SSLSOCKET_COMPRESSION_METHODDEF
2877 _SSL__SSLSOCKET_SHUTDOWN_METHODDEF
Christian Heimes9fb051f2018-09-23 08:32:31 +02002878 _SSL__SSLSOCKET_VERIFY_CLIENT_POST_HANDSHAKE_METHODDEF
Christian Heimes666991f2021-04-26 15:01:40 +02002879 _SSL__SSLSOCKET_GET_UNVERIFIED_CHAIN_METHODDEF
2880 _SSL__SSLSOCKET_GET_VERIFIED_CHAIN_METHODDEF
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002881 {NULL, NULL}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002882};
2883
Christian Heimes5c36da72020-11-20 09:40:12 +01002884static PyType_Slot PySSLSocket_slots[] = {
2885 {Py_tp_methods, PySSLMethods},
2886 {Py_tp_getset, ssl_getsetlist},
2887 {Py_tp_dealloc, PySSL_dealloc},
2888 {Py_tp_traverse, PySSL_traverse},
2889 {Py_tp_clear, PySSL_clear},
2890 {0, 0},
2891};
2892
2893static PyType_Spec PySSLSocket_spec = {
2894 "_ssl._SSLSocket",
2895 sizeof(PySSLSocket),
2896 0,
2897 Py_TPFLAGS_DEFAULT,
2898 PySSLSocket_slots,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002899};
2900
Antoine Pitrou152efa22010-05-16 18:19:27 +00002901/*
2902 * _SSLContext objects
2903 */
2904
Christian Heimes5fe668c2016-09-12 00:01:11 +02002905static int
Christian Heimes9fb051f2018-09-23 08:32:31 +02002906_set_verify_mode(PySSLContext *self, enum py_ssl_cert_requirements n)
Christian Heimes5fe668c2016-09-12 00:01:11 +02002907{
2908 int mode;
2909 int (*verify_cb)(int, X509_STORE_CTX *) = NULL;
2910
2911 switch(n) {
2912 case PY_SSL_CERT_NONE:
2913 mode = SSL_VERIFY_NONE;
2914 break;
2915 case PY_SSL_CERT_OPTIONAL:
2916 mode = SSL_VERIFY_PEER;
2917 break;
2918 case PY_SSL_CERT_REQUIRED:
2919 mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
2920 break;
2921 default:
2922 PyErr_SetString(PyExc_ValueError,
2923 "invalid value for verify_mode");
2924 return -1;
2925 }
Christian Heimesf0f59302019-07-01 08:29:17 +02002926
2927 /* bpo-37428: newPySSLSocket() sets SSL_VERIFY_POST_HANDSHAKE flag for
2928 * server sockets and SSL_set_post_handshake_auth() for client. */
2929
Christian Heimes5fe668c2016-09-12 00:01:11 +02002930 /* keep current verify cb */
Christian Heimes9fb051f2018-09-23 08:32:31 +02002931 verify_cb = SSL_CTX_get_verify_callback(self->ctx);
2932 SSL_CTX_set_verify(self->ctx, mode, verify_cb);
Christian Heimes5fe668c2016-09-12 00:01:11 +02002933 return 0;
2934}
2935
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002936/*[clinic input]
2937@classmethod
2938_ssl._SSLContext.__new__
2939 protocol as proto_version: int
2940 /
2941[clinic start generated code]*/
2942
Antoine Pitrou152efa22010-05-16 18:19:27 +00002943static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002944_ssl__SSLContext_impl(PyTypeObject *type, int proto_version)
2945/*[clinic end generated code: output=2cf0d7a0741b6bd1 input=8d58a805b95fc534]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00002946{
Antoine Pitrou152efa22010-05-16 18:19:27 +00002947 PySSLContext *self;
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01002948 long options;
Christian Heimes2875c602021-04-19 07:27:10 +02002949 const SSL_METHOD *method = NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002950 SSL_CTX *ctx = NULL;
Christian Heimes61d478c2018-01-27 15:51:38 +01002951 X509_VERIFY_PARAM *params;
Christian Heimes358cfd42016-09-10 22:43:48 +02002952 int result;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002953
Christian Heimes7f1305e2021-04-17 20:06:38 +02002954 /* slower approach, walk MRO and get borrowed reference to module.
2955 * _PyType_GetModuleByDef is required for SSLContext subclasses */
2956 PyObject *module = _PyType_GetModuleByDef(type, &_sslmodule_def);
2957 if (module == NULL) {
2958 PyErr_SetString(PyExc_RuntimeError,
2959 "Cannot find internal module state");
2960 return NULL;
2961 }
2962
Christian Heimes6e8cda92020-05-16 03:33:05 +02002963 switch(proto_version) {
2964#if defined(SSL3_VERSION) && !defined(OPENSSL_NO_SSL3)
2965 case PY_SSL_VERSION_SSL3:
Christian Heimes2875c602021-04-19 07:27:10 +02002966 PY_SSL_DEPRECATED("PROTOCOL_SSLv3", 2, NULL);
2967 method = SSLv3_method();
Christian Heimes6e8cda92020-05-16 03:33:05 +02002968 break;
Benjamin Petersone32467c2014-12-05 21:59:35 -05002969#endif
Christian Heimesa871f692020-06-01 08:58:14 +02002970#if (defined(TLS1_VERSION) && \
2971 !defined(OPENSSL_NO_TLS1) && \
2972 !defined(OPENSSL_NO_TLS1_METHOD))
Christian Heimes6e8cda92020-05-16 03:33:05 +02002973 case PY_SSL_VERSION_TLS1:
Christian Heimes2875c602021-04-19 07:27:10 +02002974 PY_SSL_DEPRECATED("PROTOCOL_TLSv1", 2, NULL);
2975 method = TLSv1_method();
Christian Heimes6e8cda92020-05-16 03:33:05 +02002976 break;
Victor Stinner3de49192011-05-09 00:42:58 +02002977#endif
Christian Heimesa871f692020-06-01 08:58:14 +02002978#if (defined(TLS1_1_VERSION) && \
2979 !defined(OPENSSL_NO_TLS1_1) && \
2980 !defined(OPENSSL_NO_TLS1_1_METHOD))
Christian Heimes6e8cda92020-05-16 03:33:05 +02002981 case PY_SSL_VERSION_TLS1_1:
Christian Heimes2875c602021-04-19 07:27:10 +02002982 PY_SSL_DEPRECATED("PROTOCOL_TLSv1_1", 2, NULL);
2983 method = TLSv1_1_method();
Christian Heimes6e8cda92020-05-16 03:33:05 +02002984 break;
2985#endif
Christian Heimesa871f692020-06-01 08:58:14 +02002986#if (defined(TLS1_2_VERSION) && \
2987 !defined(OPENSSL_NO_TLS1_2) && \
2988 !defined(OPENSSL_NO_TLS1_2_METHOD))
Christian Heimes6e8cda92020-05-16 03:33:05 +02002989 case PY_SSL_VERSION_TLS1_2:
Christian Heimes2875c602021-04-19 07:27:10 +02002990 PY_SSL_DEPRECATED("PROTOCOL_TLSv1_2", 2, NULL);
2991 method = TLSv1_2_method();
Christian Heimes6e8cda92020-05-16 03:33:05 +02002992 break;
2993#endif
2994 case PY_SSL_VERSION_TLS:
Christian Heimes2875c602021-04-19 07:27:10 +02002995 PY_SSL_DEPRECATED("PROTOCOL_TLS", 2, NULL);
2996 method = TLS_method();
Christian Heimes6e8cda92020-05-16 03:33:05 +02002997 break;
2998 case PY_SSL_VERSION_TLS_CLIENT:
Christian Heimes2875c602021-04-19 07:27:10 +02002999 method = TLS_client_method();
Christian Heimes6e8cda92020-05-16 03:33:05 +02003000 break;
3001 case PY_SSL_VERSION_TLS_SERVER:
Christian Heimes2875c602021-04-19 07:27:10 +02003002 method = TLS_server_method();
Christian Heimes6e8cda92020-05-16 03:33:05 +02003003 break;
3004 default:
Christian Heimes2875c602021-04-19 07:27:10 +02003005 method = NULL;
Christian Heimes6e8cda92020-05-16 03:33:05 +02003006 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003007
Christian Heimes2875c602021-04-19 07:27:10 +02003008 if (method == NULL) {
3009 PyErr_Format(PyExc_ValueError,
3010 "invalid or unsupported protocol version %i",
3011 proto_version);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003012 return NULL;
3013 }
Christian Heimes2875c602021-04-19 07:27:10 +02003014
3015 PySSL_BEGIN_ALLOW_THREADS
3016 ctx = SSL_CTX_new(method);
3017 PySSL_END_ALLOW_THREADS
3018
Antoine Pitrou152efa22010-05-16 18:19:27 +00003019 if (ctx == NULL) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02003020 _setSSLError(get_ssl_state(module), NULL, 0, __FILE__, __LINE__);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003021 return NULL;
3022 }
3023
3024 assert(type != NULL && type->tp_alloc != NULL);
3025 self = (PySSLContext *) type->tp_alloc(type, 0);
3026 if (self == NULL) {
3027 SSL_CTX_free(ctx);
3028 return NULL;
3029 }
3030 self->ctx = ctx;
Christian Heimes61d478c2018-01-27 15:51:38 +01003031 self->hostflags = X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS;
Christian Heimes11a14932018-02-24 02:35:08 +01003032 self->protocol = proto_version;
Christian Heimesc7f70692019-05-31 11:44:05 +02003033 self->msg_cb = NULL;
Christian Heimesc7f70692019-05-31 11:44:05 +02003034 self->keylog_filename = NULL;
3035 self->keylog_bio = NULL;
Benjamin Petersoncca27322015-01-23 16:35:37 -05003036 self->alpn_protocols = NULL;
Christian Heimes11a14932018-02-24 02:35:08 +01003037 self->set_sni_cb = NULL;
Christian Heimes7f1305e2021-04-17 20:06:38 +02003038 self->state = get_ssl_state(module);
3039
Christian Heimes1aa9a752013-12-02 02:41:19 +01003040 /* Don't check host name by default */
Christian Heimes5fe668c2016-09-12 00:01:11 +02003041 if (proto_version == PY_SSL_VERSION_TLS_CLIENT) {
3042 self->check_hostname = 1;
Christian Heimes9fb051f2018-09-23 08:32:31 +02003043 if (_set_verify_mode(self, PY_SSL_CERT_REQUIRED) == -1) {
Christian Heimes5fe668c2016-09-12 00:01:11 +02003044 Py_DECREF(self);
3045 return NULL;
3046 }
3047 } else {
3048 self->check_hostname = 0;
Christian Heimes9fb051f2018-09-23 08:32:31 +02003049 if (_set_verify_mode(self, PY_SSL_CERT_NONE) == -1) {
Christian Heimes5fe668c2016-09-12 00:01:11 +02003050 Py_DECREF(self);
3051 return NULL;
3052 }
3053 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003054 /* Defaults */
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01003055 options = SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
3056 if (proto_version != PY_SSL_VERSION_SSL2)
3057 options |= SSL_OP_NO_SSLv2;
Benjamin Petersona9dcdab2015-11-11 22:38:41 -08003058 if (proto_version != PY_SSL_VERSION_SSL3)
3059 options |= SSL_OP_NO_SSLv3;
Christian Heimes358cfd42016-09-10 22:43:48 +02003060 /* Minimal security flags for server and client side context.
3061 * Client sockets ignore server-side parameters. */
3062#ifdef SSL_OP_NO_COMPRESSION
3063 options |= SSL_OP_NO_COMPRESSION;
3064#endif
3065#ifdef SSL_OP_CIPHER_SERVER_PREFERENCE
3066 options |= SSL_OP_CIPHER_SERVER_PREFERENCE;
3067#endif
3068#ifdef SSL_OP_SINGLE_DH_USE
3069 options |= SSL_OP_SINGLE_DH_USE;
3070#endif
3071#ifdef SSL_OP_SINGLE_ECDH_USE
3072 options |= SSL_OP_SINGLE_ECDH_USE;
3073#endif
Christian Heimes6f37ebc2021-04-09 17:59:21 +02003074#ifdef SSL_OP_IGNORE_UNEXPECTED_EOF
3075 /* Make OpenSSL 3.0.0 behave like 1.1.1 */
3076 options |= SSL_OP_IGNORE_UNEXPECTED_EOF;
3077#endif
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01003078 SSL_CTX_set_options(self->ctx, options);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003079
Semen Zhydenko1295e112017-10-15 21:28:31 +02003080 /* A bare minimum cipher list without completely broken cipher suites.
Christian Heimes358cfd42016-09-10 22:43:48 +02003081 * It's far from perfect but gives users a better head start. */
3082 if (proto_version != PY_SSL_VERSION_SSL2) {
Christian Heimes892d66e2018-01-29 14:10:18 +01003083#if PY_SSL_DEFAULT_CIPHERS == 2
3084 /* stick to OpenSSL's default settings */
3085 result = 1;
3086#else
3087 result = SSL_CTX_set_cipher_list(ctx, PY_SSL_DEFAULT_CIPHER_STRING);
3088#endif
Christian Heimes358cfd42016-09-10 22:43:48 +02003089 } else {
3090 /* SSLv2 needs MD5 */
3091 result = SSL_CTX_set_cipher_list(ctx, "HIGH:!aNULL:!eNULL");
3092 }
3093 if (result == 0) {
3094 Py_DECREF(self);
3095 ERR_clear_error();
Christian Heimes7f1305e2021-04-17 20:06:38 +02003096 PyErr_SetString(get_state_ctx(self)->PySSLErrorObject,
Christian Heimes358cfd42016-09-10 22:43:48 +02003097 "No cipher can be selected.");
3098 return NULL;
3099 }
3100
Benjamin Peterson3b1a8b32016-01-07 21:37:37 -08003101 /* Set SSL_MODE_RELEASE_BUFFERS. This potentially greatly reduces memory
Christian Heimes39258d32021-04-17 11:36:35 +02003102 usage for no cost at all. */
3103 SSL_CTX_set_mode(self->ctx, SSL_MODE_RELEASE_BUFFERS);
Antoine Pitrou0bebbc32014-03-22 18:13:50 +01003104
Antoine Pitroufc113ee2010-10-13 12:46:13 +00003105#define SID_CTX "Python"
3106 SSL_CTX_set_session_id_context(self->ctx, (const unsigned char *) SID_CTX,
3107 sizeof(SID_CTX));
3108#undef SID_CTX
3109
Christian Heimes61d478c2018-01-27 15:51:38 +01003110 params = SSL_CTX_get0_param(self->ctx);
Christian Heimes61d478c2018-01-27 15:51:38 +01003111 /* Improve trust chain building when cross-signed intermediate
3112 certificates are present. See https://bugs.python.org/issue23476. */
3113 X509_VERIFY_PARAM_set_flags(params, X509_V_FLAG_TRUSTED_FIRST);
Christian Heimes61d478c2018-01-27 15:51:38 +01003114 X509_VERIFY_PARAM_set_hostflags(params, self->hostflags);
Benjamin Petersonfdb19712015-03-04 22:11:12 -05003115
Christian Heimes9fb051f2018-09-23 08:32:31 +02003116#ifdef TLS1_3_VERSION
3117 self->post_handshake_auth = 0;
3118 SSL_CTX_set_post_handshake_auth(self->ctx, self->post_handshake_auth);
3119#endif
3120
Antoine Pitrou152efa22010-05-16 18:19:27 +00003121 return (PyObject *)self;
3122}
3123
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003124static int
3125context_traverse(PySSLContext *self, visitproc visit, void *arg)
3126{
Christian Heimes11a14932018-02-24 02:35:08 +01003127 Py_VISIT(self->set_sni_cb);
Christian Heimesc7f70692019-05-31 11:44:05 +02003128 Py_VISIT(self->msg_cb);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003129 return 0;
3130}
3131
3132static int
3133context_clear(PySSLContext *self)
3134{
Christian Heimes11a14932018-02-24 02:35:08 +01003135 Py_CLEAR(self->set_sni_cb);
Christian Heimesc7f70692019-05-31 11:44:05 +02003136 Py_CLEAR(self->msg_cb);
Christian Heimesc7f70692019-05-31 11:44:05 +02003137 Py_CLEAR(self->keylog_filename);
3138 if (self->keylog_bio != NULL) {
3139 PySSL_BEGIN_ALLOW_THREADS
3140 BIO_free_all(self->keylog_bio);
3141 PySSL_END_ALLOW_THREADS
3142 self->keylog_bio = NULL;
3143 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003144 return 0;
3145}
3146
Antoine Pitrou152efa22010-05-16 18:19:27 +00003147static void
3148context_dealloc(PySSLContext *self)
3149{
Christian Heimes5c36da72020-11-20 09:40:12 +01003150 PyTypeObject *tp = Py_TYPE(self);
INADA Naokia6296d32017-08-24 14:55:17 +09003151 /* bpo-31095: UnTrack is needed before calling any callbacks */
3152 PyObject_GC_UnTrack(self);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003153 context_clear(self);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003154 SSL_CTX_free(self->ctx);
Christian Heimes39258d32021-04-17 11:36:35 +02003155 PyMem_FREE(self->alpn_protocols);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003156 Py_TYPE(self)->tp_free(self);
Christian Heimes5c36da72020-11-20 09:40:12 +01003157 Py_DECREF(tp);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003158}
3159
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003160/*[clinic input]
3161_ssl._SSLContext.set_ciphers
3162 cipherlist: str
3163 /
3164[clinic start generated code]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003165
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003166static PyObject *
3167_ssl__SSLContext_set_ciphers_impl(PySSLContext *self, const char *cipherlist)
3168/*[clinic end generated code: output=3a3162f3557c0f3f input=a7ac931b9f3ca7fc]*/
3169{
3170 int ret = SSL_CTX_set_cipher_list(self->ctx, cipherlist);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003171 if (ret == 0) {
Antoine Pitrou65ec8ae2010-05-16 19:56:32 +00003172 /* Clearing the error queue is necessary on some OpenSSL versions,
3173 otherwise the error will be reported again when another SSL call
3174 is done. */
3175 ERR_clear_error();
Christian Heimes7f1305e2021-04-17 20:06:38 +02003176 PyErr_SetString(get_state_ctx(self)->PySSLErrorObject,
Antoine Pitrou152efa22010-05-16 18:19:27 +00003177 "No cipher can be selected.");
3178 return NULL;
3179 }
3180 Py_RETURN_NONE;
3181}
3182
Christian Heimes25bfcd52016-09-06 00:04:45 +02003183/*[clinic input]
3184_ssl._SSLContext.get_ciphers
3185[clinic start generated code]*/
3186
3187static PyObject *
3188_ssl__SSLContext_get_ciphers_impl(PySSLContext *self)
3189/*[clinic end generated code: output=a56e4d68a406dfc4 input=a2aadc9af89b79c5]*/
3190{
3191 SSL *ssl = NULL;
3192 STACK_OF(SSL_CIPHER) *sk = NULL;
Christian Heimes99a65702016-09-10 23:44:53 +02003193 const SSL_CIPHER *cipher;
Christian Heimes25bfcd52016-09-06 00:04:45 +02003194 int i=0;
3195 PyObject *result = NULL, *dct;
3196
3197 ssl = SSL_new(self->ctx);
3198 if (ssl == NULL) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02003199 _setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
Christian Heimes25bfcd52016-09-06 00:04:45 +02003200 goto exit;
3201 }
3202 sk = SSL_get_ciphers(ssl);
3203
3204 result = PyList_New(sk_SSL_CIPHER_num(sk));
3205 if (result == NULL) {
3206 goto exit;
3207 }
3208
3209 for (i = 0; i < sk_SSL_CIPHER_num(sk); i++) {
3210 cipher = sk_SSL_CIPHER_value(sk, i);
3211 dct = cipher_to_dict(cipher);
3212 if (dct == NULL) {
3213 Py_CLEAR(result);
3214 goto exit;
3215 }
3216 PyList_SET_ITEM(result, i, dct);
3217 }
3218
3219 exit:
3220 if (ssl != NULL)
3221 SSL_free(ssl);
3222 return result;
3223
3224}
Christian Heimes25bfcd52016-09-06 00:04:45 +02003225
3226
Benjamin Petersoncca27322015-01-23 16:35:37 -05003227static int
Benjamin Peterson88615022015-01-23 17:30:26 -05003228do_protocol_selection(int alpn, unsigned char **out, unsigned char *outlen,
3229 const unsigned char *server_protocols, unsigned int server_protocols_len,
3230 const unsigned char *client_protocols, unsigned int client_protocols_len)
Benjamin Petersoncca27322015-01-23 16:35:37 -05003231{
Benjamin Peterson88615022015-01-23 17:30:26 -05003232 int ret;
3233 if (client_protocols == NULL) {
3234 client_protocols = (unsigned char *)"";
3235 client_protocols_len = 0;
3236 }
3237 if (server_protocols == NULL) {
3238 server_protocols = (unsigned char *)"";
3239 server_protocols_len = 0;
Benjamin Petersoncca27322015-01-23 16:35:37 -05003240 }
3241
Benjamin Peterson88615022015-01-23 17:30:26 -05003242 ret = SSL_select_next_proto(out, outlen,
3243 server_protocols, server_protocols_len,
3244 client_protocols, client_protocols_len);
3245 if (alpn && ret != OPENSSL_NPN_NEGOTIATED)
3246 return SSL_TLSEXT_ERR_NOACK;
Benjamin Petersoncca27322015-01-23 16:35:37 -05003247
3248 return SSL_TLSEXT_ERR_OK;
3249}
3250
Benjamin Petersoncca27322015-01-23 16:35:37 -05003251static int
3252_selectALPN_cb(SSL *s,
3253 const unsigned char **out, unsigned char *outlen,
3254 const unsigned char *client_protocols, unsigned int client_protocols_len,
3255 void *args)
3256{
3257 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Peterson88615022015-01-23 17:30:26 -05003258 return do_protocol_selection(1, (unsigned char **)out, outlen,
3259 ctx->alpn_protocols, ctx->alpn_protocols_len,
3260 client_protocols, client_protocols_len);
Benjamin Petersoncca27322015-01-23 16:35:37 -05003261}
Benjamin Petersoncca27322015-01-23 16:35:37 -05003262
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003263/*[clinic input]
3264_ssl._SSLContext._set_alpn_protocols
3265 protos: Py_buffer
3266 /
3267[clinic start generated code]*/
3268
Benjamin Petersoncca27322015-01-23 16:35:37 -05003269static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003270_ssl__SSLContext__set_alpn_protocols_impl(PySSLContext *self,
3271 Py_buffer *protos)
3272/*[clinic end generated code: output=87599a7f76651a9b input=9bba964595d519be]*/
Benjamin Petersoncca27322015-01-23 16:35:37 -05003273{
Victor Stinner5a615592017-09-14 01:10:30 -07003274 if ((size_t)protos->len > UINT_MAX) {
Segev Finer5cff6372017-07-27 01:19:17 +03003275 PyErr_Format(PyExc_OverflowError,
Serhiy Storchakad53fe5f2019-03-13 22:59:55 +02003276 "protocols longer than %u bytes", UINT_MAX);
Segev Finer5cff6372017-07-27 01:19:17 +03003277 return NULL;
3278 }
3279
Victor Stinner00d7abd2020-12-01 09:56:42 +01003280 PyMem_Free(self->alpn_protocols);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003281 self->alpn_protocols = PyMem_Malloc(protos->len);
Benjamin Petersoncca27322015-01-23 16:35:37 -05003282 if (!self->alpn_protocols)
3283 return PyErr_NoMemory();
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003284 memcpy(self->alpn_protocols, protos->buf, protos->len);
Segev Finer5cff6372017-07-27 01:19:17 +03003285 self->alpn_protocols_len = (unsigned int)protos->len;
Benjamin Petersoncca27322015-01-23 16:35:37 -05003286
3287 if (SSL_CTX_set_alpn_protos(self->ctx, self->alpn_protocols, self->alpn_protocols_len))
3288 return PyErr_NoMemory();
3289 SSL_CTX_set_alpn_select_cb(self->ctx, _selectALPN_cb, self);
3290
Benjamin Petersoncca27322015-01-23 16:35:37 -05003291 Py_RETURN_NONE;
Benjamin Petersoncca27322015-01-23 16:35:37 -05003292}
3293
Antoine Pitrou152efa22010-05-16 18:19:27 +00003294static PyObject *
3295get_verify_mode(PySSLContext *self, void *c)
3296{
Christian Heimes9fb051f2018-09-23 08:32:31 +02003297 /* ignore SSL_VERIFY_CLIENT_ONCE and SSL_VERIFY_POST_HANDSHAKE */
3298 int mask = (SSL_VERIFY_NONE | SSL_VERIFY_PEER |
3299 SSL_VERIFY_FAIL_IF_NO_PEER_CERT);
3300 switch (SSL_CTX_get_verify_mode(self->ctx) & mask) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003301 case SSL_VERIFY_NONE:
3302 return PyLong_FromLong(PY_SSL_CERT_NONE);
3303 case SSL_VERIFY_PEER:
3304 return PyLong_FromLong(PY_SSL_CERT_OPTIONAL);
3305 case SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT:
3306 return PyLong_FromLong(PY_SSL_CERT_REQUIRED);
3307 }
Christian Heimes7f1305e2021-04-17 20:06:38 +02003308 PyErr_SetString(get_state_ctx(self)->PySSLErrorObject,
Antoine Pitrou152efa22010-05-16 18:19:27 +00003309 "invalid return value from SSL_CTX_get_verify_mode");
3310 return NULL;
3311}
3312
3313static int
3314set_verify_mode(PySSLContext *self, PyObject *arg, void *c)
3315{
Christian Heimes5fe668c2016-09-12 00:01:11 +02003316 int n;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003317 if (!PyArg_Parse(arg, "i", &n))
3318 return -1;
Christian Heimes5fe668c2016-09-12 00:01:11 +02003319 if (n == PY_SSL_CERT_NONE && self->check_hostname) {
Christian Heimes1aa9a752013-12-02 02:41:19 +01003320 PyErr_SetString(PyExc_ValueError,
3321 "Cannot set verify_mode to CERT_NONE when "
3322 "check_hostname is enabled.");
3323 return -1;
3324 }
Christian Heimes9fb051f2018-09-23 08:32:31 +02003325 return _set_verify_mode(self, n);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003326}
3327
3328static PyObject *
Christian Heimes22587792013-11-21 23:56:13 +01003329get_verify_flags(PySSLContext *self, void *c)
3330{
Christian Heimes598894f2016-09-05 23:19:05 +02003331 X509_VERIFY_PARAM *param;
Christian Heimes22587792013-11-21 23:56:13 +01003332 unsigned long flags;
3333
Christian Heimes61d478c2018-01-27 15:51:38 +01003334 param = SSL_CTX_get0_param(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02003335 flags = X509_VERIFY_PARAM_get_flags(param);
Christian Heimes22587792013-11-21 23:56:13 +01003336 return PyLong_FromUnsignedLong(flags);
3337}
3338
3339static int
3340set_verify_flags(PySSLContext *self, PyObject *arg, void *c)
3341{
Christian Heimes598894f2016-09-05 23:19:05 +02003342 X509_VERIFY_PARAM *param;
Christian Heimes22587792013-11-21 23:56:13 +01003343 unsigned long new_flags, flags, set, clear;
3344
3345 if (!PyArg_Parse(arg, "k", &new_flags))
3346 return -1;
Christian Heimes61d478c2018-01-27 15:51:38 +01003347 param = SSL_CTX_get0_param(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02003348 flags = X509_VERIFY_PARAM_get_flags(param);
Christian Heimes22587792013-11-21 23:56:13 +01003349 clear = flags & ~new_flags;
3350 set = ~flags & new_flags;
3351 if (clear) {
Christian Heimes598894f2016-09-05 23:19:05 +02003352 if (!X509_VERIFY_PARAM_clear_flags(param, clear)) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02003353 _setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
Christian Heimes22587792013-11-21 23:56:13 +01003354 return -1;
3355 }
3356 }
3357 if (set) {
Christian Heimes598894f2016-09-05 23:19:05 +02003358 if (!X509_VERIFY_PARAM_set_flags(param, set)) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02003359 _setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
Christian Heimes22587792013-11-21 23:56:13 +01003360 return -1;
3361 }
3362 }
3363 return 0;
3364}
3365
Christian Heimes698dde12018-02-27 11:54:43 +01003366/* Getter and setter for protocol version */
Christian Heimes698dde12018-02-27 11:54:43 +01003367static int
3368set_min_max_proto_version(PySSLContext *self, PyObject *arg, int what)
3369{
3370 long v;
3371 int result;
3372
3373 if (!PyArg_Parse(arg, "l", &v))
3374 return -1;
3375 if (v > INT_MAX) {
3376 PyErr_SetString(PyExc_OverflowError, "Option is too long");
3377 return -1;
3378 }
3379
3380 switch(self->protocol) {
3381 case PY_SSL_VERSION_TLS_CLIENT: /* fall through */
3382 case PY_SSL_VERSION_TLS_SERVER: /* fall through */
3383 case PY_SSL_VERSION_TLS:
3384 break;
3385 default:
3386 PyErr_SetString(
3387 PyExc_ValueError,
3388 "The context's protocol doesn't support modification of "
3389 "highest and lowest version."
3390 );
3391 return -1;
3392 }
3393
Christian Heimes2875c602021-04-19 07:27:10 +02003394 /* check for deprecations and supported values */
3395 switch(v) {
3396 case PY_PROTO_SSLv3:
3397 PY_SSL_DEPRECATED("TLSVersion.SSLv3", 2, -1);
3398 break;
3399 case PY_PROTO_TLSv1:
3400 PY_SSL_DEPRECATED("TLSVersion.TLSv1", 2, -1);
3401 break;
3402 case PY_PROTO_TLSv1_1:
3403 PY_SSL_DEPRECATED("TLSVersion.TLSv1_1", 2, -1);
3404 break;
3405 case PY_PROTO_MINIMUM_SUPPORTED:
3406 case PY_PROTO_MAXIMUM_SUPPORTED:
3407 case PY_PROTO_TLSv1_2:
3408 case PY_PROTO_TLSv1_3:
3409 /* ok */
3410 break;
3411 default:
3412 PyErr_Format(PyExc_ValueError,
3413 "Unsupported TLS/SSL version 0x%x", v);
3414 return -1;
3415 }
3416
Christian Heimes698dde12018-02-27 11:54:43 +01003417 if (what == 0) {
3418 switch(v) {
3419 case PY_PROTO_MINIMUM_SUPPORTED:
3420 v = 0;
3421 break;
3422 case PY_PROTO_MAXIMUM_SUPPORTED:
3423 /* Emulate max for set_min_proto_version */
3424 v = PY_PROTO_MAXIMUM_AVAILABLE;
3425 break;
3426 default:
3427 break;
3428 }
3429 result = SSL_CTX_set_min_proto_version(self->ctx, v);
3430 }
3431 else {
3432 switch(v) {
3433 case PY_PROTO_MAXIMUM_SUPPORTED:
3434 v = 0;
3435 break;
3436 case PY_PROTO_MINIMUM_SUPPORTED:
3437 /* Emulate max for set_min_proto_version */
3438 v = PY_PROTO_MINIMUM_AVAILABLE;
3439 break;
3440 default:
3441 break;
3442 }
3443 result = SSL_CTX_set_max_proto_version(self->ctx, v);
3444 }
3445 if (result == 0) {
3446 PyErr_Format(PyExc_ValueError,
3447 "Unsupported protocol version 0x%x", v);
3448 return -1;
3449 }
3450 return 0;
3451}
3452
3453static PyObject *
3454get_minimum_version(PySSLContext *self, void *c)
3455{
3456 int v = SSL_CTX_ctrl(self->ctx, SSL_CTRL_GET_MIN_PROTO_VERSION, 0, NULL);
3457 if (v == 0) {
3458 v = PY_PROTO_MINIMUM_SUPPORTED;
3459 }
3460 return PyLong_FromLong(v);
3461}
3462
3463static int
3464set_minimum_version(PySSLContext *self, PyObject *arg, void *c)
3465{
3466 return set_min_max_proto_version(self, arg, 0);
3467}
3468
3469static PyObject *
3470get_maximum_version(PySSLContext *self, void *c)
3471{
3472 int v = SSL_CTX_ctrl(self->ctx, SSL_CTRL_GET_MAX_PROTO_VERSION, 0, NULL);
3473 if (v == 0) {
3474 v = PY_PROTO_MAXIMUM_SUPPORTED;
3475 }
3476 return PyLong_FromLong(v);
3477}
3478
3479static int
3480set_maximum_version(PySSLContext *self, PyObject *arg, void *c)
3481{
3482 return set_min_max_proto_version(self, arg, 1);
3483}
Christian Heimes698dde12018-02-27 11:54:43 +01003484
Christian Heimes39258d32021-04-17 11:36:35 +02003485#ifdef TLS1_3_VERSION
Christian Heimes78c7d522019-06-03 21:00:10 +02003486static PyObject *
3487get_num_tickets(PySSLContext *self, void *c)
3488{
Victor Stinner76611c72019-07-09 13:30:52 +02003489 return PyLong_FromSize_t(SSL_CTX_get_num_tickets(self->ctx));
Christian Heimes78c7d522019-06-03 21:00:10 +02003490}
3491
3492static int
3493set_num_tickets(PySSLContext *self, PyObject *arg, void *c)
3494{
3495 long num;
3496 if (!PyArg_Parse(arg, "l", &num))
3497 return -1;
3498 if (num < 0) {
3499 PyErr_SetString(PyExc_ValueError, "value must be non-negative");
3500 return -1;
3501 }
3502 if (self->protocol != PY_SSL_VERSION_TLS_SERVER) {
3503 PyErr_SetString(PyExc_ValueError,
3504 "SSLContext is not a server context.");
3505 return -1;
3506 }
3507 if (SSL_CTX_set_num_tickets(self->ctx, num) != 1) {
3508 PyErr_SetString(PyExc_ValueError, "failed to set num tickets.");
3509 return -1;
3510 }
3511 return 0;
3512}
3513
3514PyDoc_STRVAR(PySSLContext_num_tickets_doc,
3515"Control the number of TLSv1.3 session tickets");
Christian Heimes39258d32021-04-17 11:36:35 +02003516#endif /* TLS1_3_VERSION */
Christian Heimes78c7d522019-06-03 21:00:10 +02003517
matthewhughes9348e836bb2020-07-17 09:59:15 +01003518static PyObject *
3519get_security_level(PySSLContext *self, void *c)
3520{
3521 return PyLong_FromLong(SSL_CTX_get_security_level(self->ctx));
3522}
3523PyDoc_STRVAR(PySSLContext_security_level_doc, "The current security level");
matthewhughes9348e836bb2020-07-17 09:59:15 +01003524
Christian Heimes22587792013-11-21 23:56:13 +01003525static PyObject *
Antoine Pitroub5218772010-05-21 09:56:06 +00003526get_options(PySSLContext *self, void *c)
3527{
3528 return PyLong_FromLong(SSL_CTX_get_options(self->ctx));
3529}
3530
3531static int
3532set_options(PySSLContext *self, PyObject *arg, void *c)
3533{
3534 long new_opts, opts, set, clear;
Christian Heimes2875c602021-04-19 07:27:10 +02003535 long opt_no = (
3536 SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1 |
3537 SSL_OP_NO_TLSv1_1 | SSL_OP_NO_TLSv1_2 | SSL_OP_NO_TLSv1_2
3538 );
3539
Antoine Pitroub5218772010-05-21 09:56:06 +00003540 if (!PyArg_Parse(arg, "l", &new_opts))
3541 return -1;
3542 opts = SSL_CTX_get_options(self->ctx);
3543 clear = opts & ~new_opts;
3544 set = ~opts & new_opts;
Christian Heimes2875c602021-04-19 07:27:10 +02003545
3546 if ((set & opt_no) != 0) {
3547 if (_ssl_deprecated("Setting OP_NO_SSL* or SSL_NO_TLS* options is "
3548 "deprecated", 2) < 0) {
3549 return -1;
3550 }
3551 }
Antoine Pitroub5218772010-05-21 09:56:06 +00003552 if (clear) {
Antoine Pitroub5218772010-05-21 09:56:06 +00003553 SSL_CTX_clear_options(self->ctx, clear);
Antoine Pitroub5218772010-05-21 09:56:06 +00003554 }
3555 if (set)
3556 SSL_CTX_set_options(self->ctx, set);
3557 return 0;
3558}
3559
Christian Heimes1aa9a752013-12-02 02:41:19 +01003560static PyObject *
Christian Heimes61d478c2018-01-27 15:51:38 +01003561get_host_flags(PySSLContext *self, void *c)
3562{
3563 return PyLong_FromUnsignedLong(self->hostflags);
3564}
3565
3566static int
3567set_host_flags(PySSLContext *self, PyObject *arg, void *c)
3568{
3569 X509_VERIFY_PARAM *param;
3570 unsigned int new_flags = 0;
3571
3572 if (!PyArg_Parse(arg, "I", &new_flags))
3573 return -1;
3574
3575 param = SSL_CTX_get0_param(self->ctx);
3576 self->hostflags = new_flags;
3577 X509_VERIFY_PARAM_set_hostflags(param, new_flags);
3578 return 0;
3579}
3580
3581static PyObject *
Christian Heimes1aa9a752013-12-02 02:41:19 +01003582get_check_hostname(PySSLContext *self, void *c)
3583{
3584 return PyBool_FromLong(self->check_hostname);
3585}
3586
3587static int
3588set_check_hostname(PySSLContext *self, PyObject *arg, void *c)
3589{
3590 int check_hostname;
3591 if (!PyArg_Parse(arg, "p", &check_hostname))
3592 return -1;
3593 if (check_hostname &&
3594 SSL_CTX_get_verify_mode(self->ctx) == SSL_VERIFY_NONE) {
Christian Heimese82c0342017-09-15 20:29:57 +02003595 /* check_hostname = True sets verify_mode = CERT_REQUIRED */
Christian Heimes9fb051f2018-09-23 08:32:31 +02003596 if (_set_verify_mode(self, PY_SSL_CERT_REQUIRED) == -1) {
Christian Heimese82c0342017-09-15 20:29:57 +02003597 return -1;
3598 }
Christian Heimes1aa9a752013-12-02 02:41:19 +01003599 }
3600 self->check_hostname = check_hostname;
3601 return 0;
3602}
3603
Christian Heimes11a14932018-02-24 02:35:08 +01003604static PyObject *
Christian Heimes9fb051f2018-09-23 08:32:31 +02003605get_post_handshake_auth(PySSLContext *self, void *c) {
3606#if TLS1_3_VERSION
3607 return PyBool_FromLong(self->post_handshake_auth);
3608#else
3609 Py_RETURN_NONE;
3610#endif
3611}
3612
3613#if TLS1_3_VERSION
3614static int
3615set_post_handshake_auth(PySSLContext *self, PyObject *arg, void *c) {
Zackery Spytz842acaa2018-12-17 07:52:45 -07003616 if (arg == NULL) {
3617 PyErr_SetString(PyExc_AttributeError, "cannot delete attribute");
3618 return -1;
3619 }
Christian Heimes9fb051f2018-09-23 08:32:31 +02003620 int pha = PyObject_IsTrue(arg);
3621
3622 if (pha == -1) {
3623 return -1;
3624 }
3625 self->post_handshake_auth = pha;
3626
Christian Heimesf0f59302019-07-01 08:29:17 +02003627 /* bpo-37428: newPySSLSocket() sets SSL_VERIFY_POST_HANDSHAKE flag for
3628 * server sockets and SSL_set_post_handshake_auth() for client. */
Christian Heimes9fb051f2018-09-23 08:32:31 +02003629
3630 return 0;
3631}
3632#endif
3633
3634static PyObject *
Christian Heimes11a14932018-02-24 02:35:08 +01003635get_protocol(PySSLContext *self, void *c) {
3636 return PyLong_FromLong(self->protocol);
3637}
Christian Heimes1aa9a752013-12-02 02:41:19 +01003638
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003639typedef struct {
3640 PyThreadState *thread_state;
3641 PyObject *callable;
3642 char *password;
Victor Stinner9ee02032013-06-23 15:08:23 +02003643 int size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003644 int error;
3645} _PySSLPasswordInfo;
3646
3647static int
3648_pwinfo_set(_PySSLPasswordInfo *pw_info, PyObject* password,
3649 const char *bad_type_error)
3650{
3651 /* Set the password and size fields of a _PySSLPasswordInfo struct
3652 from a unicode, bytes, or byte array object.
3653 The password field will be dynamically allocated and must be freed
3654 by the caller */
3655 PyObject *password_bytes = NULL;
3656 const char *data = NULL;
3657 Py_ssize_t size;
3658
3659 if (PyUnicode_Check(password)) {
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03003660 password_bytes = PyUnicode_AsUTF8String(password);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003661 if (!password_bytes) {
3662 goto error;
3663 }
3664 data = PyBytes_AS_STRING(password_bytes);
3665 size = PyBytes_GET_SIZE(password_bytes);
3666 } else if (PyBytes_Check(password)) {
3667 data = PyBytes_AS_STRING(password);
3668 size = PyBytes_GET_SIZE(password);
3669 } else if (PyByteArray_Check(password)) {
3670 data = PyByteArray_AS_STRING(password);
3671 size = PyByteArray_GET_SIZE(password);
3672 } else {
3673 PyErr_SetString(PyExc_TypeError, bad_type_error);
3674 goto error;
3675 }
3676
Victor Stinner9ee02032013-06-23 15:08:23 +02003677 if (size > (Py_ssize_t)INT_MAX) {
3678 PyErr_Format(PyExc_ValueError,
3679 "password cannot be longer than %d bytes", INT_MAX);
3680 goto error;
3681 }
3682
Victor Stinner11ebff22013-07-07 17:07:52 +02003683 PyMem_Free(pw_info->password);
3684 pw_info->password = PyMem_Malloc(size);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003685 if (!pw_info->password) {
3686 PyErr_SetString(PyExc_MemoryError,
3687 "unable to allocate password buffer");
3688 goto error;
3689 }
3690 memcpy(pw_info->password, data, size);
Victor Stinner9ee02032013-06-23 15:08:23 +02003691 pw_info->size = (int)size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003692
3693 Py_XDECREF(password_bytes);
3694 return 1;
3695
3696error:
3697 Py_XDECREF(password_bytes);
3698 return 0;
3699}
3700
3701static int
3702_password_callback(char *buf, int size, int rwflag, void *userdata)
3703{
3704 _PySSLPasswordInfo *pw_info = (_PySSLPasswordInfo*) userdata;
3705 PyObject *fn_ret = NULL;
3706
3707 PySSL_END_ALLOW_THREADS_S(pw_info->thread_state);
3708
Christian Heimesd3b73f32021-04-09 15:23:38 +02003709 if (pw_info->error) {
3710 /* already failed previously. OpenSSL 3.0.0-alpha14 invokes the
3711 * callback multiple times which can lead to fatal Python error in
3712 * exception check. */
3713 goto error;
3714 }
3715
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003716 if (pw_info->callable) {
Victor Stinnerf17c3de2016-12-06 18:46:19 +01003717 fn_ret = _PyObject_CallNoArg(pw_info->callable);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003718 if (!fn_ret) {
3719 /* TODO: It would be nice to move _ctypes_add_traceback() into the
3720 core python API, so we could use it to add a frame here */
3721 goto error;
3722 }
3723
3724 if (!_pwinfo_set(pw_info, fn_ret,
3725 "password callback must return a string")) {
3726 goto error;
3727 }
3728 Py_CLEAR(fn_ret);
3729 }
3730
3731 if (pw_info->size > size) {
3732 PyErr_Format(PyExc_ValueError,
3733 "password cannot be longer than %d bytes", size);
3734 goto error;
3735 }
3736
3737 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
3738 memcpy(buf, pw_info->password, pw_info->size);
3739 return pw_info->size;
3740
3741error:
3742 Py_XDECREF(fn_ret);
3743 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
3744 pw_info->error = 1;
3745 return -1;
3746}
3747
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003748/*[clinic input]
3749_ssl._SSLContext.load_cert_chain
3750 certfile: object
Serhiy Storchaka279f4462019-09-14 12:24:05 +03003751 keyfile: object = None
3752 password: object = None
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003753
3754[clinic start generated code]*/
3755
Antoine Pitroub5218772010-05-21 09:56:06 +00003756static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003757_ssl__SSLContext_load_cert_chain_impl(PySSLContext *self, PyObject *certfile,
3758 PyObject *keyfile, PyObject *password)
Serhiy Storchaka279f4462019-09-14 12:24:05 +03003759/*[clinic end generated code: output=9480bc1c380e2095 input=30bc7e967ea01a58]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003760{
Antoine Pitrou152efa22010-05-16 18:19:27 +00003761 PyObject *certfile_bytes = NULL, *keyfile_bytes = NULL;
Christian Heimes598894f2016-09-05 23:19:05 +02003762 pem_password_cb *orig_passwd_cb = SSL_CTX_get_default_passwd_cb(self->ctx);
3763 void *orig_passwd_userdata = SSL_CTX_get_default_passwd_cb_userdata(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003764 _PySSLPasswordInfo pw_info = { NULL, NULL, NULL, 0, 0 };
Antoine Pitrou152efa22010-05-16 18:19:27 +00003765 int r;
3766
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003767 errno = 0;
Antoine Pitrou67e8e562010-09-01 20:55:41 +00003768 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00003769 if (keyfile == Py_None)
3770 keyfile = NULL;
3771 if (!PyUnicode_FSConverter(certfile, &certfile_bytes)) {
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03003772 if (PyErr_ExceptionMatches(PyExc_TypeError)) {
3773 PyErr_SetString(PyExc_TypeError,
3774 "certfile should be a valid filesystem path");
3775 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003776 return NULL;
3777 }
3778 if (keyfile && !PyUnicode_FSConverter(keyfile, &keyfile_bytes)) {
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03003779 if (PyErr_ExceptionMatches(PyExc_TypeError)) {
3780 PyErr_SetString(PyExc_TypeError,
3781 "keyfile should be a valid filesystem path");
3782 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003783 goto error;
3784 }
Serhiy Storchaka279f4462019-09-14 12:24:05 +03003785 if (password != Py_None) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003786 if (PyCallable_Check(password)) {
3787 pw_info.callable = password;
3788 } else if (!_pwinfo_set(&pw_info, password,
3789 "password should be a string or callable")) {
3790 goto error;
3791 }
3792 SSL_CTX_set_default_passwd_cb(self->ctx, _password_callback);
3793 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, &pw_info);
3794 }
3795 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003796 r = SSL_CTX_use_certificate_chain_file(self->ctx,
3797 PyBytes_AS_STRING(certfile_bytes));
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003798 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003799 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003800 if (pw_info.error) {
3801 ERR_clear_error();
3802 /* the password callback has already set the error information */
3803 }
3804 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00003805 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03003806 PyErr_SetFromErrno(PyExc_OSError);
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003807 }
3808 else {
Christian Heimes7f1305e2021-04-17 20:06:38 +02003809 _setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003810 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003811 goto error;
3812 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003813 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou9c254862011-04-03 18:15:34 +02003814 r = SSL_CTX_use_PrivateKey_file(self->ctx,
Antoine Pitrou152efa22010-05-16 18:19:27 +00003815 PyBytes_AS_STRING(keyfile ? keyfile_bytes : certfile_bytes),
3816 SSL_FILETYPE_PEM);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003817 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
3818 Py_CLEAR(keyfile_bytes);
3819 Py_CLEAR(certfile_bytes);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003820 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003821 if (pw_info.error) {
3822 ERR_clear_error();
3823 /* the password callback has already set the error information */
3824 }
3825 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00003826 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03003827 PyErr_SetFromErrno(PyExc_OSError);
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003828 }
3829 else {
Christian Heimes7f1305e2021-04-17 20:06:38 +02003830 _setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003831 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003832 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003833 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003834 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003835 r = SSL_CTX_check_private_key(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003836 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003837 if (r != 1) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02003838 _setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003839 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003840 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003841 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
3842 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02003843 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003844 Py_RETURN_NONE;
3845
3846error:
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003847 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
3848 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02003849 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003850 Py_XDECREF(keyfile_bytes);
3851 Py_XDECREF(certfile_bytes);
3852 return NULL;
3853}
3854
Christian Heimesefff7062013-11-21 03:35:02 +01003855/* internal helper function, returns -1 on error
3856 */
3857static int
Serhiy Storchaka8f87eef2020-04-12 14:58:27 +03003858_add_ca_certs(PySSLContext *self, const void *data, Py_ssize_t len,
Christian Heimesefff7062013-11-21 03:35:02 +01003859 int filetype)
3860{
3861 BIO *biobuf = NULL;
3862 X509_STORE *store;
Christian Heimesb9ad88b2021-04-23 13:51:40 +02003863 int retval = -1, err, loaded = 0;
Christian Heimesefff7062013-11-21 03:35:02 +01003864
3865 assert(filetype == SSL_FILETYPE_ASN1 || filetype == SSL_FILETYPE_PEM);
3866
3867 if (len <= 0) {
3868 PyErr_SetString(PyExc_ValueError,
3869 "Empty certificate data");
3870 return -1;
3871 } else if (len > INT_MAX) {
3872 PyErr_SetString(PyExc_OverflowError,
3873 "Certificate data is too long.");
3874 return -1;
3875 }
3876
Christian Heimes1dbf61f2013-11-22 00:34:18 +01003877 biobuf = BIO_new_mem_buf(data, (int)len);
Christian Heimesefff7062013-11-21 03:35:02 +01003878 if (biobuf == NULL) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02003879 _setSSLError(get_state_ctx(self), "Can't allocate buffer", 0, __FILE__, __LINE__);
Christian Heimesefff7062013-11-21 03:35:02 +01003880 return -1;
3881 }
3882
3883 store = SSL_CTX_get_cert_store(self->ctx);
3884 assert(store != NULL);
3885
3886 while (1) {
3887 X509 *cert = NULL;
3888 int r;
3889
3890 if (filetype == SSL_FILETYPE_ASN1) {
3891 cert = d2i_X509_bio(biobuf, NULL);
3892 } else {
3893 cert = PEM_read_bio_X509(biobuf, NULL,
Christian Heimes598894f2016-09-05 23:19:05 +02003894 SSL_CTX_get_default_passwd_cb(self->ctx),
3895 SSL_CTX_get_default_passwd_cb_userdata(self->ctx)
3896 );
Christian Heimesefff7062013-11-21 03:35:02 +01003897 }
3898 if (cert == NULL) {
3899 break;
3900 }
3901 r = X509_STORE_add_cert(store, cert);
3902 X509_free(cert);
3903 if (!r) {
3904 err = ERR_peek_last_error();
3905 if ((ERR_GET_LIB(err) == ERR_LIB_X509) &&
3906 (ERR_GET_REASON(err) == X509_R_CERT_ALREADY_IN_HASH_TABLE)) {
3907 /* cert already in hash table, not an error */
3908 ERR_clear_error();
3909 } else {
3910 break;
3911 }
3912 }
3913 loaded++;
3914 }
3915
3916 err = ERR_peek_last_error();
Christian Heimesb9ad88b2021-04-23 13:51:40 +02003917 if (loaded == 0) {
3918 const char *msg = NULL;
3919 if (filetype == SSL_FILETYPE_PEM) {
3920 msg = "no start line: cadata does not contain a certificate";
3921 } else {
3922 msg = "not enough data: cadata does not contain a certificate";
3923 }
3924 _setSSLError(get_state_ctx(self), msg, 0, __FILE__, __LINE__);
3925 retval = -1;
3926 } else if ((filetype == SSL_FILETYPE_ASN1) &&
3927 (ERR_GET_LIB(err) == ERR_LIB_ASN1) &&
3928 (ERR_GET_REASON(err) == ASN1_R_HEADER_TOO_LONG)) {
Christian Heimesefff7062013-11-21 03:35:02 +01003929 /* EOF ASN1 file, not an error */
3930 ERR_clear_error();
3931 retval = 0;
3932 } else if ((filetype == SSL_FILETYPE_PEM) &&
Christian Heimesefff7062013-11-21 03:35:02 +01003933 (ERR_GET_LIB(err) == ERR_LIB_PEM) &&
3934 (ERR_GET_REASON(err) == PEM_R_NO_START_LINE)) {
3935 /* EOF PEM file, not an error */
3936 ERR_clear_error();
3937 retval = 0;
Christian Heimesb9ad88b2021-04-23 13:51:40 +02003938 } else if (err != 0) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02003939 _setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
Christian Heimesefff7062013-11-21 03:35:02 +01003940 retval = -1;
Christian Heimesb9ad88b2021-04-23 13:51:40 +02003941 } else {
3942 retval = 0;
Christian Heimesefff7062013-11-21 03:35:02 +01003943 }
3944
3945 BIO_free(biobuf);
3946 return retval;
3947}
3948
3949
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003950/*[clinic input]
3951_ssl._SSLContext.load_verify_locations
Serhiy Storchaka279f4462019-09-14 12:24:05 +03003952 cafile: object = None
3953 capath: object = None
3954 cadata: object = None
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003955
3956[clinic start generated code]*/
3957
Antoine Pitrou152efa22010-05-16 18:19:27 +00003958static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003959_ssl__SSLContext_load_verify_locations_impl(PySSLContext *self,
3960 PyObject *cafile,
3961 PyObject *capath,
3962 PyObject *cadata)
Serhiy Storchaka279f4462019-09-14 12:24:05 +03003963/*[clinic end generated code: output=454c7e41230ca551 input=42ecfe258233e194]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003964{
Antoine Pitrou152efa22010-05-16 18:19:27 +00003965 PyObject *cafile_bytes = NULL, *capath_bytes = NULL;
3966 const char *cafile_buf = NULL, *capath_buf = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01003967 int r = 0, ok = 1;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003968
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003969 errno = 0;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003970 if (cafile == Py_None)
3971 cafile = NULL;
3972 if (capath == Py_None)
3973 capath = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01003974 if (cadata == Py_None)
3975 cadata = NULL;
3976
3977 if (cafile == NULL && capath == NULL && cadata == NULL) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003978 PyErr_SetString(PyExc_TypeError,
Christian Heimesefff7062013-11-21 03:35:02 +01003979 "cafile, capath and cadata cannot be all omitted");
3980 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003981 }
3982 if (cafile && !PyUnicode_FSConverter(cafile, &cafile_bytes)) {
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03003983 if (PyErr_ExceptionMatches(PyExc_TypeError)) {
3984 PyErr_SetString(PyExc_TypeError,
3985 "cafile should be a valid filesystem path");
3986 }
Christian Heimesefff7062013-11-21 03:35:02 +01003987 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003988 }
3989 if (capath && !PyUnicode_FSConverter(capath, &capath_bytes)) {
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03003990 if (PyErr_ExceptionMatches(PyExc_TypeError)) {
3991 PyErr_SetString(PyExc_TypeError,
3992 "capath should be a valid filesystem path");
3993 }
Christian Heimesefff7062013-11-21 03:35:02 +01003994 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003995 }
Christian Heimesefff7062013-11-21 03:35:02 +01003996
3997 /* validata cadata type and load cadata */
3998 if (cadata) {
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03003999 if (PyUnicode_Check(cadata)) {
4000 PyObject *cadata_ascii = PyUnicode_AsASCIIString(cadata);
4001 if (cadata_ascii == NULL) {
4002 if (PyErr_ExceptionMatches(PyExc_UnicodeEncodeError)) {
4003 goto invalid_cadata;
4004 }
4005 goto error;
4006 }
4007 r = _add_ca_certs(self,
4008 PyBytes_AS_STRING(cadata_ascii),
4009 PyBytes_GET_SIZE(cadata_ascii),
4010 SSL_FILETYPE_PEM);
4011 Py_DECREF(cadata_ascii);
4012 if (r == -1) {
4013 goto error;
4014 }
4015 }
4016 else if (PyObject_CheckBuffer(cadata)) {
4017 Py_buffer buf;
4018 if (PyObject_GetBuffer(cadata, &buf, PyBUF_SIMPLE)) {
4019 goto error;
4020 }
Christian Heimesefff7062013-11-21 03:35:02 +01004021 if (!PyBuffer_IsContiguous(&buf, 'C') || buf.ndim > 1) {
4022 PyBuffer_Release(&buf);
4023 PyErr_SetString(PyExc_TypeError,
4024 "cadata should be a contiguous buffer with "
4025 "a single dimension");
4026 goto error;
4027 }
4028 r = _add_ca_certs(self, buf.buf, buf.len, SSL_FILETYPE_ASN1);
4029 PyBuffer_Release(&buf);
4030 if (r == -1) {
4031 goto error;
4032 }
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03004033 }
4034 else {
4035 invalid_cadata:
4036 PyErr_SetString(PyExc_TypeError,
4037 "cadata should be an ASCII string or a "
4038 "bytes-like object");
4039 goto error;
Christian Heimesefff7062013-11-21 03:35:02 +01004040 }
4041 }
4042
4043 /* load cafile or capath */
4044 if (cafile || capath) {
4045 if (cafile)
4046 cafile_buf = PyBytes_AS_STRING(cafile_bytes);
4047 if (capath)
4048 capath_buf = PyBytes_AS_STRING(capath_bytes);
4049 PySSL_BEGIN_ALLOW_THREADS
4050 r = SSL_CTX_load_verify_locations(self->ctx, cafile_buf, capath_buf);
4051 PySSL_END_ALLOW_THREADS
4052 if (r != 1) {
Christian Heimesefff7062013-11-21 03:35:02 +01004053 if (errno != 0) {
4054 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03004055 PyErr_SetFromErrno(PyExc_OSError);
Christian Heimesefff7062013-11-21 03:35:02 +01004056 }
4057 else {
Christian Heimes7f1305e2021-04-17 20:06:38 +02004058 _setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
Christian Heimesefff7062013-11-21 03:35:02 +01004059 }
4060 goto error;
4061 }
4062 }
4063 goto end;
4064
4065 error:
4066 ok = 0;
4067 end:
Antoine Pitrou152efa22010-05-16 18:19:27 +00004068 Py_XDECREF(cafile_bytes);
4069 Py_XDECREF(capath_bytes);
Christian Heimesefff7062013-11-21 03:35:02 +01004070 if (ok) {
4071 Py_RETURN_NONE;
4072 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00004073 return NULL;
4074 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00004075}
4076
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004077/*[clinic input]
4078_ssl._SSLContext.load_dh_params
4079 path as filepath: object
4080 /
4081
4082[clinic start generated code]*/
4083
Antoine Pitrou152efa22010-05-16 18:19:27 +00004084static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004085_ssl__SSLContext_load_dh_params(PySSLContext *self, PyObject *filepath)
4086/*[clinic end generated code: output=1c8e57a38e055af0 input=c8871f3c796ae1d6]*/
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004087{
4088 FILE *f;
4089 DH *dh;
4090
Victor Stinnerdaf45552013-08-28 00:53:59 +02004091 f = _Py_fopen_obj(filepath, "rb");
Victor Stinnere42ccd22015-03-18 01:39:23 +01004092 if (f == NULL)
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004093 return NULL;
Victor Stinnere42ccd22015-03-18 01:39:23 +01004094
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004095 errno = 0;
4096 PySSL_BEGIN_ALLOW_THREADS
4097 dh = PEM_read_DHparams(f, NULL, NULL, NULL);
Antoine Pitrou457a2292013-01-12 21:43:45 +01004098 fclose(f);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004099 PySSL_END_ALLOW_THREADS
4100 if (dh == NULL) {
4101 if (errno != 0) {
4102 ERR_clear_error();
4103 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
4104 }
4105 else {
Christian Heimes7f1305e2021-04-17 20:06:38 +02004106 _setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004107 }
4108 return NULL;
4109 }
Zackery Spytzaebc0492020-07-07 22:21:58 -06004110 if (!SSL_CTX_set_tmp_dh(self->ctx, dh)) {
4111 DH_free(dh);
Christian Heimes7f1305e2021-04-17 20:06:38 +02004112 return _setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
Zackery Spytzaebc0492020-07-07 22:21:58 -06004113 }
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004114 DH_free(dh);
4115 Py_RETURN_NONE;
4116}
4117
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004118/*[clinic input]
4119_ssl._SSLContext._wrap_socket
Christian Heimes7f1305e2021-04-17 20:06:38 +02004120 sock: object(subclass_of="get_state_ctx(self)->Sock_Type")
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004121 server_side: int
4122 server_hostname as hostname_obj: object = None
Christian Heimes141c5e82018-02-24 21:10:57 +01004123 *
4124 owner: object = None
4125 session: object = None
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004126
4127[clinic start generated code]*/
4128
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004129static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004130_ssl__SSLContext__wrap_socket_impl(PySSLContext *self, PyObject *sock,
Christian Heimes141c5e82018-02-24 21:10:57 +01004131 int server_side, PyObject *hostname_obj,
4132 PyObject *owner, PyObject *session)
Christian Heimes7f1305e2021-04-17 20:06:38 +02004133/*[clinic end generated code: output=f103f238633940b4 input=f5916eadbc6eae81]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004134{
Antoine Pitroud5323212010-10-22 18:19:07 +00004135 char *hostname = NULL;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004136 PyObject *res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004137
Antoine Pitroud5323212010-10-22 18:19:07 +00004138 /* server_hostname is either None (or absent), or to be encoded
Christian Heimesd02ac252018-03-25 12:36:13 +02004139 as IDN A-label (ASCII str) without NULL bytes. */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004140 if (hostname_obj != Py_None) {
Christian Heimes11a14932018-02-24 02:35:08 +01004141 if (!PyArg_Parse(hostname_obj, "es", "ascii", &hostname))
Antoine Pitroud5323212010-10-22 18:19:07 +00004142 return NULL;
Antoine Pitroud5323212010-10-22 18:19:07 +00004143 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00004144
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004145 res = (PyObject *) newPySSLSocket(self, (PySocketSockObject *)sock,
4146 server_side, hostname,
Christian Heimes141c5e82018-02-24 21:10:57 +01004147 owner, session,
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004148 NULL, NULL);
Antoine Pitroud5323212010-10-22 18:19:07 +00004149 if (hostname != NULL)
4150 PyMem_Free(hostname);
4151 return res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004152}
4153
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004154/*[clinic input]
4155_ssl._SSLContext._wrap_bio
Christian Heimes7f1305e2021-04-17 20:06:38 +02004156 incoming: object(subclass_of="get_state_ctx(self)->PySSLMemoryBIO_Type", type="PySSLMemoryBIO *")
4157 outgoing: object(subclass_of="get_state_ctx(self)->PySSLMemoryBIO_Type", type="PySSLMemoryBIO *")
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004158 server_side: int
4159 server_hostname as hostname_obj: object = None
Christian Heimes141c5e82018-02-24 21:10:57 +01004160 *
4161 owner: object = None
4162 session: object = None
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004163
4164[clinic start generated code]*/
4165
Antoine Pitroub0182c82010-10-12 20:09:02 +00004166static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004167_ssl__SSLContext__wrap_bio_impl(PySSLContext *self, PySSLMemoryBIO *incoming,
4168 PySSLMemoryBIO *outgoing, int server_side,
Christian Heimes141c5e82018-02-24 21:10:57 +01004169 PyObject *hostname_obj, PyObject *owner,
4170 PyObject *session)
Christian Heimes7f1305e2021-04-17 20:06:38 +02004171/*[clinic end generated code: output=5c5d6d9b41f99332 input=331edeec9c738382]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004172{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004173 char *hostname = NULL;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004174 PyObject *res;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004175
4176 /* server_hostname is either None (or absent), or to be encoded
Christian Heimesd02ac252018-03-25 12:36:13 +02004177 as IDN A-label (ASCII str) without NULL bytes. */
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004178 if (hostname_obj != Py_None) {
Christian Heimes11a14932018-02-24 02:35:08 +01004179 if (!PyArg_Parse(hostname_obj, "es", "ascii", &hostname))
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004180 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004181 }
4182
4183 res = (PyObject *) newPySSLSocket(self, NULL, server_side, hostname,
Christian Heimes141c5e82018-02-24 21:10:57 +01004184 owner, session,
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004185 incoming, outgoing);
4186
4187 PyMem_Free(hostname);
4188 return res;
4189}
4190
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004191/*[clinic input]
4192_ssl._SSLContext.session_stats
4193[clinic start generated code]*/
4194
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004195static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004196_ssl__SSLContext_session_stats_impl(PySSLContext *self)
4197/*[clinic end generated code: output=0d96411c42893bfb input=7e0a81fb11102c8b]*/
Antoine Pitroub0182c82010-10-12 20:09:02 +00004198{
4199 int r;
4200 PyObject *value, *stats = PyDict_New();
4201 if (!stats)
4202 return NULL;
4203
4204#define ADD_STATS(SSL_NAME, KEY_NAME) \
4205 value = PyLong_FromLong(SSL_CTX_sess_ ## SSL_NAME (self->ctx)); \
4206 if (value == NULL) \
4207 goto error; \
4208 r = PyDict_SetItemString(stats, KEY_NAME, value); \
4209 Py_DECREF(value); \
4210 if (r < 0) \
4211 goto error;
4212
4213 ADD_STATS(number, "number");
4214 ADD_STATS(connect, "connect");
4215 ADD_STATS(connect_good, "connect_good");
4216 ADD_STATS(connect_renegotiate, "connect_renegotiate");
4217 ADD_STATS(accept, "accept");
4218 ADD_STATS(accept_good, "accept_good");
4219 ADD_STATS(accept_renegotiate, "accept_renegotiate");
4220 ADD_STATS(accept, "accept");
4221 ADD_STATS(hits, "hits");
4222 ADD_STATS(misses, "misses");
4223 ADD_STATS(timeouts, "timeouts");
4224 ADD_STATS(cache_full, "cache_full");
4225
4226#undef ADD_STATS
4227
4228 return stats;
4229
4230error:
4231 Py_DECREF(stats);
4232 return NULL;
4233}
4234
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004235/*[clinic input]
4236_ssl._SSLContext.set_default_verify_paths
4237[clinic start generated code]*/
4238
Antoine Pitrou664c2d12010-11-17 20:29:42 +00004239static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004240_ssl__SSLContext_set_default_verify_paths_impl(PySSLContext *self)
4241/*[clinic end generated code: output=0bee74e6e09deaaa input=35f3408021463d74]*/
Antoine Pitrou664c2d12010-11-17 20:29:42 +00004242{
4243 if (!SSL_CTX_set_default_verify_paths(self->ctx)) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02004244 _setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
Antoine Pitrou664c2d12010-11-17 20:29:42 +00004245 return NULL;
4246 }
4247 Py_RETURN_NONE;
4248}
4249
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004250/*[clinic input]
4251_ssl._SSLContext.set_ecdh_curve
4252 name: object
4253 /
4254
4255[clinic start generated code]*/
4256
Antoine Pitrou923df6f2011-12-19 17:16:51 +01004257static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004258_ssl__SSLContext_set_ecdh_curve(PySSLContext *self, PyObject *name)
4259/*[clinic end generated code: output=23022c196e40d7d2 input=c2bafb6f6e34726b]*/
Antoine Pitrou923df6f2011-12-19 17:16:51 +01004260{
4261 PyObject *name_bytes;
4262 int nid;
4263 EC_KEY *key;
4264
4265 if (!PyUnicode_FSConverter(name, &name_bytes))
4266 return NULL;
4267 assert(PyBytes_Check(name_bytes));
4268 nid = OBJ_sn2nid(PyBytes_AS_STRING(name_bytes));
4269 Py_DECREF(name_bytes);
4270 if (nid == 0) {
4271 PyErr_Format(PyExc_ValueError,
4272 "unknown elliptic curve name %R", name);
4273 return NULL;
4274 }
4275 key = EC_KEY_new_by_curve_name(nid);
4276 if (key == NULL) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02004277 _setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
Antoine Pitrou923df6f2011-12-19 17:16:51 +01004278 return NULL;
4279 }
4280 SSL_CTX_set_tmp_ecdh(self->ctx, key);
4281 EC_KEY_free(key);
4282 Py_RETURN_NONE;
4283}
4284
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004285static int
4286_servername_callback(SSL *s, int *al, void *args)
4287{
4288 int ret;
Christian Heimes7f1305e2021-04-17 20:06:38 +02004289 PySSLContext *sslctx = (PySSLContext *) args;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004290 PySSLSocket *ssl;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004291 PyObject *result;
4292 /* The high-level ssl.SSLSocket object */
4293 PyObject *ssl_socket;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004294 const char *servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
Stefan Krah20d60802013-01-17 17:07:17 +01004295 PyGILState_STATE gstate = PyGILState_Ensure();
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004296
Christian Heimes7f1305e2021-04-17 20:06:38 +02004297 if (sslctx->set_sni_cb == NULL) {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004298 /* remove race condition in this the call back while if removing the
4299 * callback is in progress */
4300 PyGILState_Release(gstate);
Antoine Pitrou5dd12a52013-01-06 15:25:36 +01004301 return SSL_TLSEXT_ERR_OK;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004302 }
4303
4304 ssl = SSL_get_app_data(s);
Christian Heimes7f1305e2021-04-17 20:06:38 +02004305 assert(Py_IS_TYPE(ssl, get_state_ctx(sslctx)->PySSLSocket_Type));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004306
Serhiy Storchakaf51d7152015-11-02 14:40:41 +02004307 /* The servername callback expects an argument that represents the current
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004308 * SSL connection and that has a .context attribute that can be changed to
4309 * identify the requested hostname. Since the official API is the Python
4310 * level API we want to pass the callback a Python level object rather than
4311 * a _ssl.SSLSocket instance. If there's an "owner" (typically an
4312 * SSLObject) that will be passed. Otherwise if there's a socket then that
4313 * will be passed. If both do not exist only then the C-level object is
4314 * passed. */
4315 if (ssl->owner)
4316 ssl_socket = PyWeakref_GetObject(ssl->owner);
4317 else if (ssl->Socket)
4318 ssl_socket = PyWeakref_GetObject(ssl->Socket);
4319 else
4320 ssl_socket = (PyObject *) ssl;
4321
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004322 Py_INCREF(ssl_socket);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004323 if (ssl_socket == Py_None)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004324 goto error;
Victor Stinner7e001512013-06-25 00:44:31 +02004325
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004326 if (servername == NULL) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02004327 result = PyObject_CallFunctionObjArgs(sslctx->set_sni_cb, ssl_socket,
4328 Py_None, sslctx, NULL);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004329 }
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004330 else {
Christian Heimes11a14932018-02-24 02:35:08 +01004331 PyObject *servername_bytes;
4332 PyObject *servername_str;
4333
4334 servername_bytes = PyBytes_FromString(servername);
4335 if (servername_bytes == NULL) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02004336 PyErr_WriteUnraisable((PyObject *) sslctx);
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004337 goto error;
4338 }
Christian Heimes11a14932018-02-24 02:35:08 +01004339 /* server_hostname was encoded to an A-label by our caller; put it
4340 * back into a str object, but still as an A-label (bpo-28414)
4341 */
4342 servername_str = PyUnicode_FromEncodedObject(servername_bytes, "ascii", NULL);
Christian Heimes11a14932018-02-24 02:35:08 +01004343 if (servername_str == NULL) {
4344 PyErr_WriteUnraisable(servername_bytes);
Zackery Spytzee96f322020-07-09 04:00:21 -06004345 Py_DECREF(servername_bytes);
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004346 goto error;
4347 }
Zackery Spytzee96f322020-07-09 04:00:21 -06004348 Py_DECREF(servername_bytes);
Christian Heimes11a14932018-02-24 02:35:08 +01004349 result = PyObject_CallFunctionObjArgs(
Christian Heimes7f1305e2021-04-17 20:06:38 +02004350 sslctx->set_sni_cb, ssl_socket, servername_str,
4351 sslctx, NULL);
Christian Heimes11a14932018-02-24 02:35:08 +01004352 Py_DECREF(servername_str);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004353 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004354 Py_DECREF(ssl_socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004355
4356 if (result == NULL) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02004357 PyErr_WriteUnraisable(sslctx->set_sni_cb);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004358 *al = SSL_AD_HANDSHAKE_FAILURE;
4359 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
4360 }
4361 else {
Christian Heimes11a14932018-02-24 02:35:08 +01004362 /* Result may be None, a SSLContext or an integer
4363 * None and SSLContext are OK, integer or other values are an error.
4364 */
4365 if (result == Py_None) {
4366 ret = SSL_TLSEXT_ERR_OK;
4367 } else {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004368 *al = (int) PyLong_AsLong(result);
4369 if (PyErr_Occurred()) {
4370 PyErr_WriteUnraisable(result);
4371 *al = SSL_AD_INTERNAL_ERROR;
4372 }
4373 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
4374 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004375 Py_DECREF(result);
4376 }
4377
4378 PyGILState_Release(gstate);
4379 return ret;
4380
4381error:
4382 Py_DECREF(ssl_socket);
4383 *al = SSL_AD_INTERNAL_ERROR;
4384 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
4385 PyGILState_Release(gstate);
4386 return ret;
4387}
4388
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004389static PyObject *
Christian Heimes11a14932018-02-24 02:35:08 +01004390get_sni_callback(PySSLContext *self, void *c)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004391{
Christian Heimes11a14932018-02-24 02:35:08 +01004392 PyObject *cb = self->set_sni_cb;
4393 if (cb == NULL) {
4394 Py_RETURN_NONE;
4395 }
4396 Py_INCREF(cb);
4397 return cb;
4398}
4399
4400static int
4401set_sni_callback(PySSLContext *self, PyObject *arg, void *c)
4402{
4403 if (self->protocol == PY_SSL_VERSION_TLS_CLIENT) {
4404 PyErr_SetString(PyExc_ValueError,
4405 "sni_callback cannot be set on TLS_CLIENT context");
4406 return -1;
4407 }
Christian Heimes11a14932018-02-24 02:35:08 +01004408 Py_CLEAR(self->set_sni_cb);
4409 if (arg == Py_None) {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004410 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
4411 }
4412 else {
Christian Heimes11a14932018-02-24 02:35:08 +01004413 if (!PyCallable_Check(arg)) {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004414 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
4415 PyErr_SetString(PyExc_TypeError,
4416 "not a callable object");
Christian Heimes11a14932018-02-24 02:35:08 +01004417 return -1;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004418 }
Christian Heimes11a14932018-02-24 02:35:08 +01004419 Py_INCREF(arg);
4420 self->set_sni_cb = arg;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004421 SSL_CTX_set_tlsext_servername_callback(self->ctx, _servername_callback);
4422 SSL_CTX_set_tlsext_servername_arg(self->ctx, self);
4423 }
Christian Heimes11a14932018-02-24 02:35:08 +01004424 return 0;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004425}
4426
Christian Heimes11a14932018-02-24 02:35:08 +01004427PyDoc_STRVAR(PySSLContext_sni_callback_doc,
4428"Set a callback that will be called when a server name is provided by the SSL/TLS client in the SNI extension.\n\
4429\n\
4430If the argument is None then the callback is disabled. The method is called\n\
4431with the SSLSocket, the server name as a string, and the SSLContext object.\n\
4432See RFC 6066 for details of the SNI extension.");
4433
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004434/*[clinic input]
4435_ssl._SSLContext.cert_store_stats
4436
4437Returns quantities of loaded X.509 certificates.
4438
4439X.509 certificates with a CA extension and certificate revocation lists
4440inside the context's cert store.
4441
4442NOTE: Certificates in a capath directory aren't loaded unless they have
4443been used at least once.
4444[clinic start generated code]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004445
4446static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004447_ssl__SSLContext_cert_store_stats_impl(PySSLContext *self)
4448/*[clinic end generated code: output=5f356f4d9cca874d input=eb40dd0f6d0e40cf]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004449{
4450 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02004451 STACK_OF(X509_OBJECT) *objs;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004452 X509_OBJECT *obj;
Christian Heimes598894f2016-09-05 23:19:05 +02004453 int x509 = 0, crl = 0, ca = 0, i;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004454
4455 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02004456 objs = X509_STORE_get0_objects(store);
4457 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
4458 obj = sk_X509_OBJECT_value(objs, i);
4459 switch (X509_OBJECT_get_type(obj)) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004460 case X509_LU_X509:
4461 x509++;
Christian Heimes598894f2016-09-05 23:19:05 +02004462 if (X509_check_ca(X509_OBJECT_get0_X509(obj))) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004463 ca++;
4464 }
4465 break;
4466 case X509_LU_CRL:
4467 crl++;
4468 break;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004469 default:
4470 /* Ignore X509_LU_FAIL, X509_LU_RETRY, X509_LU_PKEY.
4471 * As far as I can tell they are internal states and never
4472 * stored in a cert store */
4473 break;
4474 }
4475 }
4476 return Py_BuildValue("{sisisi}", "x509", x509, "crl", crl,
4477 "x509_ca", ca);
4478}
4479
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004480/*[clinic input]
4481_ssl._SSLContext.get_ca_certs
4482 binary_form: bool = False
4483
4484Returns a list of dicts with information of loaded CA certs.
4485
4486If the optional argument is True, returns a DER-encoded copy of the CA
4487certificate.
4488
4489NOTE: Certificates in a capath directory aren't loaded unless they have
4490been used at least once.
4491[clinic start generated code]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004492
4493static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004494_ssl__SSLContext_get_ca_certs_impl(PySSLContext *self, int binary_form)
4495/*[clinic end generated code: output=0d58f148f37e2938 input=6887b5a09b7f9076]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004496{
4497 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02004498 STACK_OF(X509_OBJECT) *objs;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004499 PyObject *ci = NULL, *rlist = NULL;
4500 int i;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004501
4502 if ((rlist = PyList_New(0)) == NULL) {
4503 return NULL;
4504 }
4505
4506 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02004507 objs = X509_STORE_get0_objects(store);
4508 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004509 X509_OBJECT *obj;
4510 X509 *cert;
4511
Christian Heimes598894f2016-09-05 23:19:05 +02004512 obj = sk_X509_OBJECT_value(objs, i);
4513 if (X509_OBJECT_get_type(obj) != X509_LU_X509) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004514 /* not a x509 cert */
4515 continue;
4516 }
4517 /* CA for any purpose */
Christian Heimes598894f2016-09-05 23:19:05 +02004518 cert = X509_OBJECT_get0_X509(obj);
Christian Heimes9a5395a2013-06-17 15:44:12 +02004519 if (!X509_check_ca(cert)) {
4520 continue;
4521 }
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004522 if (binary_form) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02004523 ci = _certificate_to_der(get_state_ctx(self), cert);
Christian Heimes9a5395a2013-06-17 15:44:12 +02004524 } else {
Christian Heimes7f1305e2021-04-17 20:06:38 +02004525 ci = _decode_certificate(get_state_ctx(self), cert);
Christian Heimes9a5395a2013-06-17 15:44:12 +02004526 }
4527 if (ci == NULL) {
4528 goto error;
4529 }
4530 if (PyList_Append(rlist, ci) == -1) {
4531 goto error;
4532 }
4533 Py_CLEAR(ci);
4534 }
4535 return rlist;
4536
4537 error:
4538 Py_XDECREF(ci);
4539 Py_XDECREF(rlist);
4540 return NULL;
4541}
4542
4543
Antoine Pitrou152efa22010-05-16 18:19:27 +00004544static PyGetSetDef context_getsetlist[] = {
Christian Heimes1aa9a752013-12-02 02:41:19 +01004545 {"check_hostname", (getter) get_check_hostname,
4546 (setter) set_check_hostname, NULL},
Christian Heimes61d478c2018-01-27 15:51:38 +01004547 {"_host_flags", (getter) get_host_flags,
4548 (setter) set_host_flags, NULL},
Christian Heimes698dde12018-02-27 11:54:43 +01004549 {"minimum_version", (getter) get_minimum_version,
4550 (setter) set_minimum_version, NULL},
4551 {"maximum_version", (getter) get_maximum_version,
4552 (setter) set_maximum_version, NULL},
Christian Heimesc7f70692019-05-31 11:44:05 +02004553 {"keylog_filename", (getter) _PySSLContext_get_keylog_filename,
4554 (setter) _PySSLContext_set_keylog_filename, NULL},
Christian Heimesc7f70692019-05-31 11:44:05 +02004555 {"_msg_callback", (getter) _PySSLContext_get_msg_callback,
4556 (setter) _PySSLContext_set_msg_callback, NULL},
Christian Heimes11a14932018-02-24 02:35:08 +01004557 {"sni_callback", (getter) get_sni_callback,
Christian Heimes698dde12018-02-27 11:54:43 +01004558 (setter) set_sni_callback, PySSLContext_sni_callback_doc},
Christian Heimes39258d32021-04-17 11:36:35 +02004559#ifdef TLS1_3_VERSION
Christian Heimes78c7d522019-06-03 21:00:10 +02004560 {"num_tickets", (getter) get_num_tickets,
4561 (setter) set_num_tickets, PySSLContext_num_tickets_doc},
4562#endif
Antoine Pitroub5218772010-05-21 09:56:06 +00004563 {"options", (getter) get_options,
4564 (setter) set_options, NULL},
Christian Heimes9fb051f2018-09-23 08:32:31 +02004565 {"post_handshake_auth", (getter) get_post_handshake_auth,
4566#ifdef TLS1_3_VERSION
4567 (setter) set_post_handshake_auth,
4568#else
4569 NULL,
4570#endif
4571 NULL},
Christian Heimes11a14932018-02-24 02:35:08 +01004572 {"protocol", (getter) get_protocol,
4573 NULL, NULL},
Christian Heimes22587792013-11-21 23:56:13 +01004574 {"verify_flags", (getter) get_verify_flags,
4575 (setter) set_verify_flags, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00004576 {"verify_mode", (getter) get_verify_mode,
4577 (setter) set_verify_mode, NULL},
matthewhughes9348e836bb2020-07-17 09:59:15 +01004578 {"security_level", (getter) get_security_level,
4579 NULL, PySSLContext_security_level_doc},
Antoine Pitrou152efa22010-05-16 18:19:27 +00004580 {NULL}, /* sentinel */
4581};
4582
4583static struct PyMethodDef context_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004584 _SSL__SSLCONTEXT__WRAP_SOCKET_METHODDEF
4585 _SSL__SSLCONTEXT__WRAP_BIO_METHODDEF
4586 _SSL__SSLCONTEXT_SET_CIPHERS_METHODDEF
4587 _SSL__SSLCONTEXT__SET_ALPN_PROTOCOLS_METHODDEF
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004588 _SSL__SSLCONTEXT_LOAD_CERT_CHAIN_METHODDEF
4589 _SSL__SSLCONTEXT_LOAD_DH_PARAMS_METHODDEF
4590 _SSL__SSLCONTEXT_LOAD_VERIFY_LOCATIONS_METHODDEF
4591 _SSL__SSLCONTEXT_SESSION_STATS_METHODDEF
4592 _SSL__SSLCONTEXT_SET_DEFAULT_VERIFY_PATHS_METHODDEF
4593 _SSL__SSLCONTEXT_SET_ECDH_CURVE_METHODDEF
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004594 _SSL__SSLCONTEXT_CERT_STORE_STATS_METHODDEF
4595 _SSL__SSLCONTEXT_GET_CA_CERTS_METHODDEF
Christian Heimes25bfcd52016-09-06 00:04:45 +02004596 _SSL__SSLCONTEXT_GET_CIPHERS_METHODDEF
Antoine Pitrou152efa22010-05-16 18:19:27 +00004597 {NULL, NULL} /* sentinel */
4598};
4599
Christian Heimes5c36da72020-11-20 09:40:12 +01004600static PyType_Slot PySSLContext_slots[] = {
4601 {Py_tp_methods, context_methods},
4602 {Py_tp_getset, context_getsetlist},
4603 {Py_tp_new, _ssl__SSLContext},
4604 {Py_tp_dealloc, context_dealloc},
4605 {Py_tp_traverse, context_traverse},
4606 {Py_tp_clear, context_clear},
4607 {0, 0},
4608};
4609
4610static PyType_Spec PySSLContext_spec = {
4611 "_ssl._SSLContext",
4612 sizeof(PySSLContext),
4613 0,
4614 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
4615 PySSLContext_slots,
Antoine Pitrou152efa22010-05-16 18:19:27 +00004616};
4617
4618
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004619/*
4620 * MemoryBIO objects
4621 */
4622
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004623/*[clinic input]
4624@classmethod
4625_ssl.MemoryBIO.__new__
4626
4627[clinic start generated code]*/
4628
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004629static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004630_ssl_MemoryBIO_impl(PyTypeObject *type)
4631/*[clinic end generated code: output=8820a58db78330ac input=26d22e4909ecb1b5]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004632{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004633 BIO *bio;
4634 PySSLMemoryBIO *self;
4635
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004636 bio = BIO_new(BIO_s_mem());
4637 if (bio == NULL) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02004638 PyErr_SetString(PyExc_MemoryError, "failed to allocate BIO");
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004639 return NULL;
4640 }
4641 /* Since our BIO is non-blocking an empty read() does not indicate EOF,
4642 * just that no data is currently available. The SSL routines should retry
4643 * the read, which we can achieve by calling BIO_set_retry_read(). */
4644 BIO_set_retry_read(bio);
4645 BIO_set_mem_eof_return(bio, -1);
4646
4647 assert(type != NULL && type->tp_alloc != NULL);
4648 self = (PySSLMemoryBIO *) type->tp_alloc(type, 0);
4649 if (self == NULL) {
4650 BIO_free(bio);
4651 return NULL;
4652 }
4653 self->bio = bio;
4654 self->eof_written = 0;
4655
4656 return (PyObject *) self;
4657}
4658
4659static void
4660memory_bio_dealloc(PySSLMemoryBIO *self)
4661{
Christian Heimes5c36da72020-11-20 09:40:12 +01004662 PyTypeObject *tp = Py_TYPE(self);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004663 BIO_free(self->bio);
4664 Py_TYPE(self)->tp_free(self);
Christian Heimes5c36da72020-11-20 09:40:12 +01004665 Py_DECREF(tp);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004666}
4667
4668static PyObject *
4669memory_bio_get_pending(PySSLMemoryBIO *self, void *c)
4670{
Segev Finer5cff6372017-07-27 01:19:17 +03004671 return PyLong_FromSize_t(BIO_ctrl_pending(self->bio));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004672}
4673
4674PyDoc_STRVAR(PySSL_memory_bio_pending_doc,
4675"The number of bytes pending in the memory BIO.");
4676
4677static PyObject *
4678memory_bio_get_eof(PySSLMemoryBIO *self, void *c)
4679{
4680 return PyBool_FromLong((BIO_ctrl_pending(self->bio) == 0)
4681 && self->eof_written);
4682}
4683
4684PyDoc_STRVAR(PySSL_memory_bio_eof_doc,
4685"Whether the memory BIO is at EOF.");
4686
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004687/*[clinic input]
4688_ssl.MemoryBIO.read
4689 size as len: int = -1
4690 /
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004691
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004692Read up to size bytes from the memory BIO.
4693
4694If size is not specified, read the entire buffer.
4695If the return value is an empty bytes instance, this means either
4696EOF or that no data is available. Use the "eof" property to
4697distinguish between the two.
4698[clinic start generated code]*/
4699
4700static PyObject *
4701_ssl_MemoryBIO_read_impl(PySSLMemoryBIO *self, int len)
4702/*[clinic end generated code: output=a657aa1e79cd01b3 input=574d7be06a902366]*/
4703{
4704 int avail, nbytes;
4705 PyObject *result;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004706
Segev Finer5cff6372017-07-27 01:19:17 +03004707 avail = (int)Py_MIN(BIO_ctrl_pending(self->bio), INT_MAX);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004708 if ((len < 0) || (len > avail))
4709 len = avail;
4710
4711 result = PyBytes_FromStringAndSize(NULL, len);
4712 if ((result == NULL) || (len == 0))
4713 return result;
4714
4715 nbytes = BIO_read(self->bio, PyBytes_AS_STRING(result), len);
Zackery Spytz365ad2e2018-10-06 11:41:45 -06004716 if (nbytes < 0) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02004717 _sslmodulestate *state = get_state_mbio(self);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004718 Py_DECREF(result);
Christian Heimes7f1305e2021-04-17 20:06:38 +02004719 _setSSLError(state, NULL, 0, __FILE__, __LINE__);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004720 return NULL;
4721 }
4722
Zackery Spytz365ad2e2018-10-06 11:41:45 -06004723 /* There should never be any short reads but check anyway. */
4724 if (nbytes < len) {
4725 _PyBytes_Resize(&result, nbytes);
4726 }
4727
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004728 return result;
4729}
4730
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004731/*[clinic input]
4732_ssl.MemoryBIO.write
4733 b: Py_buffer
4734 /
4735
4736Writes the bytes b into the memory BIO.
4737
4738Returns the number of bytes written.
4739[clinic start generated code]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004740
4741static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004742_ssl_MemoryBIO_write_impl(PySSLMemoryBIO *self, Py_buffer *b)
4743/*[clinic end generated code: output=156ec59110d75935 input=e45757b3e17c4808]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004744{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004745 int nbytes;
4746
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004747 if (b->len > INT_MAX) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004748 PyErr_Format(PyExc_OverflowError,
4749 "string longer than %d bytes", INT_MAX);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004750 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004751 }
4752
4753 if (self->eof_written) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02004754 PyObject *module = PyType_GetModule(Py_TYPE(self));
4755 if (module == NULL)
4756 return NULL;
4757 PyErr_SetString(get_ssl_state(module)->PySSLErrorObject,
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004758 "cannot write() after write_eof()");
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004759 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004760 }
4761
Segev Finer5cff6372017-07-27 01:19:17 +03004762 nbytes = BIO_write(self->bio, b->buf, (int)b->len);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004763 if (nbytes < 0) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02004764 _sslmodulestate *state = get_state_mbio(self);
4765 _setSSLError(state, NULL, 0, __FILE__, __LINE__);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004766 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004767 }
4768
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004769 return PyLong_FromLong(nbytes);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004770}
4771
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004772/*[clinic input]
4773_ssl.MemoryBIO.write_eof
4774
4775Write an EOF marker to the memory BIO.
4776
4777When all data has been read, the "eof" property will be True.
4778[clinic start generated code]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004779
4780static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004781_ssl_MemoryBIO_write_eof_impl(PySSLMemoryBIO *self)
4782/*[clinic end generated code: output=d4106276ccd1ed34 input=56a945f1d29e8bd6]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004783{
4784 self->eof_written = 1;
4785 /* After an EOF is written, a zero return from read() should be a real EOF
4786 * i.e. it should not be retried. Clear the SHOULD_RETRY flag. */
4787 BIO_clear_retry_flags(self->bio);
4788 BIO_set_mem_eof_return(self->bio, 0);
4789
4790 Py_RETURN_NONE;
4791}
4792
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004793static PyGetSetDef memory_bio_getsetlist[] = {
4794 {"pending", (getter) memory_bio_get_pending, NULL,
4795 PySSL_memory_bio_pending_doc},
4796 {"eof", (getter) memory_bio_get_eof, NULL,
4797 PySSL_memory_bio_eof_doc},
4798 {NULL}, /* sentinel */
4799};
4800
4801static struct PyMethodDef memory_bio_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004802 _SSL_MEMORYBIO_READ_METHODDEF
4803 _SSL_MEMORYBIO_WRITE_METHODDEF
4804 _SSL_MEMORYBIO_WRITE_EOF_METHODDEF
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004805 {NULL, NULL} /* sentinel */
4806};
4807
Christian Heimes5c36da72020-11-20 09:40:12 +01004808static PyType_Slot PySSLMemoryBIO_slots[] = {
4809 {Py_tp_methods, memory_bio_methods},
4810 {Py_tp_getset, memory_bio_getsetlist},
4811 {Py_tp_new, _ssl_MemoryBIO},
4812 {Py_tp_dealloc, memory_bio_dealloc},
4813 {0, 0},
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004814};
4815
Christian Heimes5c36da72020-11-20 09:40:12 +01004816static PyType_Spec PySSLMemoryBIO_spec = {
4817 "_ssl.MemoryBIO",
4818 sizeof(PySSLMemoryBIO),
4819 0,
4820 Py_TPFLAGS_DEFAULT,
4821 PySSLMemoryBIO_slots,
4822};
Antoine Pitrou152efa22010-05-16 18:19:27 +00004823
Christian Heimes99a65702016-09-10 23:44:53 +02004824/*
4825 * SSL Session object
4826 */
4827
4828static void
4829PySSLSession_dealloc(PySSLSession *self)
4830{
Christian Heimes5c36da72020-11-20 09:40:12 +01004831 PyTypeObject *tp = Py_TYPE(self);
INADA Naokia6296d32017-08-24 14:55:17 +09004832 /* bpo-31095: UnTrack is needed before calling any callbacks */
Christian Heimesa5d07652016-09-24 10:48:05 +02004833 PyObject_GC_UnTrack(self);
Christian Heimes99a65702016-09-10 23:44:53 +02004834 Py_XDECREF(self->ctx);
4835 if (self->session != NULL) {
4836 SSL_SESSION_free(self->session);
4837 }
Christian Heimesa5d07652016-09-24 10:48:05 +02004838 PyObject_GC_Del(self);
Christian Heimes5c36da72020-11-20 09:40:12 +01004839 Py_DECREF(tp);
Christian Heimes99a65702016-09-10 23:44:53 +02004840}
4841
4842static PyObject *
4843PySSLSession_richcompare(PyObject *left, PyObject *right, int op)
4844{
4845 int result;
Christian Heimes7f1305e2021-04-17 20:06:38 +02004846 PyTypeObject *sesstype = ((PySSLSession*)left)->ctx->state->PySSLSession_Type;
Christian Heimes99a65702016-09-10 23:44:53 +02004847
4848 if (left == NULL || right == NULL) {
4849 PyErr_BadInternalCall();
4850 return NULL;
4851 }
4852
Christian Heimes7f1305e2021-04-17 20:06:38 +02004853 if (!Py_IS_TYPE(left, sesstype) || !Py_IS_TYPE(right, sesstype)) {
Christian Heimes99a65702016-09-10 23:44:53 +02004854 Py_RETURN_NOTIMPLEMENTED;
4855 }
4856
4857 if (left == right) {
4858 result = 0;
4859 } else {
4860 const unsigned char *left_id, *right_id;
4861 unsigned int left_len, right_len;
4862 left_id = SSL_SESSION_get_id(((PySSLSession *)left)->session,
4863 &left_len);
4864 right_id = SSL_SESSION_get_id(((PySSLSession *)right)->session,
4865 &right_len);
4866 if (left_len == right_len) {
4867 result = memcmp(left_id, right_id, left_len);
4868 } else {
4869 result = 1;
4870 }
4871 }
4872
4873 switch (op) {
4874 case Py_EQ:
4875 if (result == 0) {
4876 Py_RETURN_TRUE;
4877 } else {
4878 Py_RETURN_FALSE;
4879 }
4880 break;
4881 case Py_NE:
4882 if (result != 0) {
4883 Py_RETURN_TRUE;
4884 } else {
4885 Py_RETURN_FALSE;
4886 }
4887 break;
4888 case Py_LT:
4889 case Py_LE:
4890 case Py_GT:
4891 case Py_GE:
4892 Py_RETURN_NOTIMPLEMENTED;
4893 break;
4894 default:
4895 PyErr_BadArgument();
4896 return NULL;
4897 }
4898}
4899
4900static int
4901PySSLSession_traverse(PySSLSession *self, visitproc visit, void *arg)
4902{
4903 Py_VISIT(self->ctx);
4904 return 0;
4905}
4906
4907static int
4908PySSLSession_clear(PySSLSession *self)
4909{
4910 Py_CLEAR(self->ctx);
4911 return 0;
4912}
4913
4914
4915static PyObject *
4916PySSLSession_get_time(PySSLSession *self, void *closure) {
4917 return PyLong_FromLong(SSL_SESSION_get_time(self->session));
4918}
4919
4920PyDoc_STRVAR(PySSLSession_get_time_doc,
4921"Session creation time (seconds since epoch).");
4922
4923
4924static PyObject *
4925PySSLSession_get_timeout(PySSLSession *self, void *closure) {
4926 return PyLong_FromLong(SSL_SESSION_get_timeout(self->session));
4927}
4928
4929PyDoc_STRVAR(PySSLSession_get_timeout_doc,
4930"Session timeout (delta in seconds).");
4931
4932
4933static PyObject *
4934PySSLSession_get_ticket_lifetime_hint(PySSLSession *self, void *closure) {
4935 unsigned long hint = SSL_SESSION_get_ticket_lifetime_hint(self->session);
4936 return PyLong_FromUnsignedLong(hint);
4937}
4938
4939PyDoc_STRVAR(PySSLSession_get_ticket_lifetime_hint_doc,
4940"Ticket life time hint.");
4941
4942
4943static PyObject *
4944PySSLSession_get_session_id(PySSLSession *self, void *closure) {
4945 const unsigned char *id;
4946 unsigned int len;
4947 id = SSL_SESSION_get_id(self->session, &len);
4948 return PyBytes_FromStringAndSize((const char *)id, len);
4949}
4950
4951PyDoc_STRVAR(PySSLSession_get_session_id_doc,
4952"Session id");
4953
4954
4955static PyObject *
4956PySSLSession_get_has_ticket(PySSLSession *self, void *closure) {
4957 if (SSL_SESSION_has_ticket(self->session)) {
4958 Py_RETURN_TRUE;
4959 } else {
4960 Py_RETURN_FALSE;
4961 }
4962}
4963
4964PyDoc_STRVAR(PySSLSession_get_has_ticket_doc,
4965"Does the session contain a ticket?");
4966
4967
4968static PyGetSetDef PySSLSession_getsetlist[] = {
4969 {"has_ticket", (getter) PySSLSession_get_has_ticket, NULL,
4970 PySSLSession_get_has_ticket_doc},
4971 {"id", (getter) PySSLSession_get_session_id, NULL,
4972 PySSLSession_get_session_id_doc},
4973 {"ticket_lifetime_hint", (getter) PySSLSession_get_ticket_lifetime_hint,
4974 NULL, PySSLSession_get_ticket_lifetime_hint_doc},
4975 {"time", (getter) PySSLSession_get_time, NULL,
4976 PySSLSession_get_time_doc},
4977 {"timeout", (getter) PySSLSession_get_timeout, NULL,
4978 PySSLSession_get_timeout_doc},
4979 {NULL}, /* sentinel */
4980};
4981
Christian Heimes5c36da72020-11-20 09:40:12 +01004982static PyType_Slot PySSLSession_slots[] = {
4983 {Py_tp_getset,PySSLSession_getsetlist},
4984 {Py_tp_richcompare, PySSLSession_richcompare},
4985 {Py_tp_dealloc, PySSLSession_dealloc},
4986 {Py_tp_traverse, PySSLSession_traverse},
4987 {Py_tp_clear, PySSLSession_clear},
4988 {0, 0},
4989};
4990
4991static PyType_Spec PySSLSession_spec = {
4992 "_ssl.SSLSession",
4993 sizeof(PySSLSession),
4994 0,
4995 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,
4996 PySSLSession_slots,
Christian Heimes99a65702016-09-10 23:44:53 +02004997};
4998
4999
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005000/* helper routines for seeding the SSL PRNG */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005001/*[clinic input]
5002_ssl.RAND_add
Larry Hastingsdbfdc382015-05-04 06:59:46 -07005003 string as view: Py_buffer(accept={str, buffer})
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005004 entropy: double
5005 /
5006
5007Mix string into the OpenSSL PRNG state.
5008
5009entropy (a float) is a lower bound on the entropy contained in
Chandan Kumar63c2c8a2017-06-09 15:13:58 +05305010string. See RFC 4086.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005011[clinic start generated code]*/
5012
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005013static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005014_ssl_RAND_add_impl(PyObject *module, Py_buffer *view, double entropy)
Serhiy Storchaka5f31d5c2017-06-10 13:13:51 +03005015/*[clinic end generated code: output=e6dd48df9c9024e9 input=5c33017422828f5c]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005016{
Serhiy Storchaka8490f5a2015-03-20 09:00:36 +02005017 const char *buf;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02005018 Py_ssize_t len, written;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005019
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005020 buf = (const char *)view->buf;
5021 len = view->len;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02005022 do {
5023 written = Py_MIN(len, INT_MAX);
5024 RAND_add(buf, (int)written, entropy);
5025 buf += written;
5026 len -= written;
5027 } while (len);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02005028 Py_RETURN_NONE;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005029}
5030
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005031static PyObject *
Christian Heimes7f1305e2021-04-17 20:06:38 +02005032PySSL_RAND(PyObject *module, int len, int pseudo)
Victor Stinner99c8b162011-05-24 12:05:19 +02005033{
5034 int ok;
5035 PyObject *bytes;
5036 unsigned long err;
5037 const char *errstr;
5038 PyObject *v;
5039
Victor Stinner1e81a392013-12-19 16:47:04 +01005040 if (len < 0) {
5041 PyErr_SetString(PyExc_ValueError, "num must be positive");
5042 return NULL;
5043 }
5044
Victor Stinner99c8b162011-05-24 12:05:19 +02005045 bytes = PyBytes_FromStringAndSize(NULL, len);
5046 if (bytes == NULL)
5047 return NULL;
5048 if (pseudo) {
Christian Heimesa871f692020-06-01 08:58:14 +02005049 ok = RAND_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
Victor Stinner99c8b162011-05-24 12:05:19 +02005050 if (ok == 0 || ok == 1)
5051 return Py_BuildValue("NO", bytes, ok == 1 ? Py_True : Py_False);
5052 }
5053 else {
5054 ok = RAND_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
5055 if (ok == 1)
5056 return bytes;
5057 }
5058 Py_DECREF(bytes);
5059
5060 err = ERR_get_error();
5061 errstr = ERR_reason_error_string(err);
5062 v = Py_BuildValue("(ks)", err, errstr);
5063 if (v != NULL) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02005064 PyErr_SetObject(get_ssl_state(module)->PySSLErrorObject, v);
Victor Stinner99c8b162011-05-24 12:05:19 +02005065 Py_DECREF(v);
5066 }
5067 return NULL;
5068}
5069
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005070/*[clinic input]
5071_ssl.RAND_bytes
5072 n: int
5073 /
5074
5075Generate n cryptographically strong pseudo-random bytes.
5076[clinic start generated code]*/
5077
Victor Stinner99c8b162011-05-24 12:05:19 +02005078static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005079_ssl_RAND_bytes_impl(PyObject *module, int n)
5080/*[clinic end generated code: output=977da635e4838bc7 input=678ddf2872dfebfc]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02005081{
Christian Heimes7f1305e2021-04-17 20:06:38 +02005082 return PySSL_RAND(module, n, 0);
Victor Stinner99c8b162011-05-24 12:05:19 +02005083}
5084
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005085/*[clinic input]
5086_ssl.RAND_pseudo_bytes
5087 n: int
5088 /
5089
5090Generate n pseudo-random bytes.
5091
5092Return a pair (bytes, is_cryptographic). is_cryptographic is True
5093if the bytes generated are cryptographically strong.
5094[clinic start generated code]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02005095
5096static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005097_ssl_RAND_pseudo_bytes_impl(PyObject *module, int n)
5098/*[clinic end generated code: output=b1509e937000e52d input=58312bd53f9bbdd0]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02005099{
Christian Heimes2875c602021-04-19 07:27:10 +02005100 PY_SSL_DEPRECATED("RAND_pseudo_bytes", 1, NULL);
Christian Heimes7f1305e2021-04-17 20:06:38 +02005101 return PySSL_RAND(module, n, 1);
Victor Stinner99c8b162011-05-24 12:05:19 +02005102}
5103
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005104/*[clinic input]
5105_ssl.RAND_status
5106
Zackery Spytz7d37b862021-04-23 10:07:37 -06005107Returns True if the OpenSSL PRNG has been seeded with enough data and False if not.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005108
5109It is necessary to seed the PRNG with RAND_add() on some platforms before
5110using the ssl() function.
5111[clinic start generated code]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02005112
5113static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005114_ssl_RAND_status_impl(PyObject *module)
Zackery Spytz7d37b862021-04-23 10:07:37 -06005115/*[clinic end generated code: output=7e0aaa2d39fdc1ad input=d5ae5aea52f36e01]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005116{
Zackery Spytz7d37b862021-04-23 10:07:37 -06005117 return PyBool_FromLong(RAND_status());
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005118}
5119
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005120/*[clinic input]
5121_ssl.get_default_verify_paths
5122
5123Return search paths and environment vars that are used by SSLContext's set_default_verify_paths() to load default CAs.
5124
5125The values are 'cert_file_env', 'cert_file', 'cert_dir_env', 'cert_dir'.
5126[clinic start generated code]*/
Christian Heimes6d7ad132013-06-09 18:02:55 +02005127
5128static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005129_ssl_get_default_verify_paths_impl(PyObject *module)
5130/*[clinic end generated code: output=e5b62a466271928b input=5210c953d98c3eb5]*/
Christian Heimes6d7ad132013-06-09 18:02:55 +02005131{
5132 PyObject *ofile_env = NULL;
5133 PyObject *ofile = NULL;
5134 PyObject *odir_env = NULL;
5135 PyObject *odir = NULL;
5136
Benjamin Petersond113c962015-07-18 10:59:13 -07005137#define CONVERT(info, target) { \
Christian Heimes6d7ad132013-06-09 18:02:55 +02005138 const char *tmp = (info); \
5139 target = NULL; \
5140 if (!tmp) { Py_INCREF(Py_None); target = Py_None; } \
5141 else if ((target = PyUnicode_DecodeFSDefault(tmp)) == NULL) { \
5142 target = PyBytes_FromString(tmp); } \
5143 if (!target) goto error; \
Benjamin Peterson025a1fd2015-11-14 15:12:38 -08005144 }
Christian Heimes6d7ad132013-06-09 18:02:55 +02005145
Benjamin Petersond113c962015-07-18 10:59:13 -07005146 CONVERT(X509_get_default_cert_file_env(), ofile_env);
5147 CONVERT(X509_get_default_cert_file(), ofile);
5148 CONVERT(X509_get_default_cert_dir_env(), odir_env);
5149 CONVERT(X509_get_default_cert_dir(), odir);
5150#undef CONVERT
Christian Heimes6d7ad132013-06-09 18:02:55 +02005151
Christian Heimes200bb1b2013-06-14 15:14:29 +02005152 return Py_BuildValue("NNNN", ofile_env, ofile, odir_env, odir);
Christian Heimes6d7ad132013-06-09 18:02:55 +02005153
5154 error:
5155 Py_XDECREF(ofile_env);
5156 Py_XDECREF(ofile);
5157 Py_XDECREF(odir_env);
5158 Py_XDECREF(odir);
5159 return NULL;
5160}
5161
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005162static PyObject*
Christian Heimes7f1305e2021-04-17 20:06:38 +02005163asn1obj2py(_sslmodulestate *state, ASN1_OBJECT *obj)
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005164{
5165 int nid;
5166 const char *ln, *sn;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005167
5168 nid = OBJ_obj2nid(obj);
5169 if (nid == NID_undef) {
5170 PyErr_Format(PyExc_ValueError, "Unknown object");
5171 return NULL;
5172 }
5173 sn = OBJ_nid2sn(nid);
5174 ln = OBJ_nid2ln(nid);
Christian Heimes7f1305e2021-04-17 20:06:38 +02005175 return Py_BuildValue("issN", nid, sn, ln, _asn1obj2py(state, obj, 1));
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005176}
5177
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005178/*[clinic input]
5179_ssl.txt2obj
5180 txt: str
5181 name: bool = False
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005182
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005183Lookup NID, short name, long name and OID of an ASN1_OBJECT.
5184
5185By default objects are looked up by OID. With name=True short and
5186long name are also matched.
5187[clinic start generated code]*/
5188
5189static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005190_ssl_txt2obj_impl(PyObject *module, const char *txt, int name)
5191/*[clinic end generated code: output=c38e3991347079c1 input=1c1e7d0aa7c48602]*/
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005192{
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005193 PyObject *result = NULL;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005194 ASN1_OBJECT *obj;
5195
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005196 obj = OBJ_txt2obj(txt, name ? 0 : 1);
5197 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01005198 PyErr_Format(PyExc_ValueError, "unknown object '%.100s'", txt);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005199 return NULL;
5200 }
Christian Heimes7f1305e2021-04-17 20:06:38 +02005201 result = asn1obj2py(get_ssl_state(module), obj);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005202 ASN1_OBJECT_free(obj);
5203 return result;
5204}
5205
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005206/*[clinic input]
5207_ssl.nid2obj
5208 nid: int
5209 /
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005210
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005211Lookup NID, short name, long name and OID of an ASN1_OBJECT by NID.
5212[clinic start generated code]*/
5213
5214static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005215_ssl_nid2obj_impl(PyObject *module, int nid)
5216/*[clinic end generated code: output=4a98ab691cd4f84a input=51787a3bee7d8f98]*/
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005217{
5218 PyObject *result = NULL;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005219 ASN1_OBJECT *obj;
5220
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005221 if (nid < NID_undef) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01005222 PyErr_SetString(PyExc_ValueError, "NID must be positive.");
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005223 return NULL;
5224 }
5225 obj = OBJ_nid2obj(nid);
5226 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01005227 PyErr_Format(PyExc_ValueError, "unknown NID %i", nid);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005228 return NULL;
5229 }
Christian Heimes7f1305e2021-04-17 20:06:38 +02005230 result = asn1obj2py(get_ssl_state(module), obj);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005231 ASN1_OBJECT_free(obj);
5232 return result;
5233}
5234
Christian Heimes46bebee2013-06-09 19:03:31 +02005235#ifdef _MSC_VER
Christian Heimes44109d72013-11-22 01:51:30 +01005236
5237static PyObject*
5238certEncodingType(DWORD encodingType)
5239{
5240 static PyObject *x509_asn = NULL;
5241 static PyObject *pkcs_7_asn = NULL;
5242
5243 if (x509_asn == NULL) {
5244 x509_asn = PyUnicode_InternFromString("x509_asn");
5245 if (x509_asn == NULL)
5246 return NULL;
5247 }
5248 if (pkcs_7_asn == NULL) {
5249 pkcs_7_asn = PyUnicode_InternFromString("pkcs_7_asn");
5250 if (pkcs_7_asn == NULL)
5251 return NULL;
5252 }
5253 switch(encodingType) {
5254 case X509_ASN_ENCODING:
5255 Py_INCREF(x509_asn);
5256 return x509_asn;
5257 case PKCS_7_ASN_ENCODING:
5258 Py_INCREF(pkcs_7_asn);
5259 return pkcs_7_asn;
5260 default:
5261 return PyLong_FromLong(encodingType);
5262 }
5263}
5264
5265static PyObject*
5266parseKeyUsage(PCCERT_CONTEXT pCertCtx, DWORD flags)
5267{
5268 CERT_ENHKEY_USAGE *usage;
5269 DWORD size, error, i;
5270 PyObject *retval;
5271
5272 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, NULL, &size)) {
5273 error = GetLastError();
5274 if (error == CRYPT_E_NOT_FOUND) {
5275 Py_RETURN_TRUE;
5276 }
5277 return PyErr_SetFromWindowsErr(error);
5278 }
5279
5280 usage = (CERT_ENHKEY_USAGE*)PyMem_Malloc(size);
5281 if (usage == NULL) {
5282 return PyErr_NoMemory();
5283 }
5284
5285 /* Now get the actual enhanced usage property */
5286 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, usage, &size)) {
5287 PyMem_Free(usage);
5288 error = GetLastError();
5289 if (error == CRYPT_E_NOT_FOUND) {
5290 Py_RETURN_TRUE;
5291 }
5292 return PyErr_SetFromWindowsErr(error);
5293 }
Christian Heimes915cd3f2019-09-09 18:06:55 +02005294 retval = PyFrozenSet_New(NULL);
Christian Heimes44109d72013-11-22 01:51:30 +01005295 if (retval == NULL) {
5296 goto error;
5297 }
5298 for (i = 0; i < usage->cUsageIdentifier; ++i) {
5299 if (usage->rgpszUsageIdentifier[i]) {
5300 PyObject *oid;
5301 int err;
5302 oid = PyUnicode_FromString(usage->rgpszUsageIdentifier[i]);
5303 if (oid == NULL) {
5304 Py_CLEAR(retval);
5305 goto error;
5306 }
5307 err = PySet_Add(retval, oid);
5308 Py_DECREF(oid);
5309 if (err == -1) {
5310 Py_CLEAR(retval);
5311 goto error;
5312 }
5313 }
5314 }
5315 error:
5316 PyMem_Free(usage);
5317 return retval;
5318}
5319
kctherookied93fbbf2019-03-29 00:59:06 +07005320static HCERTSTORE
5321ssl_collect_certificates(const char *store_name)
5322{
5323/* this function collects the system certificate stores listed in
5324 * system_stores into a collection certificate store for being
5325 * enumerated. The store must be readable to be added to the
5326 * store collection.
5327 */
5328
5329 HCERTSTORE hCollectionStore = NULL, hSystemStore = NULL;
5330 static DWORD system_stores[] = {
5331 CERT_SYSTEM_STORE_LOCAL_MACHINE,
5332 CERT_SYSTEM_STORE_LOCAL_MACHINE_ENTERPRISE,
5333 CERT_SYSTEM_STORE_LOCAL_MACHINE_GROUP_POLICY,
5334 CERT_SYSTEM_STORE_CURRENT_USER,
5335 CERT_SYSTEM_STORE_CURRENT_USER_GROUP_POLICY,
5336 CERT_SYSTEM_STORE_SERVICES,
5337 CERT_SYSTEM_STORE_USERS};
5338 size_t i, storesAdded;
5339 BOOL result;
5340
5341 hCollectionStore = CertOpenStore(CERT_STORE_PROV_COLLECTION, 0,
5342 (HCRYPTPROV)NULL, 0, NULL);
5343 if (!hCollectionStore) {
5344 return NULL;
5345 }
5346 storesAdded = 0;
5347 for (i = 0; i < sizeof(system_stores) / sizeof(DWORD); i++) {
5348 hSystemStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0,
5349 (HCRYPTPROV)NULL,
5350 CERT_STORE_READONLY_FLAG |
5351 system_stores[i], store_name);
5352 if (hSystemStore) {
5353 result = CertAddStoreToCollection(hCollectionStore, hSystemStore,
5354 CERT_PHYSICAL_STORE_ADD_ENABLE_FLAG, 0);
5355 if (result) {
5356 ++storesAdded;
5357 }
neoneneed701292019-09-09 21:33:43 +09005358 CertCloseStore(hSystemStore, 0); /* flag must be 0 */
kctherookied93fbbf2019-03-29 00:59:06 +07005359 }
5360 }
5361 if (storesAdded == 0) {
5362 CertCloseStore(hCollectionStore, CERT_CLOSE_STORE_FORCE_FLAG);
5363 return NULL;
5364 }
5365
5366 return hCollectionStore;
5367}
5368
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005369/*[clinic input]
5370_ssl.enum_certificates
5371 store_name: str
5372
5373Retrieve certificates from Windows' cert store.
5374
5375store_name may be one of 'CA', 'ROOT' or 'MY'. The system may provide
5376more cert storages, too. The function returns a list of (bytes,
5377encoding_type, trust) tuples. The encoding_type flag can be interpreted
5378with X509_ASN_ENCODING or PKCS_7_ASN_ENCODING. The trust setting is either
5379a set of OIDs or the boolean True.
5380[clinic start generated code]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00005381
Christian Heimes46bebee2013-06-09 19:03:31 +02005382static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005383_ssl_enum_certificates_impl(PyObject *module, const char *store_name)
5384/*[clinic end generated code: output=5134dc8bb3a3c893 input=915f60d70461ea4e]*/
Christian Heimes46bebee2013-06-09 19:03:31 +02005385{
kctherookied93fbbf2019-03-29 00:59:06 +07005386 HCERTSTORE hCollectionStore = NULL;
Christian Heimes44109d72013-11-22 01:51:30 +01005387 PCCERT_CONTEXT pCertCtx = NULL;
5388 PyObject *keyusage = NULL, *cert = NULL, *enc = NULL, *tup = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02005389 PyObject *result = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02005390
Christian Heimes915cd3f2019-09-09 18:06:55 +02005391 result = PySet_New(NULL);
Christian Heimes44109d72013-11-22 01:51:30 +01005392 if (result == NULL) {
5393 return NULL;
5394 }
kctherookied93fbbf2019-03-29 00:59:06 +07005395 hCollectionStore = ssl_collect_certificates(store_name);
5396 if (hCollectionStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02005397 Py_DECREF(result);
5398 return PyErr_SetFromWindowsErr(GetLastError());
5399 }
5400
kctherookied93fbbf2019-03-29 00:59:06 +07005401 while (pCertCtx = CertEnumCertificatesInStore(hCollectionStore, pCertCtx)) {
Christian Heimes44109d72013-11-22 01:51:30 +01005402 cert = PyBytes_FromStringAndSize((const char*)pCertCtx->pbCertEncoded,
5403 pCertCtx->cbCertEncoded);
5404 if (!cert) {
5405 Py_CLEAR(result);
5406 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02005407 }
Christian Heimes44109d72013-11-22 01:51:30 +01005408 if ((enc = certEncodingType(pCertCtx->dwCertEncodingType)) == NULL) {
5409 Py_CLEAR(result);
5410 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02005411 }
Christian Heimes44109d72013-11-22 01:51:30 +01005412 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG);
5413 if (keyusage == Py_True) {
5414 Py_DECREF(keyusage);
5415 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_EXT_ONLY_ENHKEY_USAGE_FLAG);
Christian Heimes46bebee2013-06-09 19:03:31 +02005416 }
Christian Heimes44109d72013-11-22 01:51:30 +01005417 if (keyusage == NULL) {
5418 Py_CLEAR(result);
5419 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02005420 }
Christian Heimes44109d72013-11-22 01:51:30 +01005421 if ((tup = PyTuple_New(3)) == NULL) {
5422 Py_CLEAR(result);
5423 break;
5424 }
5425 PyTuple_SET_ITEM(tup, 0, cert);
5426 cert = NULL;
5427 PyTuple_SET_ITEM(tup, 1, enc);
5428 enc = NULL;
5429 PyTuple_SET_ITEM(tup, 2, keyusage);
5430 keyusage = NULL;
Christian Heimes915cd3f2019-09-09 18:06:55 +02005431 if (PySet_Add(result, tup) == -1) {
5432 Py_CLEAR(result);
5433 Py_CLEAR(tup);
5434 break;
Christian Heimes44109d72013-11-22 01:51:30 +01005435 }
5436 Py_CLEAR(tup);
5437 }
5438 if (pCertCtx) {
5439 /* loop ended with an error, need to clean up context manually */
5440 CertFreeCertificateContext(pCertCtx);
Christian Heimes46bebee2013-06-09 19:03:31 +02005441 }
5442
5443 /* In error cases cert, enc and tup may not be NULL */
5444 Py_XDECREF(cert);
5445 Py_XDECREF(enc);
Christian Heimes44109d72013-11-22 01:51:30 +01005446 Py_XDECREF(keyusage);
Christian Heimes46bebee2013-06-09 19:03:31 +02005447 Py_XDECREF(tup);
5448
kctherookied93fbbf2019-03-29 00:59:06 +07005449 /* CERT_CLOSE_STORE_FORCE_FLAG forces freeing of memory for all contexts
5450 associated with the store, in this case our collection store and the
5451 associated system stores. */
5452 if (!CertCloseStore(hCollectionStore, CERT_CLOSE_STORE_FORCE_FLAG)) {
Christian Heimes46bebee2013-06-09 19:03:31 +02005453 /* This error case might shadow another exception.*/
Christian Heimes44109d72013-11-22 01:51:30 +01005454 Py_XDECREF(result);
5455 return PyErr_SetFromWindowsErr(GetLastError());
5456 }
kctherookied93fbbf2019-03-29 00:59:06 +07005457
Christian Heimes915cd3f2019-09-09 18:06:55 +02005458 /* convert set to list */
5459 if (result == NULL) {
5460 return NULL;
5461 } else {
5462 PyObject *lst = PySequence_List(result);
5463 Py_DECREF(result);
5464 return lst;
5465 }
Christian Heimes44109d72013-11-22 01:51:30 +01005466}
5467
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005468/*[clinic input]
5469_ssl.enum_crls
5470 store_name: str
5471
5472Retrieve CRLs from Windows' cert store.
5473
5474store_name may be one of 'CA', 'ROOT' or 'MY'. The system may provide
5475more cert storages, too. The function returns a list of (bytes,
5476encoding_type) tuples. The encoding_type flag can be interpreted with
5477X509_ASN_ENCODING or PKCS_7_ASN_ENCODING.
5478[clinic start generated code]*/
Christian Heimes44109d72013-11-22 01:51:30 +01005479
5480static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005481_ssl_enum_crls_impl(PyObject *module, const char *store_name)
5482/*[clinic end generated code: output=bce467f60ccd03b6 input=a1f1d7629f1c5d3d]*/
Christian Heimes44109d72013-11-22 01:51:30 +01005483{
kctherookied93fbbf2019-03-29 00:59:06 +07005484 HCERTSTORE hCollectionStore = NULL;
Christian Heimes44109d72013-11-22 01:51:30 +01005485 PCCRL_CONTEXT pCrlCtx = NULL;
5486 PyObject *crl = NULL, *enc = NULL, *tup = NULL;
5487 PyObject *result = NULL;
5488
Christian Heimes915cd3f2019-09-09 18:06:55 +02005489 result = PySet_New(NULL);
Christian Heimes44109d72013-11-22 01:51:30 +01005490 if (result == NULL) {
5491 return NULL;
5492 }
kctherookied93fbbf2019-03-29 00:59:06 +07005493 hCollectionStore = ssl_collect_certificates(store_name);
5494 if (hCollectionStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02005495 Py_DECREF(result);
5496 return PyErr_SetFromWindowsErr(GetLastError());
5497 }
Christian Heimes44109d72013-11-22 01:51:30 +01005498
kctherookied93fbbf2019-03-29 00:59:06 +07005499 while (pCrlCtx = CertEnumCRLsInStore(hCollectionStore, pCrlCtx)) {
Christian Heimes44109d72013-11-22 01:51:30 +01005500 crl = PyBytes_FromStringAndSize((const char*)pCrlCtx->pbCrlEncoded,
5501 pCrlCtx->cbCrlEncoded);
5502 if (!crl) {
5503 Py_CLEAR(result);
5504 break;
5505 }
5506 if ((enc = certEncodingType(pCrlCtx->dwCertEncodingType)) == NULL) {
5507 Py_CLEAR(result);
5508 break;
5509 }
5510 if ((tup = PyTuple_New(2)) == NULL) {
5511 Py_CLEAR(result);
5512 break;
5513 }
5514 PyTuple_SET_ITEM(tup, 0, crl);
5515 crl = NULL;
5516 PyTuple_SET_ITEM(tup, 1, enc);
5517 enc = NULL;
5518
Christian Heimes915cd3f2019-09-09 18:06:55 +02005519 if (PySet_Add(result, tup) == -1) {
5520 Py_CLEAR(result);
5521 Py_CLEAR(tup);
5522 break;
Christian Heimes44109d72013-11-22 01:51:30 +01005523 }
5524 Py_CLEAR(tup);
Christian Heimes46bebee2013-06-09 19:03:31 +02005525 }
Christian Heimes44109d72013-11-22 01:51:30 +01005526 if (pCrlCtx) {
5527 /* loop ended with an error, need to clean up context manually */
5528 CertFreeCRLContext(pCrlCtx);
5529 }
5530
5531 /* In error cases cert, enc and tup may not be NULL */
5532 Py_XDECREF(crl);
5533 Py_XDECREF(enc);
5534 Py_XDECREF(tup);
5535
kctherookied93fbbf2019-03-29 00:59:06 +07005536 /* CERT_CLOSE_STORE_FORCE_FLAG forces freeing of memory for all contexts
5537 associated with the store, in this case our collection store and the
5538 associated system stores. */
5539 if (!CertCloseStore(hCollectionStore, CERT_CLOSE_STORE_FORCE_FLAG)) {
Christian Heimes44109d72013-11-22 01:51:30 +01005540 /* This error case might shadow another exception.*/
5541 Py_XDECREF(result);
5542 return PyErr_SetFromWindowsErr(GetLastError());
5543 }
Christian Heimes915cd3f2019-09-09 18:06:55 +02005544 /* convert set to list */
5545 if (result == NULL) {
5546 return NULL;
5547 } else {
5548 PyObject *lst = PySequence_List(result);
5549 Py_DECREF(result);
5550 return lst;
5551 }
Christian Heimes46bebee2013-06-09 19:03:31 +02005552}
Christian Heimes44109d72013-11-22 01:51:30 +01005553
5554#endif /* _MSC_VER */
Bill Janssen40a0f662008-08-12 16:56:25 +00005555
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005556/* List of functions exported by this module. */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005557static PyMethodDef PySSL_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005558 _SSL__TEST_DECODE_CERT_METHODDEF
5559 _SSL_RAND_ADD_METHODDEF
5560 _SSL_RAND_BYTES_METHODDEF
5561 _SSL_RAND_PSEUDO_BYTES_METHODDEF
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005562 _SSL_RAND_STATUS_METHODDEF
5563 _SSL_GET_DEFAULT_VERIFY_PATHS_METHODDEF
5564 _SSL_ENUM_CERTIFICATES_METHODDEF
5565 _SSL_ENUM_CRLS_METHODDEF
5566 _SSL_TXT2OBJ_METHODDEF
5567 _SSL_NID2OBJ_METHODDEF
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005568 {NULL, NULL} /* Sentinel */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005569};
5570
5571
Christian Heimes7f1305e2021-04-17 20:06:38 +02005572PyDoc_STRVAR(module_doc,
5573"Implementation module for SSL socket operations. See the socket module\n\
5574for documentation.");
Christian Heimes5c36da72020-11-20 09:40:12 +01005575
5576static int
5577sslmodule_init_exceptions(PyObject *module)
5578{
Christian Heimes7f1305e2021-04-17 20:06:38 +02005579 _sslmodulestate *state = get_ssl_state(module);
Christian Heimes5c36da72020-11-20 09:40:12 +01005580 PyObject *bases = NULL;
5581
Christian Heimes7f1305e2021-04-17 20:06:38 +02005582#define add_exception(exc, name, doc, base) \
5583do { \
5584 (exc) = PyErr_NewExceptionWithDoc("ssl." name, (doc), (base), NULL); \
5585 if ((state) == NULL) goto error; \
5586 if (PyModule_AddObjectRef(module, name, exc) < 0) goto error; \
Christian Heimes5c36da72020-11-20 09:40:12 +01005587} while(0)
5588
Christian Heimes7f1305e2021-04-17 20:06:38 +02005589 state->PySSLErrorObject = PyType_FromSpecWithBases(
5590 &sslerror_type_spec, PyExc_OSError);
5591 if (state->PySSLErrorObject == NULL) {
Christian Heimes5c36da72020-11-20 09:40:12 +01005592 goto error;
5593 }
Christian Heimes7f1305e2021-04-17 20:06:38 +02005594 if (PyModule_AddObjectRef(module, "SSLError", state->PySSLErrorObject) < 0) {
Christian Heimes5c36da72020-11-20 09:40:12 +01005595 goto error;
5596 }
5597
5598 /* ssl.CertificateError used to be a subclass of ValueError */
Christian Heimes7f1305e2021-04-17 20:06:38 +02005599 bases = PyTuple_Pack(2, state->PySSLErrorObject, PyExc_ValueError);
Christian Heimes5c36da72020-11-20 09:40:12 +01005600 if (bases == NULL) {
5601 goto error;
5602 }
5603 add_exception(
Christian Heimes7f1305e2021-04-17 20:06:38 +02005604 state->PySSLCertVerificationErrorObject,
Christian Heimes5c36da72020-11-20 09:40:12 +01005605 "SSLCertVerificationError",
5606 SSLCertVerificationError_doc,
5607 bases
5608 );
5609 Py_CLEAR(bases);
5610
5611 add_exception(
Christian Heimes7f1305e2021-04-17 20:06:38 +02005612 state->PySSLZeroReturnErrorObject,
Christian Heimes5c36da72020-11-20 09:40:12 +01005613 "SSLZeroReturnError",
5614 SSLZeroReturnError_doc,
Christian Heimes7f1305e2021-04-17 20:06:38 +02005615 state->PySSLErrorObject
Christian Heimes5c36da72020-11-20 09:40:12 +01005616 );
5617
5618 add_exception(
Christian Heimes7f1305e2021-04-17 20:06:38 +02005619 state->PySSLWantWriteErrorObject,
Christian Heimes5c36da72020-11-20 09:40:12 +01005620 "SSLWantWriteError",
5621 SSLWantWriteError_doc,
Christian Heimes7f1305e2021-04-17 20:06:38 +02005622 state->PySSLErrorObject
Christian Heimes5c36da72020-11-20 09:40:12 +01005623 );
5624
5625 add_exception(
Christian Heimes7f1305e2021-04-17 20:06:38 +02005626 state->PySSLWantReadErrorObject,
Christian Heimes5c36da72020-11-20 09:40:12 +01005627 "SSLWantReadError",
5628 SSLWantReadError_doc,
Christian Heimes7f1305e2021-04-17 20:06:38 +02005629 state->PySSLErrorObject
Christian Heimes5c36da72020-11-20 09:40:12 +01005630 );
5631
5632 add_exception(
Christian Heimes7f1305e2021-04-17 20:06:38 +02005633 state->PySSLSyscallErrorObject,
Christian Heimes5c36da72020-11-20 09:40:12 +01005634 "SSLSyscallError",
5635 SSLSyscallError_doc,
Christian Heimes7f1305e2021-04-17 20:06:38 +02005636 state->PySSLErrorObject
Christian Heimes5c36da72020-11-20 09:40:12 +01005637 );
5638
5639 add_exception(
Christian Heimes7f1305e2021-04-17 20:06:38 +02005640 state->PySSLEOFErrorObject,
Christian Heimes5c36da72020-11-20 09:40:12 +01005641 "SSLEOFError",
5642 SSLEOFError_doc,
Christian Heimes7f1305e2021-04-17 20:06:38 +02005643 state->PySSLErrorObject
Christian Heimes5c36da72020-11-20 09:40:12 +01005644 );
5645#undef add_exception
5646
5647 return 0;
5648 error:
5649 Py_XDECREF(bases);
5650 return -1;
5651}
5652
5653static int
5654sslmodule_init_socketapi(PyObject *module)
5655{
Christian Heimes7f1305e2021-04-17 20:06:38 +02005656 _sslmodulestate *state = get_ssl_state(module);
5657 PySocketModule_APIObject *sockmod = PySocketModule_ImportModuleAndAPI();
Christian Heimes5c36da72020-11-20 09:40:12 +01005658
Christian Heimes7f1305e2021-04-17 20:06:38 +02005659 if ((sockmod == NULL) || (sockmod->Sock_Type == NULL)) {
Christian Heimes5c36da72020-11-20 09:40:12 +01005660 return -1;
Christian Heimes5c36da72020-11-20 09:40:12 +01005661 }
Christian Heimes7f1305e2021-04-17 20:06:38 +02005662 state->Sock_Type = sockmod->Sock_Type;
5663 Py_INCREF(state->Sock_Type);
Christian Heimes5c36da72020-11-20 09:40:12 +01005664 return 0;
5665}
Christian Heimesc941e622017-09-05 15:47:11 +02005666
Christian Heimes5c36da72020-11-20 09:40:12 +01005667static int
5668sslmodule_init_constants(PyObject *m)
5669{
Christian Heimes7f1305e2021-04-17 20:06:38 +02005670
Christian Heimes892d66e2018-01-29 14:10:18 +01005671 PyModule_AddStringConstant(m, "_DEFAULT_CIPHERS",
5672 PY_SSL_DEFAULT_CIPHER_STRING);
5673
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005674 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
5675 PY_SSL_ERROR_ZERO_RETURN);
5676 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
5677 PY_SSL_ERROR_WANT_READ);
5678 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
5679 PY_SSL_ERROR_WANT_WRITE);
5680 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
5681 PY_SSL_ERROR_WANT_X509_LOOKUP);
5682 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
5683 PY_SSL_ERROR_SYSCALL);
5684 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
5685 PY_SSL_ERROR_SSL);
5686 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
5687 PY_SSL_ERROR_WANT_CONNECT);
5688 /* non ssl.h errorcodes */
5689 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
5690 PY_SSL_ERROR_EOF);
5691 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
5692 PY_SSL_ERROR_INVALID_ERROR_CODE);
5693 /* cert requirements */
5694 PyModule_AddIntConstant(m, "CERT_NONE",
5695 PY_SSL_CERT_NONE);
5696 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
5697 PY_SSL_CERT_OPTIONAL);
5698 PyModule_AddIntConstant(m, "CERT_REQUIRED",
5699 PY_SSL_CERT_REQUIRED);
Christian Heimes22587792013-11-21 23:56:13 +01005700 /* CRL verification for verification_flags */
5701 PyModule_AddIntConstant(m, "VERIFY_DEFAULT",
5702 0);
5703 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_LEAF",
5704 X509_V_FLAG_CRL_CHECK);
5705 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_CHAIN",
5706 X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
5707 PyModule_AddIntConstant(m, "VERIFY_X509_STRICT",
5708 X509_V_FLAG_X509_STRICT);
Chris Burre0b4aa02021-03-18 09:24:01 +01005709 PyModule_AddIntConstant(m, "VERIFY_ALLOW_PROXY_CERTS",
5710 X509_V_FLAG_ALLOW_PROXY_CERTS);
Benjamin Peterson990fcaa2015-03-04 22:49:41 -05005711 PyModule_AddIntConstant(m, "VERIFY_X509_TRUSTED_FIRST",
5712 X509_V_FLAG_TRUSTED_FIRST);
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00005713
l0x64d97522021-04-19 13:51:18 +02005714#ifdef X509_V_FLAG_PARTIAL_CHAIN
5715 PyModule_AddIntConstant(m, "VERIFY_X509_PARTIAL_CHAIN",
5716 X509_V_FLAG_PARTIAL_CHAIN);
5717#endif
5718
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01005719 /* Alert Descriptions from ssl.h */
5720 /* note RESERVED constants no longer intended for use have been removed */
5721 /* http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-6 */
5722
5723#define ADD_AD_CONSTANT(s) \
5724 PyModule_AddIntConstant(m, "ALERT_DESCRIPTION_"#s, \
5725 SSL_AD_##s)
5726
5727 ADD_AD_CONSTANT(CLOSE_NOTIFY);
5728 ADD_AD_CONSTANT(UNEXPECTED_MESSAGE);
5729 ADD_AD_CONSTANT(BAD_RECORD_MAC);
5730 ADD_AD_CONSTANT(RECORD_OVERFLOW);
5731 ADD_AD_CONSTANT(DECOMPRESSION_FAILURE);
5732 ADD_AD_CONSTANT(HANDSHAKE_FAILURE);
5733 ADD_AD_CONSTANT(BAD_CERTIFICATE);
5734 ADD_AD_CONSTANT(UNSUPPORTED_CERTIFICATE);
5735 ADD_AD_CONSTANT(CERTIFICATE_REVOKED);
5736 ADD_AD_CONSTANT(CERTIFICATE_EXPIRED);
5737 ADD_AD_CONSTANT(CERTIFICATE_UNKNOWN);
5738 ADD_AD_CONSTANT(ILLEGAL_PARAMETER);
5739 ADD_AD_CONSTANT(UNKNOWN_CA);
5740 ADD_AD_CONSTANT(ACCESS_DENIED);
5741 ADD_AD_CONSTANT(DECODE_ERROR);
5742 ADD_AD_CONSTANT(DECRYPT_ERROR);
5743 ADD_AD_CONSTANT(PROTOCOL_VERSION);
5744 ADD_AD_CONSTANT(INSUFFICIENT_SECURITY);
5745 ADD_AD_CONSTANT(INTERNAL_ERROR);
5746 ADD_AD_CONSTANT(USER_CANCELLED);
5747 ADD_AD_CONSTANT(NO_RENEGOTIATION);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01005748 /* Not all constants are in old OpenSSL versions */
Antoine Pitrou912fbff2013-03-30 16:29:32 +01005749#ifdef SSL_AD_UNSUPPORTED_EXTENSION
5750 ADD_AD_CONSTANT(UNSUPPORTED_EXTENSION);
5751#endif
5752#ifdef SSL_AD_CERTIFICATE_UNOBTAINABLE
5753 ADD_AD_CONSTANT(CERTIFICATE_UNOBTAINABLE);
5754#endif
5755#ifdef SSL_AD_UNRECOGNIZED_NAME
5756 ADD_AD_CONSTANT(UNRECOGNIZED_NAME);
5757#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01005758#ifdef SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE
5759 ADD_AD_CONSTANT(BAD_CERTIFICATE_STATUS_RESPONSE);
5760#endif
5761#ifdef SSL_AD_BAD_CERTIFICATE_HASH_VALUE
5762 ADD_AD_CONSTANT(BAD_CERTIFICATE_HASH_VALUE);
5763#endif
5764#ifdef SSL_AD_UNKNOWN_PSK_IDENTITY
5765 ADD_AD_CONSTANT(UNKNOWN_PSK_IDENTITY);
5766#endif
5767
5768#undef ADD_AD_CONSTANT
5769
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005770 /* protocol versions */
Victor Stinner3de49192011-05-09 00:42:58 +02005771#ifndef OPENSSL_NO_SSL2
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005772 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
5773 PY_SSL_VERSION_SSL2);
Victor Stinner3de49192011-05-09 00:42:58 +02005774#endif
Benjamin Petersone32467c2014-12-05 21:59:35 -05005775#ifndef OPENSSL_NO_SSL3
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005776 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
5777 PY_SSL_VERSION_SSL3);
Benjamin Petersone32467c2014-12-05 21:59:35 -05005778#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005779 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
Christian Heimes598894f2016-09-05 23:19:05 +02005780 PY_SSL_VERSION_TLS);
5781 PyModule_AddIntConstant(m, "PROTOCOL_TLS",
5782 PY_SSL_VERSION_TLS);
Christian Heimes5fe668c2016-09-12 00:01:11 +02005783 PyModule_AddIntConstant(m, "PROTOCOL_TLS_CLIENT",
5784 PY_SSL_VERSION_TLS_CLIENT);
5785 PyModule_AddIntConstant(m, "PROTOCOL_TLS_SERVER",
5786 PY_SSL_VERSION_TLS_SERVER);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005787 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
5788 PY_SSL_VERSION_TLS1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01005789 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_1",
5790 PY_SSL_VERSION_TLS1_1);
5791 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_2",
5792 PY_SSL_VERSION_TLS1_2);
Antoine Pitrou04f6a322010-04-05 21:40:07 +00005793
Antoine Pitroub5218772010-05-21 09:56:06 +00005794 /* protocol options */
Antoine Pitrou3f366312012-01-27 09:50:45 +01005795 PyModule_AddIntConstant(m, "OP_ALL",
5796 SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
Antoine Pitroub5218772010-05-21 09:56:06 +00005797 PyModule_AddIntConstant(m, "OP_NO_SSLv2", SSL_OP_NO_SSLv2);
5798 PyModule_AddIntConstant(m, "OP_NO_SSLv3", SSL_OP_NO_SSLv3);
5799 PyModule_AddIntConstant(m, "OP_NO_TLSv1", SSL_OP_NO_TLSv1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01005800 PyModule_AddIntConstant(m, "OP_NO_TLSv1_1", SSL_OP_NO_TLSv1_1);
5801 PyModule_AddIntConstant(m, "OP_NO_TLSv1_2", SSL_OP_NO_TLSv1_2);
Christian Heimescb5b68a2017-09-07 18:07:00 -07005802#ifdef SSL_OP_NO_TLSv1_3
5803 PyModule_AddIntConstant(m, "OP_NO_TLSv1_3", SSL_OP_NO_TLSv1_3);
5804#else
5805 PyModule_AddIntConstant(m, "OP_NO_TLSv1_3", 0);
5806#endif
Antoine Pitrou6db49442011-12-19 13:27:11 +01005807 PyModule_AddIntConstant(m, "OP_CIPHER_SERVER_PREFERENCE",
5808 SSL_OP_CIPHER_SERVER_PREFERENCE);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01005809 PyModule_AddIntConstant(m, "OP_SINGLE_DH_USE", SSL_OP_SINGLE_DH_USE);
Christian Heimes99a65702016-09-10 23:44:53 +02005810 PyModule_AddIntConstant(m, "OP_NO_TICKET", SSL_OP_NO_TICKET);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01005811#ifdef SSL_OP_SINGLE_ECDH_USE
Antoine Pitrou923df6f2011-12-19 17:16:51 +01005812 PyModule_AddIntConstant(m, "OP_SINGLE_ECDH_USE", SSL_OP_SINGLE_ECDH_USE);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01005813#endif
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01005814#ifdef SSL_OP_NO_COMPRESSION
5815 PyModule_AddIntConstant(m, "OP_NO_COMPRESSION",
5816 SSL_OP_NO_COMPRESSION);
5817#endif
Christian Heimes05d9fe32018-02-27 08:55:39 +01005818#ifdef SSL_OP_ENABLE_MIDDLEBOX_COMPAT
5819 PyModule_AddIntConstant(m, "OP_ENABLE_MIDDLEBOX_COMPAT",
5820 SSL_OP_ENABLE_MIDDLEBOX_COMPAT);
5821#endif
Christian Heimes67c48012018-05-15 16:25:40 -04005822#ifdef SSL_OP_NO_RENEGOTIATION
5823 PyModule_AddIntConstant(m, "OP_NO_RENEGOTIATION",
5824 SSL_OP_NO_RENEGOTIATION);
5825#endif
Christian Heimes6f37ebc2021-04-09 17:59:21 +02005826#ifdef SSL_OP_IGNORE_UNEXPECTED_EOF
5827 PyModule_AddIntConstant(m, "OP_IGNORE_UNEXPECTED_EOF",
5828 SSL_OP_IGNORE_UNEXPECTED_EOF);
5829#endif
Antoine Pitroub5218772010-05-21 09:56:06 +00005830
Christian Heimes61d478c2018-01-27 15:51:38 +01005831#ifdef X509_CHECK_FLAG_ALWAYS_CHECK_SUBJECT
5832 PyModule_AddIntConstant(m, "HOSTFLAG_ALWAYS_CHECK_SUBJECT",
5833 X509_CHECK_FLAG_ALWAYS_CHECK_SUBJECT);
5834#endif
5835#ifdef X509_CHECK_FLAG_NEVER_CHECK_SUBJECT
5836 PyModule_AddIntConstant(m, "HOSTFLAG_NEVER_CHECK_SUBJECT",
5837 X509_CHECK_FLAG_NEVER_CHECK_SUBJECT);
5838#endif
5839#ifdef X509_CHECK_FLAG_NO_WILDCARDS
5840 PyModule_AddIntConstant(m, "HOSTFLAG_NO_WILDCARDS",
5841 X509_CHECK_FLAG_NO_WILDCARDS);
5842#endif
5843#ifdef X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS
5844 PyModule_AddIntConstant(m, "HOSTFLAG_NO_PARTIAL_WILDCARDS",
5845 X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS);
5846#endif
5847#ifdef X509_CHECK_FLAG_MULTI_LABEL_WILDCARDS
5848 PyModule_AddIntConstant(m, "HOSTFLAG_MULTI_LABEL_WILDCARDS",
5849 X509_CHECK_FLAG_MULTI_LABEL_WILDCARDS);
5850#endif
5851#ifdef X509_CHECK_FLAG_SINGLE_LABEL_SUBDOMAINS
5852 PyModule_AddIntConstant(m, "HOSTFLAG_SINGLE_LABEL_SUBDOMAINS",
5853 X509_CHECK_FLAG_SINGLE_LABEL_SUBDOMAINS);
5854#endif
5855
Christian Heimes666991f2021-04-26 15:01:40 +02005856 /* file types */
5857 PyModule_AddIntConstant(m, "ENCODING_PEM", PY_SSL_ENCODING_PEM);
5858 PyModule_AddIntConstant(m, "ENCODING_DER", PY_SSL_ENCODING_DER);
5859
Christian Heimes698dde12018-02-27 11:54:43 +01005860 /* protocol versions */
5861 PyModule_AddIntConstant(m, "PROTO_MINIMUM_SUPPORTED",
5862 PY_PROTO_MINIMUM_SUPPORTED);
5863 PyModule_AddIntConstant(m, "PROTO_MAXIMUM_SUPPORTED",
5864 PY_PROTO_MAXIMUM_SUPPORTED);
5865 PyModule_AddIntConstant(m, "PROTO_SSLv3", PY_PROTO_SSLv3);
5866 PyModule_AddIntConstant(m, "PROTO_TLSv1", PY_PROTO_TLSv1);
5867 PyModule_AddIntConstant(m, "PROTO_TLSv1_1", PY_PROTO_TLSv1_1);
5868 PyModule_AddIntConstant(m, "PROTO_TLSv1_2", PY_PROTO_TLSv1_2);
5869 PyModule_AddIntConstant(m, "PROTO_TLSv1_3", PY_PROTO_TLSv1_3);
Antoine Pitroud5323212010-10-22 18:19:07 +00005870
Victor Stinnerb37672d2018-11-22 03:37:50 +01005871#define addbool(m, key, value) \
5872 do { \
5873 PyObject *bool_obj = (value) ? Py_True : Py_False; \
5874 Py_INCREF(bool_obj); \
5875 PyModule_AddObject((m), (key), bool_obj); \
5876 } while (0)
Christian Heimes698dde12018-02-27 11:54:43 +01005877
Christian Heimes698dde12018-02-27 11:54:43 +01005878 addbool(m, "HAS_SNI", 1);
Christian Heimes698dde12018-02-27 11:54:43 +01005879 addbool(m, "HAS_TLS_UNIQUE", 1);
Christian Heimes698dde12018-02-27 11:54:43 +01005880 addbool(m, "HAS_ECDH", 1);
Christian Heimes698dde12018-02-27 11:54:43 +01005881 addbool(m, "HAS_NPN", 0);
Christian Heimes698dde12018-02-27 11:54:43 +01005882 addbool(m, "HAS_ALPN", 1);
Christian Heimes698dde12018-02-27 11:54:43 +01005883
5884#if defined(SSL2_VERSION) && !defined(OPENSSL_NO_SSL2)
5885 addbool(m, "HAS_SSLv2", 1);
5886#else
5887 addbool(m, "HAS_SSLv2", 0);
5888#endif
5889
5890#if defined(SSL3_VERSION) && !defined(OPENSSL_NO_SSL3)
5891 addbool(m, "HAS_SSLv3", 1);
5892#else
5893 addbool(m, "HAS_SSLv3", 0);
5894#endif
5895
5896#if defined(TLS1_VERSION) && !defined(OPENSSL_NO_TLS1)
5897 addbool(m, "HAS_TLSv1", 1);
5898#else
5899 addbool(m, "HAS_TLSv1", 0);
5900#endif
5901
5902#if defined(TLS1_1_VERSION) && !defined(OPENSSL_NO_TLS1_1)
5903 addbool(m, "HAS_TLSv1_1", 1);
5904#else
5905 addbool(m, "HAS_TLSv1_1", 0);
5906#endif
5907
5908#if defined(TLS1_2_VERSION) && !defined(OPENSSL_NO_TLS1_2)
5909 addbool(m, "HAS_TLSv1_2", 1);
5910#else
5911 addbool(m, "HAS_TLSv1_2", 0);
5912#endif
Benjamin Petersoncca27322015-01-23 16:35:37 -05005913
Christian Heimescb5b68a2017-09-07 18:07:00 -07005914#if defined(TLS1_3_VERSION) && !defined(OPENSSL_NO_TLS1_3)
Christian Heimes698dde12018-02-27 11:54:43 +01005915 addbool(m, "HAS_TLSv1_3", 1);
Christian Heimescb5b68a2017-09-07 18:07:00 -07005916#else
Christian Heimes698dde12018-02-27 11:54:43 +01005917 addbool(m, "HAS_TLSv1_3", 0);
Christian Heimescb5b68a2017-09-07 18:07:00 -07005918#endif
Christian Heimescb5b68a2017-09-07 18:07:00 -07005919
Christian Heimes5c36da72020-11-20 09:40:12 +01005920 return 0;
5921}
5922
Christian Heimes7f1305e2021-04-17 20:06:38 +02005923static int
5924sslmodule_init_errorcodes(PyObject *module)
5925{
5926 _sslmodulestate *state = get_ssl_state(module);
Christian Heimes5c36da72020-11-20 09:40:12 +01005927
Christian Heimes7f1305e2021-04-17 20:06:38 +02005928 struct py_ssl_error_code *errcode;
5929 struct py_ssl_library_code *libcode;
Christian Heimes5c36da72020-11-20 09:40:12 +01005930
Christian Heimes7f1305e2021-04-17 20:06:38 +02005931 /* Mappings for error codes */
5932 state->err_codes_to_names = PyDict_New();
5933 if (state->err_codes_to_names == NULL)
5934 return -1;
5935 state->err_names_to_codes = PyDict_New();
5936 if (state->err_names_to_codes == NULL)
5937 return -1;
5938 state->lib_codes_to_names = PyDict_New();
5939 if (state->lib_codes_to_names == NULL)
5940 return -1;
5941
5942 errcode = error_codes;
5943 while (errcode->mnemonic != NULL) {
5944 PyObject *mnemo, *key;
5945 mnemo = PyUnicode_FromString(errcode->mnemonic);
5946 key = Py_BuildValue("ii", errcode->library, errcode->reason);
5947 if (mnemo == NULL || key == NULL)
5948 return -1;
5949 if (PyDict_SetItem(state->err_codes_to_names, key, mnemo))
5950 return -1;
5951 if (PyDict_SetItem(state->err_names_to_codes, mnemo, key))
5952 return -1;
5953 Py_DECREF(key);
5954 Py_DECREF(mnemo);
5955 errcode++;
5956 }
5957
5958 libcode = library_codes;
5959 while (libcode->library != NULL) {
5960 PyObject *mnemo, *key;
5961 key = PyLong_FromLong(libcode->code);
5962 mnemo = PyUnicode_FromString(libcode->library);
5963 if (key == NULL || mnemo == NULL)
5964 return -1;
5965 if (PyDict_SetItem(state->lib_codes_to_names, key, mnemo))
5966 return -1;
5967 Py_DECREF(key);
5968 Py_DECREF(mnemo);
5969 libcode++;
5970 }
5971
5972 if (PyModule_AddObjectRef(module, "err_codes_to_names", state->err_codes_to_names))
5973 return -1;
5974 if (PyModule_AddObjectRef(module, "err_names_to_codes", state->err_names_to_codes))
5975 return -1;
5976 if (PyModule_AddObjectRef(module, "lib_codes_to_names", state->lib_codes_to_names))
5977 return -1;
5978
5979 return 0;
5980}
5981
5982static void
5983parse_openssl_version(unsigned long libver,
5984 unsigned int *major, unsigned int *minor,
5985 unsigned int *fix, unsigned int *patch,
5986 unsigned int *status)
5987{
5988 *status = libver & 0xF;
5989 libver >>= 4;
5990 *patch = libver & 0xFF;
5991 libver >>= 8;
5992 *fix = libver & 0xFF;
5993 libver >>= 8;
5994 *minor = libver & 0xFF;
5995 libver >>= 8;
5996 *major = libver & 0xFF;
5997}
5998
5999static int
6000sslmodule_init_versioninfo(PyObject *m)
6001{
6002 PyObject *r;
6003 unsigned long libver;
6004 unsigned int major, minor, fix, patch, status;
6005
6006 /* OpenSSL version */
6007 /* SSLeay() gives us the version of the library linked against,
6008 which could be different from the headers version.
6009 */
6010 libver = OpenSSL_version_num();
6011 r = PyLong_FromUnsignedLong(libver);
6012 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r))
6013 return -1;
6014
6015 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
6016 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
6017 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r))
6018 return -1;
6019
6020 r = PyUnicode_FromString(OpenSSL_version(OPENSSL_VERSION));
6021 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r))
6022 return -1;
6023
6024 libver = OPENSSL_VERSION_NUMBER;
6025 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
6026 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
6027 if (r == NULL || PyModule_AddObject(m, "_OPENSSL_API_VERSION", r))
6028 return -1;
6029
6030 return 0;
6031}
6032
6033static int
6034sslmodule_init_types(PyObject *module)
6035{
6036 _sslmodulestate *state = get_ssl_state(module);
6037
6038 state->PySSLContext_Type = (PyTypeObject *)PyType_FromModuleAndSpec(
6039 module, &PySSLContext_spec, NULL
6040 );
6041 if (state->PySSLContext_Type == NULL)
6042 return -1;
6043
6044 state->PySSLSocket_Type = (PyTypeObject *)PyType_FromModuleAndSpec(
6045 module, &PySSLSocket_spec, NULL
6046 );
6047 if (state->PySSLSocket_Type == NULL)
6048 return -1;
6049
6050 state->PySSLMemoryBIO_Type = (PyTypeObject *)PyType_FromModuleAndSpec(
6051 module, &PySSLMemoryBIO_spec, NULL
6052 );
6053 if (state->PySSLMemoryBIO_Type == NULL)
6054 return -1;
6055
6056 state->PySSLSession_Type = (PyTypeObject *)PyType_FromModuleAndSpec(
6057 module, &PySSLSession_spec, NULL
6058 );
6059 if (state->PySSLSession_Type == NULL)
6060 return -1;
6061
Christian Heimes666991f2021-04-26 15:01:40 +02006062 state->PySSLCertificate_Type = (PyTypeObject *)PyType_FromModuleAndSpec(
6063 module, &PySSLCertificate_spec, NULL
6064 );
6065 if (state->PySSLCertificate_Type == NULL)
6066 return -1;
6067
Christian Heimes7f1305e2021-04-17 20:06:38 +02006068 if (PyModule_AddType(module, state->PySSLContext_Type))
6069 return -1;
6070 if (PyModule_AddType(module, state->PySSLSocket_Type))
6071 return -1;
6072 if (PyModule_AddType(module, state->PySSLMemoryBIO_Type))
6073 return -1;
6074 if (PyModule_AddType(module, state->PySSLSession_Type))
6075 return -1;
Christian Heimes666991f2021-04-26 15:01:40 +02006076 if (PyModule_AddType(module, state->PySSLCertificate_Type))
6077 return -1;
Christian Heimes7f1305e2021-04-17 20:06:38 +02006078 return 0;
6079}
6080
6081static PyModuleDef_Slot sslmodule_slots[] = {
6082 {Py_mod_exec, sslmodule_init_types},
6083 {Py_mod_exec, sslmodule_init_exceptions},
6084 {Py_mod_exec, sslmodule_init_socketapi},
6085 {Py_mod_exec, sslmodule_init_errorcodes},
6086 {Py_mod_exec, sslmodule_init_constants},
6087 {Py_mod_exec, sslmodule_init_versioninfo},
6088 {0, NULL}
6089};
6090
6091static int
6092sslmodule_traverse(PyObject *m, visitproc visit, void *arg)
6093{
6094 _sslmodulestate *state = get_ssl_state(m);
6095
6096 Py_VISIT(state->PySSLContext_Type);
6097 Py_VISIT(state->PySSLSocket_Type);
6098 Py_VISIT(state->PySSLMemoryBIO_Type);
6099 Py_VISIT(state->PySSLSession_Type);
Christian Heimes666991f2021-04-26 15:01:40 +02006100 Py_VISIT(state->PySSLCertificate_Type);
Christian Heimes7f1305e2021-04-17 20:06:38 +02006101 Py_VISIT(state->PySSLErrorObject);
6102 Py_VISIT(state->PySSLCertVerificationErrorObject);
6103 Py_VISIT(state->PySSLZeroReturnErrorObject);
6104 Py_VISIT(state->PySSLWantReadErrorObject);
6105 Py_VISIT(state->PySSLWantWriteErrorObject);
6106 Py_VISIT(state->PySSLSyscallErrorObject);
6107 Py_VISIT(state->PySSLEOFErrorObject);
6108 Py_VISIT(state->err_codes_to_names);
6109 Py_VISIT(state->err_names_to_codes);
6110 Py_VISIT(state->lib_codes_to_names);
6111 Py_VISIT(state->Sock_Type);
6112
6113 return 0;
6114}
6115
6116static int
6117sslmodule_clear(PyObject *m)
6118{
6119 _sslmodulestate *state = get_ssl_state(m);
6120
6121 Py_CLEAR(state->PySSLContext_Type);
6122 Py_CLEAR(state->PySSLSocket_Type);
6123 Py_CLEAR(state->PySSLMemoryBIO_Type);
6124 Py_CLEAR(state->PySSLSession_Type);
Christian Heimes666991f2021-04-26 15:01:40 +02006125 Py_CLEAR(state->PySSLCertificate_Type);
Christian Heimes7f1305e2021-04-17 20:06:38 +02006126 Py_CLEAR(state->PySSLErrorObject);
6127 Py_CLEAR(state->PySSLCertVerificationErrorObject);
6128 Py_CLEAR(state->PySSLZeroReturnErrorObject);
6129 Py_CLEAR(state->PySSLWantReadErrorObject);
6130 Py_CLEAR(state->PySSLWantWriteErrorObject);
6131 Py_CLEAR(state->PySSLSyscallErrorObject);
6132 Py_CLEAR(state->PySSLEOFErrorObject);
6133 Py_CLEAR(state->err_codes_to_names);
6134 Py_CLEAR(state->err_names_to_codes);
6135 Py_CLEAR(state->lib_codes_to_names);
6136 Py_CLEAR(state->Sock_Type);
6137
6138 return 0;
6139}
6140
6141static void
6142sslmodule_free(void *m)
6143{
6144 sslmodule_clear((PyObject *)m);
6145}
6146
6147static struct PyModuleDef _sslmodule_def = {
Christian Heimes5c36da72020-11-20 09:40:12 +01006148 PyModuleDef_HEAD_INIT,
Christian Heimes7f1305e2021-04-17 20:06:38 +02006149 .m_name = "_ssl",
6150 .m_doc = module_doc,
6151 .m_size = sizeof(_sslmodulestate),
6152 .m_methods = PySSL_methods,
6153 .m_slots = sslmodule_slots,
6154 .m_traverse = sslmodule_traverse,
6155 .m_clear = sslmodule_clear,
6156 .m_free = sslmodule_free
Christian Heimes5c36da72020-11-20 09:40:12 +01006157};
6158
6159PyMODINIT_FUNC
6160PyInit__ssl(void)
6161{
Christian Heimes7f1305e2021-04-17 20:06:38 +02006162 return PyModuleDef_Init(&_sslmodule_def);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00006163}