blob: d2b257e1ff462ca92dfa1d2d3829d926b2f9a479 [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
Steve Dower68d663c2017-07-17 11:15:48 +020028/* Redefined below for Windows debug builds after important #includes */
29#define _PySSL_FIX_ERRNO
Christian Heimesf77b4b22013-08-21 13:26:05 +020030
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +020031#define PySSL_BEGIN_ALLOW_THREADS_S(save) \
32 do { if (_ssl_locks_count>0) { (save) = PyEval_SaveThread(); } } while (0)
33#define PySSL_END_ALLOW_THREADS_S(save) \
Steve Dower68d663c2017-07-17 11:15:48 +020034 do { if (_ssl_locks_count>0) { PyEval_RestoreThread(save); } _PySSL_FIX_ERRNO; } while (0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +000035#define PySSL_BEGIN_ALLOW_THREADS { \
Antoine Pitroucbb82eb2010-05-05 15:57:33 +000036 PyThreadState *_save = NULL; \
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +020037 PySSL_BEGIN_ALLOW_THREADS_S(_save);
38#define PySSL_BLOCK_THREADS PySSL_END_ALLOW_THREADS_S(_save);
39#define PySSL_UNBLOCK_THREADS PySSL_BEGIN_ALLOW_THREADS_S(_save);
40#define PySSL_END_ALLOW_THREADS PySSL_END_ALLOW_THREADS_S(_save); }
Thomas Wouters1b7f8912007-09-19 03:06:30 +000041
Antoine Pitrou2463e5f2013-03-28 22:24:43 +010042/* Include symbols from _socket module */
43#include "socketmodule.h"
44
45static PySocketModule_APIObject PySocketModule;
46
47#if defined(HAVE_POLL_H)
48#include <poll.h>
49#elif defined(HAVE_SYS_POLL_H)
50#include <sys/poll.h>
51#endif
52
53/* Include OpenSSL header files */
54#include "openssl/rsa.h"
55#include "openssl/crypto.h"
56#include "openssl/x509.h"
57#include "openssl/x509v3.h"
58#include "openssl/pem.h"
59#include "openssl/ssl.h"
60#include "openssl/err.h"
61#include "openssl/rand.h"
Antoine Pitroub1fdf472014-10-05 20:41:53 +020062#include "openssl/bio.h"
Alexandru Ardeleanb3a271f2018-09-17 14:53:31 +030063#include "openssl/dh.h"
Antoine Pitrou2463e5f2013-03-28 22:24:43 +010064
Christian Heimesff5be6e2018-01-20 13:19:21 +010065#ifndef HAVE_X509_VERIFY_PARAM_SET1_HOST
Christian Heimes61d478c2018-01-27 15:51:38 +010066# ifdef LIBRESSL_VERSION_NUMBER
67# error "LibreSSL is missing X509_VERIFY_PARAM_set1_host(), see https://github.com/libressl-portable/portable/issues/381"
68# elif OPENSSL_VERSION_NUMBER > 0x1000200fL
Christian Heimesff5be6e2018-01-20 13:19:21 +010069# define HAVE_X509_VERIFY_PARAM_SET1_HOST
Christian Heimes61d478c2018-01-27 15:51:38 +010070# else
71# error "libssl is too old and does not support X509_VERIFY_PARAM_set1_host()"
Christian Heimesff5be6e2018-01-20 13:19:21 +010072# endif
73#endif
74
Christian Heimesc087a262020-05-15 20:55:25 +020075#ifndef OPENSSL_THREADS
76# error "OPENSSL_THREADS is not defined, Python requires thread-safe OpenSSL"
77#endif
78
Antoine Pitrou2463e5f2013-03-28 22:24:43 +010079/* SSL error object */
80static PyObject *PySSLErrorObject;
Christian Heimesb3ad0e52017-09-08 12:00:19 -070081static PyObject *PySSLCertVerificationErrorObject;
Antoine Pitrou2463e5f2013-03-28 22:24:43 +010082static PyObject *PySSLZeroReturnErrorObject;
83static PyObject *PySSLWantReadErrorObject;
84static PyObject *PySSLWantWriteErrorObject;
85static PyObject *PySSLSyscallErrorObject;
86static PyObject *PySSLEOFErrorObject;
87
88/* Error mappings */
89static PyObject *err_codes_to_names;
90static PyObject *err_names_to_codes;
91static PyObject *lib_codes_to_names;
92
93struct py_ssl_error_code {
94 const char *mnemonic;
95 int library, reason;
96};
97struct py_ssl_library_code {
98 const char *library;
99 int code;
100};
101
Steve Dower68d663c2017-07-17 11:15:48 +0200102#if defined(MS_WINDOWS) && defined(Py_DEBUG)
103/* Debug builds on Windows rely on getting errno directly from OpenSSL.
104 * However, because it uses a different CRT, we need to transfer the
105 * value of errno from OpenSSL into our debug CRT.
106 *
107 * Don't be fooled - this is horribly ugly code. The only reasonable
108 * alternative is to do both debug and release builds of OpenSSL, which
109 * requires much uglier code to transform their automatically generated
110 * makefile. This is the lesser of all the evils.
111 */
112
113static void _PySSLFixErrno(void) {
114 HMODULE ucrtbase = GetModuleHandleW(L"ucrtbase.dll");
115 if (!ucrtbase) {
116 /* If ucrtbase.dll is not loaded but the SSL DLLs are, we likely
117 * have a catastrophic failure, but this function is not the
118 * place to raise it. */
119 return;
120 }
121
122 typedef int *(__stdcall *errno_func)(void);
123 errno_func ssl_errno = (errno_func)GetProcAddress(ucrtbase, "_errno");
124 if (ssl_errno) {
125 errno = *ssl_errno();
126 *ssl_errno() = 0;
127 } else {
128 errno = ENOTRECOVERABLE;
129 }
130}
131
132#undef _PySSL_FIX_ERRNO
133#define _PySSL_FIX_ERRNO _PySSLFixErrno()
134#endif
135
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100136/* Include generated data (error codes) */
Christian Heimes150af752021-04-09 17:02:00 +0200137#if (OPENSSL_VERSION_NUMBER >= 0x30000000L)
138#include "_ssl_data_300.h"
139#elif (OPENSSL_VERSION_NUMBER >= 0x10101000L) && !defined(LIBRESSL_VERSION_NUMBER)
140#include "_ssl_data_111.h"
141#else
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100142#include "_ssl_data.h"
Christian Heimes150af752021-04-09 17:02:00 +0200143#endif
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100144
Christian Heimes598894f2016-09-05 23:19:05 +0200145#if (OPENSSL_VERSION_NUMBER >= 0x10100000L) && !defined(LIBRESSL_VERSION_NUMBER)
146# define OPENSSL_VERSION_1_1 1
Christian Heimes4ca07392018-03-24 15:41:37 +0100147# define PY_OPENSSL_1_1_API 1
148#endif
149
Christian Heimesa4833882021-04-13 08:17:26 +0200150/* OpenSSL API 1.1.0+ does not include version methods. Define the methods
151 * unless OpenSSL is compiled without the methods. It's the easiest way to
152 * make 1.0.2, 1.1.0, 1.1.1, and 3.0.0 happy without deprecation warnings.
153 */
Christian Heimesa871f692020-06-01 08:58:14 +0200154#ifndef OPENSSL_NO_TLS1_METHOD
Christian Heimesa4833882021-04-13 08:17:26 +0200155extern const SSL_METHOD *TLSv1_method(void);
Christian Heimesa871f692020-06-01 08:58:14 +0200156#endif
157#ifndef OPENSSL_NO_TLS1_1_METHOD
Christian Heimesa4833882021-04-13 08:17:26 +0200158extern const SSL_METHOD *TLSv1_1_method(void);
Christian Heimesa871f692020-06-01 08:58:14 +0200159#endif
160#ifndef OPENSSL_NO_TLS1_2_METHOD
Christian Heimesa4833882021-04-13 08:17:26 +0200161extern const SSL_METHOD *TLSv1_2_method(void);
Christian Heimesa871f692020-06-01 08:58:14 +0200162#endif
163
Christian Heimes4ca07392018-03-24 15:41:37 +0100164/* LibreSSL 2.7.0 provides necessary OpenSSL 1.1.0 APIs */
165#if defined(LIBRESSL_VERSION_NUMBER) && LIBRESSL_VERSION_NUMBER >= 0x2070000fL
166# define PY_OPENSSL_1_1_API 1
Christian Heimes598894f2016-09-05 23:19:05 +0200167#endif
168
Christian Heimes470fba12013-11-28 15:12:15 +0100169/* SNI support (client- and server-side) appeared in OpenSSL 1.0.0 and 0.9.8f
Antoine Pitrou912fbff2013-03-30 16:29:32 +0100170 * This includes the SSL_set_SSL_CTX() function.
171 */
172#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
173# define HAVE_SNI 1
174#else
175# define HAVE_SNI 0
176#endif
177
Benjamin Petersond3308222015-09-27 00:09:02 -0700178#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
Christian Heimes29eab552018-02-25 12:31:33 +0100179# define HAVE_ALPN 1
180#else
181# define HAVE_ALPN 0
Benjamin Petersoncca27322015-01-23 16:35:37 -0500182#endif
183
Christian Heimes6cdb7952018-02-24 22:12:40 +0100184/* We cannot rely on OPENSSL_NO_NEXTPROTONEG because LibreSSL 2.6.1 dropped
185 * NPN support but did not set OPENSSL_NO_NEXTPROTONEG for compatibility
186 * reasons. The check for TLSEXT_TYPE_next_proto_neg works with
187 * OpenSSL 1.0.1+ and LibreSSL.
Christian Heimes29eab552018-02-25 12:31:33 +0100188 * OpenSSL 1.1.1-pre1 dropped NPN but still has TLSEXT_TYPE_next_proto_neg.
Christian Heimes6cdb7952018-02-24 22:12:40 +0100189 */
190#ifdef OPENSSL_NO_NEXTPROTONEG
Christian Heimes29eab552018-02-25 12:31:33 +0100191# define HAVE_NPN 0
192#elif (OPENSSL_VERSION_NUMBER >= 0x10101000L) && !defined(LIBRESSL_VERSION_NUMBER)
193# define HAVE_NPN 0
Christian Heimes6cdb7952018-02-24 22:12:40 +0100194#elif defined(TLSEXT_TYPE_next_proto_neg)
Christian Heimes29eab552018-02-25 12:31:33 +0100195# define HAVE_NPN 1
Christian Heimes6cdb7952018-02-24 22:12:40 +0100196#else
Christian Heimes29eab552018-02-25 12:31:33 +0100197# define HAVE_NPN 0
198#endif
Christian Heimes6cdb7952018-02-24 22:12:40 +0100199
Christian Heimesc7f70692019-05-31 11:44:05 +0200200#if (OPENSSL_VERSION_NUMBER >= 0x10101000L) && !defined(LIBRESSL_VERSION_NUMBER)
201#define HAVE_OPENSSL_KEYLOG 1
202#endif
203
Victor Stinner524714e2016-07-22 17:43:59 +0200204#ifndef INVALID_SOCKET /* MS defines this */
205#define INVALID_SOCKET (-1)
206#endif
207
Christian Heimes4ca07392018-03-24 15:41:37 +0100208/* OpenSSL 1.0.2 and LibreSSL needs extra code for locking */
209#ifndef OPENSSL_VERSION_1_1
210#define HAVE_OPENSSL_CRYPTO_LOCK
211#endif
212
213#if defined(OPENSSL_VERSION_1_1) && !defined(OPENSSL_NO_SSL2)
Christian Heimes598894f2016-09-05 23:19:05 +0200214#define OPENSSL_NO_SSL2
215#endif
Christian Heimes4ca07392018-03-24 15:41:37 +0100216
217#ifndef PY_OPENSSL_1_1_API
218/* OpenSSL 1.1 API shims for OpenSSL < 1.1.0 and LibreSSL < 2.7.0 */
Christian Heimes598894f2016-09-05 23:19:05 +0200219
220#define TLS_method SSLv23_method
Christian Heimes5fe668c2016-09-12 00:01:11 +0200221#define TLS_client_method SSLv23_client_method
222#define TLS_server_method SSLv23_server_method
Christian Heimesa871f692020-06-01 08:58:14 +0200223#define ASN1_STRING_get0_data ASN1_STRING_data
224#define X509_get0_notBefore X509_get_notBefore
225#define X509_get0_notAfter X509_get_notAfter
226#define OpenSSL_version_num SSLeay
227#define OpenSSL_version SSLeay_version
228#define OPENSSL_VERSION SSLEAY_VERSION
Christian Heimes598894f2016-09-05 23:19:05 +0200229
230static int X509_NAME_ENTRY_set(const X509_NAME_ENTRY *ne)
231{
232 return ne->set;
233}
234
235#ifndef OPENSSL_NO_COMP
Christian Heimesa5d07652016-09-24 10:48:05 +0200236/* LCOV_EXCL_START */
Christian Heimes598894f2016-09-05 23:19:05 +0200237static int COMP_get_type(const COMP_METHOD *meth)
238{
239 return meth->type;
240}
Christian Heimes1a63b9f2016-09-24 12:07:21 +0200241/* LCOV_EXCL_STOP */
Christian Heimes598894f2016-09-05 23:19:05 +0200242#endif
243
244static pem_password_cb *SSL_CTX_get_default_passwd_cb(SSL_CTX *ctx)
245{
246 return ctx->default_passwd_callback;
247}
248
249static void *SSL_CTX_get_default_passwd_cb_userdata(SSL_CTX *ctx)
250{
251 return ctx->default_passwd_callback_userdata;
252}
253
254static int X509_OBJECT_get_type(X509_OBJECT *x)
255{
256 return x->type;
257}
258
259static X509 *X509_OBJECT_get0_X509(X509_OBJECT *x)
260{
261 return x->data.x509;
262}
263
264static int BIO_up_ref(BIO *b)
265{
266 CRYPTO_add(&b->references, 1, CRYPTO_LOCK_BIO);
267 return 1;
268}
269
270static STACK_OF(X509_OBJECT) *X509_STORE_get0_objects(X509_STORE *store) {
271 return store->objs;
272}
273
Christian Heimes99a65702016-09-10 23:44:53 +0200274static int
275SSL_SESSION_has_ticket(const SSL_SESSION *s)
276{
277 return (s->tlsext_ticklen > 0) ? 1 : 0;
278}
279
280static unsigned long
281SSL_SESSION_get_ticket_lifetime_hint(const SSL_SESSION *s)
282{
283 return s->tlsext_tick_lifetime_hint;
284}
285
Christian Heimes4ca07392018-03-24 15:41:37 +0100286#endif /* OpenSSL < 1.1.0 or LibreSSL < 2.7.0 */
Christian Heimes598894f2016-09-05 23:19:05 +0200287
Christian Heimes892d66e2018-01-29 14:10:18 +0100288/* Default cipher suites */
289#ifndef PY_SSL_DEFAULT_CIPHERS
290#define PY_SSL_DEFAULT_CIPHERS 1
291#endif
292
293#if PY_SSL_DEFAULT_CIPHERS == 0
294 #ifndef PY_SSL_DEFAULT_CIPHER_STRING
295 #error "Py_SSL_DEFAULT_CIPHERS 0 needs Py_SSL_DEFAULT_CIPHER_STRING"
296 #endif
297#elif PY_SSL_DEFAULT_CIPHERS == 1
Stéphane Wirtel07fbbfd2018-10-05 16:17:18 +0200298/* Python custom selection of sensible cipher suites
Christian Heimes892d66e2018-01-29 14:10:18 +0100299 * DEFAULT: OpenSSL's default cipher list. Since 1.0.2 the list is in sensible order.
300 * !aNULL:!eNULL: really no NULL ciphers
301 * !MD5:!3DES:!DES:!RC4:!IDEA:!SEED: no weak or broken algorithms on old OpenSSL versions.
302 * !aDSS: no authentication with discrete logarithm DSA algorithm
303 * !SRP:!PSK: no secure remote password or pre-shared key authentication
304 */
305 #define PY_SSL_DEFAULT_CIPHER_STRING "DEFAULT:!aNULL:!eNULL:!MD5:!3DES:!DES:!RC4:!IDEA:!SEED:!aDSS:!SRP:!PSK"
306#elif PY_SSL_DEFAULT_CIPHERS == 2
307/* Ignored in SSLContext constructor, only used to as _ssl.DEFAULT_CIPHER_STRING */
308 #define PY_SSL_DEFAULT_CIPHER_STRING SSL_DEFAULT_CIPHER_LIST
309#else
310 #error "Unsupported PY_SSL_DEFAULT_CIPHERS"
311#endif
312
Christian Heimes598894f2016-09-05 23:19:05 +0200313
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000314enum py_ssl_error {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000315 /* these mirror ssl.h */
316 PY_SSL_ERROR_NONE,
317 PY_SSL_ERROR_SSL,
318 PY_SSL_ERROR_WANT_READ,
319 PY_SSL_ERROR_WANT_WRITE,
320 PY_SSL_ERROR_WANT_X509_LOOKUP,
321 PY_SSL_ERROR_SYSCALL, /* look at error stack/return value/errno */
322 PY_SSL_ERROR_ZERO_RETURN,
323 PY_SSL_ERROR_WANT_CONNECT,
324 /* start of non ssl.h errorcodes */
325 PY_SSL_ERROR_EOF, /* special case of SSL_ERROR_SYSCALL */
326 PY_SSL_ERROR_NO_SOCKET, /* socket has been GC'd */
327 PY_SSL_ERROR_INVALID_ERROR_CODE
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000328};
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000329
Thomas Woutersed03b412007-08-28 21:37:11 +0000330enum py_ssl_server_or_client {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000331 PY_SSL_CLIENT,
332 PY_SSL_SERVER
Thomas Woutersed03b412007-08-28 21:37:11 +0000333};
334
335enum py_ssl_cert_requirements {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000336 PY_SSL_CERT_NONE,
337 PY_SSL_CERT_OPTIONAL,
338 PY_SSL_CERT_REQUIRED
Thomas Woutersed03b412007-08-28 21:37:11 +0000339};
340
341enum py_ssl_version {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000342 PY_SSL_VERSION_SSL2,
Victor Stinner3de49192011-05-09 00:42:58 +0200343 PY_SSL_VERSION_SSL3=1,
Christian Heimes5fe668c2016-09-12 00:01:11 +0200344 PY_SSL_VERSION_TLS, /* SSLv23 */
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100345 PY_SSL_VERSION_TLS1,
346 PY_SSL_VERSION_TLS1_1,
Christian Heimes5fe668c2016-09-12 00:01:11 +0200347 PY_SSL_VERSION_TLS1_2,
Christian Heimes5fe668c2016-09-12 00:01:11 +0200348 PY_SSL_VERSION_TLS_CLIENT=0x10,
349 PY_SSL_VERSION_TLS_SERVER,
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100350};
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200351
Christian Heimes698dde12018-02-27 11:54:43 +0100352enum py_proto_version {
353 PY_PROTO_MINIMUM_SUPPORTED = -2,
354 PY_PROTO_SSLv3 = SSL3_VERSION,
355 PY_PROTO_TLSv1 = TLS1_VERSION,
356 PY_PROTO_TLSv1_1 = TLS1_1_VERSION,
357 PY_PROTO_TLSv1_2 = TLS1_2_VERSION,
358#ifdef TLS1_3_VERSION
359 PY_PROTO_TLSv1_3 = TLS1_3_VERSION,
360#else
361 PY_PROTO_TLSv1_3 = 0x304,
362#endif
363 PY_PROTO_MAXIMUM_SUPPORTED = -1,
364
365/* OpenSSL has no dedicated API to set the minimum version to the maximum
366 * available version, and the other way around. We have to figure out the
367 * minimum and maximum available version on our own and hope for the best.
368 */
369#if defined(SSL3_VERSION) && !defined(OPENSSL_NO_SSL3)
370 PY_PROTO_MINIMUM_AVAILABLE = PY_PROTO_SSLv3,
371#elif defined(TLS1_VERSION) && !defined(OPENSSL_NO_TLS1)
372 PY_PROTO_MINIMUM_AVAILABLE = PY_PROTO_TLSv1,
373#elif defined(TLS1_1_VERSION) && !defined(OPENSSL_NO_TLS1_1)
374 PY_PROTO_MINIMUM_AVAILABLE = PY_PROTO_TLSv1_1,
375#elif defined(TLS1_2_VERSION) && !defined(OPENSSL_NO_TLS1_2)
376 PY_PROTO_MINIMUM_AVAILABLE = PY_PROTO_TLSv1_2,
377#elif defined(TLS1_3_VERSION) && !defined(OPENSSL_NO_TLS1_3)
378 PY_PROTO_MINIMUM_AVAILABLE = PY_PROTO_TLSv1_3,
379#else
380 #error "PY_PROTO_MINIMUM_AVAILABLE not found"
381#endif
382
383#if defined(TLS1_3_VERSION) && !defined(OPENSSL_NO_TLS1_3)
384 PY_PROTO_MAXIMUM_AVAILABLE = PY_PROTO_TLSv1_3,
385#elif defined(TLS1_2_VERSION) && !defined(OPENSSL_NO_TLS1_2)
386 PY_PROTO_MAXIMUM_AVAILABLE = PY_PROTO_TLSv1_2,
387#elif defined(TLS1_1_VERSION) && !defined(OPENSSL_NO_TLS1_1)
388 PY_PROTO_MAXIMUM_AVAILABLE = PY_PROTO_TLSv1_1,
389#elif defined(TLS1_VERSION) && !defined(OPENSSL_NO_TLS1)
390 PY_PROTO_MAXIMUM_AVAILABLE = PY_PROTO_TLSv1,
391#elif defined(SSL3_VERSION) && !defined(OPENSSL_NO_SSL3)
392 PY_PROTO_MAXIMUM_AVAILABLE = PY_PROTO_SSLv3,
393#else
394 #error "PY_PROTO_MAXIMUM_AVAILABLE not found"
395#endif
396};
397
398
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000399/* serves as a flag to see whether we've initialized the SSL thread support. */
400/* 0 means no, greater than 0 means yes */
401
402static unsigned int _ssl_locks_count = 0;
403
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000404/* SSL socket object */
405
406#define X509_NAME_MAXLEN 256
407
Gregory P. Smithbd4dacb2010-10-13 03:53:21 +0000408/* SSL_CTX_clear_options() and SSL_clear_options() were first added in
409 * OpenSSL 0.9.8m but do not appear in some 0.9.9-dev versions such the
410 * 0.9.9 from "May 2008" that NetBSD 5.0 uses. */
411#if OPENSSL_VERSION_NUMBER >= 0x009080dfL && OPENSSL_VERSION_NUMBER != 0x00909000L
Antoine Pitroub5218772010-05-21 09:56:06 +0000412# define HAVE_SSL_CTX_CLEAR_OPTIONS
413#else
414# undef HAVE_SSL_CTX_CLEAR_OPTIONS
415#endif
416
Antoine Pitroud6494802011-07-21 01:11:30 +0200417/* In case of 'tls-unique' it will be 12 bytes for TLS, 36 bytes for
418 * older SSL, but let's be safe */
419#define PySSL_CB_MAXLEN 128
420
Antoine Pitroua9bf2ac2012-02-17 18:47:54 +0100421
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000422typedef struct {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000423 PyObject_HEAD
Antoine Pitrou152efa22010-05-16 18:19:27 +0000424 SSL_CTX *ctx;
Christian Heimes29eab552018-02-25 12:31:33 +0100425#if HAVE_NPN
Benjamin Petersoncca27322015-01-23 16:35:37 -0500426 unsigned char *npn_protocols;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100427 int npn_protocols_len;
428#endif
Christian Heimes29eab552018-02-25 12:31:33 +0100429#if HAVE_ALPN
Benjamin Petersoncca27322015-01-23 16:35:37 -0500430 unsigned char *alpn_protocols;
Segev Finer5cff6372017-07-27 01:19:17 +0300431 unsigned int alpn_protocols_len;
Benjamin Petersoncca27322015-01-23 16:35:37 -0500432#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100433#ifndef OPENSSL_NO_TLSEXT
Christian Heimes11a14932018-02-24 02:35:08 +0100434 PyObject *set_sni_cb;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100435#endif
Christian Heimes1aa9a752013-12-02 02:41:19 +0100436 int check_hostname;
Christian Heimes61d478c2018-01-27 15:51:38 +0100437 /* OpenSSL has no API to get hostflags from X509_VERIFY_PARAM* struct.
438 * We have to maintain our own copy. OpenSSL's hostflags default to 0.
439 */
440 unsigned int hostflags;
Christian Heimes11a14932018-02-24 02:35:08 +0100441 int protocol;
Christian Heimes9fb051f2018-09-23 08:32:31 +0200442#ifdef TLS1_3_VERSION
443 int post_handshake_auth;
444#endif
Christian Heimesc7f70692019-05-31 11:44:05 +0200445 PyObject *msg_cb;
446#ifdef HAVE_OPENSSL_KEYLOG
447 PyObject *keylog_filename;
448 BIO *keylog_bio;
449#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +0000450} PySSLContext;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000451
Antoine Pitrou152efa22010-05-16 18:19:27 +0000452typedef struct {
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700453 int ssl; /* last seen error from SSL */
454 int c; /* last seen error from libc */
455#ifdef MS_WINDOWS
456 int ws; /* last seen error from winsock */
457#endif
458} _PySSLError;
459
460typedef struct {
Antoine Pitrou152efa22010-05-16 18:19:27 +0000461 PyObject_HEAD
462 PyObject *Socket; /* weakref to socket on which we're layered */
463 SSL *ssl;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100464 PySSLContext *ctx; /* weakref to SSL context */
Antoine Pitrou20b85552013-09-29 19:50:53 +0200465 char shutdown_seen_zero;
Antoine Pitroud6494802011-07-21 01:11:30 +0200466 enum py_ssl_server_or_client socket_type;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200467 PyObject *owner; /* Python level "owner" passed to servername callback */
468 PyObject *server_hostname;
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700469 _PySSLError err; /* last seen error from various sources */
Christian Heimesc7f70692019-05-31 11:44:05 +0200470 /* Some SSL callbacks don't have error reporting. Callback wrappers
471 * store exception information on the socket. The handshake, read, write,
472 * and shutdown methods check for chained exceptions.
473 */
474 PyObject *exc_type;
475 PyObject *exc_value;
476 PyObject *exc_tb;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000477} PySSLSocket;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000478
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200479typedef struct {
480 PyObject_HEAD
481 BIO *bio;
482 int eof_written;
483} PySSLMemoryBIO;
484
Christian Heimes99a65702016-09-10 23:44:53 +0200485typedef struct {
486 PyObject_HEAD
487 SSL_SESSION *session;
488 PySSLContext *ctx;
489} PySSLSession;
490
Christian Heimes5c36da72020-11-20 09:40:12 +0100491static PyTypeObject *PySSLContext_Type;
492static PyTypeObject *PySSLSocket_Type;
493static PyTypeObject *PySSLMemoryBIO_Type;
494static PyTypeObject *PySSLSession_Type;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000495
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700496static inline _PySSLError _PySSL_errno(int failed, const SSL *ssl, int retcode)
497{
498 _PySSLError err = { 0 };
499 if (failed) {
Steve Dowere6eb48c2017-09-08 15:16:15 -0700500#ifdef MS_WINDOWS
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700501 err.ws = WSAGetLastError();
502 _PySSL_FIX_ERRNO;
Steve Dowere6eb48c2017-09-08 15:16:15 -0700503#endif
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700504 err.c = errno;
505 err.ssl = SSL_get_error(ssl, retcode);
506 }
507 return err;
508}
Steve Dowere6eb48c2017-09-08 15:16:15 -0700509
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +0300510/*[clinic input]
511module _ssl
Christian Heimes5c36da72020-11-20 09:40:12 +0100512class _ssl._SSLContext "PySSLContext *" "PySSLContext_Type"
513class _ssl._SSLSocket "PySSLSocket *" "PySSLSocket_Type"
514class _ssl.MemoryBIO "PySSLMemoryBIO *" "PySSLMemoryBIO_Type"
515class _ssl.SSLSession "PySSLSession *" "PySSLSession_Type"
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +0300516[clinic start generated code]*/
Christian Heimes5c36da72020-11-20 09:40:12 +0100517/*[clinic end generated code: output=da39a3ee5e6b4b0d input=cc4883756da17954]*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +0300518
519#include "clinic/_ssl.c.h"
520
Victor Stinner14690702015-04-06 22:46:13 +0200521static int PySSL_select(PySocketSockObject *s, int writing, _PyTime_t timeout);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000522
Christian Heimes141c5e82018-02-24 21:10:57 +0100523static int PySSL_set_owner(PySSLSocket *, PyObject *, void *);
524static int PySSL_set_session(PySSLSocket *, PyObject *, void *);
Christian Heimes5c36da72020-11-20 09:40:12 +0100525#define PySSLSocket_Check(v) Py_IS_TYPE(v, PySSLSocket_Type)
526#define PySSLMemoryBIO_Check(v) Py_IS_TYPE(v, PySSLMemoryBIO_Type)
527#define PySSLSession_Check(v) Py_IS_TYPE(v, PySSLSession_Type)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000528
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000529typedef enum {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000530 SOCKET_IS_NONBLOCKING,
531 SOCKET_IS_BLOCKING,
532 SOCKET_HAS_TIMED_OUT,
533 SOCKET_HAS_BEEN_CLOSED,
534 SOCKET_TOO_LARGE_FOR_SELECT,
535 SOCKET_OPERATION_OK
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000536} timeout_state;
537
Thomas Woutersed03b412007-08-28 21:37:11 +0000538/* Wrap error strings with filename and line # */
Thomas Woutersed03b412007-08-28 21:37:11 +0000539#define ERRSTR1(x,y,z) (x ":" y ": " z)
Victor Stinner45e8e2f2014-05-14 17:24:35 +0200540#define ERRSTR(x) ERRSTR1("_ssl.c", Py_STRINGIFY(__LINE__), x)
Thomas Woutersed03b412007-08-28 21:37:11 +0000541
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200542/* Get the socket from a PySSLSocket, if it has one */
543#define GET_SOCKET(obj) ((obj)->Socket ? \
544 (PySocketSockObject *) PyWeakref_GetObject((obj)->Socket) : NULL)
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200545
Victor Stinner14690702015-04-06 22:46:13 +0200546/* If sock is NULL, use a timeout of 0 second */
547#define GET_SOCKET_TIMEOUT(sock) \
548 ((sock != NULL) ? (sock)->sock_timeout : 0)
549
Christian Heimesc7f70692019-05-31 11:44:05 +0200550#include "_ssl/debughelpers.c"
551
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200552/*
553 * SSL errors.
554 */
555
556PyDoc_STRVAR(SSLError_doc,
557"An error occurred in the SSL implementation.");
558
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700559PyDoc_STRVAR(SSLCertVerificationError_doc,
560"A certificate could not be verified.");
561
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200562PyDoc_STRVAR(SSLZeroReturnError_doc,
563"SSL/TLS session closed cleanly.");
564
565PyDoc_STRVAR(SSLWantReadError_doc,
566"Non-blocking SSL socket needs to read more data\n"
567"before the requested operation can be completed.");
568
569PyDoc_STRVAR(SSLWantWriteError_doc,
570"Non-blocking SSL socket needs to write more data\n"
571"before the requested operation can be completed.");
572
573PyDoc_STRVAR(SSLSyscallError_doc,
574"System error when attempting SSL operation.");
575
576PyDoc_STRVAR(SSLEOFError_doc,
577"SSL/TLS connection terminated abruptly.");
578
579static PyObject *
580SSLError_str(PyOSErrorObject *self)
581{
582 if (self->strerror != NULL && PyUnicode_Check(self->strerror)) {
583 Py_INCREF(self->strerror);
584 return self->strerror;
585 }
586 else
587 return PyObject_Str(self->args);
588}
589
590static PyType_Slot sslerror_type_slots[] = {
Inada Naoki926b0cb2019-04-17 08:39:46 +0900591 {Py_tp_doc, (void*)SSLError_doc},
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200592 {Py_tp_str, SSLError_str},
593 {0, 0},
594};
595
596static PyType_Spec sslerror_type_spec = {
597 "ssl.SSLError",
598 sizeof(PyOSErrorObject),
599 0,
600 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
601 sslerror_type_slots
602};
603
604static void
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700605fill_and_set_sslerror(PySSLSocket *sslsock, PyObject *type, int ssl_errno,
606 const char *errstr, int lineno, unsigned long errcode)
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200607{
608 PyObject *err_value = NULL, *reason_obj = NULL, *lib_obj = NULL;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700609 PyObject *verify_obj = NULL, *verify_code_obj = NULL;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200610 PyObject *init_value, *msg, *key;
611 _Py_IDENTIFIER(reason);
612 _Py_IDENTIFIER(library);
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700613 _Py_IDENTIFIER(verify_message);
614 _Py_IDENTIFIER(verify_code);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200615
616 if (errcode != 0) {
617 int lib, reason;
618
619 lib = ERR_GET_LIB(errcode);
620 reason = ERR_GET_REASON(errcode);
621 key = Py_BuildValue("ii", lib, reason);
622 if (key == NULL)
623 goto fail;
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +0300624 reason_obj = PyDict_GetItemWithError(err_codes_to_names, key);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200625 Py_DECREF(key);
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +0300626 if (reason_obj == NULL && PyErr_Occurred()) {
627 goto fail;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200628 }
629 key = PyLong_FromLong(lib);
630 if (key == NULL)
631 goto fail;
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +0300632 lib_obj = PyDict_GetItemWithError(lib_codes_to_names, key);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200633 Py_DECREF(key);
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +0300634 if (lib_obj == NULL && PyErr_Occurred()) {
635 goto fail;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200636 }
637 if (errstr == NULL)
638 errstr = ERR_reason_error_string(errcode);
639 }
640 if (errstr == NULL)
641 errstr = "unknown error";
642
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700643 /* verify code for cert validation error */
644 if ((sslsock != NULL) && (type == PySSLCertVerificationErrorObject)) {
645 const char *verify_str = NULL;
646 long verify_code;
647
648 verify_code = SSL_get_verify_result(sslsock->ssl);
649 verify_code_obj = PyLong_FromLong(verify_code);
650 if (verify_code_obj == NULL) {
651 goto fail;
652 }
653
654 switch (verify_code) {
Christian Heimes09153602017-09-08 14:47:58 -0700655#ifdef X509_V_ERR_HOSTNAME_MISMATCH
656 /* OpenSSL >= 1.0.2, LibreSSL >= 2.5.3 */
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700657 case X509_V_ERR_HOSTNAME_MISMATCH:
658 verify_obj = PyUnicode_FromFormat(
659 "Hostname mismatch, certificate is not valid for '%S'.",
660 sslsock->server_hostname
661 );
662 break;
Christian Heimes09153602017-09-08 14:47:58 -0700663#endif
664#ifdef X509_V_ERR_IP_ADDRESS_MISMATCH
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700665 case X509_V_ERR_IP_ADDRESS_MISMATCH:
666 verify_obj = PyUnicode_FromFormat(
667 "IP address mismatch, certificate is not valid for '%S'.",
668 sslsock->server_hostname
669 );
670 break;
Christian Heimes09153602017-09-08 14:47:58 -0700671#endif
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700672 default:
673 verify_str = X509_verify_cert_error_string(verify_code);
674 if (verify_str != NULL) {
675 verify_obj = PyUnicode_FromString(verify_str);
676 } else {
677 verify_obj = Py_None;
678 Py_INCREF(verify_obj);
679 }
680 break;
681 }
682 if (verify_obj == NULL) {
683 goto fail;
684 }
685 }
686
687 if (verify_obj && reason_obj && lib_obj)
688 msg = PyUnicode_FromFormat("[%S: %S] %s: %S (_ssl.c:%d)",
689 lib_obj, reason_obj, errstr, verify_obj,
690 lineno);
691 else if (reason_obj && lib_obj)
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200692 msg = PyUnicode_FromFormat("[%S: %S] %s (_ssl.c:%d)",
693 lib_obj, reason_obj, errstr, lineno);
694 else if (lib_obj)
695 msg = PyUnicode_FromFormat("[%S] %s (_ssl.c:%d)",
696 lib_obj, errstr, lineno);
697 else
698 msg = PyUnicode_FromFormat("%s (_ssl.c:%d)", errstr, lineno);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200699 if (msg == NULL)
700 goto fail;
Victor Stinnerba9be472013-10-31 15:00:24 +0100701
Paul Monsonfb7e7502019-05-15 15:38:55 -0700702 init_value = Py_BuildValue("iN", ERR_GET_REASON(ssl_errno), msg);
Victor Stinnerba9be472013-10-31 15:00:24 +0100703 if (init_value == NULL)
704 goto fail;
705
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200706 err_value = PyObject_CallObject(type, init_value);
707 Py_DECREF(init_value);
708 if (err_value == NULL)
709 goto fail;
Victor Stinnerba9be472013-10-31 15:00:24 +0100710
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200711 if (reason_obj == NULL)
712 reason_obj = Py_None;
713 if (_PyObject_SetAttrId(err_value, &PyId_reason, reason_obj))
714 goto fail;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700715
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200716 if (lib_obj == NULL)
717 lib_obj = Py_None;
718 if (_PyObject_SetAttrId(err_value, &PyId_library, lib_obj))
719 goto fail;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700720
721 if ((sslsock != NULL) && (type == PySSLCertVerificationErrorObject)) {
722 /* Only set verify code / message for SSLCertVerificationError */
723 if (_PyObject_SetAttrId(err_value, &PyId_verify_code,
724 verify_code_obj))
725 goto fail;
726 if (_PyObject_SetAttrId(err_value, &PyId_verify_message, verify_obj))
727 goto fail;
728 }
729
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200730 PyErr_SetObject(type, err_value);
731fail:
732 Py_XDECREF(err_value);
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700733 Py_XDECREF(verify_code_obj);
734 Py_XDECREF(verify_obj);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200735}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000736
Christian Heimesc7f70692019-05-31 11:44:05 +0200737static int
738PySSL_ChainExceptions(PySSLSocket *sslsock) {
739 if (sslsock->exc_type == NULL)
740 return 0;
741
742 _PyErr_ChainExceptions(sslsock->exc_type, sslsock->exc_value, sslsock->exc_tb);
743 sslsock->exc_type = NULL;
744 sslsock->exc_value = NULL;
745 sslsock->exc_tb = NULL;
746 return -1;
747}
748
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000749static PyObject *
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700750PySSL_SetError(PySSLSocket *sslsock, int ret, const char *filename, int lineno)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000751{
Antoine Pitrou41032a62011-10-27 23:56:55 +0200752 PyObject *type = PySSLErrorObject;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200753 char *errstr = NULL;
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700754 _PySSLError err;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000755 enum py_ssl_error p = PY_SSL_ERROR_NONE;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200756 unsigned long e = 0;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000757
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000758 assert(ret <= 0);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200759 e = ERR_peek_last_error();
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000760
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700761 if (sslsock->ssl != NULL) {
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700762 err = sslsock->err;
Thomas Woutersed03b412007-08-28 21:37:11 +0000763
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700764 switch (err.ssl) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000765 case SSL_ERROR_ZERO_RETURN:
Antoine Pitrou41032a62011-10-27 23:56:55 +0200766 errstr = "TLS/SSL connection has been closed (EOF)";
767 type = PySSLZeroReturnErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000768 p = PY_SSL_ERROR_ZERO_RETURN;
769 break;
770 case SSL_ERROR_WANT_READ:
771 errstr = "The operation did not complete (read)";
Antoine Pitrou41032a62011-10-27 23:56:55 +0200772 type = PySSLWantReadErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000773 p = PY_SSL_ERROR_WANT_READ;
774 break;
775 case SSL_ERROR_WANT_WRITE:
776 p = PY_SSL_ERROR_WANT_WRITE;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200777 type = PySSLWantWriteErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000778 errstr = "The operation did not complete (write)";
779 break;
780 case SSL_ERROR_WANT_X509_LOOKUP:
781 p = PY_SSL_ERROR_WANT_X509_LOOKUP;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000782 errstr = "The operation did not complete (X509 lookup)";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000783 break;
784 case SSL_ERROR_WANT_CONNECT:
785 p = PY_SSL_ERROR_WANT_CONNECT;
786 errstr = "The operation did not complete (connect)";
787 break;
788 case SSL_ERROR_SYSCALL:
789 {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000790 if (e == 0) {
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700791 PySocketSockObject *s = GET_SOCKET(sslsock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000792 if (ret == 0 || (((PyObject *)s) == Py_None)) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000793 p = PY_SSL_ERROR_EOF;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200794 type = PySSLEOFErrorObject;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000795 errstr = "EOF occurred in violation of protocol";
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200796 } else if (s && ret == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000797 /* underlying BIO reported an I/O error */
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000798 ERR_clear_error();
Steve Dowere6eb48c2017-09-08 15:16:15 -0700799#ifdef MS_WINDOWS
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700800 if (err.ws) {
801 return PyErr_SetFromWindowsErr(err.ws);
802 }
Steve Dowere6eb48c2017-09-08 15:16:15 -0700803#endif
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700804 if (err.c) {
805 errno = err.c;
Steve Dowere6eb48c2017-09-08 15:16:15 -0700806 return PyErr_SetFromErrno(PyExc_OSError);
807 }
Dima Tisnek495bd032020-08-16 02:01:19 +0900808 else {
809 p = PY_SSL_ERROR_EOF;
810 type = PySSLEOFErrorObject;
811 errstr = "EOF occurred in violation of protocol";
812 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000813 } else { /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000814 p = PY_SSL_ERROR_SYSCALL;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200815 type = PySSLSyscallErrorObject;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000816 errstr = "Some I/O error occurred";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000817 }
818 } else {
819 p = PY_SSL_ERROR_SYSCALL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000820 }
821 break;
822 }
823 case SSL_ERROR_SSL:
824 {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000825 p = PY_SSL_ERROR_SSL;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700826 if (e == 0) {
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200827 /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000828 errstr = "A failure in the SSL library occurred";
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700829 }
830 if (ERR_GET_LIB(e) == ERR_LIB_SSL &&
831 ERR_GET_REASON(e) == SSL_R_CERTIFICATE_VERIFY_FAILED) {
832 type = PySSLCertVerificationErrorObject;
833 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000834 break;
835 }
836 default:
837 p = PY_SSL_ERROR_INVALID_ERROR_CODE;
838 errstr = "Invalid error code";
839 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000840 }
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700841 fill_and_set_sslerror(sslsock, type, p, errstr, lineno, e);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000842 ERR_clear_error();
Christian Heimesc7f70692019-05-31 11:44:05 +0200843 PySSL_ChainExceptions(sslsock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000844 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000845}
846
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000847static PyObject *
Serhiy Storchakaef1585e2015-12-25 20:01:53 +0200848_setSSLError (const char *errstr, int errcode, const char *filename, int lineno) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000849
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200850 if (errstr == NULL)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000851 errcode = ERR_peek_last_error();
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200852 else
853 errcode = 0;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700854 fill_and_set_sslerror(NULL, PySSLErrorObject, errcode, errstr, lineno, errcode);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000855 ERR_clear_error();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000856 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000857}
858
Christian Heimes61d478c2018-01-27 15:51:38 +0100859/*
860 * SSL objects
861 */
862
863static int
864_ssl_configure_hostname(PySSLSocket *self, const char* server_hostname)
865{
866 int retval = -1;
867 ASN1_OCTET_STRING *ip;
868 PyObject *hostname;
869 size_t len;
870
871 assert(server_hostname);
872
873 /* Disable OpenSSL's special mode with leading dot in hostname:
874 * When name starts with a dot (e.g ".example.com"), it will be
875 * matched by a certificate valid for any sub-domain of name.
876 */
877 len = strlen(server_hostname);
878 if (len == 0 || *server_hostname == '.') {
879 PyErr_SetString(
880 PyExc_ValueError,
881 "server_hostname cannot be an empty string or start with a "
882 "leading dot.");
883 return retval;
884 }
885
886 /* inet_pton is not available on all platforms. */
887 ip = a2i_IPADDRESS(server_hostname);
888 if (ip == NULL) {
889 ERR_clear_error();
890 }
891
Christian Heimes11a14932018-02-24 02:35:08 +0100892 hostname = PyUnicode_Decode(server_hostname, len, "ascii", "strict");
Christian Heimes61d478c2018-01-27 15:51:38 +0100893 if (hostname == NULL) {
894 goto error;
895 }
896 self->server_hostname = hostname;
897
898 /* Only send SNI extension for non-IP hostnames */
899 if (ip == NULL) {
900 if (!SSL_set_tlsext_host_name(self->ssl, server_hostname)) {
901 _setSSLError(NULL, 0, __FILE__, __LINE__);
Zackery Spytzc32f2972020-10-25 12:02:30 -0600902 goto error;
Christian Heimes61d478c2018-01-27 15:51:38 +0100903 }
904 }
905 if (self->ctx->check_hostname) {
906 X509_VERIFY_PARAM *param = SSL_get0_param(self->ssl);
907 if (ip == NULL) {
Christian Heimesd02ac252018-03-25 12:36:13 +0200908 if (!X509_VERIFY_PARAM_set1_host(param, server_hostname,
909 strlen(server_hostname))) {
Christian Heimes61d478c2018-01-27 15:51:38 +0100910 _setSSLError(NULL, 0, __FILE__, __LINE__);
911 goto error;
912 }
913 } else {
Christian Heimesa871f692020-06-01 08:58:14 +0200914 if (!X509_VERIFY_PARAM_set1_ip(param, ASN1_STRING_get0_data(ip),
Christian Heimes61d478c2018-01-27 15:51:38 +0100915 ASN1_STRING_length(ip))) {
916 _setSSLError(NULL, 0, __FILE__, __LINE__);
917 goto error;
918 }
919 }
920 }
921 retval = 0;
922 error:
923 if (ip != NULL) {
924 ASN1_OCTET_STRING_free(ip);
925 }
926 return retval;
927}
928
Antoine Pitrou152efa22010-05-16 18:19:27 +0000929static PySSLSocket *
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100930newPySSLSocket(PySSLContext *sslctx, PySocketSockObject *sock,
Antoine Pitroud5323212010-10-22 18:19:07 +0000931 enum py_ssl_server_or_client socket_type,
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200932 char *server_hostname,
Christian Heimes141c5e82018-02-24 21:10:57 +0100933 PyObject *owner, PyObject *session,
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200934 PySSLMemoryBIO *inbio, PySSLMemoryBIO *outbio)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000935{
Antoine Pitrou152efa22010-05-16 18:19:27 +0000936 PySSLSocket *self;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100937 SSL_CTX *ctx = sslctx->ctx;
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700938 _PySSLError err = { 0 };
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000939
Christian Heimes5c36da72020-11-20 09:40:12 +0100940 self = PyObject_New(PySSLSocket, PySSLSocket_Type);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000941 if (self == NULL)
942 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000943
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000944 self->ssl = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000945 self->Socket = NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100946 self->ctx = sslctx;
Nathaniel J. Smith65ece7c2017-06-07 23:30:43 -0700947 Py_INCREF(sslctx);
Antoine Pitrou860aee72013-09-29 19:52:45 +0200948 self->shutdown_seen_zero = 0;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200949 self->owner = NULL;
Benjamin Peterson81b9ecd2016-08-15 21:55:37 -0700950 self->server_hostname = NULL;
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700951 self->err = err;
Christian Heimesc7f70692019-05-31 11:44:05 +0200952 self->exc_type = NULL;
953 self->exc_value = NULL;
954 self->exc_tb = NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200955
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000956 /* Make sure the SSL error state is initialized */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000957 ERR_clear_error();
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000958
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000959 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitrou152efa22010-05-16 18:19:27 +0000960 self->ssl = SSL_new(ctx);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000961 PySSL_END_ALLOW_THREADS
Zackery Spytz4c49da02018-12-07 03:11:30 -0700962 if (self->ssl == NULL) {
963 Py_DECREF(self);
964 _setSSLError(NULL, 0, __FILE__, __LINE__);
965 return NULL;
966 }
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200967 SSL_set_app_data(self->ssl, self);
968 if (sock) {
969 SSL_set_fd(self->ssl, Py_SAFE_DOWNCAST(sock->sock_fd, SOCKET_T, int));
970 } else {
971 /* BIOs are reference counted and SSL_set_bio borrows our reference.
972 * To prevent a double free in memory_bio_dealloc() we need to take an
973 * extra reference here. */
Christian Heimes598894f2016-09-05 23:19:05 +0200974 BIO_up_ref(inbio->bio);
975 BIO_up_ref(outbio->bio);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200976 SSL_set_bio(self->ssl, inbio->bio, outbio->bio);
977 }
Alex Gaynorf0422422018-05-14 11:51:45 -0400978 SSL_set_mode(self->ssl,
979 SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER | SSL_MODE_AUTO_RETRY);
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000980
Christian Heimesf0f59302019-07-01 08:29:17 +0200981#ifdef TLS1_3_VERSION
982 if (sslctx->post_handshake_auth == 1) {
983 if (socket_type == PY_SSL_SERVER) {
984 /* bpo-37428: OpenSSL does not ignore SSL_VERIFY_POST_HANDSHAKE.
985 * Set SSL_VERIFY_POST_HANDSHAKE flag only for server sockets and
986 * only in combination with SSL_VERIFY_PEER flag. */
987 int mode = SSL_get_verify_mode(self->ssl);
988 if (mode & SSL_VERIFY_PEER) {
989 int (*verify_cb)(int, X509_STORE_CTX *) = NULL;
990 verify_cb = SSL_get_verify_callback(self->ssl);
991 mode |= SSL_VERIFY_POST_HANDSHAKE;
992 SSL_set_verify(self->ssl, mode, verify_cb);
993 }
994 } else {
995 /* client socket */
996 SSL_set_post_handshake_auth(self->ssl, 1);
997 }
998 }
999#endif
1000
Christian Heimes61d478c2018-01-27 15:51:38 +01001001 if (server_hostname != NULL) {
1002 if (_ssl_configure_hostname(self, server_hostname) < 0) {
1003 Py_DECREF(self);
1004 return NULL;
1005 }
1006 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001007 /* If the socket is in non-blocking mode or timeout mode, set the BIO
1008 * to non-blocking mode (blocking is the default)
1009 */
Victor Stinnere2452312015-03-28 03:00:46 +01001010 if (sock && sock->sock_timeout >= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001011 BIO_set_nbio(SSL_get_rbio(self->ssl), 1);
1012 BIO_set_nbio(SSL_get_wbio(self->ssl), 1);
1013 }
Guido van Rossum4f707ac2003-01-31 18:13:18 +00001014
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001015 PySSL_BEGIN_ALLOW_THREADS
1016 if (socket_type == PY_SSL_CLIENT)
1017 SSL_set_connect_state(self->ssl);
1018 else
1019 SSL_set_accept_state(self->ssl);
1020 PySSL_END_ALLOW_THREADS
Martin v. Löwis09c35f72002-07-28 09:57:45 +00001021
Antoine Pitroud6494802011-07-21 01:11:30 +02001022 self->socket_type = socket_type;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001023 if (sock != NULL) {
1024 self->Socket = PyWeakref_NewRef((PyObject *) sock, NULL);
1025 if (self->Socket == NULL) {
1026 Py_DECREF(self);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001027 return NULL;
1028 }
Victor Stinnera9eb38f2013-10-31 16:35:38 +01001029 }
Christian Heimes141c5e82018-02-24 21:10:57 +01001030 if (owner && owner != Py_None) {
1031 if (PySSL_set_owner(self, owner, NULL) == -1) {
1032 Py_DECREF(self);
1033 return NULL;
1034 }
1035 }
1036 if (session && session != Py_None) {
1037 if (PySSL_set_session(self, session, NULL) == -1) {
1038 Py_DECREF(self);
1039 return NULL;
1040 }
1041 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001042 return self;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001043}
1044
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001045/* SSL object methods */
1046
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001047/*[clinic input]
1048_ssl._SSLSocket.do_handshake
1049[clinic start generated code]*/
1050
1051static PyObject *
1052_ssl__SSLSocket_do_handshake_impl(PySSLSocket *self)
1053/*[clinic end generated code: output=6c0898a8936548f6 input=d2d737de3df018c8]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001054{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001055 int ret;
Steve Dowerc6fd1c12018-09-17 11:34:47 -07001056 _PySSLError err;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001057 int sockstate, nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001058 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02001059 _PyTime_t timeout, deadline = 0;
1060 int has_timeout;
Antoine Pitroud3f8ab82010-04-24 21:26:44 +00001061
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001062 if (sock) {
1063 if (((PyObject*)sock) == Py_None) {
1064 _setSSLError("Underlying socket connection gone",
1065 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1066 return NULL;
1067 }
1068 Py_INCREF(sock);
1069
1070 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01001071 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001072 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1073 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001074 }
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001075
Victor Stinner14690702015-04-06 22:46:13 +02001076 timeout = GET_SOCKET_TIMEOUT(sock);
1077 has_timeout = (timeout > 0);
1078 if (has_timeout)
1079 deadline = _PyTime_GetMonotonicClock() + timeout;
1080
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001081 /* Actually negotiate SSL connection */
1082 /* XXX If SSL_do_handshake() returns 0, it's also a failure. */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001083 do {
Bill Janssen6e027db2007-11-15 22:23:56 +00001084 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001085 ret = SSL_do_handshake(self->ssl);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07001086 err = _PySSL_errno(ret < 1, self->ssl, ret);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001087 PySSL_END_ALLOW_THREADS
Steve Dowerc6fd1c12018-09-17 11:34:47 -07001088 self->err = err;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001089
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001090 if (PyErr_CheckSignals())
1091 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001092
Victor Stinner14690702015-04-06 22:46:13 +02001093 if (has_timeout)
1094 timeout = deadline - _PyTime_GetMonotonicClock();
1095
Steve Dowerc6fd1c12018-09-17 11:34:47 -07001096 if (err.ssl == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +02001097 sockstate = PySSL_select(sock, 0, timeout);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07001098 } else if (err.ssl == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +02001099 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001100 } else {
1101 sockstate = SOCKET_OPERATION_OK;
1102 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001103
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001104 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Christian Heimes03c8ddd2020-11-20 09:26:07 +01001105 PyErr_SetString(PyExc_TimeoutError,
Antoine Pitrou525807b2010-05-12 14:05:24 +00001106 ERRSTR("The handshake operation timed out"));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001107 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001108 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1109 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +00001110 ERRSTR("Underlying socket has been closed."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001111 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001112 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1113 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +00001114 ERRSTR("Underlying socket too large for select()."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001115 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001116 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1117 break;
1118 }
Steve Dowerc6fd1c12018-09-17 11:34:47 -07001119 } while (err.ssl == SSL_ERROR_WANT_READ ||
1120 err.ssl == SSL_ERROR_WANT_WRITE);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001121 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001122 if (ret < 1)
1123 return PySSL_SetError(self, ret, __FILE__, __LINE__);
Christian Heimesc7f70692019-05-31 11:44:05 +02001124 if (PySSL_ChainExceptions(self) < 0)
1125 return NULL;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001126 Py_RETURN_NONE;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001127error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001128 Py_XDECREF(sock);
Christian Heimesc7f70692019-05-31 11:44:05 +02001129 PySSL_ChainExceptions(self);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001130 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001131}
1132
Thomas Woutersed03b412007-08-28 21:37:11 +00001133static PyObject *
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001134_asn1obj2py(const ASN1_OBJECT *name, int no_name)
1135{
1136 char buf[X509_NAME_MAXLEN];
1137 char *namebuf = buf;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001138 int buflen;
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001139 PyObject *name_obj = NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001140
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001141 buflen = OBJ_obj2txt(namebuf, X509_NAME_MAXLEN, name, no_name);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001142 if (buflen < 0) {
1143 _setSSLError(NULL, 0, __FILE__, __LINE__);
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001144 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001145 }
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001146 /* initial buffer is too small for oid + terminating null byte */
1147 if (buflen > X509_NAME_MAXLEN - 1) {
1148 /* make OBJ_obj2txt() calculate the required buflen */
1149 buflen = OBJ_obj2txt(NULL, 0, name, no_name);
1150 /* allocate len + 1 for terminating NULL byte */
1151 namebuf = PyMem_Malloc(buflen + 1);
1152 if (namebuf == NULL) {
1153 PyErr_NoMemory();
1154 return NULL;
1155 }
1156 buflen = OBJ_obj2txt(namebuf, buflen + 1, name, no_name);
1157 if (buflen < 0) {
1158 _setSSLError(NULL, 0, __FILE__, __LINE__);
1159 goto done;
1160 }
1161 }
1162 if (!buflen && no_name) {
1163 Py_INCREF(Py_None);
1164 name_obj = Py_None;
1165 }
1166 else {
1167 name_obj = PyUnicode_FromStringAndSize(namebuf, buflen);
1168 }
1169
1170 done:
1171 if (buf != namebuf) {
1172 PyMem_Free(namebuf);
1173 }
1174 return name_obj;
1175}
1176
1177static PyObject *
1178_create_tuple_for_attribute(ASN1_OBJECT *name, ASN1_STRING *value)
1179{
1180 Py_ssize_t buflen;
1181 unsigned char *valuebuf = NULL;
1182 PyObject *attr;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001183
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001184 buflen = ASN1_STRING_to_UTF8(&valuebuf, value);
1185 if (buflen < 0) {
1186 _setSSLError(NULL, 0, __FILE__, __LINE__);
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001187 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001188 }
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001189 attr = Py_BuildValue("Ns#", _asn1obj2py(name, 0), valuebuf, buflen);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001190 OPENSSL_free(valuebuf);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001191 return attr;
Thomas Woutersed03b412007-08-28 21:37:11 +00001192}
1193
1194static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001195_create_tuple_for_X509_NAME (X509_NAME *xname)
Thomas Woutersed03b412007-08-28 21:37:11 +00001196{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001197 PyObject *dn = NULL; /* tuple which represents the "distinguished name" */
1198 PyObject *rdn = NULL; /* tuple to hold a "relative distinguished name" */
1199 PyObject *rdnt;
1200 PyObject *attr = NULL; /* tuple to hold an attribute */
1201 int entry_count = X509_NAME_entry_count(xname);
1202 X509_NAME_ENTRY *entry;
1203 ASN1_OBJECT *name;
1204 ASN1_STRING *value;
1205 int index_counter;
1206 int rdn_level = -1;
1207 int retcode;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001208
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001209 dn = PyList_New(0);
1210 if (dn == NULL)
1211 return NULL;
1212 /* now create another tuple to hold the top-level RDN */
1213 rdn = PyList_New(0);
1214 if (rdn == NULL)
1215 goto fail0;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001216
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001217 for (index_counter = 0;
1218 index_counter < entry_count;
1219 index_counter++)
1220 {
1221 entry = X509_NAME_get_entry(xname, index_counter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001222
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001223 /* check to see if we've gotten to a new RDN */
1224 if (rdn_level >= 0) {
Christian Heimes598894f2016-09-05 23:19:05 +02001225 if (rdn_level != X509_NAME_ENTRY_set(entry)) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001226 /* yes, new RDN */
1227 /* add old RDN to DN */
1228 rdnt = PyList_AsTuple(rdn);
1229 Py_DECREF(rdn);
1230 if (rdnt == NULL)
1231 goto fail0;
1232 retcode = PyList_Append(dn, rdnt);
1233 Py_DECREF(rdnt);
1234 if (retcode < 0)
1235 goto fail0;
1236 /* create new RDN */
1237 rdn = PyList_New(0);
1238 if (rdn == NULL)
1239 goto fail0;
1240 }
1241 }
Christian Heimes598894f2016-09-05 23:19:05 +02001242 rdn_level = X509_NAME_ENTRY_set(entry);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001243
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001244 /* now add this attribute to the current RDN */
1245 name = X509_NAME_ENTRY_get_object(entry);
1246 value = X509_NAME_ENTRY_get_data(entry);
1247 attr = _create_tuple_for_attribute(name, value);
1248 /*
1249 fprintf(stderr, "RDN level %d, attribute %s: %s\n",
1250 entry->set,
1251 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 0)),
1252 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 1)));
1253 */
1254 if (attr == NULL)
1255 goto fail1;
1256 retcode = PyList_Append(rdn, attr);
1257 Py_DECREF(attr);
1258 if (retcode < 0)
1259 goto fail1;
1260 }
1261 /* now, there's typically a dangling RDN */
Antoine Pitrou2f5a1632012-02-15 22:25:27 +01001262 if (rdn != NULL) {
1263 if (PyList_GET_SIZE(rdn) > 0) {
1264 rdnt = PyList_AsTuple(rdn);
1265 Py_DECREF(rdn);
1266 if (rdnt == NULL)
1267 goto fail0;
1268 retcode = PyList_Append(dn, rdnt);
1269 Py_DECREF(rdnt);
1270 if (retcode < 0)
1271 goto fail0;
1272 }
1273 else {
1274 Py_DECREF(rdn);
1275 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001276 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001277
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001278 /* convert list to tuple */
1279 rdnt = PyList_AsTuple(dn);
1280 Py_DECREF(dn);
1281 if (rdnt == NULL)
1282 return NULL;
1283 return rdnt;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001284
1285 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001286 Py_XDECREF(rdn);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001287
1288 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001289 Py_XDECREF(dn);
1290 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001291}
1292
1293static PyObject *
1294_get_peer_alt_names (X509 *certificate) {
Guido van Rossumf06628b2007-11-21 20:01:53 +00001295
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001296 /* this code follows the procedure outlined in
1297 OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print()
1298 function to extract the STACK_OF(GENERAL_NAME),
1299 then iterates through the stack to add the
1300 names. */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001301
Alex Gaynorb87c0df2017-06-06 07:53:11 -04001302 int j;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001303 PyObject *peer_alt_names = Py_None;
Christian Heimes60bf2fc2013-09-05 16:04:35 +02001304 PyObject *v = NULL, *t;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001305 GENERAL_NAMES *names = NULL;
1306 GENERAL_NAME *name;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001307 BIO *biobuf = NULL;
1308 char buf[2048];
1309 char *vptr;
1310 int len;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001311
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001312 if (certificate == NULL)
1313 return peer_alt_names;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001314
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001315 /* get a memory buffer */
1316 biobuf = BIO_new(BIO_s_mem());
Zackery Spytz4c49da02018-12-07 03:11:30 -07001317 if (biobuf == NULL) {
1318 PyErr_SetString(PySSLErrorObject, "failed to allocate BIO");
1319 return NULL;
1320 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001321
Alex Gaynorb87c0df2017-06-06 07:53:11 -04001322 names = (GENERAL_NAMES *)X509_get_ext_d2i(
1323 certificate, NID_subject_alt_name, NULL, NULL);
1324 if (names != NULL) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001325 if (peer_alt_names == Py_None) {
1326 peer_alt_names = PyList_New(0);
1327 if (peer_alt_names == NULL)
1328 goto fail;
1329 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001330
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001331 for(j = 0; j < sk_GENERAL_NAME_num(names); j++) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001332 /* get a rendering of each name in the set of names */
Christian Heimes824f7f32013-08-17 00:54:47 +02001333 int gntype;
1334 ASN1_STRING *as = NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001335
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001336 name = sk_GENERAL_NAME_value(names, j);
Christian Heimes474afdd2013-08-17 17:18:56 +02001337 gntype = name->type;
Christian Heimes824f7f32013-08-17 00:54:47 +02001338 switch (gntype) {
1339 case GEN_DIRNAME:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001340 /* we special-case DirName as a tuple of
1341 tuples of attributes */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001342
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001343 t = PyTuple_New(2);
1344 if (t == NULL) {
1345 goto fail;
1346 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001347
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001348 v = PyUnicode_FromString("DirName");
1349 if (v == NULL) {
1350 Py_DECREF(t);
1351 goto fail;
1352 }
1353 PyTuple_SET_ITEM(t, 0, v);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001354
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001355 v = _create_tuple_for_X509_NAME (name->d.dirn);
1356 if (v == NULL) {
1357 Py_DECREF(t);
1358 goto fail;
1359 }
1360 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +02001361 break;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001362
Christian Heimes824f7f32013-08-17 00:54:47 +02001363 case GEN_EMAIL:
1364 case GEN_DNS:
1365 case GEN_URI:
1366 /* GENERAL_NAME_print() doesn't handle NULL bytes in ASN1_string
1367 correctly, CVE-2013-4238 */
1368 t = PyTuple_New(2);
1369 if (t == NULL)
1370 goto fail;
1371 switch (gntype) {
1372 case GEN_EMAIL:
1373 v = PyUnicode_FromString("email");
1374 as = name->d.rfc822Name;
1375 break;
1376 case GEN_DNS:
1377 v = PyUnicode_FromString("DNS");
1378 as = name->d.dNSName;
1379 break;
1380 case GEN_URI:
1381 v = PyUnicode_FromString("URI");
1382 as = name->d.uniformResourceIdentifier;
1383 break;
1384 }
1385 if (v == NULL) {
1386 Py_DECREF(t);
1387 goto fail;
1388 }
1389 PyTuple_SET_ITEM(t, 0, v);
Christian Heimesa871f692020-06-01 08:58:14 +02001390 v = PyUnicode_FromStringAndSize((char *)ASN1_STRING_get0_data(as),
Christian Heimes824f7f32013-08-17 00:54:47 +02001391 ASN1_STRING_length(as));
1392 if (v == NULL) {
1393 Py_DECREF(t);
1394 goto fail;
1395 }
1396 PyTuple_SET_ITEM(t, 1, v);
1397 break;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001398
Christian Heimes1c03abd2016-09-06 23:25:35 +02001399 case GEN_RID:
1400 t = PyTuple_New(2);
1401 if (t == NULL)
1402 goto fail;
1403
1404 v = PyUnicode_FromString("Registered ID");
1405 if (v == NULL) {
1406 Py_DECREF(t);
1407 goto fail;
1408 }
1409 PyTuple_SET_ITEM(t, 0, v);
1410
1411 len = i2t_ASN1_OBJECT(buf, sizeof(buf)-1, name->d.rid);
1412 if (len < 0) {
1413 Py_DECREF(t);
1414 _setSSLError(NULL, 0, __FILE__, __LINE__);
1415 goto fail;
1416 } else if (len >= (int)sizeof(buf)) {
1417 v = PyUnicode_FromString("<INVALID>");
1418 } else {
1419 v = PyUnicode_FromStringAndSize(buf, len);
1420 }
1421 if (v == NULL) {
1422 Py_DECREF(t);
1423 goto fail;
1424 }
1425 PyTuple_SET_ITEM(t, 1, v);
1426 break;
1427
Christian Heimes2b7de662019-12-07 17:59:36 +01001428 case GEN_IPADD:
1429 /* OpenSSL < 3.0.0 adds a trailing \n to IPv6. 3.0.0 removed
1430 * the trailing newline. Remove it in all versions
1431 */
1432 t = PyTuple_New(2);
1433 if (t == NULL)
1434 goto fail;
1435
1436 v = PyUnicode_FromString("IP Address");
1437 if (v == NULL) {
1438 Py_DECREF(t);
1439 goto fail;
1440 }
1441 PyTuple_SET_ITEM(t, 0, v);
1442
1443 if (name->d.ip->length == 4) {
1444 unsigned char *p = name->d.ip->data;
1445 v = PyUnicode_FromFormat(
1446 "%d.%d.%d.%d",
1447 p[0], p[1], p[2], p[3]
1448 );
1449 } else if (name->d.ip->length == 16) {
1450 /* PyUnicode_FromFormat() does not support %X */
1451 unsigned char *p = name->d.ip->data;
1452 len = sprintf(
1453 buf,
1454 "%X:%X:%X:%X:%X:%X:%X:%X",
1455 p[0] << 8 | p[1],
1456 p[2] << 8 | p[3],
1457 p[4] << 8 | p[5],
1458 p[6] << 8 | p[7],
1459 p[8] << 8 | p[9],
1460 p[10] << 8 | p[11],
1461 p[12] << 8 | p[13],
1462 p[14] << 8 | p[15]
1463 );
1464 v = PyUnicode_FromStringAndSize(buf, len);
1465 } else {
1466 v = PyUnicode_FromString("<invalid>");
1467 }
1468
1469 if (v == NULL) {
1470 Py_DECREF(t);
1471 goto fail;
1472 }
1473 PyTuple_SET_ITEM(t, 1, v);
1474 break;
1475
Christian Heimes824f7f32013-08-17 00:54:47 +02001476 default:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001477 /* for everything else, we use the OpenSSL print form */
Christian Heimes824f7f32013-08-17 00:54:47 +02001478 switch (gntype) {
1479 /* check for new general name type */
1480 case GEN_OTHERNAME:
1481 case GEN_X400:
1482 case GEN_EDIPARTY:
Christian Heimes824f7f32013-08-17 00:54:47 +02001483 case GEN_RID:
1484 break;
1485 default:
1486 if (PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
1487 "Unknown general name type %d",
1488 gntype) == -1) {
1489 goto fail;
1490 }
1491 break;
1492 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001493 (void) BIO_reset(biobuf);
1494 GENERAL_NAME_print(biobuf, name);
1495 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1496 if (len < 0) {
1497 _setSSLError(NULL, 0, __FILE__, __LINE__);
1498 goto fail;
1499 }
1500 vptr = strchr(buf, ':');
Christian Heimes1c03abd2016-09-06 23:25:35 +02001501 if (vptr == NULL) {
1502 PyErr_Format(PyExc_ValueError,
1503 "Invalid value %.200s",
1504 buf);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001505 goto fail;
Christian Heimes1c03abd2016-09-06 23:25:35 +02001506 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001507 t = PyTuple_New(2);
1508 if (t == NULL)
1509 goto fail;
1510 v = PyUnicode_FromStringAndSize(buf, (vptr - buf));
1511 if (v == NULL) {
1512 Py_DECREF(t);
1513 goto fail;
1514 }
1515 PyTuple_SET_ITEM(t, 0, v);
1516 v = PyUnicode_FromStringAndSize((vptr + 1),
1517 (len - (vptr - buf + 1)));
1518 if (v == NULL) {
1519 Py_DECREF(t);
1520 goto fail;
1521 }
1522 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +02001523 break;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001524 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001525
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001526 /* and add that rendering to the list */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001527
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001528 if (PyList_Append(peer_alt_names, t) < 0) {
1529 Py_DECREF(t);
1530 goto fail;
1531 }
1532 Py_DECREF(t);
1533 }
Antoine Pitrou116d6b92011-11-23 01:39:19 +01001534 sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001535 }
1536 BIO_free(biobuf);
1537 if (peer_alt_names != Py_None) {
1538 v = PyList_AsTuple(peer_alt_names);
1539 Py_DECREF(peer_alt_names);
1540 return v;
1541 } else {
1542 return peer_alt_names;
1543 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001544
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001545
1546 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001547 if (biobuf != NULL)
1548 BIO_free(biobuf);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001549
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001550 if (peer_alt_names != Py_None) {
1551 Py_XDECREF(peer_alt_names);
1552 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001553
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001554 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001555}
1556
1557static PyObject *
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001558_get_aia_uri(X509 *certificate, int nid) {
1559 PyObject *lst = NULL, *ostr = NULL;
1560 int i, result;
1561 AUTHORITY_INFO_ACCESS *info;
1562
1563 info = X509_get_ext_d2i(certificate, NID_info_access, NULL, NULL);
Benjamin Petersonf0c90382015-11-14 15:12:18 -08001564 if (info == NULL)
1565 return Py_None;
1566 if (sk_ACCESS_DESCRIPTION_num(info) == 0) {
1567 AUTHORITY_INFO_ACCESS_free(info);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001568 return Py_None;
1569 }
1570
1571 if ((lst = PyList_New(0)) == NULL) {
1572 goto fail;
1573 }
1574
1575 for (i = 0; i < sk_ACCESS_DESCRIPTION_num(info); i++) {
1576 ACCESS_DESCRIPTION *ad = sk_ACCESS_DESCRIPTION_value(info, i);
1577 ASN1_IA5STRING *uri;
1578
1579 if ((OBJ_obj2nid(ad->method) != nid) ||
1580 (ad->location->type != GEN_URI)) {
1581 continue;
1582 }
1583 uri = ad->location->d.uniformResourceIdentifier;
1584 ostr = PyUnicode_FromStringAndSize((char *)uri->data,
1585 uri->length);
1586 if (ostr == NULL) {
1587 goto fail;
1588 }
1589 result = PyList_Append(lst, ostr);
1590 Py_DECREF(ostr);
1591 if (result < 0) {
1592 goto fail;
1593 }
1594 }
1595 AUTHORITY_INFO_ACCESS_free(info);
1596
1597 /* convert to tuple or None */
1598 if (PyList_Size(lst) == 0) {
1599 Py_DECREF(lst);
1600 return Py_None;
1601 } else {
1602 PyObject *tup;
1603 tup = PyList_AsTuple(lst);
1604 Py_DECREF(lst);
1605 return tup;
1606 }
1607
1608 fail:
1609 AUTHORITY_INFO_ACCESS_free(info);
Christian Heimes18fc7be2013-11-21 23:57:49 +01001610 Py_XDECREF(lst);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001611 return NULL;
1612}
1613
1614static PyObject *
1615_get_crl_dp(X509 *certificate) {
1616 STACK_OF(DIST_POINT) *dps;
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001617 int i, j;
1618 PyObject *lst, *res = NULL;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001619
Christian Heimes598894f2016-09-05 23:19:05 +02001620 dps = X509_get_ext_d2i(certificate, NID_crl_distribution_points, NULL, NULL);
Christian Heimes949ec142013-11-21 16:26:51 +01001621
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001622 if (dps == NULL)
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001623 return Py_None;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001624
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001625 lst = PyList_New(0);
1626 if (lst == NULL)
1627 goto done;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001628
1629 for (i=0; i < sk_DIST_POINT_num(dps); i++) {
1630 DIST_POINT *dp;
1631 STACK_OF(GENERAL_NAME) *gns;
1632
1633 dp = sk_DIST_POINT_value(dps, i);
Christian Heimesa37f5242019-01-15 23:47:42 +01001634 if (dp->distpoint == NULL) {
1635 /* Ignore empty DP value, CVE-2019-5010 */
1636 continue;
1637 }
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001638 gns = dp->distpoint->name.fullname;
1639
1640 for (j=0; j < sk_GENERAL_NAME_num(gns); j++) {
1641 GENERAL_NAME *gn;
1642 ASN1_IA5STRING *uri;
1643 PyObject *ouri;
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001644 int err;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001645
1646 gn = sk_GENERAL_NAME_value(gns, j);
1647 if (gn->type != GEN_URI) {
1648 continue;
1649 }
1650 uri = gn->d.uniformResourceIdentifier;
1651 ouri = PyUnicode_FromStringAndSize((char *)uri->data,
1652 uri->length);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001653 if (ouri == NULL)
1654 goto done;
1655
1656 err = PyList_Append(lst, ouri);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001657 Py_DECREF(ouri);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001658 if (err < 0)
1659 goto done;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001660 }
1661 }
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001662
1663 /* Convert to tuple. */
1664 res = (PyList_GET_SIZE(lst) > 0) ? PyList_AsTuple(lst) : Py_None;
1665
1666 done:
1667 Py_XDECREF(lst);
Olivier Vielpeau2849cc32017-04-14 21:06:07 -04001668 CRL_DIST_POINTS_free(dps);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001669 return res;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001670}
1671
1672static PyObject *
Antoine Pitroufb046912010-11-09 20:21:19 +00001673_decode_certificate(X509 *certificate) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001674
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001675 PyObject *retval = NULL;
1676 BIO *biobuf = NULL;
1677 PyObject *peer;
1678 PyObject *peer_alt_names = NULL;
1679 PyObject *issuer;
1680 PyObject *version;
1681 PyObject *sn_obj;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001682 PyObject *obj;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001683 ASN1_INTEGER *serialNumber;
1684 char buf[2048];
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001685 int len, result;
Christian Heimesa871f692020-06-01 08:58:14 +02001686 const ASN1_TIME *notBefore, *notAfter;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001687 PyObject *pnotBefore, *pnotAfter;
Thomas Woutersed03b412007-08-28 21:37:11 +00001688
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001689 retval = PyDict_New();
1690 if (retval == NULL)
1691 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001692
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001693 peer = _create_tuple_for_X509_NAME(
1694 X509_get_subject_name(certificate));
1695 if (peer == NULL)
1696 goto fail0;
1697 if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) {
1698 Py_DECREF(peer);
1699 goto fail0;
1700 }
1701 Py_DECREF(peer);
Thomas Woutersed03b412007-08-28 21:37:11 +00001702
Antoine Pitroufb046912010-11-09 20:21:19 +00001703 issuer = _create_tuple_for_X509_NAME(
1704 X509_get_issuer_name(certificate));
1705 if (issuer == NULL)
1706 goto fail0;
1707 if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001708 Py_DECREF(issuer);
Antoine Pitroufb046912010-11-09 20:21:19 +00001709 goto fail0;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001710 }
Antoine Pitroufb046912010-11-09 20:21:19 +00001711 Py_DECREF(issuer);
1712
1713 version = PyLong_FromLong(X509_get_version(certificate) + 1);
Christian Heimes5962bef2013-07-26 15:51:18 +02001714 if (version == NULL)
1715 goto fail0;
Antoine Pitroufb046912010-11-09 20:21:19 +00001716 if (PyDict_SetItemString(retval, "version", version) < 0) {
1717 Py_DECREF(version);
1718 goto fail0;
1719 }
1720 Py_DECREF(version);
Guido van Rossumf06628b2007-11-21 20:01:53 +00001721
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001722 /* get a memory buffer */
1723 biobuf = BIO_new(BIO_s_mem());
Zackery Spytz4c49da02018-12-07 03:11:30 -07001724 if (biobuf == NULL) {
1725 PyErr_SetString(PySSLErrorObject, "failed to allocate BIO");
1726 goto fail0;
1727 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001728
Antoine Pitroufb046912010-11-09 20:21:19 +00001729 (void) BIO_reset(biobuf);
1730 serialNumber = X509_get_serialNumber(certificate);
1731 /* should not exceed 20 octets, 160 bits, so buf is big enough */
1732 i2a_ASN1_INTEGER(biobuf, serialNumber);
1733 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1734 if (len < 0) {
1735 _setSSLError(NULL, 0, __FILE__, __LINE__);
1736 goto fail1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001737 }
Antoine Pitroufb046912010-11-09 20:21:19 +00001738 sn_obj = PyUnicode_FromStringAndSize(buf, len);
1739 if (sn_obj == NULL)
1740 goto fail1;
1741 if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) {
1742 Py_DECREF(sn_obj);
1743 goto fail1;
1744 }
1745 Py_DECREF(sn_obj);
1746
1747 (void) BIO_reset(biobuf);
Christian Heimesa871f692020-06-01 08:58:14 +02001748 notBefore = X509_get0_notBefore(certificate);
Antoine Pitroufb046912010-11-09 20:21:19 +00001749 ASN1_TIME_print(biobuf, notBefore);
1750 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1751 if (len < 0) {
1752 _setSSLError(NULL, 0, __FILE__, __LINE__);
1753 goto fail1;
1754 }
1755 pnotBefore = PyUnicode_FromStringAndSize(buf, len);
1756 if (pnotBefore == NULL)
1757 goto fail1;
1758 if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) {
1759 Py_DECREF(pnotBefore);
1760 goto fail1;
1761 }
1762 Py_DECREF(pnotBefore);
Thomas Woutersed03b412007-08-28 21:37:11 +00001763
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001764 (void) BIO_reset(biobuf);
Christian Heimesa871f692020-06-01 08:58:14 +02001765 notAfter = X509_get0_notAfter(certificate);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001766 ASN1_TIME_print(biobuf, notAfter);
1767 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1768 if (len < 0) {
1769 _setSSLError(NULL, 0, __FILE__, __LINE__);
1770 goto fail1;
1771 }
1772 pnotAfter = PyUnicode_FromStringAndSize(buf, len);
1773 if (pnotAfter == NULL)
1774 goto fail1;
1775 if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) {
1776 Py_DECREF(pnotAfter);
1777 goto fail1;
1778 }
1779 Py_DECREF(pnotAfter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001780
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001781 /* Now look for subjectAltName */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001782
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001783 peer_alt_names = _get_peer_alt_names(certificate);
1784 if (peer_alt_names == NULL)
1785 goto fail1;
1786 else if (peer_alt_names != Py_None) {
1787 if (PyDict_SetItemString(retval, "subjectAltName",
1788 peer_alt_names) < 0) {
1789 Py_DECREF(peer_alt_names);
1790 goto fail1;
1791 }
1792 Py_DECREF(peer_alt_names);
1793 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001794
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001795 /* Authority Information Access: OCSP URIs */
1796 obj = _get_aia_uri(certificate, NID_ad_OCSP);
1797 if (obj == NULL) {
1798 goto fail1;
1799 } else if (obj != Py_None) {
1800 result = PyDict_SetItemString(retval, "OCSP", obj);
1801 Py_DECREF(obj);
1802 if (result < 0) {
1803 goto fail1;
1804 }
1805 }
1806
1807 obj = _get_aia_uri(certificate, NID_ad_ca_issuers);
1808 if (obj == NULL) {
1809 goto fail1;
1810 } else if (obj != Py_None) {
1811 result = PyDict_SetItemString(retval, "caIssuers", obj);
1812 Py_DECREF(obj);
1813 if (result < 0) {
1814 goto fail1;
1815 }
1816 }
1817
1818 /* CDP (CRL distribution points) */
1819 obj = _get_crl_dp(certificate);
1820 if (obj == NULL) {
1821 goto fail1;
1822 } else if (obj != Py_None) {
1823 result = PyDict_SetItemString(retval, "crlDistributionPoints", obj);
1824 Py_DECREF(obj);
1825 if (result < 0) {
1826 goto fail1;
1827 }
1828 }
1829
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001830 BIO_free(biobuf);
1831 return retval;
Thomas Woutersed03b412007-08-28 21:37:11 +00001832
1833 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001834 if (biobuf != NULL)
1835 BIO_free(biobuf);
Thomas Woutersed03b412007-08-28 21:37:11 +00001836 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001837 Py_XDECREF(retval);
1838 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001839}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001840
Christian Heimes9a5395a2013-06-17 15:44:12 +02001841static PyObject *
1842_certificate_to_der(X509 *certificate)
1843{
1844 unsigned char *bytes_buf = NULL;
1845 int len;
1846 PyObject *retval;
1847
1848 bytes_buf = NULL;
1849 len = i2d_X509(certificate, &bytes_buf);
1850 if (len < 0) {
1851 _setSSLError(NULL, 0, __FILE__, __LINE__);
1852 return NULL;
1853 }
1854 /* this is actually an immutable bytes sequence */
1855 retval = PyBytes_FromStringAndSize((const char *) bytes_buf, len);
1856 OPENSSL_free(bytes_buf);
1857 return retval;
1858}
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001859
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001860/*[clinic input]
1861_ssl._test_decode_cert
1862 path: object(converter="PyUnicode_FSConverter")
1863 /
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001864
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001865[clinic start generated code]*/
1866
1867static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001868_ssl__test_decode_cert_impl(PyObject *module, PyObject *path)
1869/*[clinic end generated code: output=96becb9abb23c091 input=cdeaaf02d4346628]*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001870{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001871 PyObject *retval = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001872 X509 *x=NULL;
1873 BIO *cert;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001874
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001875 if ((cert=BIO_new(BIO_s_file())) == NULL) {
1876 PyErr_SetString(PySSLErrorObject,
1877 "Can't malloc memory to read file");
1878 goto fail0;
1879 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001880
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001881 if (BIO_read_filename(cert, PyBytes_AsString(path)) <= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001882 PyErr_SetString(PySSLErrorObject,
1883 "Can't open file");
1884 goto fail0;
1885 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001886
Alex Gaynor40dad952019-08-15 08:31:28 -04001887 x = PEM_read_bio_X509(cert, NULL, NULL, NULL);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001888 if (x == NULL) {
1889 PyErr_SetString(PySSLErrorObject,
1890 "Error decoding PEM-encoded file");
1891 goto fail0;
1892 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001893
Antoine Pitroufb046912010-11-09 20:21:19 +00001894 retval = _decode_certificate(x);
Mark Dickinsonee55df52010-08-03 18:31:54 +00001895 X509_free(x);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001896
1897 fail0:
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001898 Py_DECREF(path);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001899 if (cert != NULL) BIO_free(cert);
1900 return retval;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001901}
1902
1903
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001904/*[clinic input]
Christian Heimes141c5e82018-02-24 21:10:57 +01001905_ssl._SSLSocket.getpeercert
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001906 der as binary_mode: bool = False
1907 /
1908
1909Returns the certificate for the peer.
1910
1911If no certificate was provided, returns None. If a certificate was
1912provided, but not validated, returns an empty dictionary. Otherwise
1913returns a dict containing information about the peer certificate.
1914
1915If the optional argument is True, returns a DER-encoded copy of the
1916peer certificate, or None if no certificate was provided. This will
1917return the certificate even if it wasn't validated.
1918[clinic start generated code]*/
1919
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001920static PyObject *
Christian Heimes141c5e82018-02-24 21:10:57 +01001921_ssl__SSLSocket_getpeercert_impl(PySSLSocket *self, int binary_mode)
1922/*[clinic end generated code: output=1f0ab66dfb693c88 input=c0fbe802e57629b7]*/
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001923{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001924 int verification;
Christian Heimes66dc33b2017-05-23 16:02:02 -07001925 X509 *peer_cert;
1926 PyObject *result;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001927
Christian Heimes66dc33b2017-05-23 16:02:02 -07001928 if (!SSL_is_init_finished(self->ssl)) {
Antoine Pitrou20b85552013-09-29 19:50:53 +02001929 PyErr_SetString(PyExc_ValueError,
1930 "handshake not done yet");
1931 return NULL;
1932 }
Christian Heimes66dc33b2017-05-23 16:02:02 -07001933 peer_cert = SSL_get_peer_certificate(self->ssl);
1934 if (peer_cert == NULL)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001935 Py_RETURN_NONE;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001936
Antoine Pitrou721738f2012-08-15 23:20:39 +02001937 if (binary_mode) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001938 /* return cert in DER-encoded format */
Christian Heimes66dc33b2017-05-23 16:02:02 -07001939 result = _certificate_to_der(peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001940 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00001941 verification = SSL_CTX_get_verify_mode(SSL_get_SSL_CTX(self->ssl));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001942 if ((verification & SSL_VERIFY_PEER) == 0)
Christian Heimes66dc33b2017-05-23 16:02:02 -07001943 result = PyDict_New();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001944 else
Christian Heimes66dc33b2017-05-23 16:02:02 -07001945 result = _decode_certificate(peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001946 }
Christian Heimes66dc33b2017-05-23 16:02:02 -07001947 X509_free(peer_cert);
1948 return result;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001949}
1950
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001951static PyObject *
1952cipher_to_tuple(const SSL_CIPHER *cipher)
1953{
1954 const char *cipher_name, *cipher_protocol;
1955 PyObject *v, *retval = PyTuple_New(3);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001956 if (retval == NULL)
1957 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001958
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001959 cipher_name = SSL_CIPHER_get_name(cipher);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001960 if (cipher_name == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001961 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001962 PyTuple_SET_ITEM(retval, 0, Py_None);
1963 } else {
1964 v = PyUnicode_FromString(cipher_name);
1965 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001966 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001967 PyTuple_SET_ITEM(retval, 0, v);
1968 }
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001969
1970 cipher_protocol = SSL_CIPHER_get_version(cipher);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001971 if (cipher_protocol == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001972 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001973 PyTuple_SET_ITEM(retval, 1, Py_None);
1974 } else {
1975 v = PyUnicode_FromString(cipher_protocol);
1976 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001977 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001978 PyTuple_SET_ITEM(retval, 1, v);
1979 }
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001980
1981 v = PyLong_FromLong(SSL_CIPHER_get_bits(cipher, NULL));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001982 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001983 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001984 PyTuple_SET_ITEM(retval, 2, v);
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001985
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001986 return retval;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001987
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001988 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001989 Py_DECREF(retval);
1990 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001991}
1992
Christian Heimes25bfcd52016-09-06 00:04:45 +02001993#if OPENSSL_VERSION_NUMBER >= 0x10002000UL
1994static PyObject *
1995cipher_to_dict(const SSL_CIPHER *cipher)
1996{
1997 const char *cipher_name, *cipher_protocol;
1998
1999 unsigned long cipher_id;
2000 int alg_bits, strength_bits, len;
2001 char buf[512] = {0};
2002#if OPENSSL_VERSION_1_1
2003 int aead, nid;
2004 const char *skcipher = NULL, *digest = NULL, *kx = NULL, *auth = NULL;
2005#endif
Christian Heimes25bfcd52016-09-06 00:04:45 +02002006
2007 /* can be NULL */
2008 cipher_name = SSL_CIPHER_get_name(cipher);
2009 cipher_protocol = SSL_CIPHER_get_version(cipher);
2010 cipher_id = SSL_CIPHER_get_id(cipher);
2011 SSL_CIPHER_description(cipher, buf, sizeof(buf) - 1);
Segev Finer5cff6372017-07-27 01:19:17 +03002012 /* Downcast to avoid a warning. Safe since buf is always 512 bytes */
2013 len = (int)strlen(buf);
Christian Heimes25bfcd52016-09-06 00:04:45 +02002014 if (len > 1 && buf[len-1] == '\n')
2015 buf[len-1] = '\0';
2016 strength_bits = SSL_CIPHER_get_bits(cipher, &alg_bits);
2017
2018#if OPENSSL_VERSION_1_1
2019 aead = SSL_CIPHER_is_aead(cipher);
2020 nid = SSL_CIPHER_get_cipher_nid(cipher);
2021 skcipher = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
2022 nid = SSL_CIPHER_get_digest_nid(cipher);
2023 digest = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
2024 nid = SSL_CIPHER_get_kx_nid(cipher);
2025 kx = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
2026 nid = SSL_CIPHER_get_auth_nid(cipher);
2027 auth = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
2028#endif
2029
Victor Stinner410b9882016-09-12 12:00:23 +02002030 return Py_BuildValue(
Christian Heimes25bfcd52016-09-06 00:04:45 +02002031 "{sksssssssisi"
2032#if OPENSSL_VERSION_1_1
2033 "sOssssssss"
2034#endif
2035 "}",
2036 "id", cipher_id,
2037 "name", cipher_name,
2038 "protocol", cipher_protocol,
2039 "description", buf,
2040 "strength_bits", strength_bits,
2041 "alg_bits", alg_bits
2042#if OPENSSL_VERSION_1_1
2043 ,"aead", aead ? Py_True : Py_False,
2044 "symmetric", skcipher,
2045 "digest", digest,
2046 "kea", kx,
2047 "auth", auth
2048#endif
2049 );
Christian Heimes25bfcd52016-09-06 00:04:45 +02002050}
2051#endif
2052
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002053/*[clinic input]
2054_ssl._SSLSocket.shared_ciphers
2055[clinic start generated code]*/
2056
2057static PyObject *
2058_ssl__SSLSocket_shared_ciphers_impl(PySSLSocket *self)
2059/*[clinic end generated code: output=3d174ead2e42c4fd input=0bfe149da8fe6306]*/
Benjamin Peterson4cb17812015-01-07 11:14:26 -06002060{
2061 STACK_OF(SSL_CIPHER) *ciphers;
2062 int i;
2063 PyObject *res;
2064
Christian Heimes598894f2016-09-05 23:19:05 +02002065 ciphers = SSL_get_ciphers(self->ssl);
2066 if (!ciphers)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06002067 Py_RETURN_NONE;
Benjamin Peterson4cb17812015-01-07 11:14:26 -06002068 res = PyList_New(sk_SSL_CIPHER_num(ciphers));
2069 if (!res)
2070 return NULL;
2071 for (i = 0; i < sk_SSL_CIPHER_num(ciphers); i++) {
2072 PyObject *tup = cipher_to_tuple(sk_SSL_CIPHER_value(ciphers, i));
2073 if (!tup) {
2074 Py_DECREF(res);
2075 return NULL;
2076 }
2077 PyList_SET_ITEM(res, i, tup);
2078 }
2079 return res;
2080}
2081
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002082/*[clinic input]
2083_ssl._SSLSocket.cipher
2084[clinic start generated code]*/
2085
2086static PyObject *
2087_ssl__SSLSocket_cipher_impl(PySSLSocket *self)
2088/*[clinic end generated code: output=376417c16d0e5815 input=548fb0e27243796d]*/
Benjamin Peterson4cb17812015-01-07 11:14:26 -06002089{
2090 const SSL_CIPHER *current;
2091
2092 if (self->ssl == NULL)
2093 Py_RETURN_NONE;
2094 current = SSL_get_current_cipher(self->ssl);
2095 if (current == NULL)
2096 Py_RETURN_NONE;
2097 return cipher_to_tuple(current);
2098}
2099
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002100/*[clinic input]
2101_ssl._SSLSocket.version
2102[clinic start generated code]*/
2103
2104static PyObject *
2105_ssl__SSLSocket_version_impl(PySSLSocket *self)
2106/*[clinic end generated code: output=178aed33193b2cdb input=900186a503436fd6]*/
Antoine Pitrou47e40422014-09-04 21:00:10 +02002107{
2108 const char *version;
2109
2110 if (self->ssl == NULL)
2111 Py_RETURN_NONE;
Christian Heimes68771112017-09-05 21:55:40 -07002112 if (!SSL_is_init_finished(self->ssl)) {
2113 /* handshake not finished */
2114 Py_RETURN_NONE;
2115 }
Antoine Pitrou47e40422014-09-04 21:00:10 +02002116 version = SSL_get_version(self->ssl);
2117 if (!strcmp(version, "unknown"))
2118 Py_RETURN_NONE;
2119 return PyUnicode_FromString(version);
2120}
2121
Christian Heimes29eab552018-02-25 12:31:33 +01002122#if HAVE_NPN
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002123/*[clinic input]
2124_ssl._SSLSocket.selected_npn_protocol
2125[clinic start generated code]*/
2126
2127static PyObject *
2128_ssl__SSLSocket_selected_npn_protocol_impl(PySSLSocket *self)
2129/*[clinic end generated code: output=b91d494cd207ecf6 input=c28fde139204b826]*/
2130{
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002131 const unsigned char *out;
2132 unsigned int outlen;
2133
Victor Stinner4569cd52013-06-23 14:58:43 +02002134 SSL_get0_next_proto_negotiated(self->ssl,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002135 &out, &outlen);
2136
2137 if (out == NULL)
2138 Py_RETURN_NONE;
Benjamin Petersoncca27322015-01-23 16:35:37 -05002139 return PyUnicode_FromStringAndSize((char *)out, outlen);
2140}
2141#endif
2142
Christian Heimes29eab552018-02-25 12:31:33 +01002143#if HAVE_ALPN
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002144/*[clinic input]
2145_ssl._SSLSocket.selected_alpn_protocol
2146[clinic start generated code]*/
2147
2148static PyObject *
2149_ssl__SSLSocket_selected_alpn_protocol_impl(PySSLSocket *self)
2150/*[clinic end generated code: output=ec33688b303d250f input=442de30e35bc2913]*/
2151{
Benjamin Petersoncca27322015-01-23 16:35:37 -05002152 const unsigned char *out;
2153 unsigned int outlen;
2154
2155 SSL_get0_alpn_selected(self->ssl, &out, &outlen);
2156
2157 if (out == NULL)
2158 Py_RETURN_NONE;
2159 return PyUnicode_FromStringAndSize((char *)out, outlen);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002160}
2161#endif
2162
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002163/*[clinic input]
2164_ssl._SSLSocket.compression
2165[clinic start generated code]*/
2166
2167static PyObject *
2168_ssl__SSLSocket_compression_impl(PySSLSocket *self)
2169/*[clinic end generated code: output=bd16cb1bb4646ae7 input=5d059d0a2bbc32c8]*/
2170{
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01002171#ifdef OPENSSL_NO_COMP
2172 Py_RETURN_NONE;
2173#else
2174 const COMP_METHOD *comp_method;
2175 const char *short_name;
2176
2177 if (self->ssl == NULL)
2178 Py_RETURN_NONE;
2179 comp_method = SSL_get_current_compression(self->ssl);
Christian Heimes598894f2016-09-05 23:19:05 +02002180 if (comp_method == NULL || COMP_get_type(comp_method) == NID_undef)
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01002181 Py_RETURN_NONE;
Christian Heimes281e5f82016-09-06 01:10:39 +02002182 short_name = OBJ_nid2sn(COMP_get_type(comp_method));
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01002183 if (short_name == NULL)
2184 Py_RETURN_NONE;
2185 return PyUnicode_DecodeFSDefault(short_name);
2186#endif
2187}
2188
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002189static PySSLContext *PySSL_get_context(PySSLSocket *self, void *closure) {
2190 Py_INCREF(self->ctx);
2191 return self->ctx;
2192}
2193
2194static int PySSL_set_context(PySSLSocket *self, PyObject *value,
2195 void *closure) {
2196
Christian Heimes5c36da72020-11-20 09:40:12 +01002197 if (PyObject_TypeCheck(value, PySSLContext_Type)) {
Antoine Pitrou912fbff2013-03-30 16:29:32 +01002198#if !HAVE_SNI
2199 PyErr_SetString(PyExc_NotImplementedError, "setting a socket's "
2200 "context is not supported by your OpenSSL library");
Antoine Pitrou41f8c4f2013-03-30 16:36:54 +01002201 return -1;
Antoine Pitrou912fbff2013-03-30 16:29:32 +01002202#else
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002203 Py_INCREF(value);
Serhiy Storchaka57a01d32016-04-10 18:05:40 +03002204 Py_SETREF(self->ctx, (PySSLContext *)value);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002205 SSL_set_SSL_CTX(self->ssl, self->ctx->ctx);
Christian Heimes77cde502021-03-21 16:13:09 +01002206 /* Set SSL* internal msg_callback to state of new context's state */
2207 SSL_set_msg_callback(
2208 self->ssl,
2209 self->ctx->msg_cb ? _PySSL_msg_callback : NULL
2210 );
Antoine Pitrou912fbff2013-03-30 16:29:32 +01002211#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002212 } else {
Ned Deily4531ec72018-06-11 20:26:28 -04002213 PyErr_SetString(PyExc_TypeError, "The value must be a SSLContext");
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002214 return -1;
2215 }
2216
2217 return 0;
2218}
2219
2220PyDoc_STRVAR(PySSL_set_context_doc,
2221"_setter_context(ctx)\n\
2222\
2223This changes the context associated with the SSLSocket. This is typically\n\
Christian Heimes11a14932018-02-24 02:35:08 +01002224used from within a callback function set by the sni_callback\n\
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002225on the SSLContext to change the certificate information associated with the\n\
2226SSLSocket before the cryptographic exchange handshake messages\n");
2227
2228
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002229static PyObject *
2230PySSL_get_server_side(PySSLSocket *self, void *c)
2231{
2232 return PyBool_FromLong(self->socket_type == PY_SSL_SERVER);
2233}
2234
2235PyDoc_STRVAR(PySSL_get_server_side_doc,
2236"Whether this is a server-side socket.");
2237
2238static PyObject *
2239PySSL_get_server_hostname(PySSLSocket *self, void *c)
2240{
2241 if (self->server_hostname == NULL)
2242 Py_RETURN_NONE;
2243 Py_INCREF(self->server_hostname);
2244 return self->server_hostname;
2245}
2246
2247PyDoc_STRVAR(PySSL_get_server_hostname_doc,
2248"The currently set server hostname (for SNI).");
2249
2250static PyObject *
2251PySSL_get_owner(PySSLSocket *self, void *c)
2252{
2253 PyObject *owner;
2254
2255 if (self->owner == NULL)
2256 Py_RETURN_NONE;
2257
2258 owner = PyWeakref_GetObject(self->owner);
2259 Py_INCREF(owner);
2260 return owner;
2261}
2262
2263static int
2264PySSL_set_owner(PySSLSocket *self, PyObject *value, void *c)
2265{
Serhiy Storchaka48842712016-04-06 09:45:48 +03002266 Py_XSETREF(self->owner, PyWeakref_NewRef(value, NULL));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002267 if (self->owner == NULL)
2268 return -1;
2269 return 0;
2270}
2271
2272PyDoc_STRVAR(PySSL_get_owner_doc,
2273"The Python-level owner of this object.\
2274Passed as \"self\" in servername callback.");
2275
Christian Heimesc7f70692019-05-31 11:44:05 +02002276static int
2277PySSL_traverse(PySSLSocket *self, visitproc visit, void *arg)
2278{
2279 Py_VISIT(self->exc_type);
2280 Py_VISIT(self->exc_value);
2281 Py_VISIT(self->exc_tb);
2282 return 0;
2283}
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002284
Christian Heimesc7f70692019-05-31 11:44:05 +02002285static int
2286PySSL_clear(PySSLSocket *self)
2287{
2288 Py_CLEAR(self->exc_type);
2289 Py_CLEAR(self->exc_value);
2290 Py_CLEAR(self->exc_tb);
2291 return 0;
2292}
2293
2294static void
2295PySSL_dealloc(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002296{
Christian Heimes5c36da72020-11-20 09:40:12 +01002297 PyTypeObject *tp = Py_TYPE(self);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002298 if (self->ssl)
2299 SSL_free(self->ssl);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002300 Py_XDECREF(self->Socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002301 Py_XDECREF(self->ctx);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002302 Py_XDECREF(self->server_hostname);
2303 Py_XDECREF(self->owner);
Victor Stinner32bd68c2020-12-01 10:37:39 +01002304 PyObject_Free(self);
Christian Heimes5c36da72020-11-20 09:40:12 +01002305 Py_DECREF(tp);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002306}
2307
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002308/* If the socket has a timeout, do a select()/poll() on the socket.
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002309 The argument writing indicates the direction.
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00002310 Returns one of the possibilities in the timeout_state enum (above).
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002311 */
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00002312
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002313static int
Victor Stinner14690702015-04-06 22:46:13 +02002314PySSL_select(PySocketSockObject *s, int writing, _PyTime_t timeout)
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002315{
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002316 int rc;
2317#ifdef HAVE_POLL
2318 struct pollfd pollfd;
2319 _PyTime_t ms;
2320#else
2321 int nfds;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002322 fd_set fds;
2323 struct timeval tv;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002324#endif
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002325
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002326 /* Nothing to do unless we're in timeout mode (not non-blocking) */
Victor Stinner14690702015-04-06 22:46:13 +02002327 if ((s == NULL) || (timeout == 0))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002328 return SOCKET_IS_NONBLOCKING;
Victor Stinner14690702015-04-06 22:46:13 +02002329 else if (timeout < 0) {
2330 if (s->sock_timeout > 0)
2331 return SOCKET_HAS_TIMED_OUT;
2332 else
2333 return SOCKET_IS_BLOCKING;
2334 }
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002335
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002336 /* Guard against closed socket */
Victor Stinner524714e2016-07-22 17:43:59 +02002337 if (s->sock_fd == INVALID_SOCKET)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002338 return SOCKET_HAS_BEEN_CLOSED;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002339
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002340 /* Prefer poll, if available, since you can poll() any fd
2341 * which can't be done with select(). */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002342#ifdef HAVE_POLL
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002343 pollfd.fd = s->sock_fd;
2344 pollfd.events = writing ? POLLOUT : POLLIN;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002345
Victor Stinner14690702015-04-06 22:46:13 +02002346 /* timeout is in seconds, poll() uses milliseconds */
2347 ms = (int)_PyTime_AsMilliseconds(timeout, _PyTime_ROUND_CEILING);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002348 assert(ms <= INT_MAX);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002349
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002350 PySSL_BEGIN_ALLOW_THREADS
2351 rc = poll(&pollfd, 1, (int)ms);
2352 PySSL_END_ALLOW_THREADS
2353#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002354 /* Guard against socket too large for select*/
Charles-François Nataliaa26b272011-08-28 17:51:43 +02002355 if (!_PyIsSelectable_fd(s->sock_fd))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002356 return SOCKET_TOO_LARGE_FOR_SELECT;
Neal Norwitz082b2df2006-02-07 07:04:46 +00002357
Victor Stinner14690702015-04-06 22:46:13 +02002358 _PyTime_AsTimeval_noraise(timeout, &tv, _PyTime_ROUND_CEILING);
Victor Stinnere2452312015-03-28 03:00:46 +01002359
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002360 FD_ZERO(&fds);
2361 FD_SET(s->sock_fd, &fds);
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002362
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002363 /* Wait until the socket becomes ready */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002364 PySSL_BEGIN_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002365 nfds = Py_SAFE_DOWNCAST(s->sock_fd+1, SOCKET_T, int);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002366 if (writing)
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002367 rc = select(nfds, NULL, &fds, NULL, &tv);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002368 else
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002369 rc = select(nfds, &fds, NULL, NULL, &tv);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002370 PySSL_END_ALLOW_THREADS
Bill Janssen6e027db2007-11-15 22:23:56 +00002371#endif
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002372
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002373 /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
2374 (when we are able to write or when there's something to read) */
2375 return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002376}
2377
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002378/*[clinic input]
2379_ssl._SSLSocket.write
2380 b: Py_buffer
2381 /
2382
2383Writes the bytes-like object b into the SSL object.
2384
2385Returns the number of bytes written.
2386[clinic start generated code]*/
2387
2388static PyObject *
2389_ssl__SSLSocket_write_impl(PySSLSocket *self, Py_buffer *b)
2390/*[clinic end generated code: output=aa7a6be5527358d8 input=77262d994fe5100a]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002391{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002392 int len;
2393 int sockstate;
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002394 _PySSLError err;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002395 int nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002396 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002397 _PyTime_t timeout, deadline = 0;
2398 int has_timeout;
Bill Janssen54cc54c2007-12-14 22:08:56 +00002399
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002400 if (sock != NULL) {
2401 if (((PyObject*)sock) == Py_None) {
2402 _setSSLError("Underlying socket connection gone",
2403 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2404 return NULL;
2405 }
2406 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002407 }
2408
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002409 if (b->len > INT_MAX) {
Victor Stinner6efa9652013-06-25 00:42:31 +02002410 PyErr_Format(PyExc_OverflowError,
2411 "string longer than %d bytes", INT_MAX);
2412 goto error;
2413 }
2414
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002415 if (sock != NULL) {
2416 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002417 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002418 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2419 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
2420 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002421
Victor Stinner14690702015-04-06 22:46:13 +02002422 timeout = GET_SOCKET_TIMEOUT(sock);
2423 has_timeout = (timeout > 0);
2424 if (has_timeout)
2425 deadline = _PyTime_GetMonotonicClock() + timeout;
2426
2427 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002428 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Christian Heimes03c8ddd2020-11-20 09:26:07 +01002429 PyErr_SetString(PyExc_TimeoutError,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002430 "The write operation timed out");
2431 goto error;
2432 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
2433 PyErr_SetString(PySSLErrorObject,
2434 "Underlying socket has been closed.");
2435 goto error;
2436 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
2437 PyErr_SetString(PySSLErrorObject,
2438 "Underlying socket too large for select().");
2439 goto error;
2440 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002441
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002442 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002443 PySSL_BEGIN_ALLOW_THREADS
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002444 len = SSL_write(self->ssl, b->buf, (int)b->len);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002445 err = _PySSL_errno(len <= 0, self->ssl, len);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002446 PySSL_END_ALLOW_THREADS
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002447 self->err = err;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002448
2449 if (PyErr_CheckSignals())
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002450 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002451
Victor Stinner14690702015-04-06 22:46:13 +02002452 if (has_timeout)
2453 timeout = deadline - _PyTime_GetMonotonicClock();
2454
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002455 if (err.ssl == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +02002456 sockstate = PySSL_select(sock, 0, timeout);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002457 } else if (err.ssl == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +02002458 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002459 } else {
2460 sockstate = SOCKET_OPERATION_OK;
2461 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002462
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002463 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Christian Heimes03c8ddd2020-11-20 09:26:07 +01002464 PyErr_SetString(PyExc_TimeoutError,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002465 "The write operation timed out");
2466 goto error;
2467 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
2468 PyErr_SetString(PySSLErrorObject,
2469 "Underlying socket has been closed.");
2470 goto error;
2471 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
2472 break;
2473 }
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002474 } while (err.ssl == SSL_ERROR_WANT_READ ||
2475 err.ssl == SSL_ERROR_WANT_WRITE);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002476
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002477 Py_XDECREF(sock);
Christian Heimesc7f70692019-05-31 11:44:05 +02002478 if (len <= 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002479 return PySSL_SetError(self, len, __FILE__, __LINE__);
Christian Heimesc7f70692019-05-31 11:44:05 +02002480 if (PySSL_ChainExceptions(self) < 0)
2481 return NULL;
2482 return PyLong_FromLong(len);
Antoine Pitrou7d7aede2009-11-25 18:55:32 +00002483error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002484 Py_XDECREF(sock);
Christian Heimesc7f70692019-05-31 11:44:05 +02002485 PySSL_ChainExceptions(self);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002486 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002487}
2488
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002489/*[clinic input]
2490_ssl._SSLSocket.pending
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002491
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002492Returns the number of already decrypted bytes available for read, pending on the connection.
2493[clinic start generated code]*/
2494
2495static PyObject *
2496_ssl__SSLSocket_pending_impl(PySSLSocket *self)
2497/*[clinic end generated code: output=983d9fecdc308a83 input=2b77487d6dfd597f]*/
Bill Janssen6e027db2007-11-15 22:23:56 +00002498{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002499 int count = 0;
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002500 _PySSLError err;
Bill Janssen6e027db2007-11-15 22:23:56 +00002501
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002502 PySSL_BEGIN_ALLOW_THREADS
2503 count = SSL_pending(self->ssl);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002504 err = _PySSL_errno(count < 0, self->ssl, count);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002505 PySSL_END_ALLOW_THREADS
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002506 self->err = err;
2507
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002508 if (count < 0)
2509 return PySSL_SetError(self, count, __FILE__, __LINE__);
2510 else
2511 return PyLong_FromLong(count);
Bill Janssen6e027db2007-11-15 22:23:56 +00002512}
2513
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002514/*[clinic input]
2515_ssl._SSLSocket.read
2516 size as len: int
2517 [
Larry Hastingsdbfdc382015-05-04 06:59:46 -07002518 buffer: Py_buffer(accept={rwbuffer})
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002519 ]
2520 /
Bill Janssen6e027db2007-11-15 22:23:56 +00002521
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002522Read up to size bytes from the SSL socket.
2523[clinic start generated code]*/
2524
2525static PyObject *
2526_ssl__SSLSocket_read_impl(PySSLSocket *self, int len, int group_right_1,
2527 Py_buffer *buffer)
Larry Hastingsdbfdc382015-05-04 06:59:46 -07002528/*[clinic end generated code: output=00097776cec2a0af input=ff157eb918d0905b]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002529{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002530 PyObject *dest = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002531 char *mem;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002532 int count;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002533 int sockstate;
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002534 _PySSLError err;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002535 int nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002536 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002537 _PyTime_t timeout, deadline = 0;
2538 int has_timeout;
Bill Janssen54cc54c2007-12-14 22:08:56 +00002539
Martin Panter5503d472016-03-27 05:35:19 +00002540 if (!group_right_1 && len < 0) {
2541 PyErr_SetString(PyExc_ValueError, "size should not be negative");
2542 return NULL;
2543 }
2544
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002545 if (sock != NULL) {
2546 if (((PyObject*)sock) == Py_None) {
2547 _setSSLError("Underlying socket connection gone",
2548 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2549 return NULL;
2550 }
2551 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002552 }
2553
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002554 if (!group_right_1) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002555 dest = PyBytes_FromStringAndSize(NULL, len);
2556 if (dest == NULL)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002557 goto error;
Martin Panterbed7f1a2016-07-11 00:17:13 +00002558 if (len == 0) {
2559 Py_XDECREF(sock);
2560 return dest;
2561 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002562 mem = PyBytes_AS_STRING(dest);
2563 }
2564 else {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002565 mem = buffer->buf;
2566 if (len <= 0 || len > buffer->len) {
2567 len = (int) buffer->len;
2568 if (buffer->len != len) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002569 PyErr_SetString(PyExc_OverflowError,
2570 "maximum length can't fit in a C 'int'");
2571 goto error;
2572 }
Martin Panterbed7f1a2016-07-11 00:17:13 +00002573 if (len == 0) {
2574 count = 0;
2575 goto done;
2576 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002577 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002578 }
2579
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002580 if (sock != NULL) {
2581 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002582 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002583 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2584 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
2585 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002586
Victor Stinner14690702015-04-06 22:46:13 +02002587 timeout = GET_SOCKET_TIMEOUT(sock);
2588 has_timeout = (timeout > 0);
2589 if (has_timeout)
2590 deadline = _PyTime_GetMonotonicClock() + timeout;
2591
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002592 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002593 PySSL_BEGIN_ALLOW_THREADS
2594 count = SSL_read(self->ssl, mem, len);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002595 err = _PySSL_errno(count <= 0, self->ssl, count);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002596 PySSL_END_ALLOW_THREADS
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002597 self->err = err;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002598
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002599 if (PyErr_CheckSignals())
2600 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002601
Victor Stinner14690702015-04-06 22:46:13 +02002602 if (has_timeout)
2603 timeout = deadline - _PyTime_GetMonotonicClock();
2604
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002605 if (err.ssl == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +02002606 sockstate = PySSL_select(sock, 0, timeout);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002607 } else if (err.ssl == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +02002608 sockstate = PySSL_select(sock, 1, timeout);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002609 } else if (err.ssl == SSL_ERROR_ZERO_RETURN &&
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002610 SSL_get_shutdown(self->ssl) == SSL_RECEIVED_SHUTDOWN)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002611 {
2612 count = 0;
2613 goto done;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002614 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002615 else
2616 sockstate = SOCKET_OPERATION_OK;
2617
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002618 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Christian Heimes03c8ddd2020-11-20 09:26:07 +01002619 PyErr_SetString(PyExc_TimeoutError,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002620 "The read operation timed out");
2621 goto error;
2622 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
2623 break;
2624 }
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002625 } while (err.ssl == SSL_ERROR_WANT_READ ||
2626 err.ssl == SSL_ERROR_WANT_WRITE);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002627
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002628 if (count <= 0) {
2629 PySSL_SetError(self, count, __FILE__, __LINE__);
2630 goto error;
2631 }
Christian Heimesc7f70692019-05-31 11:44:05 +02002632 if (self->exc_type != NULL)
2633 goto error;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002634
2635done:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002636 Py_XDECREF(sock);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002637 if (!group_right_1) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002638 _PyBytes_Resize(&dest, count);
2639 return dest;
2640 }
2641 else {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002642 return PyLong_FromLong(count);
2643 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002644
2645error:
Christian Heimesc7f70692019-05-31 11:44:05 +02002646 PySSL_ChainExceptions(self);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002647 Py_XDECREF(sock);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002648 if (!group_right_1)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002649 Py_XDECREF(dest);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002650 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002651}
2652
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002653/*[clinic input]
2654_ssl._SSLSocket.shutdown
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002655
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002656Does the SSL shutdown handshake with the remote end.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002657[clinic start generated code]*/
2658
2659static PyObject *
2660_ssl__SSLSocket_shutdown_impl(PySSLSocket *self)
Christian Heimes141c5e82018-02-24 21:10:57 +01002661/*[clinic end generated code: output=ca1aa7ed9d25ca42 input=11d39e69b0a2bf4a]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00002662{
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002663 _PySSLError err;
2664 int sockstate, nonblocking, ret;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002665 int zeros = 0;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002666 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002667 _PyTime_t timeout, deadline = 0;
2668 int has_timeout;
Bill Janssen40a0f662008-08-12 16:56:25 +00002669
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002670 if (sock != NULL) {
2671 /* Guard against closed socket */
Victor Stinner524714e2016-07-22 17:43:59 +02002672 if ((((PyObject*)sock) == Py_None) || (sock->sock_fd == INVALID_SOCKET)) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002673 _setSSLError("Underlying socket connection gone",
2674 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2675 return NULL;
2676 }
2677 Py_INCREF(sock);
2678
2679 /* Just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002680 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002681 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2682 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002683 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002684
Victor Stinner14690702015-04-06 22:46:13 +02002685 timeout = GET_SOCKET_TIMEOUT(sock);
2686 has_timeout = (timeout > 0);
2687 if (has_timeout)
2688 deadline = _PyTime_GetMonotonicClock() + timeout;
2689
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002690 while (1) {
2691 PySSL_BEGIN_ALLOW_THREADS
2692 /* Disable read-ahead so that unwrap can work correctly.
2693 * Otherwise OpenSSL might read in too much data,
2694 * eating clear text data that happens to be
2695 * transmitted after the SSL shutdown.
Ezio Melotti85a86292013-08-17 16:57:41 +03002696 * Should be safe to call repeatedly every time this
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002697 * function is used and the shutdown_seen_zero != 0
2698 * condition is met.
2699 */
2700 if (self->shutdown_seen_zero)
2701 SSL_set_read_ahead(self->ssl, 0);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002702 ret = SSL_shutdown(self->ssl);
2703 err = _PySSL_errno(ret < 0, self->ssl, ret);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002704 PySSL_END_ALLOW_THREADS
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002705 self->err = err;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002706
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002707 /* If err == 1, a secure shutdown with SSL_shutdown() is complete */
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002708 if (ret > 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002709 break;
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002710 if (ret == 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002711 /* Don't loop endlessly; instead preserve legacy
2712 behaviour of trying SSL_shutdown() only twice.
2713 This looks necessary for OpenSSL < 0.9.8m */
2714 if (++zeros > 1)
2715 break;
2716 /* Shutdown was sent, now try receiving */
2717 self->shutdown_seen_zero = 1;
2718 continue;
Bill Janssen40a0f662008-08-12 16:56:25 +00002719 }
2720
Victor Stinner14690702015-04-06 22:46:13 +02002721 if (has_timeout)
2722 timeout = deadline - _PyTime_GetMonotonicClock();
2723
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002724 /* Possibly retry shutdown until timeout or failure */
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002725 if (err.ssl == SSL_ERROR_WANT_READ)
Victor Stinner14690702015-04-06 22:46:13 +02002726 sockstate = PySSL_select(sock, 0, timeout);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002727 else if (err.ssl == SSL_ERROR_WANT_WRITE)
Victor Stinner14690702015-04-06 22:46:13 +02002728 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002729 else
2730 break;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002731
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002732 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002733 if (err.ssl == SSL_ERROR_WANT_READ)
Christian Heimes03c8ddd2020-11-20 09:26:07 +01002734 PyErr_SetString(PyExc_TimeoutError,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002735 "The read operation timed out");
2736 else
Christian Heimes03c8ddd2020-11-20 09:26:07 +01002737 PyErr_SetString(PyExc_TimeoutError,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002738 "The write operation timed out");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002739 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002740 }
2741 else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
2742 PyErr_SetString(PySSLErrorObject,
2743 "Underlying socket too large for select().");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002744 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002745 }
2746 else if (sockstate != SOCKET_OPERATION_OK)
2747 /* Retain the SSL error code */
2748 break;
2749 }
Nathaniel J. Smithc0da5822018-09-21 21:44:12 -07002750 if (ret < 0) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002751 Py_XDECREF(sock);
Christian Heimesc7f70692019-05-31 11:44:05 +02002752 PySSL_SetError(self, ret, __FILE__, __LINE__);
2753 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002754 }
Christian Heimesc7f70692019-05-31 11:44:05 +02002755 if (self->exc_type != NULL)
2756 goto error;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002757 if (sock)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002758 /* It's already INCREF'ed */
2759 return (PyObject *) sock;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002760 else
2761 Py_RETURN_NONE;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002762
2763error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002764 Py_XDECREF(sock);
Christian Heimesc7f70692019-05-31 11:44:05 +02002765 PySSL_ChainExceptions(self);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002766 return NULL;
Bill Janssen40a0f662008-08-12 16:56:25 +00002767}
2768
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002769/*[clinic input]
Christian Heimes141c5e82018-02-24 21:10:57 +01002770_ssl._SSLSocket.get_channel_binding
2771 cb_type: str = "tls-unique"
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002772
Christian Heimes141c5e82018-02-24 21:10:57 +01002773Get channel binding data for current connection.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002774
Christian Heimes141c5e82018-02-24 21:10:57 +01002775Raise ValueError if the requested `cb_type` is not supported. Return bytes
2776of the data or None if the data is not available (e.g. before the handshake).
2777Only 'tls-unique' channel binding data from RFC 5929 is supported.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002778[clinic start generated code]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00002779
Antoine Pitroud6494802011-07-21 01:11:30 +02002780static PyObject *
Christian Heimes141c5e82018-02-24 21:10:57 +01002781_ssl__SSLSocket_get_channel_binding_impl(PySSLSocket *self,
2782 const char *cb_type)
2783/*[clinic end generated code: output=34bac9acb6a61d31 input=08b7e43b99c17d41]*/
Antoine Pitroud6494802011-07-21 01:11:30 +02002784{
Antoine Pitroud6494802011-07-21 01:11:30 +02002785 char buf[PySSL_CB_MAXLEN];
Victor Stinner9ee02032013-06-23 15:08:23 +02002786 size_t len;
Antoine Pitroud6494802011-07-21 01:11:30 +02002787
Christian Heimes141c5e82018-02-24 21:10:57 +01002788 if (strcmp(cb_type, "tls-unique") == 0) {
2789 if (SSL_session_reused(self->ssl) ^ !self->socket_type) {
2790 /* if session is resumed XOR we are the client */
2791 len = SSL_get_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2792 }
2793 else {
2794 /* if a new session XOR we are the server */
2795 len = SSL_get_peer_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2796 }
Antoine Pitroud6494802011-07-21 01:11:30 +02002797 }
2798 else {
Christian Heimes141c5e82018-02-24 21:10:57 +01002799 PyErr_Format(
2800 PyExc_ValueError,
2801 "'%s' channel binding type not implemented",
2802 cb_type
2803 );
2804 return NULL;
Antoine Pitroud6494802011-07-21 01:11:30 +02002805 }
2806
2807 /* It cannot be negative in current OpenSSL version as of July 2011 */
Antoine Pitroud6494802011-07-21 01:11:30 +02002808 if (len == 0)
2809 Py_RETURN_NONE;
2810
Christian Heimes141c5e82018-02-24 21:10:57 +01002811 return PyBytes_FromStringAndSize(buf, len);
Antoine Pitroud6494802011-07-21 01:11:30 +02002812}
2813
Christian Heimes9fb051f2018-09-23 08:32:31 +02002814/*[clinic input]
2815_ssl._SSLSocket.verify_client_post_handshake
2816
2817Initiate TLS 1.3 post-handshake authentication
2818[clinic start generated code]*/
2819
2820static PyObject *
2821_ssl__SSLSocket_verify_client_post_handshake_impl(PySSLSocket *self)
2822/*[clinic end generated code: output=532147f3b1341425 input=6bfa874810a3d889]*/
2823{
2824#ifdef TLS1_3_VERSION
2825 int err = SSL_verify_client_post_handshake(self->ssl);
2826 if (err == 0)
2827 return _setSSLError(NULL, 0, __FILE__, __LINE__);
2828 else
2829 Py_RETURN_NONE;
2830#else
2831 PyErr_SetString(PyExc_NotImplementedError,
2832 "Post-handshake auth is not supported by your "
2833 "OpenSSL version.");
2834 return NULL;
2835#endif
2836}
2837
Christian Heimes99a65702016-09-10 23:44:53 +02002838#ifdef OPENSSL_VERSION_1_1
2839
2840static SSL_SESSION*
2841_ssl_session_dup(SSL_SESSION *session) {
2842 SSL_SESSION *newsession = NULL;
2843 int slen;
2844 unsigned char *senc = NULL, *p;
2845 const unsigned char *const_p;
2846
2847 if (session == NULL) {
2848 PyErr_SetString(PyExc_ValueError, "Invalid session");
2849 goto error;
2850 }
2851
2852 /* get length */
2853 slen = i2d_SSL_SESSION(session, NULL);
2854 if (slen == 0 || slen > 0xFF00) {
2855 PyErr_SetString(PyExc_ValueError, "i2d() failed.");
2856 goto error;
2857 }
2858 if ((senc = PyMem_Malloc(slen)) == NULL) {
2859 PyErr_NoMemory();
2860 goto error;
2861 }
2862 p = senc;
2863 if (!i2d_SSL_SESSION(session, &p)) {
2864 PyErr_SetString(PyExc_ValueError, "i2d() failed.");
2865 goto error;
2866 }
2867 const_p = senc;
2868 newsession = d2i_SSL_SESSION(NULL, &const_p, slen);
2869 if (session == NULL) {
2870 goto error;
2871 }
2872 PyMem_Free(senc);
2873 return newsession;
2874 error:
2875 if (senc != NULL) {
2876 PyMem_Free(senc);
2877 }
2878 return NULL;
2879}
2880#endif
2881
2882static PyObject *
2883PySSL_get_session(PySSLSocket *self, void *closure) {
2884 /* get_session can return sessions from a server-side connection,
2885 * it does not check for handshake done or client socket. */
2886 PySSLSession *pysess;
2887 SSL_SESSION *session;
2888
2889#ifdef OPENSSL_VERSION_1_1
2890 /* duplicate session as workaround for session bug in OpenSSL 1.1.0,
2891 * https://github.com/openssl/openssl/issues/1550 */
2892 session = SSL_get0_session(self->ssl); /* borrowed reference */
2893 if (session == NULL) {
2894 Py_RETURN_NONE;
2895 }
2896 if ((session = _ssl_session_dup(session)) == NULL) {
2897 return NULL;
2898 }
2899#else
2900 session = SSL_get1_session(self->ssl);
2901 if (session == NULL) {
2902 Py_RETURN_NONE;
2903 }
2904#endif
Christian Heimes5c36da72020-11-20 09:40:12 +01002905 pysess = PyObject_GC_New(PySSLSession, PySSLSession_Type);
Christian Heimes99a65702016-09-10 23:44:53 +02002906 if (pysess == NULL) {
2907 SSL_SESSION_free(session);
2908 return NULL;
2909 }
2910
2911 assert(self->ctx);
2912 pysess->ctx = self->ctx;
2913 Py_INCREF(pysess->ctx);
2914 pysess->session = session;
Christian Heimesa5d07652016-09-24 10:48:05 +02002915 PyObject_GC_Track(pysess);
Christian Heimes99a65702016-09-10 23:44:53 +02002916 return (PyObject *)pysess;
2917}
2918
2919static int PySSL_set_session(PySSLSocket *self, PyObject *value,
2920 void *closure)
2921 {
2922 PySSLSession *pysess;
2923#ifdef OPENSSL_VERSION_1_1
2924 SSL_SESSION *session;
2925#endif
2926 int result;
2927
2928 if (!PySSLSession_Check(value)) {
Ned Deily4531ec72018-06-11 20:26:28 -04002929 PyErr_SetString(PyExc_TypeError, "Value is not a SSLSession.");
Christian Heimes99a65702016-09-10 23:44:53 +02002930 return -1;
2931 }
2932 pysess = (PySSLSession *)value;
2933
2934 if (self->ctx->ctx != pysess->ctx->ctx) {
2935 PyErr_SetString(PyExc_ValueError,
2936 "Session refers to a different SSLContext.");
2937 return -1;
2938 }
2939 if (self->socket_type != PY_SSL_CLIENT) {
2940 PyErr_SetString(PyExc_ValueError,
2941 "Cannot set session for server-side SSLSocket.");
2942 return -1;
2943 }
Christian Heimes66dc33b2017-05-23 16:02:02 -07002944 if (SSL_is_init_finished(self->ssl)) {
Christian Heimes99a65702016-09-10 23:44:53 +02002945 PyErr_SetString(PyExc_ValueError,
2946 "Cannot set session after handshake.");
2947 return -1;
2948 }
2949#ifdef OPENSSL_VERSION_1_1
2950 /* duplicate session */
2951 if ((session = _ssl_session_dup(pysess->session)) == NULL) {
2952 return -1;
2953 }
2954 result = SSL_set_session(self->ssl, session);
2955 /* free duplicate, SSL_set_session() bumps ref count */
2956 SSL_SESSION_free(session);
2957#else
2958 result = SSL_set_session(self->ssl, pysess->session);
2959#endif
2960 if (result == 0) {
2961 _setSSLError(NULL, 0, __FILE__, __LINE__);
2962 return -1;
2963 }
2964 return 0;
2965}
2966
2967PyDoc_STRVAR(PySSL_set_session_doc,
2968"_setter_session(session)\n\
2969\
2970Get / set SSLSession.");
2971
2972static PyObject *
2973PySSL_get_session_reused(PySSLSocket *self, void *closure) {
2974 if (SSL_session_reused(self->ssl)) {
2975 Py_RETURN_TRUE;
2976 } else {
2977 Py_RETURN_FALSE;
2978 }
2979}
2980
2981PyDoc_STRVAR(PySSL_get_session_reused_doc,
2982"Was the client session reused during handshake?");
2983
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002984static PyGetSetDef ssl_getsetlist[] = {
2985 {"context", (getter) PySSL_get_context,
2986 (setter) PySSL_set_context, PySSL_set_context_doc},
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002987 {"server_side", (getter) PySSL_get_server_side, NULL,
2988 PySSL_get_server_side_doc},
2989 {"server_hostname", (getter) PySSL_get_server_hostname, NULL,
2990 PySSL_get_server_hostname_doc},
2991 {"owner", (getter) PySSL_get_owner, (setter) PySSL_set_owner,
2992 PySSL_get_owner_doc},
Christian Heimes99a65702016-09-10 23:44:53 +02002993 {"session", (getter) PySSL_get_session,
2994 (setter) PySSL_set_session, PySSL_set_session_doc},
2995 {"session_reused", (getter) PySSL_get_session_reused, NULL,
2996 PySSL_get_session_reused_doc},
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002997 {NULL}, /* sentinel */
2998};
2999
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003000static PyMethodDef PySSLMethods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003001 _SSL__SSLSOCKET_DO_HANDSHAKE_METHODDEF
3002 _SSL__SSLSOCKET_WRITE_METHODDEF
3003 _SSL__SSLSOCKET_READ_METHODDEF
3004 _SSL__SSLSOCKET_PENDING_METHODDEF
Christian Heimes141c5e82018-02-24 21:10:57 +01003005 _SSL__SSLSOCKET_GETPEERCERT_METHODDEF
3006 _SSL__SSLSOCKET_GET_CHANNEL_BINDING_METHODDEF
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003007 _SSL__SSLSOCKET_CIPHER_METHODDEF
3008 _SSL__SSLSOCKET_SHARED_CIPHERS_METHODDEF
3009 _SSL__SSLSOCKET_VERSION_METHODDEF
3010 _SSL__SSLSOCKET_SELECTED_NPN_PROTOCOL_METHODDEF
3011 _SSL__SSLSOCKET_SELECTED_ALPN_PROTOCOL_METHODDEF
3012 _SSL__SSLSOCKET_COMPRESSION_METHODDEF
3013 _SSL__SSLSOCKET_SHUTDOWN_METHODDEF
Christian Heimes9fb051f2018-09-23 08:32:31 +02003014 _SSL__SSLSOCKET_VERIFY_CLIENT_POST_HANDSHAKE_METHODDEF
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003015 {NULL, NULL}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003016};
3017
Christian Heimes5c36da72020-11-20 09:40:12 +01003018static PyType_Slot PySSLSocket_slots[] = {
3019 {Py_tp_methods, PySSLMethods},
3020 {Py_tp_getset, ssl_getsetlist},
3021 {Py_tp_dealloc, PySSL_dealloc},
3022 {Py_tp_traverse, PySSL_traverse},
3023 {Py_tp_clear, PySSL_clear},
3024 {0, 0},
3025};
3026
3027static PyType_Spec PySSLSocket_spec = {
3028 "_ssl._SSLSocket",
3029 sizeof(PySSLSocket),
3030 0,
3031 Py_TPFLAGS_DEFAULT,
3032 PySSLSocket_slots,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003033};
3034
Antoine Pitrou152efa22010-05-16 18:19:27 +00003035
3036/*
3037 * _SSLContext objects
3038 */
3039
Christian Heimes5fe668c2016-09-12 00:01:11 +02003040static int
Christian Heimes9fb051f2018-09-23 08:32:31 +02003041_set_verify_mode(PySSLContext *self, enum py_ssl_cert_requirements n)
Christian Heimes5fe668c2016-09-12 00:01:11 +02003042{
3043 int mode;
3044 int (*verify_cb)(int, X509_STORE_CTX *) = NULL;
3045
3046 switch(n) {
3047 case PY_SSL_CERT_NONE:
3048 mode = SSL_VERIFY_NONE;
3049 break;
3050 case PY_SSL_CERT_OPTIONAL:
3051 mode = SSL_VERIFY_PEER;
3052 break;
3053 case PY_SSL_CERT_REQUIRED:
3054 mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
3055 break;
3056 default:
3057 PyErr_SetString(PyExc_ValueError,
3058 "invalid value for verify_mode");
3059 return -1;
3060 }
Christian Heimesf0f59302019-07-01 08:29:17 +02003061
3062 /* bpo-37428: newPySSLSocket() sets SSL_VERIFY_POST_HANDSHAKE flag for
3063 * server sockets and SSL_set_post_handshake_auth() for client. */
3064
Christian Heimes5fe668c2016-09-12 00:01:11 +02003065 /* keep current verify cb */
Christian Heimes9fb051f2018-09-23 08:32:31 +02003066 verify_cb = SSL_CTX_get_verify_callback(self->ctx);
3067 SSL_CTX_set_verify(self->ctx, mode, verify_cb);
Christian Heimes5fe668c2016-09-12 00:01:11 +02003068 return 0;
3069}
3070
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003071/*[clinic input]
3072@classmethod
3073_ssl._SSLContext.__new__
3074 protocol as proto_version: int
3075 /
3076[clinic start generated code]*/
3077
Antoine Pitrou152efa22010-05-16 18:19:27 +00003078static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003079_ssl__SSLContext_impl(PyTypeObject *type, int proto_version)
3080/*[clinic end generated code: output=2cf0d7a0741b6bd1 input=8d58a805b95fc534]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003081{
Antoine Pitrou152efa22010-05-16 18:19:27 +00003082 PySSLContext *self;
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01003083 long options;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003084 SSL_CTX *ctx = NULL;
Christian Heimes61d478c2018-01-27 15:51:38 +01003085 X509_VERIFY_PARAM *params;
Christian Heimes358cfd42016-09-10 22:43:48 +02003086 int result;
Berker Peksagdfcb0412016-04-14 16:48:48 +03003087#if defined(SSL_MODE_RELEASE_BUFFERS)
Benjamin Peterson3b1a8b32016-01-07 21:37:37 -08003088 unsigned long libver;
Berker Peksagdfcb0412016-04-14 16:48:48 +03003089#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00003090
Antoine Pitrou152efa22010-05-16 18:19:27 +00003091 PySSL_BEGIN_ALLOW_THREADS
Christian Heimes6e8cda92020-05-16 03:33:05 +02003092 switch(proto_version) {
3093#if defined(SSL3_VERSION) && !defined(OPENSSL_NO_SSL3)
3094 case PY_SSL_VERSION_SSL3:
Antoine Pitrou152efa22010-05-16 18:19:27 +00003095 ctx = SSL_CTX_new(SSLv3_method());
Christian Heimes6e8cda92020-05-16 03:33:05 +02003096 break;
Benjamin Petersone32467c2014-12-05 21:59:35 -05003097#endif
Christian Heimesa871f692020-06-01 08:58:14 +02003098#if (defined(TLS1_VERSION) && \
3099 !defined(OPENSSL_NO_TLS1) && \
3100 !defined(OPENSSL_NO_TLS1_METHOD))
Christian Heimes6e8cda92020-05-16 03:33:05 +02003101 case PY_SSL_VERSION_TLS1:
3102 ctx = SSL_CTX_new(TLSv1_method());
3103 break;
Victor Stinner3de49192011-05-09 00:42:58 +02003104#endif
Christian Heimesa871f692020-06-01 08:58:14 +02003105#if (defined(TLS1_1_VERSION) && \
3106 !defined(OPENSSL_NO_TLS1_1) && \
3107 !defined(OPENSSL_NO_TLS1_1_METHOD))
Christian Heimes6e8cda92020-05-16 03:33:05 +02003108 case PY_SSL_VERSION_TLS1_1:
3109 ctx = SSL_CTX_new(TLSv1_1_method());
3110 break;
3111#endif
Christian Heimesa871f692020-06-01 08:58:14 +02003112#if (defined(TLS1_2_VERSION) && \
3113 !defined(OPENSSL_NO_TLS1_2) && \
3114 !defined(OPENSSL_NO_TLS1_2_METHOD))
Christian Heimes6e8cda92020-05-16 03:33:05 +02003115 case PY_SSL_VERSION_TLS1_2:
3116 ctx = SSL_CTX_new(TLSv1_2_method());
3117 break;
3118#endif
3119 case PY_SSL_VERSION_TLS:
3120 /* SSLv23 */
Christian Heimes598894f2016-09-05 23:19:05 +02003121 ctx = SSL_CTX_new(TLS_method());
Christian Heimes6e8cda92020-05-16 03:33:05 +02003122 break;
3123 case PY_SSL_VERSION_TLS_CLIENT:
Christian Heimes5fe668c2016-09-12 00:01:11 +02003124 ctx = SSL_CTX_new(TLS_client_method());
Christian Heimes6e8cda92020-05-16 03:33:05 +02003125 break;
3126 case PY_SSL_VERSION_TLS_SERVER:
Christian Heimes5fe668c2016-09-12 00:01:11 +02003127 ctx = SSL_CTX_new(TLS_server_method());
Christian Heimes6e8cda92020-05-16 03:33:05 +02003128 break;
3129 default:
Antoine Pitrou152efa22010-05-16 18:19:27 +00003130 proto_version = -1;
Christian Heimes6e8cda92020-05-16 03:33:05 +02003131 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003132 PySSL_END_ALLOW_THREADS
3133
3134 if (proto_version == -1) {
3135 PyErr_SetString(PyExc_ValueError,
Christian Heimes6e8cda92020-05-16 03:33:05 +02003136 "invalid or unsupported protocol version");
Antoine Pitrou152efa22010-05-16 18:19:27 +00003137 return NULL;
3138 }
3139 if (ctx == NULL) {
Christian Heimes17c9ac92017-09-07 14:14:00 -07003140 _setSSLError(NULL, 0, __FILE__, __LINE__);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003141 return NULL;
3142 }
3143
3144 assert(type != NULL && type->tp_alloc != NULL);
3145 self = (PySSLContext *) type->tp_alloc(type, 0);
3146 if (self == NULL) {
3147 SSL_CTX_free(ctx);
3148 return NULL;
3149 }
3150 self->ctx = ctx;
Christian Heimes61d478c2018-01-27 15:51:38 +01003151 self->hostflags = X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS;
Christian Heimes11a14932018-02-24 02:35:08 +01003152 self->protocol = proto_version;
Christian Heimesc7f70692019-05-31 11:44:05 +02003153 self->msg_cb = NULL;
3154#ifdef HAVE_OPENSSL_KEYLOG
3155 self->keylog_filename = NULL;
3156 self->keylog_bio = NULL;
3157#endif
Christian Heimes29eab552018-02-25 12:31:33 +01003158#if HAVE_NPN
Christian Heimes5cb31c92012-09-20 12:42:54 +02003159 self->npn_protocols = NULL;
3160#endif
Christian Heimes29eab552018-02-25 12:31:33 +01003161#if HAVE_ALPN
Benjamin Petersoncca27322015-01-23 16:35:37 -05003162 self->alpn_protocols = NULL;
3163#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003164#ifndef OPENSSL_NO_TLSEXT
Christian Heimes11a14932018-02-24 02:35:08 +01003165 self->set_sni_cb = NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003166#endif
Christian Heimes1aa9a752013-12-02 02:41:19 +01003167 /* Don't check host name by default */
Christian Heimes5fe668c2016-09-12 00:01:11 +02003168 if (proto_version == PY_SSL_VERSION_TLS_CLIENT) {
3169 self->check_hostname = 1;
Christian Heimes9fb051f2018-09-23 08:32:31 +02003170 if (_set_verify_mode(self, PY_SSL_CERT_REQUIRED) == -1) {
Christian Heimes5fe668c2016-09-12 00:01:11 +02003171 Py_DECREF(self);
3172 return NULL;
3173 }
3174 } else {
3175 self->check_hostname = 0;
Christian Heimes9fb051f2018-09-23 08:32:31 +02003176 if (_set_verify_mode(self, PY_SSL_CERT_NONE) == -1) {
Christian Heimes5fe668c2016-09-12 00:01:11 +02003177 Py_DECREF(self);
3178 return NULL;
3179 }
3180 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003181 /* Defaults */
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01003182 options = SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
3183 if (proto_version != PY_SSL_VERSION_SSL2)
3184 options |= SSL_OP_NO_SSLv2;
Benjamin Petersona9dcdab2015-11-11 22:38:41 -08003185 if (proto_version != PY_SSL_VERSION_SSL3)
3186 options |= SSL_OP_NO_SSLv3;
Christian Heimes358cfd42016-09-10 22:43:48 +02003187 /* Minimal security flags for server and client side context.
3188 * Client sockets ignore server-side parameters. */
3189#ifdef SSL_OP_NO_COMPRESSION
3190 options |= SSL_OP_NO_COMPRESSION;
3191#endif
3192#ifdef SSL_OP_CIPHER_SERVER_PREFERENCE
3193 options |= SSL_OP_CIPHER_SERVER_PREFERENCE;
3194#endif
3195#ifdef SSL_OP_SINGLE_DH_USE
3196 options |= SSL_OP_SINGLE_DH_USE;
3197#endif
3198#ifdef SSL_OP_SINGLE_ECDH_USE
3199 options |= SSL_OP_SINGLE_ECDH_USE;
3200#endif
Christian Heimes6f37ebc2021-04-09 17:59:21 +02003201#ifdef SSL_OP_IGNORE_UNEXPECTED_EOF
3202 /* Make OpenSSL 3.0.0 behave like 1.1.1 */
3203 options |= SSL_OP_IGNORE_UNEXPECTED_EOF;
3204#endif
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01003205 SSL_CTX_set_options(self->ctx, options);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003206
Semen Zhydenko1295e112017-10-15 21:28:31 +02003207 /* A bare minimum cipher list without completely broken cipher suites.
Christian Heimes358cfd42016-09-10 22:43:48 +02003208 * It's far from perfect but gives users a better head start. */
3209 if (proto_version != PY_SSL_VERSION_SSL2) {
Christian Heimes892d66e2018-01-29 14:10:18 +01003210#if PY_SSL_DEFAULT_CIPHERS == 2
3211 /* stick to OpenSSL's default settings */
3212 result = 1;
3213#else
3214 result = SSL_CTX_set_cipher_list(ctx, PY_SSL_DEFAULT_CIPHER_STRING);
3215#endif
Christian Heimes358cfd42016-09-10 22:43:48 +02003216 } else {
3217 /* SSLv2 needs MD5 */
3218 result = SSL_CTX_set_cipher_list(ctx, "HIGH:!aNULL:!eNULL");
3219 }
3220 if (result == 0) {
3221 Py_DECREF(self);
3222 ERR_clear_error();
3223 PyErr_SetString(PySSLErrorObject,
3224 "No cipher can be selected.");
3225 return NULL;
3226 }
3227
Benjamin Peterson3b1a8b32016-01-07 21:37:37 -08003228#if defined(SSL_MODE_RELEASE_BUFFERS)
3229 /* Set SSL_MODE_RELEASE_BUFFERS. This potentially greatly reduces memory
3230 usage for no cost at all. However, don't do this for OpenSSL versions
3231 between 1.0.1 and 1.0.1h or 1.0.0 and 1.0.0m, which are affected by CVE
3232 2014-0198. I can't find exactly which beta fixed this CVE, so be
3233 conservative and assume it wasn't fixed until release. We do this check
3234 at runtime to avoid problems from the dynamic linker.
3235 See #25672 for more on this. */
Christian Heimesa871f692020-06-01 08:58:14 +02003236 libver = OpenSSL_version_num();
Benjamin Peterson3b1a8b32016-01-07 21:37:37 -08003237 if (!(libver >= 0x10001000UL && libver < 0x1000108fUL) &&
3238 !(libver >= 0x10000000UL && libver < 0x100000dfUL)) {
3239 SSL_CTX_set_mode(self->ctx, SSL_MODE_RELEASE_BUFFERS);
3240 }
3241#endif
3242
3243
Donald Stufft8ae264c2017-03-02 11:45:29 -05003244#if !defined(OPENSSL_NO_ECDH) && !defined(OPENSSL_VERSION_1_1)
Antoine Pitrou0bebbc32014-03-22 18:13:50 +01003245 /* Allow automatic ECDH curve selection (on OpenSSL 1.0.2+), or use
3246 prime256v1 by default. This is Apache mod_ssl's initialization
Christian Heimes598894f2016-09-05 23:19:05 +02003247 policy, so we should be safe. OpenSSL 1.1 has it enabled by default.
3248 */
Donald Stufft8ae264c2017-03-02 11:45:29 -05003249#if defined(SSL_CTX_set_ecdh_auto)
Antoine Pitrou0bebbc32014-03-22 18:13:50 +01003250 SSL_CTX_set_ecdh_auto(self->ctx, 1);
3251#else
3252 {
3253 EC_KEY *key = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
3254 SSL_CTX_set_tmp_ecdh(self->ctx, key);
3255 EC_KEY_free(key);
3256 }
3257#endif
3258#endif
3259
Antoine Pitroufc113ee2010-10-13 12:46:13 +00003260#define SID_CTX "Python"
3261 SSL_CTX_set_session_id_context(self->ctx, (const unsigned char *) SID_CTX,
3262 sizeof(SID_CTX));
3263#undef SID_CTX
3264
Christian Heimes61d478c2018-01-27 15:51:38 +01003265 params = SSL_CTX_get0_param(self->ctx);
Benjamin Petersonfdb19712015-03-04 22:11:12 -05003266#ifdef X509_V_FLAG_TRUSTED_FIRST
Christian Heimes61d478c2018-01-27 15:51:38 +01003267 /* Improve trust chain building when cross-signed intermediate
3268 certificates are present. See https://bugs.python.org/issue23476. */
3269 X509_VERIFY_PARAM_set_flags(params, X509_V_FLAG_TRUSTED_FIRST);
Benjamin Petersonfdb19712015-03-04 22:11:12 -05003270#endif
Christian Heimes61d478c2018-01-27 15:51:38 +01003271 X509_VERIFY_PARAM_set_hostflags(params, self->hostflags);
Benjamin Petersonfdb19712015-03-04 22:11:12 -05003272
Christian Heimes9fb051f2018-09-23 08:32:31 +02003273#ifdef TLS1_3_VERSION
3274 self->post_handshake_auth = 0;
3275 SSL_CTX_set_post_handshake_auth(self->ctx, self->post_handshake_auth);
3276#endif
3277
Antoine Pitrou152efa22010-05-16 18:19:27 +00003278 return (PyObject *)self;
3279}
3280
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003281static int
3282context_traverse(PySSLContext *self, visitproc visit, void *arg)
3283{
3284#ifndef OPENSSL_NO_TLSEXT
Christian Heimes11a14932018-02-24 02:35:08 +01003285 Py_VISIT(self->set_sni_cb);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003286#endif
Christian Heimesc7f70692019-05-31 11:44:05 +02003287 Py_VISIT(self->msg_cb);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003288 return 0;
3289}
3290
3291static int
3292context_clear(PySSLContext *self)
3293{
3294#ifndef OPENSSL_NO_TLSEXT
Christian Heimes11a14932018-02-24 02:35:08 +01003295 Py_CLEAR(self->set_sni_cb);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003296#endif
Christian Heimesc7f70692019-05-31 11:44:05 +02003297 Py_CLEAR(self->msg_cb);
3298#ifdef HAVE_OPENSSL_KEYLOG
3299 Py_CLEAR(self->keylog_filename);
3300 if (self->keylog_bio != NULL) {
3301 PySSL_BEGIN_ALLOW_THREADS
3302 BIO_free_all(self->keylog_bio);
3303 PySSL_END_ALLOW_THREADS
3304 self->keylog_bio = NULL;
3305 }
3306#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003307 return 0;
3308}
3309
Antoine Pitrou152efa22010-05-16 18:19:27 +00003310static void
3311context_dealloc(PySSLContext *self)
3312{
Christian Heimes5c36da72020-11-20 09:40:12 +01003313 PyTypeObject *tp = Py_TYPE(self);
INADA Naokia6296d32017-08-24 14:55:17 +09003314 /* bpo-31095: UnTrack is needed before calling any callbacks */
3315 PyObject_GC_UnTrack(self);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003316 context_clear(self);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003317 SSL_CTX_free(self->ctx);
Christian Heimes29eab552018-02-25 12:31:33 +01003318#if HAVE_NPN
Victor Stinner00d7abd2020-12-01 09:56:42 +01003319 PyMem_Free(self->npn_protocols);
Benjamin Petersoncca27322015-01-23 16:35:37 -05003320#endif
Christian Heimes29eab552018-02-25 12:31:33 +01003321#if HAVE_ALPN
Victor Stinner00d7abd2020-12-01 09:56:42 +01003322 PyMem_Free(self->alpn_protocols);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003323#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00003324 Py_TYPE(self)->tp_free(self);
Christian Heimes5c36da72020-11-20 09:40:12 +01003325 Py_DECREF(tp);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003326}
3327
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003328/*[clinic input]
3329_ssl._SSLContext.set_ciphers
3330 cipherlist: str
3331 /
3332[clinic start generated code]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003333
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003334static PyObject *
3335_ssl__SSLContext_set_ciphers_impl(PySSLContext *self, const char *cipherlist)
3336/*[clinic end generated code: output=3a3162f3557c0f3f input=a7ac931b9f3ca7fc]*/
3337{
3338 int ret = SSL_CTX_set_cipher_list(self->ctx, cipherlist);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003339 if (ret == 0) {
Antoine Pitrou65ec8ae2010-05-16 19:56:32 +00003340 /* Clearing the error queue is necessary on some OpenSSL versions,
3341 otherwise the error will be reported again when another SSL call
3342 is done. */
3343 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00003344 PyErr_SetString(PySSLErrorObject,
3345 "No cipher can be selected.");
3346 return NULL;
3347 }
3348 Py_RETURN_NONE;
3349}
3350
Christian Heimes25bfcd52016-09-06 00:04:45 +02003351#if OPENSSL_VERSION_NUMBER >= 0x10002000UL
3352/*[clinic input]
3353_ssl._SSLContext.get_ciphers
3354[clinic start generated code]*/
3355
3356static PyObject *
3357_ssl__SSLContext_get_ciphers_impl(PySSLContext *self)
3358/*[clinic end generated code: output=a56e4d68a406dfc4 input=a2aadc9af89b79c5]*/
3359{
3360 SSL *ssl = NULL;
3361 STACK_OF(SSL_CIPHER) *sk = NULL;
Christian Heimes99a65702016-09-10 23:44:53 +02003362 const SSL_CIPHER *cipher;
Christian Heimes25bfcd52016-09-06 00:04:45 +02003363 int i=0;
3364 PyObject *result = NULL, *dct;
3365
3366 ssl = SSL_new(self->ctx);
3367 if (ssl == NULL) {
3368 _setSSLError(NULL, 0, __FILE__, __LINE__);
3369 goto exit;
3370 }
3371 sk = SSL_get_ciphers(ssl);
3372
3373 result = PyList_New(sk_SSL_CIPHER_num(sk));
3374 if (result == NULL) {
3375 goto exit;
3376 }
3377
3378 for (i = 0; i < sk_SSL_CIPHER_num(sk); i++) {
3379 cipher = sk_SSL_CIPHER_value(sk, i);
3380 dct = cipher_to_dict(cipher);
3381 if (dct == NULL) {
3382 Py_CLEAR(result);
3383 goto exit;
3384 }
3385 PyList_SET_ITEM(result, i, dct);
3386 }
3387
3388 exit:
3389 if (ssl != NULL)
3390 SSL_free(ssl);
3391 return result;
3392
3393}
3394#endif
3395
3396
Christian Heimes29eab552018-02-25 12:31:33 +01003397#if HAVE_NPN || HAVE_ALPN
Benjamin Petersoncca27322015-01-23 16:35:37 -05003398static int
Benjamin Peterson88615022015-01-23 17:30:26 -05003399do_protocol_selection(int alpn, unsigned char **out, unsigned char *outlen,
3400 const unsigned char *server_protocols, unsigned int server_protocols_len,
3401 const unsigned char *client_protocols, unsigned int client_protocols_len)
Benjamin Petersoncca27322015-01-23 16:35:37 -05003402{
Benjamin Peterson88615022015-01-23 17:30:26 -05003403 int ret;
3404 if (client_protocols == NULL) {
3405 client_protocols = (unsigned char *)"";
3406 client_protocols_len = 0;
3407 }
3408 if (server_protocols == NULL) {
3409 server_protocols = (unsigned char *)"";
3410 server_protocols_len = 0;
Benjamin Petersoncca27322015-01-23 16:35:37 -05003411 }
3412
Benjamin Peterson88615022015-01-23 17:30:26 -05003413 ret = SSL_select_next_proto(out, outlen,
3414 server_protocols, server_protocols_len,
3415 client_protocols, client_protocols_len);
3416 if (alpn && ret != OPENSSL_NPN_NEGOTIATED)
3417 return SSL_TLSEXT_ERR_NOACK;
Benjamin Petersoncca27322015-01-23 16:35:37 -05003418
3419 return SSL_TLSEXT_ERR_OK;
3420}
Melvyn Sopacuab2d096b2017-09-04 23:35:15 +02003421#endif
Benjamin Petersoncca27322015-01-23 16:35:37 -05003422
Christian Heimes29eab552018-02-25 12:31:33 +01003423#if HAVE_NPN
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003424/* this callback gets passed to SSL_CTX_set_next_protos_advertise_cb */
3425static int
Victor Stinner4569cd52013-06-23 14:58:43 +02003426_advertiseNPN_cb(SSL *s,
3427 const unsigned char **data, unsigned int *len,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003428 void *args)
3429{
3430 PySSLContext *ssl_ctx = (PySSLContext *) args;
3431
3432 if (ssl_ctx->npn_protocols == NULL) {
Benjamin Petersoncca27322015-01-23 16:35:37 -05003433 *data = (unsigned char *)"";
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003434 *len = 0;
3435 } else {
Benjamin Petersoncca27322015-01-23 16:35:37 -05003436 *data = ssl_ctx->npn_protocols;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003437 *len = ssl_ctx->npn_protocols_len;
3438 }
3439
3440 return SSL_TLSEXT_ERR_OK;
3441}
3442/* this callback gets passed to SSL_CTX_set_next_proto_select_cb */
3443static int
Victor Stinner4569cd52013-06-23 14:58:43 +02003444_selectNPN_cb(SSL *s,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003445 unsigned char **out, unsigned char *outlen,
3446 const unsigned char *server, unsigned int server_len,
3447 void *args)
3448{
Benjamin Petersoncca27322015-01-23 16:35:37 -05003449 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Peterson88615022015-01-23 17:30:26 -05003450 return do_protocol_selection(0, out, outlen, server, server_len,
Benjamin Petersoncca27322015-01-23 16:35:37 -05003451 ctx->npn_protocols, ctx->npn_protocols_len);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003452}
3453#endif
3454
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003455/*[clinic input]
3456_ssl._SSLContext._set_npn_protocols
3457 protos: Py_buffer
3458 /
3459[clinic start generated code]*/
3460
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003461static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003462_ssl__SSLContext__set_npn_protocols_impl(PySSLContext *self,
3463 Py_buffer *protos)
3464/*[clinic end generated code: output=72b002c3324390c6 input=319fcb66abf95bd7]*/
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003465{
Christian Heimes29eab552018-02-25 12:31:33 +01003466#if HAVE_NPN
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003467 PyMem_Free(self->npn_protocols);
3468 self->npn_protocols = PyMem_Malloc(protos->len);
3469 if (self->npn_protocols == NULL)
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003470 return PyErr_NoMemory();
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003471 memcpy(self->npn_protocols, protos->buf, protos->len);
3472 self->npn_protocols_len = (int) protos->len;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003473
3474 /* set both server and client callbacks, because the context can
3475 * be used to create both types of sockets */
3476 SSL_CTX_set_next_protos_advertised_cb(self->ctx,
3477 _advertiseNPN_cb,
3478 self);
3479 SSL_CTX_set_next_proto_select_cb(self->ctx,
3480 _selectNPN_cb,
3481 self);
3482
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003483 Py_RETURN_NONE;
3484#else
3485 PyErr_SetString(PyExc_NotImplementedError,
3486 "The NPN extension requires OpenSSL 1.0.1 or later.");
3487 return NULL;
3488#endif
3489}
3490
Christian Heimes29eab552018-02-25 12:31:33 +01003491#if HAVE_ALPN
Benjamin Petersoncca27322015-01-23 16:35:37 -05003492static int
3493_selectALPN_cb(SSL *s,
3494 const unsigned char **out, unsigned char *outlen,
3495 const unsigned char *client_protocols, unsigned int client_protocols_len,
3496 void *args)
3497{
3498 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Peterson88615022015-01-23 17:30:26 -05003499 return do_protocol_selection(1, (unsigned char **)out, outlen,
3500 ctx->alpn_protocols, ctx->alpn_protocols_len,
3501 client_protocols, client_protocols_len);
Benjamin Petersoncca27322015-01-23 16:35:37 -05003502}
3503#endif
3504
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003505/*[clinic input]
3506_ssl._SSLContext._set_alpn_protocols
3507 protos: Py_buffer
3508 /
3509[clinic start generated code]*/
3510
Benjamin Petersoncca27322015-01-23 16:35:37 -05003511static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003512_ssl__SSLContext__set_alpn_protocols_impl(PySSLContext *self,
3513 Py_buffer *protos)
3514/*[clinic end generated code: output=87599a7f76651a9b input=9bba964595d519be]*/
Benjamin Petersoncca27322015-01-23 16:35:37 -05003515{
Christian Heimes29eab552018-02-25 12:31:33 +01003516#if HAVE_ALPN
Victor Stinner5a615592017-09-14 01:10:30 -07003517 if ((size_t)protos->len > UINT_MAX) {
Segev Finer5cff6372017-07-27 01:19:17 +03003518 PyErr_Format(PyExc_OverflowError,
Serhiy Storchakad53fe5f2019-03-13 22:59:55 +02003519 "protocols longer than %u bytes", UINT_MAX);
Segev Finer5cff6372017-07-27 01:19:17 +03003520 return NULL;
3521 }
3522
Victor Stinner00d7abd2020-12-01 09:56:42 +01003523 PyMem_Free(self->alpn_protocols);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003524 self->alpn_protocols = PyMem_Malloc(protos->len);
Benjamin Petersoncca27322015-01-23 16:35:37 -05003525 if (!self->alpn_protocols)
3526 return PyErr_NoMemory();
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003527 memcpy(self->alpn_protocols, protos->buf, protos->len);
Segev Finer5cff6372017-07-27 01:19:17 +03003528 self->alpn_protocols_len = (unsigned int)protos->len;
Benjamin Petersoncca27322015-01-23 16:35:37 -05003529
3530 if (SSL_CTX_set_alpn_protos(self->ctx, self->alpn_protocols, self->alpn_protocols_len))
3531 return PyErr_NoMemory();
3532 SSL_CTX_set_alpn_select_cb(self->ctx, _selectALPN_cb, self);
3533
Benjamin Petersoncca27322015-01-23 16:35:37 -05003534 Py_RETURN_NONE;
3535#else
3536 PyErr_SetString(PyExc_NotImplementedError,
3537 "The ALPN extension requires OpenSSL 1.0.2 or later.");
3538 return NULL;
3539#endif
3540}
3541
Antoine Pitrou152efa22010-05-16 18:19:27 +00003542static PyObject *
3543get_verify_mode(PySSLContext *self, void *c)
3544{
Christian Heimes9fb051f2018-09-23 08:32:31 +02003545 /* ignore SSL_VERIFY_CLIENT_ONCE and SSL_VERIFY_POST_HANDSHAKE */
3546 int mask = (SSL_VERIFY_NONE | SSL_VERIFY_PEER |
3547 SSL_VERIFY_FAIL_IF_NO_PEER_CERT);
3548 switch (SSL_CTX_get_verify_mode(self->ctx) & mask) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003549 case SSL_VERIFY_NONE:
3550 return PyLong_FromLong(PY_SSL_CERT_NONE);
3551 case SSL_VERIFY_PEER:
3552 return PyLong_FromLong(PY_SSL_CERT_OPTIONAL);
3553 case SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT:
3554 return PyLong_FromLong(PY_SSL_CERT_REQUIRED);
3555 }
3556 PyErr_SetString(PySSLErrorObject,
3557 "invalid return value from SSL_CTX_get_verify_mode");
3558 return NULL;
3559}
3560
3561static int
3562set_verify_mode(PySSLContext *self, PyObject *arg, void *c)
3563{
Christian Heimes5fe668c2016-09-12 00:01:11 +02003564 int n;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003565 if (!PyArg_Parse(arg, "i", &n))
3566 return -1;
Christian Heimes5fe668c2016-09-12 00:01:11 +02003567 if (n == PY_SSL_CERT_NONE && self->check_hostname) {
Christian Heimes1aa9a752013-12-02 02:41:19 +01003568 PyErr_SetString(PyExc_ValueError,
3569 "Cannot set verify_mode to CERT_NONE when "
3570 "check_hostname is enabled.");
3571 return -1;
3572 }
Christian Heimes9fb051f2018-09-23 08:32:31 +02003573 return _set_verify_mode(self, n);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003574}
3575
3576static PyObject *
Christian Heimes22587792013-11-21 23:56:13 +01003577get_verify_flags(PySSLContext *self, void *c)
3578{
Christian Heimes598894f2016-09-05 23:19:05 +02003579 X509_VERIFY_PARAM *param;
Christian Heimes22587792013-11-21 23:56:13 +01003580 unsigned long flags;
3581
Christian Heimes61d478c2018-01-27 15:51:38 +01003582 param = SSL_CTX_get0_param(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02003583 flags = X509_VERIFY_PARAM_get_flags(param);
Christian Heimes22587792013-11-21 23:56:13 +01003584 return PyLong_FromUnsignedLong(flags);
3585}
3586
3587static int
3588set_verify_flags(PySSLContext *self, PyObject *arg, void *c)
3589{
Christian Heimes598894f2016-09-05 23:19:05 +02003590 X509_VERIFY_PARAM *param;
Christian Heimes22587792013-11-21 23:56:13 +01003591 unsigned long new_flags, flags, set, clear;
3592
3593 if (!PyArg_Parse(arg, "k", &new_flags))
3594 return -1;
Christian Heimes61d478c2018-01-27 15:51:38 +01003595 param = SSL_CTX_get0_param(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02003596 flags = X509_VERIFY_PARAM_get_flags(param);
Christian Heimes22587792013-11-21 23:56:13 +01003597 clear = flags & ~new_flags;
3598 set = ~flags & new_flags;
3599 if (clear) {
Christian Heimes598894f2016-09-05 23:19:05 +02003600 if (!X509_VERIFY_PARAM_clear_flags(param, clear)) {
Christian Heimes22587792013-11-21 23:56:13 +01003601 _setSSLError(NULL, 0, __FILE__, __LINE__);
3602 return -1;
3603 }
3604 }
3605 if (set) {
Christian Heimes598894f2016-09-05 23:19:05 +02003606 if (!X509_VERIFY_PARAM_set_flags(param, set)) {
Christian Heimes22587792013-11-21 23:56:13 +01003607 _setSSLError(NULL, 0, __FILE__, __LINE__);
3608 return -1;
3609 }
3610 }
3611 return 0;
3612}
3613
Christian Heimes698dde12018-02-27 11:54:43 +01003614/* Getter and setter for protocol version */
3615#if defined(SSL_CTRL_GET_MAX_PROTO_VERSION)
3616
3617
3618static int
3619set_min_max_proto_version(PySSLContext *self, PyObject *arg, int what)
3620{
3621 long v;
3622 int result;
3623
3624 if (!PyArg_Parse(arg, "l", &v))
3625 return -1;
3626 if (v > INT_MAX) {
3627 PyErr_SetString(PyExc_OverflowError, "Option is too long");
3628 return -1;
3629 }
3630
3631 switch(self->protocol) {
3632 case PY_SSL_VERSION_TLS_CLIENT: /* fall through */
3633 case PY_SSL_VERSION_TLS_SERVER: /* fall through */
3634 case PY_SSL_VERSION_TLS:
3635 break;
3636 default:
3637 PyErr_SetString(
3638 PyExc_ValueError,
3639 "The context's protocol doesn't support modification of "
3640 "highest and lowest version."
3641 );
3642 return -1;
3643 }
3644
3645 if (what == 0) {
3646 switch(v) {
3647 case PY_PROTO_MINIMUM_SUPPORTED:
3648 v = 0;
3649 break;
3650 case PY_PROTO_MAXIMUM_SUPPORTED:
3651 /* Emulate max for set_min_proto_version */
3652 v = PY_PROTO_MAXIMUM_AVAILABLE;
3653 break;
3654 default:
3655 break;
3656 }
3657 result = SSL_CTX_set_min_proto_version(self->ctx, v);
3658 }
3659 else {
3660 switch(v) {
3661 case PY_PROTO_MAXIMUM_SUPPORTED:
3662 v = 0;
3663 break;
3664 case PY_PROTO_MINIMUM_SUPPORTED:
3665 /* Emulate max for set_min_proto_version */
3666 v = PY_PROTO_MINIMUM_AVAILABLE;
3667 break;
3668 default:
3669 break;
3670 }
3671 result = SSL_CTX_set_max_proto_version(self->ctx, v);
3672 }
3673 if (result == 0) {
3674 PyErr_Format(PyExc_ValueError,
3675 "Unsupported protocol version 0x%x", v);
3676 return -1;
3677 }
3678 return 0;
3679}
3680
3681static PyObject *
3682get_minimum_version(PySSLContext *self, void *c)
3683{
3684 int v = SSL_CTX_ctrl(self->ctx, SSL_CTRL_GET_MIN_PROTO_VERSION, 0, NULL);
3685 if (v == 0) {
3686 v = PY_PROTO_MINIMUM_SUPPORTED;
3687 }
3688 return PyLong_FromLong(v);
3689}
3690
3691static int
3692set_minimum_version(PySSLContext *self, PyObject *arg, void *c)
3693{
3694 return set_min_max_proto_version(self, arg, 0);
3695}
3696
3697static PyObject *
3698get_maximum_version(PySSLContext *self, void *c)
3699{
3700 int v = SSL_CTX_ctrl(self->ctx, SSL_CTRL_GET_MAX_PROTO_VERSION, 0, NULL);
3701 if (v == 0) {
3702 v = PY_PROTO_MAXIMUM_SUPPORTED;
3703 }
3704 return PyLong_FromLong(v);
3705}
3706
3707static int
3708set_maximum_version(PySSLContext *self, PyObject *arg, void *c)
3709{
3710 return set_min_max_proto_version(self, arg, 1);
3711}
3712#endif /* SSL_CTRL_GET_MAX_PROTO_VERSION */
3713
Christian Heimes78c7d522019-06-03 21:00:10 +02003714#if (OPENSSL_VERSION_NUMBER >= 0x10101000L) && !defined(LIBRESSL_VERSION_NUMBER)
3715static PyObject *
3716get_num_tickets(PySSLContext *self, void *c)
3717{
Victor Stinner76611c72019-07-09 13:30:52 +02003718 return PyLong_FromSize_t(SSL_CTX_get_num_tickets(self->ctx));
Christian Heimes78c7d522019-06-03 21:00:10 +02003719}
3720
3721static int
3722set_num_tickets(PySSLContext *self, PyObject *arg, void *c)
3723{
3724 long num;
3725 if (!PyArg_Parse(arg, "l", &num))
3726 return -1;
3727 if (num < 0) {
3728 PyErr_SetString(PyExc_ValueError, "value must be non-negative");
3729 return -1;
3730 }
3731 if (self->protocol != PY_SSL_VERSION_TLS_SERVER) {
3732 PyErr_SetString(PyExc_ValueError,
3733 "SSLContext is not a server context.");
3734 return -1;
3735 }
3736 if (SSL_CTX_set_num_tickets(self->ctx, num) != 1) {
3737 PyErr_SetString(PyExc_ValueError, "failed to set num tickets.");
3738 return -1;
3739 }
3740 return 0;
3741}
3742
3743PyDoc_STRVAR(PySSLContext_num_tickets_doc,
3744"Control the number of TLSv1.3 session tickets");
3745#endif /* OpenSSL 1.1.1 */
3746
matthewhughes9348e836bb2020-07-17 09:59:15 +01003747#if (OPENSSL_VERSION_NUMBER >= 0x10100000L) && !defined(LIBRESSL_VERSION_NUMBER)
3748static PyObject *
3749get_security_level(PySSLContext *self, void *c)
3750{
3751 return PyLong_FromLong(SSL_CTX_get_security_level(self->ctx));
3752}
3753PyDoc_STRVAR(PySSLContext_security_level_doc, "The current security level");
3754#endif /* OpenSSL 1.1.0 */
3755
Christian Heimes22587792013-11-21 23:56:13 +01003756static PyObject *
Antoine Pitroub5218772010-05-21 09:56:06 +00003757get_options(PySSLContext *self, void *c)
3758{
3759 return PyLong_FromLong(SSL_CTX_get_options(self->ctx));
3760}
3761
3762static int
3763set_options(PySSLContext *self, PyObject *arg, void *c)
3764{
3765 long new_opts, opts, set, clear;
3766 if (!PyArg_Parse(arg, "l", &new_opts))
3767 return -1;
3768 opts = SSL_CTX_get_options(self->ctx);
3769 clear = opts & ~new_opts;
3770 set = ~opts & new_opts;
3771 if (clear) {
3772#ifdef HAVE_SSL_CTX_CLEAR_OPTIONS
3773 SSL_CTX_clear_options(self->ctx, clear);
3774#else
3775 PyErr_SetString(PyExc_ValueError,
3776 "can't clear options before OpenSSL 0.9.8m");
3777 return -1;
3778#endif
3779 }
3780 if (set)
3781 SSL_CTX_set_options(self->ctx, set);
3782 return 0;
3783}
3784
Christian Heimes1aa9a752013-12-02 02:41:19 +01003785static PyObject *
Christian Heimes61d478c2018-01-27 15:51:38 +01003786get_host_flags(PySSLContext *self, void *c)
3787{
3788 return PyLong_FromUnsignedLong(self->hostflags);
3789}
3790
3791static int
3792set_host_flags(PySSLContext *self, PyObject *arg, void *c)
3793{
3794 X509_VERIFY_PARAM *param;
3795 unsigned int new_flags = 0;
3796
3797 if (!PyArg_Parse(arg, "I", &new_flags))
3798 return -1;
3799
3800 param = SSL_CTX_get0_param(self->ctx);
3801 self->hostflags = new_flags;
3802 X509_VERIFY_PARAM_set_hostflags(param, new_flags);
3803 return 0;
3804}
3805
3806static PyObject *
Christian Heimes1aa9a752013-12-02 02:41:19 +01003807get_check_hostname(PySSLContext *self, void *c)
3808{
3809 return PyBool_FromLong(self->check_hostname);
3810}
3811
3812static int
3813set_check_hostname(PySSLContext *self, PyObject *arg, void *c)
3814{
3815 int check_hostname;
3816 if (!PyArg_Parse(arg, "p", &check_hostname))
3817 return -1;
3818 if (check_hostname &&
3819 SSL_CTX_get_verify_mode(self->ctx) == SSL_VERIFY_NONE) {
Christian Heimese82c0342017-09-15 20:29:57 +02003820 /* check_hostname = True sets verify_mode = CERT_REQUIRED */
Christian Heimes9fb051f2018-09-23 08:32:31 +02003821 if (_set_verify_mode(self, PY_SSL_CERT_REQUIRED) == -1) {
Christian Heimese82c0342017-09-15 20:29:57 +02003822 return -1;
3823 }
Christian Heimes1aa9a752013-12-02 02:41:19 +01003824 }
3825 self->check_hostname = check_hostname;
3826 return 0;
3827}
3828
Christian Heimes11a14932018-02-24 02:35:08 +01003829static PyObject *
Christian Heimes9fb051f2018-09-23 08:32:31 +02003830get_post_handshake_auth(PySSLContext *self, void *c) {
3831#if TLS1_3_VERSION
3832 return PyBool_FromLong(self->post_handshake_auth);
3833#else
3834 Py_RETURN_NONE;
3835#endif
3836}
3837
3838#if TLS1_3_VERSION
3839static int
3840set_post_handshake_auth(PySSLContext *self, PyObject *arg, void *c) {
Zackery Spytz842acaa2018-12-17 07:52:45 -07003841 if (arg == NULL) {
3842 PyErr_SetString(PyExc_AttributeError, "cannot delete attribute");
3843 return -1;
3844 }
Christian Heimes9fb051f2018-09-23 08:32:31 +02003845 int pha = PyObject_IsTrue(arg);
3846
3847 if (pha == -1) {
3848 return -1;
3849 }
3850 self->post_handshake_auth = pha;
3851
Christian Heimesf0f59302019-07-01 08:29:17 +02003852 /* bpo-37428: newPySSLSocket() sets SSL_VERIFY_POST_HANDSHAKE flag for
3853 * server sockets and SSL_set_post_handshake_auth() for client. */
Christian Heimes9fb051f2018-09-23 08:32:31 +02003854
3855 return 0;
3856}
3857#endif
3858
3859static PyObject *
Christian Heimes11a14932018-02-24 02:35:08 +01003860get_protocol(PySSLContext *self, void *c) {
3861 return PyLong_FromLong(self->protocol);
3862}
Christian Heimes1aa9a752013-12-02 02:41:19 +01003863
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003864typedef struct {
3865 PyThreadState *thread_state;
3866 PyObject *callable;
3867 char *password;
Victor Stinner9ee02032013-06-23 15:08:23 +02003868 int size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003869 int error;
3870} _PySSLPasswordInfo;
3871
3872static int
3873_pwinfo_set(_PySSLPasswordInfo *pw_info, PyObject* password,
3874 const char *bad_type_error)
3875{
3876 /* Set the password and size fields of a _PySSLPasswordInfo struct
3877 from a unicode, bytes, or byte array object.
3878 The password field will be dynamically allocated and must be freed
3879 by the caller */
3880 PyObject *password_bytes = NULL;
3881 const char *data = NULL;
3882 Py_ssize_t size;
3883
3884 if (PyUnicode_Check(password)) {
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03003885 password_bytes = PyUnicode_AsUTF8String(password);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003886 if (!password_bytes) {
3887 goto error;
3888 }
3889 data = PyBytes_AS_STRING(password_bytes);
3890 size = PyBytes_GET_SIZE(password_bytes);
3891 } else if (PyBytes_Check(password)) {
3892 data = PyBytes_AS_STRING(password);
3893 size = PyBytes_GET_SIZE(password);
3894 } else if (PyByteArray_Check(password)) {
3895 data = PyByteArray_AS_STRING(password);
3896 size = PyByteArray_GET_SIZE(password);
3897 } else {
3898 PyErr_SetString(PyExc_TypeError, bad_type_error);
3899 goto error;
3900 }
3901
Victor Stinner9ee02032013-06-23 15:08:23 +02003902 if (size > (Py_ssize_t)INT_MAX) {
3903 PyErr_Format(PyExc_ValueError,
3904 "password cannot be longer than %d bytes", INT_MAX);
3905 goto error;
3906 }
3907
Victor Stinner11ebff22013-07-07 17:07:52 +02003908 PyMem_Free(pw_info->password);
3909 pw_info->password = PyMem_Malloc(size);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003910 if (!pw_info->password) {
3911 PyErr_SetString(PyExc_MemoryError,
3912 "unable to allocate password buffer");
3913 goto error;
3914 }
3915 memcpy(pw_info->password, data, size);
Victor Stinner9ee02032013-06-23 15:08:23 +02003916 pw_info->size = (int)size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003917
3918 Py_XDECREF(password_bytes);
3919 return 1;
3920
3921error:
3922 Py_XDECREF(password_bytes);
3923 return 0;
3924}
3925
3926static int
3927_password_callback(char *buf, int size, int rwflag, void *userdata)
3928{
3929 _PySSLPasswordInfo *pw_info = (_PySSLPasswordInfo*) userdata;
3930 PyObject *fn_ret = NULL;
3931
3932 PySSL_END_ALLOW_THREADS_S(pw_info->thread_state);
3933
Christian Heimesd3b73f32021-04-09 15:23:38 +02003934 if (pw_info->error) {
3935 /* already failed previously. OpenSSL 3.0.0-alpha14 invokes the
3936 * callback multiple times which can lead to fatal Python error in
3937 * exception check. */
3938 goto error;
3939 }
3940
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003941 if (pw_info->callable) {
Victor Stinnerf17c3de2016-12-06 18:46:19 +01003942 fn_ret = _PyObject_CallNoArg(pw_info->callable);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003943 if (!fn_ret) {
3944 /* TODO: It would be nice to move _ctypes_add_traceback() into the
3945 core python API, so we could use it to add a frame here */
3946 goto error;
3947 }
3948
3949 if (!_pwinfo_set(pw_info, fn_ret,
3950 "password callback must return a string")) {
3951 goto error;
3952 }
3953 Py_CLEAR(fn_ret);
3954 }
3955
3956 if (pw_info->size > size) {
3957 PyErr_Format(PyExc_ValueError,
3958 "password cannot be longer than %d bytes", size);
3959 goto error;
3960 }
3961
3962 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
3963 memcpy(buf, pw_info->password, pw_info->size);
3964 return pw_info->size;
3965
3966error:
3967 Py_XDECREF(fn_ret);
3968 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
3969 pw_info->error = 1;
3970 return -1;
3971}
3972
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003973/*[clinic input]
3974_ssl._SSLContext.load_cert_chain
3975 certfile: object
Serhiy Storchaka279f4462019-09-14 12:24:05 +03003976 keyfile: object = None
3977 password: object = None
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003978
3979[clinic start generated code]*/
3980
Antoine Pitroub5218772010-05-21 09:56:06 +00003981static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003982_ssl__SSLContext_load_cert_chain_impl(PySSLContext *self, PyObject *certfile,
3983 PyObject *keyfile, PyObject *password)
Serhiy Storchaka279f4462019-09-14 12:24:05 +03003984/*[clinic end generated code: output=9480bc1c380e2095 input=30bc7e967ea01a58]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003985{
Antoine Pitrou152efa22010-05-16 18:19:27 +00003986 PyObject *certfile_bytes = NULL, *keyfile_bytes = NULL;
Christian Heimes598894f2016-09-05 23:19:05 +02003987 pem_password_cb *orig_passwd_cb = SSL_CTX_get_default_passwd_cb(self->ctx);
3988 void *orig_passwd_userdata = SSL_CTX_get_default_passwd_cb_userdata(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003989 _PySSLPasswordInfo pw_info = { NULL, NULL, NULL, 0, 0 };
Antoine Pitrou152efa22010-05-16 18:19:27 +00003990 int r;
3991
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003992 errno = 0;
Antoine Pitrou67e8e562010-09-01 20:55:41 +00003993 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00003994 if (keyfile == Py_None)
3995 keyfile = NULL;
3996 if (!PyUnicode_FSConverter(certfile, &certfile_bytes)) {
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03003997 if (PyErr_ExceptionMatches(PyExc_TypeError)) {
3998 PyErr_SetString(PyExc_TypeError,
3999 "certfile should be a valid filesystem path");
4000 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00004001 return NULL;
4002 }
4003 if (keyfile && !PyUnicode_FSConverter(keyfile, &keyfile_bytes)) {
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03004004 if (PyErr_ExceptionMatches(PyExc_TypeError)) {
4005 PyErr_SetString(PyExc_TypeError,
4006 "keyfile should be a valid filesystem path");
4007 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00004008 goto error;
4009 }
Serhiy Storchaka279f4462019-09-14 12:24:05 +03004010 if (password != Py_None) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02004011 if (PyCallable_Check(password)) {
4012 pw_info.callable = password;
4013 } else if (!_pwinfo_set(&pw_info, password,
4014 "password should be a string or callable")) {
4015 goto error;
4016 }
4017 SSL_CTX_set_default_passwd_cb(self->ctx, _password_callback);
4018 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, &pw_info);
4019 }
4020 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00004021 r = SSL_CTX_use_certificate_chain_file(self->ctx,
4022 PyBytes_AS_STRING(certfile_bytes));
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02004023 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00004024 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02004025 if (pw_info.error) {
4026 ERR_clear_error();
4027 /* the password callback has already set the error information */
4028 }
4029 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00004030 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03004031 PyErr_SetFromErrno(PyExc_OSError);
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00004032 }
4033 else {
4034 _setSSLError(NULL, 0, __FILE__, __LINE__);
4035 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00004036 goto error;
4037 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02004038 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou9c254862011-04-03 18:15:34 +02004039 r = SSL_CTX_use_PrivateKey_file(self->ctx,
Antoine Pitrou152efa22010-05-16 18:19:27 +00004040 PyBytes_AS_STRING(keyfile ? keyfile_bytes : certfile_bytes),
4041 SSL_FILETYPE_PEM);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02004042 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
4043 Py_CLEAR(keyfile_bytes);
4044 Py_CLEAR(certfile_bytes);
Antoine Pitrou152efa22010-05-16 18:19:27 +00004045 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02004046 if (pw_info.error) {
4047 ERR_clear_error();
4048 /* the password callback has already set the error information */
4049 }
4050 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00004051 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03004052 PyErr_SetFromErrno(PyExc_OSError);
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00004053 }
4054 else {
4055 _setSSLError(NULL, 0, __FILE__, __LINE__);
4056 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02004057 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004058 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02004059 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00004060 r = SSL_CTX_check_private_key(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02004061 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00004062 if (r != 1) {
4063 _setSSLError(NULL, 0, __FILE__, __LINE__);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02004064 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004065 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02004066 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
4067 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02004068 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00004069 Py_RETURN_NONE;
4070
4071error:
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02004072 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
4073 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02004074 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00004075 Py_XDECREF(keyfile_bytes);
4076 Py_XDECREF(certfile_bytes);
4077 return NULL;
4078}
4079
Christian Heimesefff7062013-11-21 03:35:02 +01004080/* internal helper function, returns -1 on error
4081 */
4082static int
Serhiy Storchaka8f87eef2020-04-12 14:58:27 +03004083_add_ca_certs(PySSLContext *self, const void *data, Py_ssize_t len,
Christian Heimesefff7062013-11-21 03:35:02 +01004084 int filetype)
4085{
4086 BIO *biobuf = NULL;
4087 X509_STORE *store;
4088 int retval = 0, err, loaded = 0;
4089
4090 assert(filetype == SSL_FILETYPE_ASN1 || filetype == SSL_FILETYPE_PEM);
4091
4092 if (len <= 0) {
4093 PyErr_SetString(PyExc_ValueError,
4094 "Empty certificate data");
4095 return -1;
4096 } else if (len > INT_MAX) {
4097 PyErr_SetString(PyExc_OverflowError,
4098 "Certificate data is too long.");
4099 return -1;
4100 }
4101
Christian Heimes1dbf61f2013-11-22 00:34:18 +01004102 biobuf = BIO_new_mem_buf(data, (int)len);
Christian Heimesefff7062013-11-21 03:35:02 +01004103 if (biobuf == NULL) {
4104 _setSSLError("Can't allocate buffer", 0, __FILE__, __LINE__);
4105 return -1;
4106 }
4107
4108 store = SSL_CTX_get_cert_store(self->ctx);
4109 assert(store != NULL);
4110
4111 while (1) {
4112 X509 *cert = NULL;
4113 int r;
4114
4115 if (filetype == SSL_FILETYPE_ASN1) {
4116 cert = d2i_X509_bio(biobuf, NULL);
4117 } else {
4118 cert = PEM_read_bio_X509(biobuf, NULL,
Christian Heimes598894f2016-09-05 23:19:05 +02004119 SSL_CTX_get_default_passwd_cb(self->ctx),
4120 SSL_CTX_get_default_passwd_cb_userdata(self->ctx)
4121 );
Christian Heimesefff7062013-11-21 03:35:02 +01004122 }
4123 if (cert == NULL) {
4124 break;
4125 }
4126 r = X509_STORE_add_cert(store, cert);
4127 X509_free(cert);
4128 if (!r) {
4129 err = ERR_peek_last_error();
4130 if ((ERR_GET_LIB(err) == ERR_LIB_X509) &&
4131 (ERR_GET_REASON(err) == X509_R_CERT_ALREADY_IN_HASH_TABLE)) {
4132 /* cert already in hash table, not an error */
4133 ERR_clear_error();
4134 } else {
4135 break;
4136 }
4137 }
4138 loaded++;
4139 }
4140
4141 err = ERR_peek_last_error();
4142 if ((filetype == SSL_FILETYPE_ASN1) &&
4143 (loaded > 0) &&
4144 (ERR_GET_LIB(err) == ERR_LIB_ASN1) &&
4145 (ERR_GET_REASON(err) == ASN1_R_HEADER_TOO_LONG)) {
4146 /* EOF ASN1 file, not an error */
4147 ERR_clear_error();
4148 retval = 0;
4149 } else if ((filetype == SSL_FILETYPE_PEM) &&
4150 (loaded > 0) &&
4151 (ERR_GET_LIB(err) == ERR_LIB_PEM) &&
4152 (ERR_GET_REASON(err) == PEM_R_NO_START_LINE)) {
4153 /* EOF PEM file, not an error */
4154 ERR_clear_error();
4155 retval = 0;
4156 } else {
4157 _setSSLError(NULL, 0, __FILE__, __LINE__);
4158 retval = -1;
4159 }
4160
4161 BIO_free(biobuf);
4162 return retval;
4163}
4164
4165
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004166/*[clinic input]
4167_ssl._SSLContext.load_verify_locations
Serhiy Storchaka279f4462019-09-14 12:24:05 +03004168 cafile: object = None
4169 capath: object = None
4170 cadata: object = None
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004171
4172[clinic start generated code]*/
4173
Antoine Pitrou152efa22010-05-16 18:19:27 +00004174static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004175_ssl__SSLContext_load_verify_locations_impl(PySSLContext *self,
4176 PyObject *cafile,
4177 PyObject *capath,
4178 PyObject *cadata)
Serhiy Storchaka279f4462019-09-14 12:24:05 +03004179/*[clinic end generated code: output=454c7e41230ca551 input=42ecfe258233e194]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004180{
Antoine Pitrou152efa22010-05-16 18:19:27 +00004181 PyObject *cafile_bytes = NULL, *capath_bytes = NULL;
4182 const char *cafile_buf = NULL, *capath_buf = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01004183 int r = 0, ok = 1;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004184
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00004185 errno = 0;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004186 if (cafile == Py_None)
4187 cafile = NULL;
4188 if (capath == Py_None)
4189 capath = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01004190 if (cadata == Py_None)
4191 cadata = NULL;
4192
4193 if (cafile == NULL && capath == NULL && cadata == NULL) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00004194 PyErr_SetString(PyExc_TypeError,
Christian Heimesefff7062013-11-21 03:35:02 +01004195 "cafile, capath and cadata cannot be all omitted");
4196 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004197 }
4198 if (cafile && !PyUnicode_FSConverter(cafile, &cafile_bytes)) {
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03004199 if (PyErr_ExceptionMatches(PyExc_TypeError)) {
4200 PyErr_SetString(PyExc_TypeError,
4201 "cafile should be a valid filesystem path");
4202 }
Christian Heimesefff7062013-11-21 03:35:02 +01004203 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004204 }
4205 if (capath && !PyUnicode_FSConverter(capath, &capath_bytes)) {
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03004206 if (PyErr_ExceptionMatches(PyExc_TypeError)) {
4207 PyErr_SetString(PyExc_TypeError,
4208 "capath should be a valid filesystem path");
4209 }
Christian Heimesefff7062013-11-21 03:35:02 +01004210 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004211 }
Christian Heimesefff7062013-11-21 03:35:02 +01004212
4213 /* validata cadata type and load cadata */
4214 if (cadata) {
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03004215 if (PyUnicode_Check(cadata)) {
4216 PyObject *cadata_ascii = PyUnicode_AsASCIIString(cadata);
4217 if (cadata_ascii == NULL) {
4218 if (PyErr_ExceptionMatches(PyExc_UnicodeEncodeError)) {
4219 goto invalid_cadata;
4220 }
4221 goto error;
4222 }
4223 r = _add_ca_certs(self,
4224 PyBytes_AS_STRING(cadata_ascii),
4225 PyBytes_GET_SIZE(cadata_ascii),
4226 SSL_FILETYPE_PEM);
4227 Py_DECREF(cadata_ascii);
4228 if (r == -1) {
4229 goto error;
4230 }
4231 }
4232 else if (PyObject_CheckBuffer(cadata)) {
4233 Py_buffer buf;
4234 if (PyObject_GetBuffer(cadata, &buf, PyBUF_SIMPLE)) {
4235 goto error;
4236 }
Christian Heimesefff7062013-11-21 03:35:02 +01004237 if (!PyBuffer_IsContiguous(&buf, 'C') || buf.ndim > 1) {
4238 PyBuffer_Release(&buf);
4239 PyErr_SetString(PyExc_TypeError,
4240 "cadata should be a contiguous buffer with "
4241 "a single dimension");
4242 goto error;
4243 }
4244 r = _add_ca_certs(self, buf.buf, buf.len, SSL_FILETYPE_ASN1);
4245 PyBuffer_Release(&buf);
4246 if (r == -1) {
4247 goto error;
4248 }
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03004249 }
4250 else {
4251 invalid_cadata:
4252 PyErr_SetString(PyExc_TypeError,
4253 "cadata should be an ASCII string or a "
4254 "bytes-like object");
4255 goto error;
Christian Heimesefff7062013-11-21 03:35:02 +01004256 }
4257 }
4258
4259 /* load cafile or capath */
4260 if (cafile || capath) {
4261 if (cafile)
4262 cafile_buf = PyBytes_AS_STRING(cafile_bytes);
4263 if (capath)
4264 capath_buf = PyBytes_AS_STRING(capath_bytes);
4265 PySSL_BEGIN_ALLOW_THREADS
4266 r = SSL_CTX_load_verify_locations(self->ctx, cafile_buf, capath_buf);
4267 PySSL_END_ALLOW_THREADS
4268 if (r != 1) {
Christian Heimesefff7062013-11-21 03:35:02 +01004269 if (errno != 0) {
4270 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03004271 PyErr_SetFromErrno(PyExc_OSError);
Christian Heimesefff7062013-11-21 03:35:02 +01004272 }
4273 else {
4274 _setSSLError(NULL, 0, __FILE__, __LINE__);
4275 }
4276 goto error;
4277 }
4278 }
4279 goto end;
4280
4281 error:
4282 ok = 0;
4283 end:
Antoine Pitrou152efa22010-05-16 18:19:27 +00004284 Py_XDECREF(cafile_bytes);
4285 Py_XDECREF(capath_bytes);
Christian Heimesefff7062013-11-21 03:35:02 +01004286 if (ok) {
4287 Py_RETURN_NONE;
4288 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00004289 return NULL;
4290 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00004291}
4292
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004293/*[clinic input]
4294_ssl._SSLContext.load_dh_params
4295 path as filepath: object
4296 /
4297
4298[clinic start generated code]*/
4299
Antoine Pitrou152efa22010-05-16 18:19:27 +00004300static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004301_ssl__SSLContext_load_dh_params(PySSLContext *self, PyObject *filepath)
4302/*[clinic end generated code: output=1c8e57a38e055af0 input=c8871f3c796ae1d6]*/
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004303{
4304 FILE *f;
4305 DH *dh;
4306
Victor Stinnerdaf45552013-08-28 00:53:59 +02004307 f = _Py_fopen_obj(filepath, "rb");
Victor Stinnere42ccd22015-03-18 01:39:23 +01004308 if (f == NULL)
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004309 return NULL;
Victor Stinnere42ccd22015-03-18 01:39:23 +01004310
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004311 errno = 0;
4312 PySSL_BEGIN_ALLOW_THREADS
4313 dh = PEM_read_DHparams(f, NULL, NULL, NULL);
Antoine Pitrou457a2292013-01-12 21:43:45 +01004314 fclose(f);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004315 PySSL_END_ALLOW_THREADS
4316 if (dh == NULL) {
4317 if (errno != 0) {
4318 ERR_clear_error();
4319 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
4320 }
4321 else {
4322 _setSSLError(NULL, 0, __FILE__, __LINE__);
4323 }
4324 return NULL;
4325 }
Zackery Spytzaebc0492020-07-07 22:21:58 -06004326 if (!SSL_CTX_set_tmp_dh(self->ctx, dh)) {
4327 DH_free(dh);
4328 return _setSSLError(NULL, 0, __FILE__, __LINE__);
4329 }
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004330 DH_free(dh);
4331 Py_RETURN_NONE;
4332}
4333
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004334/*[clinic input]
4335_ssl._SSLContext._wrap_socket
4336 sock: object(subclass_of="PySocketModule.Sock_Type")
4337 server_side: int
4338 server_hostname as hostname_obj: object = None
Christian Heimes141c5e82018-02-24 21:10:57 +01004339 *
4340 owner: object = None
4341 session: object = None
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004342
4343[clinic start generated code]*/
4344
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004345static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004346_ssl__SSLContext__wrap_socket_impl(PySSLContext *self, PyObject *sock,
Christian Heimes141c5e82018-02-24 21:10:57 +01004347 int server_side, PyObject *hostname_obj,
4348 PyObject *owner, PyObject *session)
4349/*[clinic end generated code: output=f103f238633940b4 input=957d5006183d1894]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004350{
Antoine Pitroud5323212010-10-22 18:19:07 +00004351 char *hostname = NULL;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004352 PyObject *res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004353
Antoine Pitroud5323212010-10-22 18:19:07 +00004354 /* server_hostname is either None (or absent), or to be encoded
Christian Heimesd02ac252018-03-25 12:36:13 +02004355 as IDN A-label (ASCII str) without NULL bytes. */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004356 if (hostname_obj != Py_None) {
Christian Heimes11a14932018-02-24 02:35:08 +01004357 if (!PyArg_Parse(hostname_obj, "es", "ascii", &hostname))
Antoine Pitroud5323212010-10-22 18:19:07 +00004358 return NULL;
Antoine Pitroud5323212010-10-22 18:19:07 +00004359 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00004360
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004361 res = (PyObject *) newPySSLSocket(self, (PySocketSockObject *)sock,
4362 server_side, hostname,
Christian Heimes141c5e82018-02-24 21:10:57 +01004363 owner, session,
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004364 NULL, NULL);
Antoine Pitroud5323212010-10-22 18:19:07 +00004365 if (hostname != NULL)
4366 PyMem_Free(hostname);
4367 return res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004368}
4369
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004370/*[clinic input]
4371_ssl._SSLContext._wrap_bio
Christian Heimes5c36da72020-11-20 09:40:12 +01004372 incoming: object(subclass_of="PySSLMemoryBIO_Type", type="PySSLMemoryBIO *")
4373 outgoing: object(subclass_of="PySSLMemoryBIO_Type", type="PySSLMemoryBIO *")
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004374 server_side: int
4375 server_hostname as hostname_obj: object = None
Christian Heimes141c5e82018-02-24 21:10:57 +01004376 *
4377 owner: object = None
4378 session: object = None
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004379
4380[clinic start generated code]*/
4381
Antoine Pitroub0182c82010-10-12 20:09:02 +00004382static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004383_ssl__SSLContext__wrap_bio_impl(PySSLContext *self, PySSLMemoryBIO *incoming,
4384 PySSLMemoryBIO *outgoing, int server_side,
Christian Heimes141c5e82018-02-24 21:10:57 +01004385 PyObject *hostname_obj, PyObject *owner,
4386 PyObject *session)
Christian Heimes5c36da72020-11-20 09:40:12 +01004387/*[clinic end generated code: output=5c5d6d9b41f99332 input=63867b8f3e1a1aa3]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004388{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004389 char *hostname = NULL;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004390 PyObject *res;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004391
4392 /* server_hostname is either None (or absent), or to be encoded
Christian Heimesd02ac252018-03-25 12:36:13 +02004393 as IDN A-label (ASCII str) without NULL bytes. */
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004394 if (hostname_obj != Py_None) {
Christian Heimes11a14932018-02-24 02:35:08 +01004395 if (!PyArg_Parse(hostname_obj, "es", "ascii", &hostname))
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004396 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004397 }
4398
4399 res = (PyObject *) newPySSLSocket(self, NULL, server_side, hostname,
Christian Heimes141c5e82018-02-24 21:10:57 +01004400 owner, session,
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004401 incoming, outgoing);
4402
4403 PyMem_Free(hostname);
4404 return res;
4405}
4406
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004407/*[clinic input]
4408_ssl._SSLContext.session_stats
4409[clinic start generated code]*/
4410
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004411static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004412_ssl__SSLContext_session_stats_impl(PySSLContext *self)
4413/*[clinic end generated code: output=0d96411c42893bfb input=7e0a81fb11102c8b]*/
Antoine Pitroub0182c82010-10-12 20:09:02 +00004414{
4415 int r;
4416 PyObject *value, *stats = PyDict_New();
4417 if (!stats)
4418 return NULL;
4419
4420#define ADD_STATS(SSL_NAME, KEY_NAME) \
4421 value = PyLong_FromLong(SSL_CTX_sess_ ## SSL_NAME (self->ctx)); \
4422 if (value == NULL) \
4423 goto error; \
4424 r = PyDict_SetItemString(stats, KEY_NAME, value); \
4425 Py_DECREF(value); \
4426 if (r < 0) \
4427 goto error;
4428
4429 ADD_STATS(number, "number");
4430 ADD_STATS(connect, "connect");
4431 ADD_STATS(connect_good, "connect_good");
4432 ADD_STATS(connect_renegotiate, "connect_renegotiate");
4433 ADD_STATS(accept, "accept");
4434 ADD_STATS(accept_good, "accept_good");
4435 ADD_STATS(accept_renegotiate, "accept_renegotiate");
4436 ADD_STATS(accept, "accept");
4437 ADD_STATS(hits, "hits");
4438 ADD_STATS(misses, "misses");
4439 ADD_STATS(timeouts, "timeouts");
4440 ADD_STATS(cache_full, "cache_full");
4441
4442#undef ADD_STATS
4443
4444 return stats;
4445
4446error:
4447 Py_DECREF(stats);
4448 return NULL;
4449}
4450
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004451/*[clinic input]
4452_ssl._SSLContext.set_default_verify_paths
4453[clinic start generated code]*/
4454
Antoine Pitrou664c2d12010-11-17 20:29:42 +00004455static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004456_ssl__SSLContext_set_default_verify_paths_impl(PySSLContext *self)
4457/*[clinic end generated code: output=0bee74e6e09deaaa input=35f3408021463d74]*/
Antoine Pitrou664c2d12010-11-17 20:29:42 +00004458{
4459 if (!SSL_CTX_set_default_verify_paths(self->ctx)) {
4460 _setSSLError(NULL, 0, __FILE__, __LINE__);
4461 return NULL;
4462 }
4463 Py_RETURN_NONE;
4464}
4465
Antoine Pitrou501da612011-12-21 09:27:41 +01004466#ifndef OPENSSL_NO_ECDH
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004467/*[clinic input]
4468_ssl._SSLContext.set_ecdh_curve
4469 name: object
4470 /
4471
4472[clinic start generated code]*/
4473
Antoine Pitrou923df6f2011-12-19 17:16:51 +01004474static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004475_ssl__SSLContext_set_ecdh_curve(PySSLContext *self, PyObject *name)
4476/*[clinic end generated code: output=23022c196e40d7d2 input=c2bafb6f6e34726b]*/
Antoine Pitrou923df6f2011-12-19 17:16:51 +01004477{
4478 PyObject *name_bytes;
4479 int nid;
4480 EC_KEY *key;
4481
4482 if (!PyUnicode_FSConverter(name, &name_bytes))
4483 return NULL;
4484 assert(PyBytes_Check(name_bytes));
4485 nid = OBJ_sn2nid(PyBytes_AS_STRING(name_bytes));
4486 Py_DECREF(name_bytes);
4487 if (nid == 0) {
4488 PyErr_Format(PyExc_ValueError,
4489 "unknown elliptic curve name %R", name);
4490 return NULL;
4491 }
4492 key = EC_KEY_new_by_curve_name(nid);
4493 if (key == NULL) {
4494 _setSSLError(NULL, 0, __FILE__, __LINE__);
4495 return NULL;
4496 }
4497 SSL_CTX_set_tmp_ecdh(self->ctx, key);
4498 EC_KEY_free(key);
4499 Py_RETURN_NONE;
4500}
Antoine Pitrou501da612011-12-21 09:27:41 +01004501#endif
Antoine Pitrou923df6f2011-12-19 17:16:51 +01004502
Antoine Pitrou912fbff2013-03-30 16:29:32 +01004503#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004504static int
4505_servername_callback(SSL *s, int *al, void *args)
4506{
4507 int ret;
4508 PySSLContext *ssl_ctx = (PySSLContext *) args;
4509 PySSLSocket *ssl;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004510 PyObject *result;
4511 /* The high-level ssl.SSLSocket object */
4512 PyObject *ssl_socket;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004513 const char *servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
Stefan Krah20d60802013-01-17 17:07:17 +01004514 PyGILState_STATE gstate = PyGILState_Ensure();
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004515
Christian Heimes11a14932018-02-24 02:35:08 +01004516 if (ssl_ctx->set_sni_cb == NULL) {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004517 /* remove race condition in this the call back while if removing the
4518 * callback is in progress */
4519 PyGILState_Release(gstate);
Antoine Pitrou5dd12a52013-01-06 15:25:36 +01004520 return SSL_TLSEXT_ERR_OK;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004521 }
4522
4523 ssl = SSL_get_app_data(s);
4524 assert(PySSLSocket_Check(ssl));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004525
Serhiy Storchakaf51d7152015-11-02 14:40:41 +02004526 /* The servername callback expects an argument that represents the current
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004527 * SSL connection and that has a .context attribute that can be changed to
4528 * identify the requested hostname. Since the official API is the Python
4529 * level API we want to pass the callback a Python level object rather than
4530 * a _ssl.SSLSocket instance. If there's an "owner" (typically an
4531 * SSLObject) that will be passed. Otherwise if there's a socket then that
4532 * will be passed. If both do not exist only then the C-level object is
4533 * passed. */
4534 if (ssl->owner)
4535 ssl_socket = PyWeakref_GetObject(ssl->owner);
4536 else if (ssl->Socket)
4537 ssl_socket = PyWeakref_GetObject(ssl->Socket);
4538 else
4539 ssl_socket = (PyObject *) ssl;
4540
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004541 Py_INCREF(ssl_socket);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004542 if (ssl_socket == Py_None)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004543 goto error;
Victor Stinner7e001512013-06-25 00:44:31 +02004544
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004545 if (servername == NULL) {
Christian Heimes11a14932018-02-24 02:35:08 +01004546 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_sni_cb, ssl_socket,
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004547 Py_None, ssl_ctx, NULL);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004548 }
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004549 else {
Christian Heimes11a14932018-02-24 02:35:08 +01004550 PyObject *servername_bytes;
4551 PyObject *servername_str;
4552
4553 servername_bytes = PyBytes_FromString(servername);
4554 if (servername_bytes == NULL) {
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004555 PyErr_WriteUnraisable((PyObject *) ssl_ctx);
4556 goto error;
4557 }
Christian Heimes11a14932018-02-24 02:35:08 +01004558 /* server_hostname was encoded to an A-label by our caller; put it
4559 * back into a str object, but still as an A-label (bpo-28414)
4560 */
4561 servername_str = PyUnicode_FromEncodedObject(servername_bytes, "ascii", NULL);
Christian Heimes11a14932018-02-24 02:35:08 +01004562 if (servername_str == NULL) {
4563 PyErr_WriteUnraisable(servername_bytes);
Zackery Spytzee96f322020-07-09 04:00:21 -06004564 Py_DECREF(servername_bytes);
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004565 goto error;
4566 }
Zackery Spytzee96f322020-07-09 04:00:21 -06004567 Py_DECREF(servername_bytes);
Christian Heimes11a14932018-02-24 02:35:08 +01004568 result = PyObject_CallFunctionObjArgs(
4569 ssl_ctx->set_sni_cb, ssl_socket, servername_str,
4570 ssl_ctx, NULL);
4571 Py_DECREF(servername_str);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004572 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004573 Py_DECREF(ssl_socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004574
4575 if (result == NULL) {
Christian Heimes11a14932018-02-24 02:35:08 +01004576 PyErr_WriteUnraisable(ssl_ctx->set_sni_cb);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004577 *al = SSL_AD_HANDSHAKE_FAILURE;
4578 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
4579 }
4580 else {
Christian Heimes11a14932018-02-24 02:35:08 +01004581 /* Result may be None, a SSLContext or an integer
4582 * None and SSLContext are OK, integer or other values are an error.
4583 */
4584 if (result == Py_None) {
4585 ret = SSL_TLSEXT_ERR_OK;
4586 } else {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004587 *al = (int) PyLong_AsLong(result);
4588 if (PyErr_Occurred()) {
4589 PyErr_WriteUnraisable(result);
4590 *al = SSL_AD_INTERNAL_ERROR;
4591 }
4592 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
4593 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004594 Py_DECREF(result);
4595 }
4596
4597 PyGILState_Release(gstate);
4598 return ret;
4599
4600error:
4601 Py_DECREF(ssl_socket);
4602 *al = SSL_AD_INTERNAL_ERROR;
4603 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
4604 PyGILState_Release(gstate);
4605 return ret;
4606}
Antoine Pitroua5963382013-03-30 16:39:00 +01004607#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004608
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004609static PyObject *
Christian Heimes11a14932018-02-24 02:35:08 +01004610get_sni_callback(PySSLContext *self, void *c)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004611{
Christian Heimes11a14932018-02-24 02:35:08 +01004612 PyObject *cb = self->set_sni_cb;
4613 if (cb == NULL) {
4614 Py_RETURN_NONE;
4615 }
4616 Py_INCREF(cb);
4617 return cb;
4618}
4619
4620static int
4621set_sni_callback(PySSLContext *self, PyObject *arg, void *c)
4622{
4623 if (self->protocol == PY_SSL_VERSION_TLS_CLIENT) {
4624 PyErr_SetString(PyExc_ValueError,
4625 "sni_callback cannot be set on TLS_CLIENT context");
4626 return -1;
4627 }
Antoine Pitrou912fbff2013-03-30 16:29:32 +01004628#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Christian Heimes11a14932018-02-24 02:35:08 +01004629 Py_CLEAR(self->set_sni_cb);
4630 if (arg == Py_None) {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004631 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
4632 }
4633 else {
Christian Heimes11a14932018-02-24 02:35:08 +01004634 if (!PyCallable_Check(arg)) {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004635 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
4636 PyErr_SetString(PyExc_TypeError,
4637 "not a callable object");
Christian Heimes11a14932018-02-24 02:35:08 +01004638 return -1;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004639 }
Christian Heimes11a14932018-02-24 02:35:08 +01004640 Py_INCREF(arg);
4641 self->set_sni_cb = arg;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004642 SSL_CTX_set_tlsext_servername_callback(self->ctx, _servername_callback);
4643 SSL_CTX_set_tlsext_servername_arg(self->ctx, self);
4644 }
Christian Heimes11a14932018-02-24 02:35:08 +01004645 return 0;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004646#else
4647 PyErr_SetString(PyExc_NotImplementedError,
4648 "The TLS extension servername callback, "
4649 "SSL_CTX_set_tlsext_servername_callback, "
4650 "is not in the current OpenSSL library.");
Christian Heimes11a14932018-02-24 02:35:08 +01004651 return -1;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004652#endif
4653}
4654
Christian Heimes11a14932018-02-24 02:35:08 +01004655PyDoc_STRVAR(PySSLContext_sni_callback_doc,
4656"Set a callback that will be called when a server name is provided by the SSL/TLS client in the SNI extension.\n\
4657\n\
4658If the argument is None then the callback is disabled. The method is called\n\
4659with the SSLSocket, the server name as a string, and the SSLContext object.\n\
4660See RFC 6066 for details of the SNI extension.");
4661
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004662/*[clinic input]
4663_ssl._SSLContext.cert_store_stats
4664
4665Returns quantities of loaded X.509 certificates.
4666
4667X.509 certificates with a CA extension and certificate revocation lists
4668inside the context's cert store.
4669
4670NOTE: Certificates in a capath directory aren't loaded unless they have
4671been used at least once.
4672[clinic start generated code]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004673
4674static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004675_ssl__SSLContext_cert_store_stats_impl(PySSLContext *self)
4676/*[clinic end generated code: output=5f356f4d9cca874d input=eb40dd0f6d0e40cf]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004677{
4678 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02004679 STACK_OF(X509_OBJECT) *objs;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004680 X509_OBJECT *obj;
Christian Heimes598894f2016-09-05 23:19:05 +02004681 int x509 = 0, crl = 0, ca = 0, i;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004682
4683 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02004684 objs = X509_STORE_get0_objects(store);
4685 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
4686 obj = sk_X509_OBJECT_value(objs, i);
4687 switch (X509_OBJECT_get_type(obj)) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004688 case X509_LU_X509:
4689 x509++;
Christian Heimes598894f2016-09-05 23:19:05 +02004690 if (X509_check_ca(X509_OBJECT_get0_X509(obj))) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004691 ca++;
4692 }
4693 break;
4694 case X509_LU_CRL:
4695 crl++;
4696 break;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004697 default:
4698 /* Ignore X509_LU_FAIL, X509_LU_RETRY, X509_LU_PKEY.
4699 * As far as I can tell they are internal states and never
4700 * stored in a cert store */
4701 break;
4702 }
4703 }
4704 return Py_BuildValue("{sisisi}", "x509", x509, "crl", crl,
4705 "x509_ca", ca);
4706}
4707
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004708/*[clinic input]
4709_ssl._SSLContext.get_ca_certs
4710 binary_form: bool = False
4711
4712Returns a list of dicts with information of loaded CA certs.
4713
4714If the optional argument is True, returns a DER-encoded copy of the CA
4715certificate.
4716
4717NOTE: Certificates in a capath directory aren't loaded unless they have
4718been used at least once.
4719[clinic start generated code]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004720
4721static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004722_ssl__SSLContext_get_ca_certs_impl(PySSLContext *self, int binary_form)
4723/*[clinic end generated code: output=0d58f148f37e2938 input=6887b5a09b7f9076]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004724{
4725 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02004726 STACK_OF(X509_OBJECT) *objs;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004727 PyObject *ci = NULL, *rlist = NULL;
4728 int i;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004729
4730 if ((rlist = PyList_New(0)) == NULL) {
4731 return NULL;
4732 }
4733
4734 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02004735 objs = X509_STORE_get0_objects(store);
4736 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004737 X509_OBJECT *obj;
4738 X509 *cert;
4739
Christian Heimes598894f2016-09-05 23:19:05 +02004740 obj = sk_X509_OBJECT_value(objs, i);
4741 if (X509_OBJECT_get_type(obj) != X509_LU_X509) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004742 /* not a x509 cert */
4743 continue;
4744 }
4745 /* CA for any purpose */
Christian Heimes598894f2016-09-05 23:19:05 +02004746 cert = X509_OBJECT_get0_X509(obj);
Christian Heimes9a5395a2013-06-17 15:44:12 +02004747 if (!X509_check_ca(cert)) {
4748 continue;
4749 }
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004750 if (binary_form) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004751 ci = _certificate_to_der(cert);
4752 } else {
4753 ci = _decode_certificate(cert);
4754 }
4755 if (ci == NULL) {
4756 goto error;
4757 }
4758 if (PyList_Append(rlist, ci) == -1) {
4759 goto error;
4760 }
4761 Py_CLEAR(ci);
4762 }
4763 return rlist;
4764
4765 error:
4766 Py_XDECREF(ci);
4767 Py_XDECREF(rlist);
4768 return NULL;
4769}
4770
4771
Antoine Pitrou152efa22010-05-16 18:19:27 +00004772static PyGetSetDef context_getsetlist[] = {
Christian Heimes1aa9a752013-12-02 02:41:19 +01004773 {"check_hostname", (getter) get_check_hostname,
4774 (setter) set_check_hostname, NULL},
Christian Heimes61d478c2018-01-27 15:51:38 +01004775 {"_host_flags", (getter) get_host_flags,
4776 (setter) set_host_flags, NULL},
Christian Heimes698dde12018-02-27 11:54:43 +01004777#if SSL_CTRL_GET_MAX_PROTO_VERSION
4778 {"minimum_version", (getter) get_minimum_version,
4779 (setter) set_minimum_version, NULL},
4780 {"maximum_version", (getter) get_maximum_version,
4781 (setter) set_maximum_version, NULL},
4782#endif
Christian Heimesc7f70692019-05-31 11:44:05 +02004783#ifdef HAVE_OPENSSL_KEYLOG
4784 {"keylog_filename", (getter) _PySSLContext_get_keylog_filename,
4785 (setter) _PySSLContext_set_keylog_filename, NULL},
4786#endif
4787 {"_msg_callback", (getter) _PySSLContext_get_msg_callback,
4788 (setter) _PySSLContext_set_msg_callback, NULL},
Christian Heimes11a14932018-02-24 02:35:08 +01004789 {"sni_callback", (getter) get_sni_callback,
Christian Heimes698dde12018-02-27 11:54:43 +01004790 (setter) set_sni_callback, PySSLContext_sni_callback_doc},
Christian Heimes78c7d522019-06-03 21:00:10 +02004791#if (OPENSSL_VERSION_NUMBER >= 0x10101000L) && !defined(LIBRESSL_VERSION_NUMBER)
4792 {"num_tickets", (getter) get_num_tickets,
4793 (setter) set_num_tickets, PySSLContext_num_tickets_doc},
4794#endif
Antoine Pitroub5218772010-05-21 09:56:06 +00004795 {"options", (getter) get_options,
4796 (setter) set_options, NULL},
Christian Heimes9fb051f2018-09-23 08:32:31 +02004797 {"post_handshake_auth", (getter) get_post_handshake_auth,
4798#ifdef TLS1_3_VERSION
4799 (setter) set_post_handshake_auth,
4800#else
4801 NULL,
4802#endif
4803 NULL},
Christian Heimes11a14932018-02-24 02:35:08 +01004804 {"protocol", (getter) get_protocol,
4805 NULL, NULL},
Christian Heimes22587792013-11-21 23:56:13 +01004806 {"verify_flags", (getter) get_verify_flags,
4807 (setter) set_verify_flags, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00004808 {"verify_mode", (getter) get_verify_mode,
4809 (setter) set_verify_mode, NULL},
matthewhughes9348e836bb2020-07-17 09:59:15 +01004810#if (OPENSSL_VERSION_NUMBER >= 0x10100000L) && !defined(LIBRESSL_VERSION_NUMBER)
4811 {"security_level", (getter) get_security_level,
4812 NULL, PySSLContext_security_level_doc},
4813#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00004814 {NULL}, /* sentinel */
4815};
4816
4817static struct PyMethodDef context_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004818 _SSL__SSLCONTEXT__WRAP_SOCKET_METHODDEF
4819 _SSL__SSLCONTEXT__WRAP_BIO_METHODDEF
4820 _SSL__SSLCONTEXT_SET_CIPHERS_METHODDEF
4821 _SSL__SSLCONTEXT__SET_ALPN_PROTOCOLS_METHODDEF
4822 _SSL__SSLCONTEXT__SET_NPN_PROTOCOLS_METHODDEF
4823 _SSL__SSLCONTEXT_LOAD_CERT_CHAIN_METHODDEF
4824 _SSL__SSLCONTEXT_LOAD_DH_PARAMS_METHODDEF
4825 _SSL__SSLCONTEXT_LOAD_VERIFY_LOCATIONS_METHODDEF
4826 _SSL__SSLCONTEXT_SESSION_STATS_METHODDEF
4827 _SSL__SSLCONTEXT_SET_DEFAULT_VERIFY_PATHS_METHODDEF
4828 _SSL__SSLCONTEXT_SET_ECDH_CURVE_METHODDEF
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004829 _SSL__SSLCONTEXT_CERT_STORE_STATS_METHODDEF
4830 _SSL__SSLCONTEXT_GET_CA_CERTS_METHODDEF
Christian Heimes25bfcd52016-09-06 00:04:45 +02004831 _SSL__SSLCONTEXT_GET_CIPHERS_METHODDEF
Antoine Pitrou152efa22010-05-16 18:19:27 +00004832 {NULL, NULL} /* sentinel */
4833};
4834
Christian Heimes5c36da72020-11-20 09:40:12 +01004835static PyType_Slot PySSLContext_slots[] = {
4836 {Py_tp_methods, context_methods},
4837 {Py_tp_getset, context_getsetlist},
4838 {Py_tp_new, _ssl__SSLContext},
4839 {Py_tp_dealloc, context_dealloc},
4840 {Py_tp_traverse, context_traverse},
4841 {Py_tp_clear, context_clear},
4842 {0, 0},
4843};
4844
4845static PyType_Spec PySSLContext_spec = {
4846 "_ssl._SSLContext",
4847 sizeof(PySSLContext),
4848 0,
4849 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
4850 PySSLContext_slots,
Antoine Pitrou152efa22010-05-16 18:19:27 +00004851};
4852
4853
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004854/*
4855 * MemoryBIO objects
4856 */
4857
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004858/*[clinic input]
4859@classmethod
4860_ssl.MemoryBIO.__new__
4861
4862[clinic start generated code]*/
4863
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004864static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004865_ssl_MemoryBIO_impl(PyTypeObject *type)
4866/*[clinic end generated code: output=8820a58db78330ac input=26d22e4909ecb1b5]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004867{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004868 BIO *bio;
4869 PySSLMemoryBIO *self;
4870
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004871 bio = BIO_new(BIO_s_mem());
4872 if (bio == NULL) {
4873 PyErr_SetString(PySSLErrorObject,
4874 "failed to allocate BIO");
4875 return NULL;
4876 }
4877 /* Since our BIO is non-blocking an empty read() does not indicate EOF,
4878 * just that no data is currently available. The SSL routines should retry
4879 * the read, which we can achieve by calling BIO_set_retry_read(). */
4880 BIO_set_retry_read(bio);
4881 BIO_set_mem_eof_return(bio, -1);
4882
4883 assert(type != NULL && type->tp_alloc != NULL);
4884 self = (PySSLMemoryBIO *) type->tp_alloc(type, 0);
4885 if (self == NULL) {
4886 BIO_free(bio);
4887 return NULL;
4888 }
4889 self->bio = bio;
4890 self->eof_written = 0;
4891
4892 return (PyObject *) self;
4893}
4894
4895static void
4896memory_bio_dealloc(PySSLMemoryBIO *self)
4897{
Christian Heimes5c36da72020-11-20 09:40:12 +01004898 PyTypeObject *tp = Py_TYPE(self);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004899 BIO_free(self->bio);
4900 Py_TYPE(self)->tp_free(self);
Christian Heimes5c36da72020-11-20 09:40:12 +01004901 Py_DECREF(tp);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004902}
4903
4904static PyObject *
4905memory_bio_get_pending(PySSLMemoryBIO *self, void *c)
4906{
Segev Finer5cff6372017-07-27 01:19:17 +03004907 return PyLong_FromSize_t(BIO_ctrl_pending(self->bio));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004908}
4909
4910PyDoc_STRVAR(PySSL_memory_bio_pending_doc,
4911"The number of bytes pending in the memory BIO.");
4912
4913static PyObject *
4914memory_bio_get_eof(PySSLMemoryBIO *self, void *c)
4915{
4916 return PyBool_FromLong((BIO_ctrl_pending(self->bio) == 0)
4917 && self->eof_written);
4918}
4919
4920PyDoc_STRVAR(PySSL_memory_bio_eof_doc,
4921"Whether the memory BIO is at EOF.");
4922
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004923/*[clinic input]
4924_ssl.MemoryBIO.read
4925 size as len: int = -1
4926 /
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004927
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004928Read up to size bytes from the memory BIO.
4929
4930If size is not specified, read the entire buffer.
4931If the return value is an empty bytes instance, this means either
4932EOF or that no data is available. Use the "eof" property to
4933distinguish between the two.
4934[clinic start generated code]*/
4935
4936static PyObject *
4937_ssl_MemoryBIO_read_impl(PySSLMemoryBIO *self, int len)
4938/*[clinic end generated code: output=a657aa1e79cd01b3 input=574d7be06a902366]*/
4939{
4940 int avail, nbytes;
4941 PyObject *result;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004942
Segev Finer5cff6372017-07-27 01:19:17 +03004943 avail = (int)Py_MIN(BIO_ctrl_pending(self->bio), INT_MAX);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004944 if ((len < 0) || (len > avail))
4945 len = avail;
4946
4947 result = PyBytes_FromStringAndSize(NULL, len);
4948 if ((result == NULL) || (len == 0))
4949 return result;
4950
4951 nbytes = BIO_read(self->bio, PyBytes_AS_STRING(result), len);
Zackery Spytz365ad2e2018-10-06 11:41:45 -06004952 if (nbytes < 0) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004953 Py_DECREF(result);
Zackery Spytz365ad2e2018-10-06 11:41:45 -06004954 _setSSLError(NULL, 0, __FILE__, __LINE__);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004955 return NULL;
4956 }
4957
Zackery Spytz365ad2e2018-10-06 11:41:45 -06004958 /* There should never be any short reads but check anyway. */
4959 if (nbytes < len) {
4960 _PyBytes_Resize(&result, nbytes);
4961 }
4962
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004963 return result;
4964}
4965
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004966/*[clinic input]
4967_ssl.MemoryBIO.write
4968 b: Py_buffer
4969 /
4970
4971Writes the bytes b into the memory BIO.
4972
4973Returns the number of bytes written.
4974[clinic start generated code]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004975
4976static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004977_ssl_MemoryBIO_write_impl(PySSLMemoryBIO *self, Py_buffer *b)
4978/*[clinic end generated code: output=156ec59110d75935 input=e45757b3e17c4808]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004979{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004980 int nbytes;
4981
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004982 if (b->len > INT_MAX) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004983 PyErr_Format(PyExc_OverflowError,
4984 "string longer than %d bytes", INT_MAX);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004985 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004986 }
4987
4988 if (self->eof_written) {
4989 PyErr_SetString(PySSLErrorObject,
4990 "cannot write() after write_eof()");
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004991 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004992 }
4993
Segev Finer5cff6372017-07-27 01:19:17 +03004994 nbytes = BIO_write(self->bio, b->buf, (int)b->len);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004995 if (nbytes < 0) {
4996 _setSSLError(NULL, 0, __FILE__, __LINE__);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004997 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004998 }
4999
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005000 return PyLong_FromLong(nbytes);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005001}
5002
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005003/*[clinic input]
5004_ssl.MemoryBIO.write_eof
5005
5006Write an EOF marker to the memory BIO.
5007
5008When all data has been read, the "eof" property will be True.
5009[clinic start generated code]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005010
5011static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005012_ssl_MemoryBIO_write_eof_impl(PySSLMemoryBIO *self)
5013/*[clinic end generated code: output=d4106276ccd1ed34 input=56a945f1d29e8bd6]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005014{
5015 self->eof_written = 1;
5016 /* After an EOF is written, a zero return from read() should be a real EOF
5017 * i.e. it should not be retried. Clear the SHOULD_RETRY flag. */
5018 BIO_clear_retry_flags(self->bio);
5019 BIO_set_mem_eof_return(self->bio, 0);
5020
5021 Py_RETURN_NONE;
5022}
5023
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005024static PyGetSetDef memory_bio_getsetlist[] = {
5025 {"pending", (getter) memory_bio_get_pending, NULL,
5026 PySSL_memory_bio_pending_doc},
5027 {"eof", (getter) memory_bio_get_eof, NULL,
5028 PySSL_memory_bio_eof_doc},
5029 {NULL}, /* sentinel */
5030};
5031
5032static struct PyMethodDef memory_bio_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005033 _SSL_MEMORYBIO_READ_METHODDEF
5034 _SSL_MEMORYBIO_WRITE_METHODDEF
5035 _SSL_MEMORYBIO_WRITE_EOF_METHODDEF
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005036 {NULL, NULL} /* sentinel */
5037};
5038
Christian Heimes5c36da72020-11-20 09:40:12 +01005039static PyType_Slot PySSLMemoryBIO_slots[] = {
5040 {Py_tp_methods, memory_bio_methods},
5041 {Py_tp_getset, memory_bio_getsetlist},
5042 {Py_tp_new, _ssl_MemoryBIO},
5043 {Py_tp_dealloc, memory_bio_dealloc},
5044 {0, 0},
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005045};
5046
Christian Heimes5c36da72020-11-20 09:40:12 +01005047static PyType_Spec PySSLMemoryBIO_spec = {
5048 "_ssl.MemoryBIO",
5049 sizeof(PySSLMemoryBIO),
5050 0,
5051 Py_TPFLAGS_DEFAULT,
5052 PySSLMemoryBIO_slots,
5053};
Antoine Pitrou152efa22010-05-16 18:19:27 +00005054
Christian Heimes99a65702016-09-10 23:44:53 +02005055/*
5056 * SSL Session object
5057 */
5058
5059static void
5060PySSLSession_dealloc(PySSLSession *self)
5061{
Christian Heimes5c36da72020-11-20 09:40:12 +01005062 PyTypeObject *tp = Py_TYPE(self);
INADA Naokia6296d32017-08-24 14:55:17 +09005063 /* bpo-31095: UnTrack is needed before calling any callbacks */
Christian Heimesa5d07652016-09-24 10:48:05 +02005064 PyObject_GC_UnTrack(self);
Christian Heimes99a65702016-09-10 23:44:53 +02005065 Py_XDECREF(self->ctx);
5066 if (self->session != NULL) {
5067 SSL_SESSION_free(self->session);
5068 }
Christian Heimesa5d07652016-09-24 10:48:05 +02005069 PyObject_GC_Del(self);
Christian Heimes5c36da72020-11-20 09:40:12 +01005070 Py_DECREF(tp);
Christian Heimes99a65702016-09-10 23:44:53 +02005071}
5072
5073static PyObject *
5074PySSLSession_richcompare(PyObject *left, PyObject *right, int op)
5075{
5076 int result;
5077
5078 if (left == NULL || right == NULL) {
5079 PyErr_BadInternalCall();
5080 return NULL;
5081 }
5082
5083 if (!PySSLSession_Check(left) || !PySSLSession_Check(right)) {
5084 Py_RETURN_NOTIMPLEMENTED;
5085 }
5086
5087 if (left == right) {
5088 result = 0;
5089 } else {
5090 const unsigned char *left_id, *right_id;
5091 unsigned int left_len, right_len;
5092 left_id = SSL_SESSION_get_id(((PySSLSession *)left)->session,
5093 &left_len);
5094 right_id = SSL_SESSION_get_id(((PySSLSession *)right)->session,
5095 &right_len);
5096 if (left_len == right_len) {
5097 result = memcmp(left_id, right_id, left_len);
5098 } else {
5099 result = 1;
5100 }
5101 }
5102
5103 switch (op) {
5104 case Py_EQ:
5105 if (result == 0) {
5106 Py_RETURN_TRUE;
5107 } else {
5108 Py_RETURN_FALSE;
5109 }
5110 break;
5111 case Py_NE:
5112 if (result != 0) {
5113 Py_RETURN_TRUE;
5114 } else {
5115 Py_RETURN_FALSE;
5116 }
5117 break;
5118 case Py_LT:
5119 case Py_LE:
5120 case Py_GT:
5121 case Py_GE:
5122 Py_RETURN_NOTIMPLEMENTED;
5123 break;
5124 default:
5125 PyErr_BadArgument();
5126 return NULL;
5127 }
5128}
5129
5130static int
5131PySSLSession_traverse(PySSLSession *self, visitproc visit, void *arg)
5132{
5133 Py_VISIT(self->ctx);
5134 return 0;
5135}
5136
5137static int
5138PySSLSession_clear(PySSLSession *self)
5139{
5140 Py_CLEAR(self->ctx);
5141 return 0;
5142}
5143
5144
5145static PyObject *
5146PySSLSession_get_time(PySSLSession *self, void *closure) {
5147 return PyLong_FromLong(SSL_SESSION_get_time(self->session));
5148}
5149
5150PyDoc_STRVAR(PySSLSession_get_time_doc,
5151"Session creation time (seconds since epoch).");
5152
5153
5154static PyObject *
5155PySSLSession_get_timeout(PySSLSession *self, void *closure) {
5156 return PyLong_FromLong(SSL_SESSION_get_timeout(self->session));
5157}
5158
5159PyDoc_STRVAR(PySSLSession_get_timeout_doc,
5160"Session timeout (delta in seconds).");
5161
5162
5163static PyObject *
5164PySSLSession_get_ticket_lifetime_hint(PySSLSession *self, void *closure) {
5165 unsigned long hint = SSL_SESSION_get_ticket_lifetime_hint(self->session);
5166 return PyLong_FromUnsignedLong(hint);
5167}
5168
5169PyDoc_STRVAR(PySSLSession_get_ticket_lifetime_hint_doc,
5170"Ticket life time hint.");
5171
5172
5173static PyObject *
5174PySSLSession_get_session_id(PySSLSession *self, void *closure) {
5175 const unsigned char *id;
5176 unsigned int len;
5177 id = SSL_SESSION_get_id(self->session, &len);
5178 return PyBytes_FromStringAndSize((const char *)id, len);
5179}
5180
5181PyDoc_STRVAR(PySSLSession_get_session_id_doc,
5182"Session id");
5183
5184
5185static PyObject *
5186PySSLSession_get_has_ticket(PySSLSession *self, void *closure) {
5187 if (SSL_SESSION_has_ticket(self->session)) {
5188 Py_RETURN_TRUE;
5189 } else {
5190 Py_RETURN_FALSE;
5191 }
5192}
5193
5194PyDoc_STRVAR(PySSLSession_get_has_ticket_doc,
5195"Does the session contain a ticket?");
5196
5197
5198static PyGetSetDef PySSLSession_getsetlist[] = {
5199 {"has_ticket", (getter) PySSLSession_get_has_ticket, NULL,
5200 PySSLSession_get_has_ticket_doc},
5201 {"id", (getter) PySSLSession_get_session_id, NULL,
5202 PySSLSession_get_session_id_doc},
5203 {"ticket_lifetime_hint", (getter) PySSLSession_get_ticket_lifetime_hint,
5204 NULL, PySSLSession_get_ticket_lifetime_hint_doc},
5205 {"time", (getter) PySSLSession_get_time, NULL,
5206 PySSLSession_get_time_doc},
5207 {"timeout", (getter) PySSLSession_get_timeout, NULL,
5208 PySSLSession_get_timeout_doc},
5209 {NULL}, /* sentinel */
5210};
5211
Christian Heimes5c36da72020-11-20 09:40:12 +01005212static PyType_Slot PySSLSession_slots[] = {
5213 {Py_tp_getset,PySSLSession_getsetlist},
5214 {Py_tp_richcompare, PySSLSession_richcompare},
5215 {Py_tp_dealloc, PySSLSession_dealloc},
5216 {Py_tp_traverse, PySSLSession_traverse},
5217 {Py_tp_clear, PySSLSession_clear},
5218 {0, 0},
5219};
5220
5221static PyType_Spec PySSLSession_spec = {
5222 "_ssl.SSLSession",
5223 sizeof(PySSLSession),
5224 0,
5225 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,
5226 PySSLSession_slots,
Christian Heimes99a65702016-09-10 23:44:53 +02005227};
5228
5229
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005230/* helper routines for seeding the SSL PRNG */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005231/*[clinic input]
5232_ssl.RAND_add
Larry Hastingsdbfdc382015-05-04 06:59:46 -07005233 string as view: Py_buffer(accept={str, buffer})
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005234 entropy: double
5235 /
5236
5237Mix string into the OpenSSL PRNG state.
5238
5239entropy (a float) is a lower bound on the entropy contained in
Chandan Kumar63c2c8a2017-06-09 15:13:58 +05305240string. See RFC 4086.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005241[clinic start generated code]*/
5242
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005243static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005244_ssl_RAND_add_impl(PyObject *module, Py_buffer *view, double entropy)
Serhiy Storchaka5f31d5c2017-06-10 13:13:51 +03005245/*[clinic end generated code: output=e6dd48df9c9024e9 input=5c33017422828f5c]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005246{
Serhiy Storchaka8490f5a2015-03-20 09:00:36 +02005247 const char *buf;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02005248 Py_ssize_t len, written;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005249
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005250 buf = (const char *)view->buf;
5251 len = view->len;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02005252 do {
5253 written = Py_MIN(len, INT_MAX);
5254 RAND_add(buf, (int)written, entropy);
5255 buf += written;
5256 len -= written;
5257 } while (len);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02005258 Py_RETURN_NONE;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005259}
5260
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005261static PyObject *
Victor Stinner99c8b162011-05-24 12:05:19 +02005262PySSL_RAND(int len, int pseudo)
5263{
5264 int ok;
5265 PyObject *bytes;
5266 unsigned long err;
5267 const char *errstr;
5268 PyObject *v;
5269
Victor Stinner1e81a392013-12-19 16:47:04 +01005270 if (len < 0) {
5271 PyErr_SetString(PyExc_ValueError, "num must be positive");
5272 return NULL;
5273 }
5274
Victor Stinner99c8b162011-05-24 12:05:19 +02005275 bytes = PyBytes_FromStringAndSize(NULL, len);
5276 if (bytes == NULL)
5277 return NULL;
5278 if (pseudo) {
Christian Heimesa871f692020-06-01 08:58:14 +02005279#ifdef PY_OPENSSL_1_1_API
5280 ok = RAND_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
5281#else
Victor Stinner99c8b162011-05-24 12:05:19 +02005282 ok = RAND_pseudo_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
Christian Heimesa871f692020-06-01 08:58:14 +02005283#endif
Victor Stinner99c8b162011-05-24 12:05:19 +02005284 if (ok == 0 || ok == 1)
5285 return Py_BuildValue("NO", bytes, ok == 1 ? Py_True : Py_False);
5286 }
5287 else {
5288 ok = RAND_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
5289 if (ok == 1)
5290 return bytes;
5291 }
5292 Py_DECREF(bytes);
5293
5294 err = ERR_get_error();
5295 errstr = ERR_reason_error_string(err);
5296 v = Py_BuildValue("(ks)", err, errstr);
5297 if (v != NULL) {
5298 PyErr_SetObject(PySSLErrorObject, v);
5299 Py_DECREF(v);
5300 }
5301 return NULL;
5302}
5303
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005304/*[clinic input]
5305_ssl.RAND_bytes
5306 n: int
5307 /
5308
5309Generate n cryptographically strong pseudo-random bytes.
5310[clinic start generated code]*/
5311
Victor Stinner99c8b162011-05-24 12:05:19 +02005312static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005313_ssl_RAND_bytes_impl(PyObject *module, int n)
5314/*[clinic end generated code: output=977da635e4838bc7 input=678ddf2872dfebfc]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02005315{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005316 return PySSL_RAND(n, 0);
Victor Stinner99c8b162011-05-24 12:05:19 +02005317}
5318
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005319/*[clinic input]
5320_ssl.RAND_pseudo_bytes
5321 n: int
5322 /
5323
5324Generate n pseudo-random bytes.
5325
5326Return a pair (bytes, is_cryptographic). is_cryptographic is True
5327if the bytes generated are cryptographically strong.
5328[clinic start generated code]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02005329
5330static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005331_ssl_RAND_pseudo_bytes_impl(PyObject *module, int n)
5332/*[clinic end generated code: output=b1509e937000e52d input=58312bd53f9bbdd0]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02005333{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005334 return PySSL_RAND(n, 1);
Victor Stinner99c8b162011-05-24 12:05:19 +02005335}
5336
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005337/*[clinic input]
5338_ssl.RAND_status
5339
5340Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.
5341
5342It is necessary to seed the PRNG with RAND_add() on some platforms before
5343using the ssl() function.
5344[clinic start generated code]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02005345
5346static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005347_ssl_RAND_status_impl(PyObject *module)
5348/*[clinic end generated code: output=7e0aaa2d39fdc1ad input=8a774b02d1dc81f3]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005349{
Christian Heimes217cfd12007-12-02 14:31:20 +00005350 return PyLong_FromLong(RAND_status());
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005351}
5352
Benjamin Petersonb8a2f512016-07-06 23:55:15 -07005353#ifndef OPENSSL_NO_EGD
Christian Heimesa5d07652016-09-24 10:48:05 +02005354/* LCOV_EXCL_START */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005355/*[clinic input]
5356_ssl.RAND_egd
5357 path: object(converter="PyUnicode_FSConverter")
5358 /
5359
5360Queries the entropy gather daemon (EGD) on the socket named by 'path'.
5361
5362Returns number of bytes read. Raises SSLError if connection to EGD
5363fails or if it does not provide enough data to seed PRNG.
5364[clinic start generated code]*/
5365
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005366static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005367_ssl_RAND_egd_impl(PyObject *module, PyObject *path)
5368/*[clinic end generated code: output=02a67c7c367f52fa input=1aeb7eb948312195]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005369{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005370 int bytes = RAND_egd(PyBytes_AsString(path));
Victor Stinnerf9faaad2010-05-16 21:36:37 +00005371 Py_DECREF(path);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005372 if (bytes == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00005373 PyErr_SetString(PySSLErrorObject,
5374 "EGD connection failed or EGD did not return "
5375 "enough data to seed the PRNG");
5376 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005377 }
Christian Heimes217cfd12007-12-02 14:31:20 +00005378 return PyLong_FromLong(bytes);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005379}
Christian Heimesa5d07652016-09-24 10:48:05 +02005380/* LCOV_EXCL_STOP */
Benjamin Petersonb8a2f512016-07-06 23:55:15 -07005381#endif /* OPENSSL_NO_EGD */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005382
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005383
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005384
5385/*[clinic input]
5386_ssl.get_default_verify_paths
5387
5388Return search paths and environment vars that are used by SSLContext's set_default_verify_paths() to load default CAs.
5389
5390The values are 'cert_file_env', 'cert_file', 'cert_dir_env', 'cert_dir'.
5391[clinic start generated code]*/
Christian Heimes6d7ad132013-06-09 18:02:55 +02005392
5393static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005394_ssl_get_default_verify_paths_impl(PyObject *module)
5395/*[clinic end generated code: output=e5b62a466271928b input=5210c953d98c3eb5]*/
Christian Heimes6d7ad132013-06-09 18:02:55 +02005396{
5397 PyObject *ofile_env = NULL;
5398 PyObject *ofile = NULL;
5399 PyObject *odir_env = NULL;
5400 PyObject *odir = NULL;
5401
Benjamin Petersond113c962015-07-18 10:59:13 -07005402#define CONVERT(info, target) { \
Christian Heimes6d7ad132013-06-09 18:02:55 +02005403 const char *tmp = (info); \
5404 target = NULL; \
5405 if (!tmp) { Py_INCREF(Py_None); target = Py_None; } \
5406 else if ((target = PyUnicode_DecodeFSDefault(tmp)) == NULL) { \
5407 target = PyBytes_FromString(tmp); } \
5408 if (!target) goto error; \
Benjamin Peterson025a1fd2015-11-14 15:12:38 -08005409 }
Christian Heimes6d7ad132013-06-09 18:02:55 +02005410
Benjamin Petersond113c962015-07-18 10:59:13 -07005411 CONVERT(X509_get_default_cert_file_env(), ofile_env);
5412 CONVERT(X509_get_default_cert_file(), ofile);
5413 CONVERT(X509_get_default_cert_dir_env(), odir_env);
5414 CONVERT(X509_get_default_cert_dir(), odir);
5415#undef CONVERT
Christian Heimes6d7ad132013-06-09 18:02:55 +02005416
Christian Heimes200bb1b2013-06-14 15:14:29 +02005417 return Py_BuildValue("NNNN", ofile_env, ofile, odir_env, odir);
Christian Heimes6d7ad132013-06-09 18:02:55 +02005418
5419 error:
5420 Py_XDECREF(ofile_env);
5421 Py_XDECREF(ofile);
5422 Py_XDECREF(odir_env);
5423 Py_XDECREF(odir);
5424 return NULL;
5425}
5426
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005427static PyObject*
5428asn1obj2py(ASN1_OBJECT *obj)
5429{
5430 int nid;
5431 const char *ln, *sn;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005432
5433 nid = OBJ_obj2nid(obj);
5434 if (nid == NID_undef) {
5435 PyErr_Format(PyExc_ValueError, "Unknown object");
5436 return NULL;
5437 }
5438 sn = OBJ_nid2sn(nid);
5439 ln = OBJ_nid2ln(nid);
Serhiy Storchakae503ca52017-09-05 01:28:53 +03005440 return Py_BuildValue("issN", nid, sn, ln, _asn1obj2py(obj, 1));
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005441}
5442
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005443/*[clinic input]
5444_ssl.txt2obj
5445 txt: str
5446 name: bool = False
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005447
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005448Lookup NID, short name, long name and OID of an ASN1_OBJECT.
5449
5450By default objects are looked up by OID. With name=True short and
5451long name are also matched.
5452[clinic start generated code]*/
5453
5454static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005455_ssl_txt2obj_impl(PyObject *module, const char *txt, int name)
5456/*[clinic end generated code: output=c38e3991347079c1 input=1c1e7d0aa7c48602]*/
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005457{
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005458 PyObject *result = NULL;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005459 ASN1_OBJECT *obj;
5460
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005461 obj = OBJ_txt2obj(txt, name ? 0 : 1);
5462 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01005463 PyErr_Format(PyExc_ValueError, "unknown object '%.100s'", txt);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005464 return NULL;
5465 }
5466 result = asn1obj2py(obj);
5467 ASN1_OBJECT_free(obj);
5468 return result;
5469}
5470
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005471/*[clinic input]
5472_ssl.nid2obj
5473 nid: int
5474 /
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005475
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005476Lookup NID, short name, long name and OID of an ASN1_OBJECT by NID.
5477[clinic start generated code]*/
5478
5479static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005480_ssl_nid2obj_impl(PyObject *module, int nid)
5481/*[clinic end generated code: output=4a98ab691cd4f84a input=51787a3bee7d8f98]*/
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005482{
5483 PyObject *result = NULL;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005484 ASN1_OBJECT *obj;
5485
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005486 if (nid < NID_undef) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01005487 PyErr_SetString(PyExc_ValueError, "NID must be positive.");
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005488 return NULL;
5489 }
5490 obj = OBJ_nid2obj(nid);
5491 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01005492 PyErr_Format(PyExc_ValueError, "unknown NID %i", nid);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005493 return NULL;
5494 }
5495 result = asn1obj2py(obj);
5496 ASN1_OBJECT_free(obj);
5497 return result;
5498}
5499
Christian Heimes46bebee2013-06-09 19:03:31 +02005500#ifdef _MSC_VER
Christian Heimes44109d72013-11-22 01:51:30 +01005501
5502static PyObject*
5503certEncodingType(DWORD encodingType)
5504{
5505 static PyObject *x509_asn = NULL;
5506 static PyObject *pkcs_7_asn = NULL;
5507
5508 if (x509_asn == NULL) {
5509 x509_asn = PyUnicode_InternFromString("x509_asn");
5510 if (x509_asn == NULL)
5511 return NULL;
5512 }
5513 if (pkcs_7_asn == NULL) {
5514 pkcs_7_asn = PyUnicode_InternFromString("pkcs_7_asn");
5515 if (pkcs_7_asn == NULL)
5516 return NULL;
5517 }
5518 switch(encodingType) {
5519 case X509_ASN_ENCODING:
5520 Py_INCREF(x509_asn);
5521 return x509_asn;
5522 case PKCS_7_ASN_ENCODING:
5523 Py_INCREF(pkcs_7_asn);
5524 return pkcs_7_asn;
5525 default:
5526 return PyLong_FromLong(encodingType);
5527 }
5528}
5529
5530static PyObject*
5531parseKeyUsage(PCCERT_CONTEXT pCertCtx, DWORD flags)
5532{
5533 CERT_ENHKEY_USAGE *usage;
5534 DWORD size, error, i;
5535 PyObject *retval;
5536
5537 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, NULL, &size)) {
5538 error = GetLastError();
5539 if (error == CRYPT_E_NOT_FOUND) {
5540 Py_RETURN_TRUE;
5541 }
5542 return PyErr_SetFromWindowsErr(error);
5543 }
5544
5545 usage = (CERT_ENHKEY_USAGE*)PyMem_Malloc(size);
5546 if (usage == NULL) {
5547 return PyErr_NoMemory();
5548 }
5549
5550 /* Now get the actual enhanced usage property */
5551 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, usage, &size)) {
5552 PyMem_Free(usage);
5553 error = GetLastError();
5554 if (error == CRYPT_E_NOT_FOUND) {
5555 Py_RETURN_TRUE;
5556 }
5557 return PyErr_SetFromWindowsErr(error);
5558 }
Christian Heimes915cd3f2019-09-09 18:06:55 +02005559 retval = PyFrozenSet_New(NULL);
Christian Heimes44109d72013-11-22 01:51:30 +01005560 if (retval == NULL) {
5561 goto error;
5562 }
5563 for (i = 0; i < usage->cUsageIdentifier; ++i) {
5564 if (usage->rgpszUsageIdentifier[i]) {
5565 PyObject *oid;
5566 int err;
5567 oid = PyUnicode_FromString(usage->rgpszUsageIdentifier[i]);
5568 if (oid == NULL) {
5569 Py_CLEAR(retval);
5570 goto error;
5571 }
5572 err = PySet_Add(retval, oid);
5573 Py_DECREF(oid);
5574 if (err == -1) {
5575 Py_CLEAR(retval);
5576 goto error;
5577 }
5578 }
5579 }
5580 error:
5581 PyMem_Free(usage);
5582 return retval;
5583}
5584
kctherookied93fbbf2019-03-29 00:59:06 +07005585static HCERTSTORE
5586ssl_collect_certificates(const char *store_name)
5587{
5588/* this function collects the system certificate stores listed in
5589 * system_stores into a collection certificate store for being
5590 * enumerated. The store must be readable to be added to the
5591 * store collection.
5592 */
5593
5594 HCERTSTORE hCollectionStore = NULL, hSystemStore = NULL;
5595 static DWORD system_stores[] = {
5596 CERT_SYSTEM_STORE_LOCAL_MACHINE,
5597 CERT_SYSTEM_STORE_LOCAL_MACHINE_ENTERPRISE,
5598 CERT_SYSTEM_STORE_LOCAL_MACHINE_GROUP_POLICY,
5599 CERT_SYSTEM_STORE_CURRENT_USER,
5600 CERT_SYSTEM_STORE_CURRENT_USER_GROUP_POLICY,
5601 CERT_SYSTEM_STORE_SERVICES,
5602 CERT_SYSTEM_STORE_USERS};
5603 size_t i, storesAdded;
5604 BOOL result;
5605
5606 hCollectionStore = CertOpenStore(CERT_STORE_PROV_COLLECTION, 0,
5607 (HCRYPTPROV)NULL, 0, NULL);
5608 if (!hCollectionStore) {
5609 return NULL;
5610 }
5611 storesAdded = 0;
5612 for (i = 0; i < sizeof(system_stores) / sizeof(DWORD); i++) {
5613 hSystemStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0,
5614 (HCRYPTPROV)NULL,
5615 CERT_STORE_READONLY_FLAG |
5616 system_stores[i], store_name);
5617 if (hSystemStore) {
5618 result = CertAddStoreToCollection(hCollectionStore, hSystemStore,
5619 CERT_PHYSICAL_STORE_ADD_ENABLE_FLAG, 0);
5620 if (result) {
5621 ++storesAdded;
5622 }
neoneneed701292019-09-09 21:33:43 +09005623 CertCloseStore(hSystemStore, 0); /* flag must be 0 */
kctherookied93fbbf2019-03-29 00:59:06 +07005624 }
5625 }
5626 if (storesAdded == 0) {
5627 CertCloseStore(hCollectionStore, CERT_CLOSE_STORE_FORCE_FLAG);
5628 return NULL;
5629 }
5630
5631 return hCollectionStore;
5632}
5633
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005634/*[clinic input]
5635_ssl.enum_certificates
5636 store_name: str
5637
5638Retrieve certificates from Windows' cert store.
5639
5640store_name may be one of 'CA', 'ROOT' or 'MY'. The system may provide
5641more cert storages, too. The function returns a list of (bytes,
5642encoding_type, trust) tuples. The encoding_type flag can be interpreted
5643with X509_ASN_ENCODING or PKCS_7_ASN_ENCODING. The trust setting is either
5644a set of OIDs or the boolean True.
5645[clinic start generated code]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00005646
Christian Heimes46bebee2013-06-09 19:03:31 +02005647static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005648_ssl_enum_certificates_impl(PyObject *module, const char *store_name)
5649/*[clinic end generated code: output=5134dc8bb3a3c893 input=915f60d70461ea4e]*/
Christian Heimes46bebee2013-06-09 19:03:31 +02005650{
kctherookied93fbbf2019-03-29 00:59:06 +07005651 HCERTSTORE hCollectionStore = NULL;
Christian Heimes44109d72013-11-22 01:51:30 +01005652 PCCERT_CONTEXT pCertCtx = NULL;
5653 PyObject *keyusage = NULL, *cert = NULL, *enc = NULL, *tup = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02005654 PyObject *result = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02005655
Christian Heimes915cd3f2019-09-09 18:06:55 +02005656 result = PySet_New(NULL);
Christian Heimes44109d72013-11-22 01:51:30 +01005657 if (result == NULL) {
5658 return NULL;
5659 }
kctherookied93fbbf2019-03-29 00:59:06 +07005660 hCollectionStore = ssl_collect_certificates(store_name);
5661 if (hCollectionStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02005662 Py_DECREF(result);
5663 return PyErr_SetFromWindowsErr(GetLastError());
5664 }
5665
kctherookied93fbbf2019-03-29 00:59:06 +07005666 while (pCertCtx = CertEnumCertificatesInStore(hCollectionStore, pCertCtx)) {
Christian Heimes44109d72013-11-22 01:51:30 +01005667 cert = PyBytes_FromStringAndSize((const char*)pCertCtx->pbCertEncoded,
5668 pCertCtx->cbCertEncoded);
5669 if (!cert) {
5670 Py_CLEAR(result);
5671 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02005672 }
Christian Heimes44109d72013-11-22 01:51:30 +01005673 if ((enc = certEncodingType(pCertCtx->dwCertEncodingType)) == NULL) {
5674 Py_CLEAR(result);
5675 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02005676 }
Christian Heimes44109d72013-11-22 01:51:30 +01005677 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG);
5678 if (keyusage == Py_True) {
5679 Py_DECREF(keyusage);
5680 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_EXT_ONLY_ENHKEY_USAGE_FLAG);
Christian Heimes46bebee2013-06-09 19:03:31 +02005681 }
Christian Heimes44109d72013-11-22 01:51:30 +01005682 if (keyusage == NULL) {
5683 Py_CLEAR(result);
5684 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02005685 }
Christian Heimes44109d72013-11-22 01:51:30 +01005686 if ((tup = PyTuple_New(3)) == NULL) {
5687 Py_CLEAR(result);
5688 break;
5689 }
5690 PyTuple_SET_ITEM(tup, 0, cert);
5691 cert = NULL;
5692 PyTuple_SET_ITEM(tup, 1, enc);
5693 enc = NULL;
5694 PyTuple_SET_ITEM(tup, 2, keyusage);
5695 keyusage = NULL;
Christian Heimes915cd3f2019-09-09 18:06:55 +02005696 if (PySet_Add(result, tup) == -1) {
5697 Py_CLEAR(result);
5698 Py_CLEAR(tup);
5699 break;
Christian Heimes44109d72013-11-22 01:51:30 +01005700 }
5701 Py_CLEAR(tup);
5702 }
5703 if (pCertCtx) {
5704 /* loop ended with an error, need to clean up context manually */
5705 CertFreeCertificateContext(pCertCtx);
Christian Heimes46bebee2013-06-09 19:03:31 +02005706 }
5707
5708 /* In error cases cert, enc and tup may not be NULL */
5709 Py_XDECREF(cert);
5710 Py_XDECREF(enc);
Christian Heimes44109d72013-11-22 01:51:30 +01005711 Py_XDECREF(keyusage);
Christian Heimes46bebee2013-06-09 19:03:31 +02005712 Py_XDECREF(tup);
5713
kctherookied93fbbf2019-03-29 00:59:06 +07005714 /* CERT_CLOSE_STORE_FORCE_FLAG forces freeing of memory for all contexts
5715 associated with the store, in this case our collection store and the
5716 associated system stores. */
5717 if (!CertCloseStore(hCollectionStore, CERT_CLOSE_STORE_FORCE_FLAG)) {
Christian Heimes46bebee2013-06-09 19:03:31 +02005718 /* This error case might shadow another exception.*/
Christian Heimes44109d72013-11-22 01:51:30 +01005719 Py_XDECREF(result);
5720 return PyErr_SetFromWindowsErr(GetLastError());
5721 }
kctherookied93fbbf2019-03-29 00:59:06 +07005722
Christian Heimes915cd3f2019-09-09 18:06:55 +02005723 /* convert set to list */
5724 if (result == NULL) {
5725 return NULL;
5726 } else {
5727 PyObject *lst = PySequence_List(result);
5728 Py_DECREF(result);
5729 return lst;
5730 }
Christian Heimes44109d72013-11-22 01:51:30 +01005731}
5732
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005733/*[clinic input]
5734_ssl.enum_crls
5735 store_name: str
5736
5737Retrieve CRLs from Windows' cert store.
5738
5739store_name may be one of 'CA', 'ROOT' or 'MY'. The system may provide
5740more cert storages, too. The function returns a list of (bytes,
5741encoding_type) tuples. The encoding_type flag can be interpreted with
5742X509_ASN_ENCODING or PKCS_7_ASN_ENCODING.
5743[clinic start generated code]*/
Christian Heimes44109d72013-11-22 01:51:30 +01005744
5745static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005746_ssl_enum_crls_impl(PyObject *module, const char *store_name)
5747/*[clinic end generated code: output=bce467f60ccd03b6 input=a1f1d7629f1c5d3d]*/
Christian Heimes44109d72013-11-22 01:51:30 +01005748{
kctherookied93fbbf2019-03-29 00:59:06 +07005749 HCERTSTORE hCollectionStore = NULL;
Christian Heimes44109d72013-11-22 01:51:30 +01005750 PCCRL_CONTEXT pCrlCtx = NULL;
5751 PyObject *crl = NULL, *enc = NULL, *tup = NULL;
5752 PyObject *result = NULL;
5753
Christian Heimes915cd3f2019-09-09 18:06:55 +02005754 result = PySet_New(NULL);
Christian Heimes44109d72013-11-22 01:51:30 +01005755 if (result == NULL) {
5756 return NULL;
5757 }
kctherookied93fbbf2019-03-29 00:59:06 +07005758 hCollectionStore = ssl_collect_certificates(store_name);
5759 if (hCollectionStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02005760 Py_DECREF(result);
5761 return PyErr_SetFromWindowsErr(GetLastError());
5762 }
Christian Heimes44109d72013-11-22 01:51:30 +01005763
kctherookied93fbbf2019-03-29 00:59:06 +07005764 while (pCrlCtx = CertEnumCRLsInStore(hCollectionStore, pCrlCtx)) {
Christian Heimes44109d72013-11-22 01:51:30 +01005765 crl = PyBytes_FromStringAndSize((const char*)pCrlCtx->pbCrlEncoded,
5766 pCrlCtx->cbCrlEncoded);
5767 if (!crl) {
5768 Py_CLEAR(result);
5769 break;
5770 }
5771 if ((enc = certEncodingType(pCrlCtx->dwCertEncodingType)) == NULL) {
5772 Py_CLEAR(result);
5773 break;
5774 }
5775 if ((tup = PyTuple_New(2)) == NULL) {
5776 Py_CLEAR(result);
5777 break;
5778 }
5779 PyTuple_SET_ITEM(tup, 0, crl);
5780 crl = NULL;
5781 PyTuple_SET_ITEM(tup, 1, enc);
5782 enc = NULL;
5783
Christian Heimes915cd3f2019-09-09 18:06:55 +02005784 if (PySet_Add(result, tup) == -1) {
5785 Py_CLEAR(result);
5786 Py_CLEAR(tup);
5787 break;
Christian Heimes44109d72013-11-22 01:51:30 +01005788 }
5789 Py_CLEAR(tup);
Christian Heimes46bebee2013-06-09 19:03:31 +02005790 }
Christian Heimes44109d72013-11-22 01:51:30 +01005791 if (pCrlCtx) {
5792 /* loop ended with an error, need to clean up context manually */
5793 CertFreeCRLContext(pCrlCtx);
5794 }
5795
5796 /* In error cases cert, enc and tup may not be NULL */
5797 Py_XDECREF(crl);
5798 Py_XDECREF(enc);
5799 Py_XDECREF(tup);
5800
kctherookied93fbbf2019-03-29 00:59:06 +07005801 /* CERT_CLOSE_STORE_FORCE_FLAG forces freeing of memory for all contexts
5802 associated with the store, in this case our collection store and the
5803 associated system stores. */
5804 if (!CertCloseStore(hCollectionStore, CERT_CLOSE_STORE_FORCE_FLAG)) {
Christian Heimes44109d72013-11-22 01:51:30 +01005805 /* This error case might shadow another exception.*/
5806 Py_XDECREF(result);
5807 return PyErr_SetFromWindowsErr(GetLastError());
5808 }
Christian Heimes915cd3f2019-09-09 18:06:55 +02005809 /* convert set to list */
5810 if (result == NULL) {
5811 return NULL;
5812 } else {
5813 PyObject *lst = PySequence_List(result);
5814 Py_DECREF(result);
5815 return lst;
5816 }
Christian Heimes46bebee2013-06-09 19:03:31 +02005817}
Christian Heimes44109d72013-11-22 01:51:30 +01005818
5819#endif /* _MSC_VER */
Bill Janssen40a0f662008-08-12 16:56:25 +00005820
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005821/* List of functions exported by this module. */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005822static PyMethodDef PySSL_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005823 _SSL__TEST_DECODE_CERT_METHODDEF
5824 _SSL_RAND_ADD_METHODDEF
5825 _SSL_RAND_BYTES_METHODDEF
5826 _SSL_RAND_PSEUDO_BYTES_METHODDEF
5827 _SSL_RAND_EGD_METHODDEF
5828 _SSL_RAND_STATUS_METHODDEF
5829 _SSL_GET_DEFAULT_VERIFY_PATHS_METHODDEF
5830 _SSL_ENUM_CERTIFICATES_METHODDEF
5831 _SSL_ENUM_CRLS_METHODDEF
5832 _SSL_TXT2OBJ_METHODDEF
5833 _SSL_NID2OBJ_METHODDEF
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005834 {NULL, NULL} /* Sentinel */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005835};
5836
5837
Christian Heimes598894f2016-09-05 23:19:05 +02005838#ifdef HAVE_OPENSSL_CRYPTO_LOCK
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005839
5840/* an implementation of OpenSSL threading operations in terms
Christian Heimes598894f2016-09-05 23:19:05 +02005841 * of the Python C thread library
5842 * Only used up to 1.0.2. OpenSSL 1.1.0+ has its own locking code.
5843 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005844
5845static PyThread_type_lock *_ssl_locks = NULL;
5846
Christian Heimes4d98ca92013-08-19 17:36:29 +02005847#if OPENSSL_VERSION_NUMBER >= 0x10000000
5848/* use new CRYPTO_THREADID API. */
5849static void
5850_ssl_threadid_callback(CRYPTO_THREADID *id)
5851{
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +02005852 CRYPTO_THREADID_set_numeric(id, PyThread_get_thread_ident());
Christian Heimes4d98ca92013-08-19 17:36:29 +02005853}
5854#else
5855/* deprecated CRYPTO_set_id_callback() API. */
5856static unsigned long
5857_ssl_thread_id_function (void) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005858 return PyThread_get_thread_ident();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005859}
Christian Heimes4d98ca92013-08-19 17:36:29 +02005860#endif
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005861
Bill Janssen6e027db2007-11-15 22:23:56 +00005862static void _ssl_thread_locking_function
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005863 (int mode, int n, const char *file, int line) {
5864 /* this function is needed to perform locking on shared data
5865 structures. (Note that OpenSSL uses a number of global data
5866 structures that will be implicitly shared whenever multiple
5867 threads use OpenSSL.) Multi-threaded applications will
5868 crash at random if it is not set.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005869
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005870 locking_function() must be able to handle up to
5871 CRYPTO_num_locks() different mutex locks. It sets the n-th
5872 lock if mode & CRYPTO_LOCK, and releases it otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005873
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005874 file and line are the file number of the function setting the
5875 lock. They can be useful for debugging.
5876 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005877
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005878 if ((_ssl_locks == NULL) ||
5879 (n < 0) || ((unsigned)n >= _ssl_locks_count))
5880 return;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005881
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005882 if (mode & CRYPTO_LOCK) {
5883 PyThread_acquire_lock(_ssl_locks[n], 1);
5884 } else {
5885 PyThread_release_lock(_ssl_locks[n]);
5886 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005887}
5888
5889static int _setup_ssl_threads(void) {
5890
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005891 unsigned int i;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005892
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005893 if (_ssl_locks == NULL) {
5894 _ssl_locks_count = CRYPTO_num_locks();
Christian Heimesf6365e32016-09-13 20:48:13 +02005895 _ssl_locks = PyMem_Calloc(_ssl_locks_count,
5896 sizeof(PyThread_type_lock));
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02005897 if (_ssl_locks == NULL) {
5898 PyErr_NoMemory();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005899 return 0;
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02005900 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005901 for (i = 0; i < _ssl_locks_count; i++) {
5902 _ssl_locks[i] = PyThread_allocate_lock();
5903 if (_ssl_locks[i] == NULL) {
5904 unsigned int j;
5905 for (j = 0; j < i; j++) {
5906 PyThread_free_lock(_ssl_locks[j]);
5907 }
Victor Stinnerb6404912013-07-07 16:21:41 +02005908 PyMem_Free(_ssl_locks);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005909 return 0;
5910 }
5911 }
5912 CRYPTO_set_locking_callback(_ssl_thread_locking_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02005913#if OPENSSL_VERSION_NUMBER >= 0x10000000
5914 CRYPTO_THREADID_set_callback(_ssl_threadid_callback);
5915#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005916 CRYPTO_set_id_callback(_ssl_thread_id_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02005917#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005918 }
5919 return 1;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005920}
5921
Antoine Pitroua6a4dc82017-09-07 18:56:24 +02005922#endif /* HAVE_OPENSSL_CRYPTO_LOCK for OpenSSL < 1.1.0 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005923
Christian Heimes5c36da72020-11-20 09:40:12 +01005924static int
5925sslmodule_init_types(PyObject *module)
5926{
5927 PySSLContext_Type = (PyTypeObject *)PyType_FromModuleAndSpec(
5928 module, &PySSLContext_spec, NULL
5929 );
5930 if (PySSLContext_Type == NULL)
5931 return -1;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005932
Christian Heimes5c36da72020-11-20 09:40:12 +01005933 PySSLSocket_Type = (PyTypeObject *)PyType_FromModuleAndSpec(
5934 module, &PySSLSocket_spec, NULL
5935 );
5936 if (PySSLSocket_Type == NULL)
5937 return -1;
Martin v. Löwis1a214512008-06-11 05:26:20 +00005938
Christian Heimes5c36da72020-11-20 09:40:12 +01005939 PySSLMemoryBIO_Type = (PyTypeObject *)PyType_FromModuleAndSpec(
5940 module, &PySSLMemoryBIO_spec, NULL
5941 );
5942 if (PySSLMemoryBIO_Type == NULL)
5943 return -1;
Martin v. Löwis1a214512008-06-11 05:26:20 +00005944
Christian Heimes5c36da72020-11-20 09:40:12 +01005945 PySSLSession_Type = (PyTypeObject *)PyType_FromModuleAndSpec(
5946 module, &PySSLSession_spec, NULL
5947 );
5948 if (PySSLSession_Type == NULL)
5949 return -1;
5950
5951 if (PyModule_AddType(module, PySSLContext_Type))
5952 return -1;
5953 if (PyModule_AddType(module, PySSLSocket_Type))
5954 return -1;
5955 if (PyModule_AddType(module, PySSLMemoryBIO_Type))
5956 return -1;
5957 if (PyModule_AddType(module, PySSLSession_Type))
5958 return -1;
5959
5960 return 0;
5961}
5962
5963static int
5964sslmodule_init_exceptions(PyObject *module)
5965{
5966 PyObject *bases = NULL;
5967
5968#define add_exception(exc, name, doc, base) \
5969do { \
5970 (exc) = PyErr_NewExceptionWithDoc("ssl." name, (doc), (base), NULL); \
5971 if ((exc) == NULL) goto error; \
5972 if (PyModule_AddObjectRef(module, name, exc) < 0) goto error; \
5973} while(0)
5974
Serhiy Storchaka686c2032020-11-22 13:25:02 +02005975 PySSLErrorObject = PyType_FromSpecWithBases(&sslerror_type_spec, PyExc_OSError);
Christian Heimes5c36da72020-11-20 09:40:12 +01005976 if (PySSLErrorObject == NULL) {
5977 goto error;
5978 }
5979 if (PyModule_AddObjectRef(module, "SSLError", PySSLErrorObject) < 0) {
5980 goto error;
5981 }
5982
5983 /* ssl.CertificateError used to be a subclass of ValueError */
5984 bases = PyTuple_Pack(2, PySSLErrorObject, PyExc_ValueError);
5985 if (bases == NULL) {
5986 goto error;
5987 }
5988 add_exception(
5989 PySSLCertVerificationErrorObject,
5990 "SSLCertVerificationError",
5991 SSLCertVerificationError_doc,
5992 bases
5993 );
5994 Py_CLEAR(bases);
5995
5996 add_exception(
5997 PySSLZeroReturnErrorObject,
5998 "SSLZeroReturnError",
5999 SSLZeroReturnError_doc,
6000 PySSLErrorObject
6001 );
6002
6003 add_exception(
6004 PySSLWantWriteErrorObject,
6005 "SSLWantWriteError",
6006 SSLWantWriteError_doc,
6007 PySSLErrorObject
6008 );
6009
6010 add_exception(
6011 PySSLWantReadErrorObject,
6012 "SSLWantReadError",
6013 SSLWantReadError_doc,
6014 PySSLErrorObject
6015 );
6016
6017 add_exception(
6018 PySSLSyscallErrorObject,
6019 "SSLSyscallError",
6020 SSLSyscallError_doc,
6021 PySSLErrorObject
6022 );
6023
6024 add_exception(
6025 PySSLEOFErrorObject,
6026 "SSLEOFError",
6027 SSLEOFError_doc,
6028 PySSLErrorObject
6029 );
6030#undef add_exception
6031
6032 return 0;
6033 error:
6034 Py_XDECREF(bases);
6035 return -1;
6036}
6037
6038static int
6039sslmodule_init_socketapi(PyObject *module)
6040{
6041 PySocketModule_APIObject *socket_api;
6042
6043 /* Load _socket module and its C API */
6044 socket_api = PySocketModule_ImportModuleAndAPI();
6045 if (socket_api == NULL)
6046 return -1;
6047 PySocketModule = *socket_api;
6048
6049 return 0;
6050}
6051
6052static int
6053sslmodule_init_errorcodes(PyObject *module)
6054{
6055 struct py_ssl_error_code *errcode;
6056 struct py_ssl_library_code *libcode;
6057
6058 /* Mappings for error codes */
6059 err_codes_to_names = PyDict_New();
6060 if (err_codes_to_names == NULL)
6061 return -1;
6062 err_names_to_codes = PyDict_New();
6063 if (err_names_to_codes == NULL)
6064 return -1;
6065 lib_codes_to_names = PyDict_New();
6066 if (lib_codes_to_names == NULL)
6067 return -1;
6068
6069 errcode = error_codes;
6070 while (errcode->mnemonic != NULL) {
6071 PyObject *mnemo, *key;
6072 mnemo = PyUnicode_FromString(errcode->mnemonic);
6073 key = Py_BuildValue("ii", errcode->library, errcode->reason);
6074 if (mnemo == NULL || key == NULL)
6075 return -1;
6076 if (PyDict_SetItem(err_codes_to_names, key, mnemo))
6077 return -1;
6078 if (PyDict_SetItem(err_names_to_codes, mnemo, key))
6079 return -1;
6080 Py_DECREF(key);
6081 Py_DECREF(mnemo);
6082 errcode++;
6083 }
6084
6085 libcode = library_codes;
6086 while (libcode->library != NULL) {
6087 PyObject *mnemo, *key;
6088 key = PyLong_FromLong(libcode->code);
6089 mnemo = PyUnicode_FromString(libcode->library);
6090 if (key == NULL || mnemo == NULL)
6091 return -1;
6092 if (PyDict_SetItem(lib_codes_to_names, key, mnemo))
6093 return -1;
6094 Py_DECREF(key);
6095 Py_DECREF(mnemo);
6096 libcode++;
6097 }
6098
6099 if (PyModule_AddObject(module, "err_codes_to_names", err_codes_to_names))
6100 return -1;
6101 if (PyModule_AddObject(module, "err_names_to_codes", err_names_to_codes))
6102 return -1;
6103 if (PyModule_AddObject(module, "lib_codes_to_names", lib_codes_to_names))
6104 return -1;
6105
6106 return 0;
6107}
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02006108
6109static void
6110parse_openssl_version(unsigned long libver,
6111 unsigned int *major, unsigned int *minor,
6112 unsigned int *fix, unsigned int *patch,
6113 unsigned int *status)
6114{
6115 *status = libver & 0xF;
6116 libver >>= 4;
6117 *patch = libver & 0xFF;
6118 libver >>= 8;
6119 *fix = libver & 0xFF;
6120 libver >>= 8;
6121 *minor = libver & 0xFF;
6122 libver >>= 8;
6123 *major = libver & 0xFF;
6124}
6125
Christian Heimes5c36da72020-11-20 09:40:12 +01006126static int
6127sslmodule_init_versioninfo(PyObject *m)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00006128{
Christian Heimes5c36da72020-11-20 09:40:12 +01006129 PyObject *r;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006130 unsigned long libver;
6131 unsigned int major, minor, fix, patch, status;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00006132
Christian Heimes5c36da72020-11-20 09:40:12 +01006133 /* OpenSSL version */
6134 /* SSLeay() gives us the version of the library linked against,
6135 which could be different from the headers version.
6136 */
6137 libver = OpenSSL_version_num();
6138 r = PyLong_FromUnsignedLong(libver);
6139 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r))
6140 return -1;
Christian Heimes99a65702016-09-10 23:44:53 +02006141
Christian Heimes5c36da72020-11-20 09:40:12 +01006142 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
6143 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
6144 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r))
6145 return -1;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00006146
Christian Heimes5c36da72020-11-20 09:40:12 +01006147 r = PyUnicode_FromString(OpenSSL_version(OPENSSL_VERSION));
6148 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r))
6149 return -1;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00006150
Christian Heimes5c36da72020-11-20 09:40:12 +01006151 libver = OPENSSL_VERSION_NUMBER;
6152 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
6153 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
6154 if (r == NULL || PyModule_AddObject(m, "_OPENSSL_API_VERSION", r))
6155 return -1;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00006156
Christian Heimes5c36da72020-11-20 09:40:12 +01006157 return 0;
6158}
Christian Heimesc941e622017-09-05 15:47:11 +02006159
Christian Heimes5c36da72020-11-20 09:40:12 +01006160static int
6161sslmodule_init_constants(PyObject *m)
6162{
Christian Heimes892d66e2018-01-29 14:10:18 +01006163 PyModule_AddStringConstant(m, "_DEFAULT_CIPHERS",
6164 PY_SSL_DEFAULT_CIPHER_STRING);
6165
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006166 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
6167 PY_SSL_ERROR_ZERO_RETURN);
6168 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
6169 PY_SSL_ERROR_WANT_READ);
6170 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
6171 PY_SSL_ERROR_WANT_WRITE);
6172 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
6173 PY_SSL_ERROR_WANT_X509_LOOKUP);
6174 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
6175 PY_SSL_ERROR_SYSCALL);
6176 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
6177 PY_SSL_ERROR_SSL);
6178 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
6179 PY_SSL_ERROR_WANT_CONNECT);
6180 /* non ssl.h errorcodes */
6181 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
6182 PY_SSL_ERROR_EOF);
6183 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
6184 PY_SSL_ERROR_INVALID_ERROR_CODE);
6185 /* cert requirements */
6186 PyModule_AddIntConstant(m, "CERT_NONE",
6187 PY_SSL_CERT_NONE);
6188 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
6189 PY_SSL_CERT_OPTIONAL);
6190 PyModule_AddIntConstant(m, "CERT_REQUIRED",
6191 PY_SSL_CERT_REQUIRED);
Christian Heimes22587792013-11-21 23:56:13 +01006192 /* CRL verification for verification_flags */
6193 PyModule_AddIntConstant(m, "VERIFY_DEFAULT",
6194 0);
6195 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_LEAF",
6196 X509_V_FLAG_CRL_CHECK);
6197 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_CHAIN",
6198 X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
6199 PyModule_AddIntConstant(m, "VERIFY_X509_STRICT",
6200 X509_V_FLAG_X509_STRICT);
Chris Burre0b4aa02021-03-18 09:24:01 +01006201 PyModule_AddIntConstant(m, "VERIFY_ALLOW_PROXY_CERTS",
6202 X509_V_FLAG_ALLOW_PROXY_CERTS);
Benjamin Peterson990fcaa2015-03-04 22:49:41 -05006203#ifdef X509_V_FLAG_TRUSTED_FIRST
6204 PyModule_AddIntConstant(m, "VERIFY_X509_TRUSTED_FIRST",
6205 X509_V_FLAG_TRUSTED_FIRST);
6206#endif
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00006207
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01006208 /* Alert Descriptions from ssl.h */
6209 /* note RESERVED constants no longer intended for use have been removed */
6210 /* http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-6 */
6211
6212#define ADD_AD_CONSTANT(s) \
6213 PyModule_AddIntConstant(m, "ALERT_DESCRIPTION_"#s, \
6214 SSL_AD_##s)
6215
6216 ADD_AD_CONSTANT(CLOSE_NOTIFY);
6217 ADD_AD_CONSTANT(UNEXPECTED_MESSAGE);
6218 ADD_AD_CONSTANT(BAD_RECORD_MAC);
6219 ADD_AD_CONSTANT(RECORD_OVERFLOW);
6220 ADD_AD_CONSTANT(DECOMPRESSION_FAILURE);
6221 ADD_AD_CONSTANT(HANDSHAKE_FAILURE);
6222 ADD_AD_CONSTANT(BAD_CERTIFICATE);
6223 ADD_AD_CONSTANT(UNSUPPORTED_CERTIFICATE);
6224 ADD_AD_CONSTANT(CERTIFICATE_REVOKED);
6225 ADD_AD_CONSTANT(CERTIFICATE_EXPIRED);
6226 ADD_AD_CONSTANT(CERTIFICATE_UNKNOWN);
6227 ADD_AD_CONSTANT(ILLEGAL_PARAMETER);
6228 ADD_AD_CONSTANT(UNKNOWN_CA);
6229 ADD_AD_CONSTANT(ACCESS_DENIED);
6230 ADD_AD_CONSTANT(DECODE_ERROR);
6231 ADD_AD_CONSTANT(DECRYPT_ERROR);
6232 ADD_AD_CONSTANT(PROTOCOL_VERSION);
6233 ADD_AD_CONSTANT(INSUFFICIENT_SECURITY);
6234 ADD_AD_CONSTANT(INTERNAL_ERROR);
6235 ADD_AD_CONSTANT(USER_CANCELLED);
6236 ADD_AD_CONSTANT(NO_RENEGOTIATION);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01006237 /* Not all constants are in old OpenSSL versions */
Antoine Pitrou912fbff2013-03-30 16:29:32 +01006238#ifdef SSL_AD_UNSUPPORTED_EXTENSION
6239 ADD_AD_CONSTANT(UNSUPPORTED_EXTENSION);
6240#endif
6241#ifdef SSL_AD_CERTIFICATE_UNOBTAINABLE
6242 ADD_AD_CONSTANT(CERTIFICATE_UNOBTAINABLE);
6243#endif
6244#ifdef SSL_AD_UNRECOGNIZED_NAME
6245 ADD_AD_CONSTANT(UNRECOGNIZED_NAME);
6246#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01006247#ifdef SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE
6248 ADD_AD_CONSTANT(BAD_CERTIFICATE_STATUS_RESPONSE);
6249#endif
6250#ifdef SSL_AD_BAD_CERTIFICATE_HASH_VALUE
6251 ADD_AD_CONSTANT(BAD_CERTIFICATE_HASH_VALUE);
6252#endif
6253#ifdef SSL_AD_UNKNOWN_PSK_IDENTITY
6254 ADD_AD_CONSTANT(UNKNOWN_PSK_IDENTITY);
6255#endif
6256
6257#undef ADD_AD_CONSTANT
6258
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006259 /* protocol versions */
Victor Stinner3de49192011-05-09 00:42:58 +02006260#ifndef OPENSSL_NO_SSL2
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006261 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
6262 PY_SSL_VERSION_SSL2);
Victor Stinner3de49192011-05-09 00:42:58 +02006263#endif
Benjamin Petersone32467c2014-12-05 21:59:35 -05006264#ifndef OPENSSL_NO_SSL3
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006265 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
6266 PY_SSL_VERSION_SSL3);
Benjamin Petersone32467c2014-12-05 21:59:35 -05006267#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006268 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
Christian Heimes598894f2016-09-05 23:19:05 +02006269 PY_SSL_VERSION_TLS);
6270 PyModule_AddIntConstant(m, "PROTOCOL_TLS",
6271 PY_SSL_VERSION_TLS);
Christian Heimes5fe668c2016-09-12 00:01:11 +02006272 PyModule_AddIntConstant(m, "PROTOCOL_TLS_CLIENT",
6273 PY_SSL_VERSION_TLS_CLIENT);
6274 PyModule_AddIntConstant(m, "PROTOCOL_TLS_SERVER",
6275 PY_SSL_VERSION_TLS_SERVER);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006276 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
6277 PY_SSL_VERSION_TLS1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01006278 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_1",
6279 PY_SSL_VERSION_TLS1_1);
6280 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_2",
6281 PY_SSL_VERSION_TLS1_2);
Antoine Pitrou04f6a322010-04-05 21:40:07 +00006282
Antoine Pitroub5218772010-05-21 09:56:06 +00006283 /* protocol options */
Antoine Pitrou3f366312012-01-27 09:50:45 +01006284 PyModule_AddIntConstant(m, "OP_ALL",
6285 SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
Antoine Pitroub5218772010-05-21 09:56:06 +00006286 PyModule_AddIntConstant(m, "OP_NO_SSLv2", SSL_OP_NO_SSLv2);
6287 PyModule_AddIntConstant(m, "OP_NO_SSLv3", SSL_OP_NO_SSLv3);
6288 PyModule_AddIntConstant(m, "OP_NO_TLSv1", SSL_OP_NO_TLSv1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01006289 PyModule_AddIntConstant(m, "OP_NO_TLSv1_1", SSL_OP_NO_TLSv1_1);
6290 PyModule_AddIntConstant(m, "OP_NO_TLSv1_2", SSL_OP_NO_TLSv1_2);
Christian Heimescb5b68a2017-09-07 18:07:00 -07006291#ifdef SSL_OP_NO_TLSv1_3
6292 PyModule_AddIntConstant(m, "OP_NO_TLSv1_3", SSL_OP_NO_TLSv1_3);
6293#else
6294 PyModule_AddIntConstant(m, "OP_NO_TLSv1_3", 0);
6295#endif
Antoine Pitrou6db49442011-12-19 13:27:11 +01006296 PyModule_AddIntConstant(m, "OP_CIPHER_SERVER_PREFERENCE",
6297 SSL_OP_CIPHER_SERVER_PREFERENCE);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01006298 PyModule_AddIntConstant(m, "OP_SINGLE_DH_USE", SSL_OP_SINGLE_DH_USE);
Christian Heimes99a65702016-09-10 23:44:53 +02006299 PyModule_AddIntConstant(m, "OP_NO_TICKET", SSL_OP_NO_TICKET);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01006300#ifdef SSL_OP_SINGLE_ECDH_USE
Antoine Pitrou923df6f2011-12-19 17:16:51 +01006301 PyModule_AddIntConstant(m, "OP_SINGLE_ECDH_USE", SSL_OP_SINGLE_ECDH_USE);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01006302#endif
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01006303#ifdef SSL_OP_NO_COMPRESSION
6304 PyModule_AddIntConstant(m, "OP_NO_COMPRESSION",
6305 SSL_OP_NO_COMPRESSION);
6306#endif
Christian Heimes05d9fe32018-02-27 08:55:39 +01006307#ifdef SSL_OP_ENABLE_MIDDLEBOX_COMPAT
6308 PyModule_AddIntConstant(m, "OP_ENABLE_MIDDLEBOX_COMPAT",
6309 SSL_OP_ENABLE_MIDDLEBOX_COMPAT);
6310#endif
Christian Heimes67c48012018-05-15 16:25:40 -04006311#ifdef SSL_OP_NO_RENEGOTIATION
6312 PyModule_AddIntConstant(m, "OP_NO_RENEGOTIATION",
6313 SSL_OP_NO_RENEGOTIATION);
6314#endif
Christian Heimes6f37ebc2021-04-09 17:59:21 +02006315#ifdef SSL_OP_IGNORE_UNEXPECTED_EOF
6316 PyModule_AddIntConstant(m, "OP_IGNORE_UNEXPECTED_EOF",
6317 SSL_OP_IGNORE_UNEXPECTED_EOF);
6318#endif
Antoine Pitroub5218772010-05-21 09:56:06 +00006319
Christian Heimes61d478c2018-01-27 15:51:38 +01006320#ifdef X509_CHECK_FLAG_ALWAYS_CHECK_SUBJECT
6321 PyModule_AddIntConstant(m, "HOSTFLAG_ALWAYS_CHECK_SUBJECT",
6322 X509_CHECK_FLAG_ALWAYS_CHECK_SUBJECT);
6323#endif
6324#ifdef X509_CHECK_FLAG_NEVER_CHECK_SUBJECT
6325 PyModule_AddIntConstant(m, "HOSTFLAG_NEVER_CHECK_SUBJECT",
6326 X509_CHECK_FLAG_NEVER_CHECK_SUBJECT);
6327#endif
6328#ifdef X509_CHECK_FLAG_NO_WILDCARDS
6329 PyModule_AddIntConstant(m, "HOSTFLAG_NO_WILDCARDS",
6330 X509_CHECK_FLAG_NO_WILDCARDS);
6331#endif
6332#ifdef X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS
6333 PyModule_AddIntConstant(m, "HOSTFLAG_NO_PARTIAL_WILDCARDS",
6334 X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS);
6335#endif
6336#ifdef X509_CHECK_FLAG_MULTI_LABEL_WILDCARDS
6337 PyModule_AddIntConstant(m, "HOSTFLAG_MULTI_LABEL_WILDCARDS",
6338 X509_CHECK_FLAG_MULTI_LABEL_WILDCARDS);
6339#endif
6340#ifdef X509_CHECK_FLAG_SINGLE_LABEL_SUBDOMAINS
6341 PyModule_AddIntConstant(m, "HOSTFLAG_SINGLE_LABEL_SUBDOMAINS",
6342 X509_CHECK_FLAG_SINGLE_LABEL_SUBDOMAINS);
6343#endif
6344
Christian Heimes698dde12018-02-27 11:54:43 +01006345 /* protocol versions */
6346 PyModule_AddIntConstant(m, "PROTO_MINIMUM_SUPPORTED",
6347 PY_PROTO_MINIMUM_SUPPORTED);
6348 PyModule_AddIntConstant(m, "PROTO_MAXIMUM_SUPPORTED",
6349 PY_PROTO_MAXIMUM_SUPPORTED);
6350 PyModule_AddIntConstant(m, "PROTO_SSLv3", PY_PROTO_SSLv3);
6351 PyModule_AddIntConstant(m, "PROTO_TLSv1", PY_PROTO_TLSv1);
6352 PyModule_AddIntConstant(m, "PROTO_TLSv1_1", PY_PROTO_TLSv1_1);
6353 PyModule_AddIntConstant(m, "PROTO_TLSv1_2", PY_PROTO_TLSv1_2);
6354 PyModule_AddIntConstant(m, "PROTO_TLSv1_3", PY_PROTO_TLSv1_3);
Antoine Pitroud5323212010-10-22 18:19:07 +00006355
Victor Stinnerb37672d2018-11-22 03:37:50 +01006356#define addbool(m, key, value) \
6357 do { \
6358 PyObject *bool_obj = (value) ? Py_True : Py_False; \
6359 Py_INCREF(bool_obj); \
6360 PyModule_AddObject((m), (key), bool_obj); \
6361 } while (0)
Christian Heimes698dde12018-02-27 11:54:43 +01006362
6363#if HAVE_SNI
6364 addbool(m, "HAS_SNI", 1);
Antoine Pitrou501da612011-12-21 09:27:41 +01006365#else
Christian Heimes698dde12018-02-27 11:54:43 +01006366 addbool(m, "HAS_SNI", 0);
Antoine Pitrou501da612011-12-21 09:27:41 +01006367#endif
Christian Heimes698dde12018-02-27 11:54:43 +01006368
6369 addbool(m, "HAS_TLS_UNIQUE", 1);
6370
6371#ifndef OPENSSL_NO_ECDH
6372 addbool(m, "HAS_ECDH", 1);
6373#else
6374 addbool(m, "HAS_ECDH", 0);
6375#endif
Antoine Pitrou501da612011-12-21 09:27:41 +01006376
Christian Heimes29eab552018-02-25 12:31:33 +01006377#if HAVE_NPN
Christian Heimes698dde12018-02-27 11:54:43 +01006378 addbool(m, "HAS_NPN", 1);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01006379#else
Christian Heimes698dde12018-02-27 11:54:43 +01006380 addbool(m, "HAS_NPN", 0);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01006381#endif
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01006382
Christian Heimes29eab552018-02-25 12:31:33 +01006383#if HAVE_ALPN
Christian Heimes698dde12018-02-27 11:54:43 +01006384 addbool(m, "HAS_ALPN", 1);
Benjamin Petersoncca27322015-01-23 16:35:37 -05006385#else
Christian Heimes698dde12018-02-27 11:54:43 +01006386 addbool(m, "HAS_ALPN", 0);
Benjamin Petersoncca27322015-01-23 16:35:37 -05006387#endif
Christian Heimes698dde12018-02-27 11:54:43 +01006388
6389#if defined(SSL2_VERSION) && !defined(OPENSSL_NO_SSL2)
6390 addbool(m, "HAS_SSLv2", 1);
6391#else
6392 addbool(m, "HAS_SSLv2", 0);
6393#endif
6394
6395#if defined(SSL3_VERSION) && !defined(OPENSSL_NO_SSL3)
6396 addbool(m, "HAS_SSLv3", 1);
6397#else
6398 addbool(m, "HAS_SSLv3", 0);
6399#endif
6400
6401#if defined(TLS1_VERSION) && !defined(OPENSSL_NO_TLS1)
6402 addbool(m, "HAS_TLSv1", 1);
6403#else
6404 addbool(m, "HAS_TLSv1", 0);
6405#endif
6406
6407#if defined(TLS1_1_VERSION) && !defined(OPENSSL_NO_TLS1_1)
6408 addbool(m, "HAS_TLSv1_1", 1);
6409#else
6410 addbool(m, "HAS_TLSv1_1", 0);
6411#endif
6412
6413#if defined(TLS1_2_VERSION) && !defined(OPENSSL_NO_TLS1_2)
6414 addbool(m, "HAS_TLSv1_2", 1);
6415#else
6416 addbool(m, "HAS_TLSv1_2", 0);
6417#endif
Benjamin Petersoncca27322015-01-23 16:35:37 -05006418
Christian Heimescb5b68a2017-09-07 18:07:00 -07006419#if defined(TLS1_3_VERSION) && !defined(OPENSSL_NO_TLS1_3)
Christian Heimes698dde12018-02-27 11:54:43 +01006420 addbool(m, "HAS_TLSv1_3", 1);
Christian Heimescb5b68a2017-09-07 18:07:00 -07006421#else
Christian Heimes698dde12018-02-27 11:54:43 +01006422 addbool(m, "HAS_TLSv1_3", 0);
Christian Heimescb5b68a2017-09-07 18:07:00 -07006423#endif
Christian Heimescb5b68a2017-09-07 18:07:00 -07006424
Christian Heimes5c36da72020-11-20 09:40:12 +01006425 return 0;
6426}
6427
6428static int
6429sslmodule_legacy(PyObject *module)
6430{
6431#ifndef OPENSSL_VERSION_1_1
6432 /* Load all algorithms and initialize cpuid */
6433 OPENSSL_add_all_algorithms_noconf();
6434 /* Init OpenSSL */
6435 SSL_load_error_strings();
6436 SSL_library_init();
6437#endif
6438
6439#ifdef HAVE_OPENSSL_CRYPTO_LOCK
6440 /* note that this will start threading if not already started */
6441 if (!_setup_ssl_threads()) {
Pablo Galindo93a0ef72020-12-02 06:07:56 +00006442 return 0;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02006443 }
Christian Heimes5c36da72020-11-20 09:40:12 +01006444#elif OPENSSL_VERSION_1_1
6445 /* OpenSSL 1.1.0 builtin thread support is enabled */
6446 _ssl_locks_count++;
6447#endif
6448 return 0;
6449}
6450
6451PyDoc_STRVAR(module_doc,
6452"Implementation module for SSL socket operations. See the socket module\n\
6453for documentation.");
6454
6455
6456static struct PyModuleDef _sslmodule = {
6457 PyModuleDef_HEAD_INIT,
6458 "_ssl",
6459 module_doc,
6460 -1,
6461 PySSL_methods,
6462 NULL,
6463 NULL,
6464 NULL,
6465 NULL
6466};
6467
6468PyMODINIT_FUNC
6469PyInit__ssl(void)
6470{
6471 PyObject *m;
6472
6473 m = PyModule_Create(&_sslmodule);
6474 if (m == NULL)
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02006475 return NULL;
6476
Christian Heimes5c36da72020-11-20 09:40:12 +01006477 if (sslmodule_init_types(m) != 0)
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02006478 return NULL;
Christian Heimes5c36da72020-11-20 09:40:12 +01006479 if (sslmodule_init_exceptions(m) != 0)
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02006480 return NULL;
Christian Heimes5c36da72020-11-20 09:40:12 +01006481 if (sslmodule_init_socketapi(m) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006482 return NULL;
Christian Heimes5c36da72020-11-20 09:40:12 +01006483 if (sslmodule_init_errorcodes(m) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006484 return NULL;
Christian Heimes5c36da72020-11-20 09:40:12 +01006485 if (sslmodule_init_constants(m) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006486 return NULL;
Christian Heimes5c36da72020-11-20 09:40:12 +01006487 if (sslmodule_init_versioninfo(m) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006488 return NULL;
Christian Heimes5c36da72020-11-20 09:40:12 +01006489 if (sslmodule_legacy(m) != 0)
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02006490 return NULL;
6491
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006492 return m;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00006493}