blob: 951f9699278db71fb461f270c164a83bebfb774e [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 }
Christian Heimesb467d9a2021-04-17 10:07:19 +0200967 /* bpo43522 and OpenSSL < 1.1.1l: copy hostflags manually */
968#if !defined(LIBRESSL_VERSION_NUMBER) && OPENSSL_VERSION < 0x101010cf
969 X509_VERIFY_PARAM *ssl_params = SSL_get0_param(self->ssl);
970 X509_VERIFY_PARAM_set_hostflags(ssl_params, sslctx->hostflags);
971#endif
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200972 SSL_set_app_data(self->ssl, self);
973 if (sock) {
974 SSL_set_fd(self->ssl, Py_SAFE_DOWNCAST(sock->sock_fd, SOCKET_T, int));
975 } else {
976 /* BIOs are reference counted and SSL_set_bio borrows our reference.
977 * To prevent a double free in memory_bio_dealloc() we need to take an
978 * extra reference here. */
Christian Heimes598894f2016-09-05 23:19:05 +0200979 BIO_up_ref(inbio->bio);
980 BIO_up_ref(outbio->bio);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200981 SSL_set_bio(self->ssl, inbio->bio, outbio->bio);
982 }
Alex Gaynorf0422422018-05-14 11:51:45 -0400983 SSL_set_mode(self->ssl,
984 SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER | SSL_MODE_AUTO_RETRY);
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000985
Christian Heimesf0f59302019-07-01 08:29:17 +0200986#ifdef TLS1_3_VERSION
987 if (sslctx->post_handshake_auth == 1) {
988 if (socket_type == PY_SSL_SERVER) {
989 /* bpo-37428: OpenSSL does not ignore SSL_VERIFY_POST_HANDSHAKE.
990 * Set SSL_VERIFY_POST_HANDSHAKE flag only for server sockets and
991 * only in combination with SSL_VERIFY_PEER flag. */
992 int mode = SSL_get_verify_mode(self->ssl);
993 if (mode & SSL_VERIFY_PEER) {
994 int (*verify_cb)(int, X509_STORE_CTX *) = NULL;
995 verify_cb = SSL_get_verify_callback(self->ssl);
996 mode |= SSL_VERIFY_POST_HANDSHAKE;
997 SSL_set_verify(self->ssl, mode, verify_cb);
998 }
999 } else {
1000 /* client socket */
1001 SSL_set_post_handshake_auth(self->ssl, 1);
1002 }
1003 }
1004#endif
1005
Christian Heimes61d478c2018-01-27 15:51:38 +01001006 if (server_hostname != NULL) {
1007 if (_ssl_configure_hostname(self, server_hostname) < 0) {
1008 Py_DECREF(self);
1009 return NULL;
1010 }
1011 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001012 /* If the socket is in non-blocking mode or timeout mode, set the BIO
1013 * to non-blocking mode (blocking is the default)
1014 */
Victor Stinnere2452312015-03-28 03:00:46 +01001015 if (sock && sock->sock_timeout >= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001016 BIO_set_nbio(SSL_get_rbio(self->ssl), 1);
1017 BIO_set_nbio(SSL_get_wbio(self->ssl), 1);
1018 }
Guido van Rossum4f707ac2003-01-31 18:13:18 +00001019
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001020 PySSL_BEGIN_ALLOW_THREADS
1021 if (socket_type == PY_SSL_CLIENT)
1022 SSL_set_connect_state(self->ssl);
1023 else
1024 SSL_set_accept_state(self->ssl);
1025 PySSL_END_ALLOW_THREADS
Martin v. Löwis09c35f72002-07-28 09:57:45 +00001026
Antoine Pitroud6494802011-07-21 01:11:30 +02001027 self->socket_type = socket_type;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001028 if (sock != NULL) {
1029 self->Socket = PyWeakref_NewRef((PyObject *) sock, NULL);
1030 if (self->Socket == NULL) {
1031 Py_DECREF(self);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001032 return NULL;
1033 }
Victor Stinnera9eb38f2013-10-31 16:35:38 +01001034 }
Christian Heimes141c5e82018-02-24 21:10:57 +01001035 if (owner && owner != Py_None) {
1036 if (PySSL_set_owner(self, owner, NULL) == -1) {
1037 Py_DECREF(self);
1038 return NULL;
1039 }
1040 }
1041 if (session && session != Py_None) {
1042 if (PySSL_set_session(self, session, NULL) == -1) {
1043 Py_DECREF(self);
1044 return NULL;
1045 }
1046 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001047 return self;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001048}
1049
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001050/* SSL object methods */
1051
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001052/*[clinic input]
1053_ssl._SSLSocket.do_handshake
1054[clinic start generated code]*/
1055
1056static PyObject *
1057_ssl__SSLSocket_do_handshake_impl(PySSLSocket *self)
1058/*[clinic end generated code: output=6c0898a8936548f6 input=d2d737de3df018c8]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001059{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001060 int ret;
Steve Dowerc6fd1c12018-09-17 11:34:47 -07001061 _PySSLError err;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001062 int sockstate, nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001063 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02001064 _PyTime_t timeout, deadline = 0;
1065 int has_timeout;
Antoine Pitroud3f8ab82010-04-24 21:26:44 +00001066
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001067 if (sock) {
1068 if (((PyObject*)sock) == Py_None) {
1069 _setSSLError("Underlying socket connection gone",
1070 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1071 return NULL;
1072 }
1073 Py_INCREF(sock);
1074
1075 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01001076 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001077 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1078 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001079 }
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001080
Victor Stinner14690702015-04-06 22:46:13 +02001081 timeout = GET_SOCKET_TIMEOUT(sock);
1082 has_timeout = (timeout > 0);
1083 if (has_timeout)
1084 deadline = _PyTime_GetMonotonicClock() + timeout;
1085
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001086 /* Actually negotiate SSL connection */
1087 /* XXX If SSL_do_handshake() returns 0, it's also a failure. */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001088 do {
Bill Janssen6e027db2007-11-15 22:23:56 +00001089 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001090 ret = SSL_do_handshake(self->ssl);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07001091 err = _PySSL_errno(ret < 1, self->ssl, ret);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001092 PySSL_END_ALLOW_THREADS
Steve Dowerc6fd1c12018-09-17 11:34:47 -07001093 self->err = err;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001094
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001095 if (PyErr_CheckSignals())
1096 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001097
Victor Stinner14690702015-04-06 22:46:13 +02001098 if (has_timeout)
1099 timeout = deadline - _PyTime_GetMonotonicClock();
1100
Steve Dowerc6fd1c12018-09-17 11:34:47 -07001101 if (err.ssl == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +02001102 sockstate = PySSL_select(sock, 0, timeout);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07001103 } else if (err.ssl == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +02001104 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001105 } else {
1106 sockstate = SOCKET_OPERATION_OK;
1107 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001108
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001109 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Christian Heimes03c8ddd2020-11-20 09:26:07 +01001110 PyErr_SetString(PyExc_TimeoutError,
Antoine Pitrou525807b2010-05-12 14:05:24 +00001111 ERRSTR("The handshake operation timed out"));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001112 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001113 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1114 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +00001115 ERRSTR("Underlying socket has been closed."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001116 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001117 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1118 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +00001119 ERRSTR("Underlying socket too large for select()."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001120 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001121 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1122 break;
1123 }
Steve Dowerc6fd1c12018-09-17 11:34:47 -07001124 } while (err.ssl == SSL_ERROR_WANT_READ ||
1125 err.ssl == SSL_ERROR_WANT_WRITE);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001126 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001127 if (ret < 1)
1128 return PySSL_SetError(self, ret, __FILE__, __LINE__);
Christian Heimesc7f70692019-05-31 11:44:05 +02001129 if (PySSL_ChainExceptions(self) < 0)
1130 return NULL;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001131 Py_RETURN_NONE;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001132error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001133 Py_XDECREF(sock);
Christian Heimesc7f70692019-05-31 11:44:05 +02001134 PySSL_ChainExceptions(self);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001135 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001136}
1137
Thomas Woutersed03b412007-08-28 21:37:11 +00001138static PyObject *
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001139_asn1obj2py(const ASN1_OBJECT *name, int no_name)
1140{
1141 char buf[X509_NAME_MAXLEN];
1142 char *namebuf = buf;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001143 int buflen;
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001144 PyObject *name_obj = NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001145
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001146 buflen = OBJ_obj2txt(namebuf, X509_NAME_MAXLEN, name, no_name);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001147 if (buflen < 0) {
1148 _setSSLError(NULL, 0, __FILE__, __LINE__);
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001149 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001150 }
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001151 /* initial buffer is too small for oid + terminating null byte */
1152 if (buflen > X509_NAME_MAXLEN - 1) {
1153 /* make OBJ_obj2txt() calculate the required buflen */
1154 buflen = OBJ_obj2txt(NULL, 0, name, no_name);
1155 /* allocate len + 1 for terminating NULL byte */
1156 namebuf = PyMem_Malloc(buflen + 1);
1157 if (namebuf == NULL) {
1158 PyErr_NoMemory();
1159 return NULL;
1160 }
1161 buflen = OBJ_obj2txt(namebuf, buflen + 1, name, no_name);
1162 if (buflen < 0) {
1163 _setSSLError(NULL, 0, __FILE__, __LINE__);
1164 goto done;
1165 }
1166 }
1167 if (!buflen && no_name) {
1168 Py_INCREF(Py_None);
1169 name_obj = Py_None;
1170 }
1171 else {
1172 name_obj = PyUnicode_FromStringAndSize(namebuf, buflen);
1173 }
1174
1175 done:
1176 if (buf != namebuf) {
1177 PyMem_Free(namebuf);
1178 }
1179 return name_obj;
1180}
1181
1182static PyObject *
1183_create_tuple_for_attribute(ASN1_OBJECT *name, ASN1_STRING *value)
1184{
1185 Py_ssize_t buflen;
1186 unsigned char *valuebuf = NULL;
1187 PyObject *attr;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001188
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001189 buflen = ASN1_STRING_to_UTF8(&valuebuf, value);
1190 if (buflen < 0) {
1191 _setSSLError(NULL, 0, __FILE__, __LINE__);
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001192 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001193 }
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001194 attr = Py_BuildValue("Ns#", _asn1obj2py(name, 0), valuebuf, buflen);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001195 OPENSSL_free(valuebuf);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001196 return attr;
Thomas Woutersed03b412007-08-28 21:37:11 +00001197}
1198
1199static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001200_create_tuple_for_X509_NAME (X509_NAME *xname)
Thomas Woutersed03b412007-08-28 21:37:11 +00001201{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001202 PyObject *dn = NULL; /* tuple which represents the "distinguished name" */
1203 PyObject *rdn = NULL; /* tuple to hold a "relative distinguished name" */
1204 PyObject *rdnt;
1205 PyObject *attr = NULL; /* tuple to hold an attribute */
1206 int entry_count = X509_NAME_entry_count(xname);
1207 X509_NAME_ENTRY *entry;
1208 ASN1_OBJECT *name;
1209 ASN1_STRING *value;
1210 int index_counter;
1211 int rdn_level = -1;
1212 int retcode;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001213
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001214 dn = PyList_New(0);
1215 if (dn == NULL)
1216 return NULL;
1217 /* now create another tuple to hold the top-level RDN */
1218 rdn = PyList_New(0);
1219 if (rdn == NULL)
1220 goto fail0;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001221
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001222 for (index_counter = 0;
1223 index_counter < entry_count;
1224 index_counter++)
1225 {
1226 entry = X509_NAME_get_entry(xname, index_counter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001227
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001228 /* check to see if we've gotten to a new RDN */
1229 if (rdn_level >= 0) {
Christian Heimes598894f2016-09-05 23:19:05 +02001230 if (rdn_level != X509_NAME_ENTRY_set(entry)) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001231 /* yes, new RDN */
1232 /* add old RDN to DN */
1233 rdnt = PyList_AsTuple(rdn);
1234 Py_DECREF(rdn);
1235 if (rdnt == NULL)
1236 goto fail0;
1237 retcode = PyList_Append(dn, rdnt);
1238 Py_DECREF(rdnt);
1239 if (retcode < 0)
1240 goto fail0;
1241 /* create new RDN */
1242 rdn = PyList_New(0);
1243 if (rdn == NULL)
1244 goto fail0;
1245 }
1246 }
Christian Heimes598894f2016-09-05 23:19:05 +02001247 rdn_level = X509_NAME_ENTRY_set(entry);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001248
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001249 /* now add this attribute to the current RDN */
1250 name = X509_NAME_ENTRY_get_object(entry);
1251 value = X509_NAME_ENTRY_get_data(entry);
1252 attr = _create_tuple_for_attribute(name, value);
1253 /*
1254 fprintf(stderr, "RDN level %d, attribute %s: %s\n",
1255 entry->set,
1256 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 0)),
1257 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 1)));
1258 */
1259 if (attr == NULL)
1260 goto fail1;
1261 retcode = PyList_Append(rdn, attr);
1262 Py_DECREF(attr);
1263 if (retcode < 0)
1264 goto fail1;
1265 }
1266 /* now, there's typically a dangling RDN */
Antoine Pitrou2f5a1632012-02-15 22:25:27 +01001267 if (rdn != NULL) {
1268 if (PyList_GET_SIZE(rdn) > 0) {
1269 rdnt = PyList_AsTuple(rdn);
1270 Py_DECREF(rdn);
1271 if (rdnt == NULL)
1272 goto fail0;
1273 retcode = PyList_Append(dn, rdnt);
1274 Py_DECREF(rdnt);
1275 if (retcode < 0)
1276 goto fail0;
1277 }
1278 else {
1279 Py_DECREF(rdn);
1280 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001281 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001282
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001283 /* convert list to tuple */
1284 rdnt = PyList_AsTuple(dn);
1285 Py_DECREF(dn);
1286 if (rdnt == NULL)
1287 return NULL;
1288 return rdnt;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001289
1290 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001291 Py_XDECREF(rdn);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001292
1293 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001294 Py_XDECREF(dn);
1295 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001296}
1297
1298static PyObject *
1299_get_peer_alt_names (X509 *certificate) {
Guido van Rossumf06628b2007-11-21 20:01:53 +00001300
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001301 /* this code follows the procedure outlined in
1302 OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print()
1303 function to extract the STACK_OF(GENERAL_NAME),
1304 then iterates through the stack to add the
1305 names. */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001306
Alex Gaynorb87c0df2017-06-06 07:53:11 -04001307 int j;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001308 PyObject *peer_alt_names = Py_None;
Christian Heimes60bf2fc2013-09-05 16:04:35 +02001309 PyObject *v = NULL, *t;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001310 GENERAL_NAMES *names = NULL;
1311 GENERAL_NAME *name;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001312 BIO *biobuf = NULL;
1313 char buf[2048];
1314 char *vptr;
1315 int len;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001316
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001317 if (certificate == NULL)
1318 return peer_alt_names;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001319
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001320 /* get a memory buffer */
1321 biobuf = BIO_new(BIO_s_mem());
Zackery Spytz4c49da02018-12-07 03:11:30 -07001322 if (biobuf == NULL) {
1323 PyErr_SetString(PySSLErrorObject, "failed to allocate BIO");
1324 return NULL;
1325 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001326
Alex Gaynorb87c0df2017-06-06 07:53:11 -04001327 names = (GENERAL_NAMES *)X509_get_ext_d2i(
1328 certificate, NID_subject_alt_name, NULL, NULL);
1329 if (names != NULL) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001330 if (peer_alt_names == Py_None) {
1331 peer_alt_names = PyList_New(0);
1332 if (peer_alt_names == NULL)
1333 goto fail;
1334 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001335
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001336 for(j = 0; j < sk_GENERAL_NAME_num(names); j++) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001337 /* get a rendering of each name in the set of names */
Christian Heimes824f7f32013-08-17 00:54:47 +02001338 int gntype;
1339 ASN1_STRING *as = NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001340
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001341 name = sk_GENERAL_NAME_value(names, j);
Christian Heimes474afdd2013-08-17 17:18:56 +02001342 gntype = name->type;
Christian Heimes824f7f32013-08-17 00:54:47 +02001343 switch (gntype) {
1344 case GEN_DIRNAME:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001345 /* we special-case DirName as a tuple of
1346 tuples of attributes */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001347
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001348 t = PyTuple_New(2);
1349 if (t == NULL) {
1350 goto fail;
1351 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001352
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001353 v = PyUnicode_FromString("DirName");
1354 if (v == NULL) {
1355 Py_DECREF(t);
1356 goto fail;
1357 }
1358 PyTuple_SET_ITEM(t, 0, v);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001359
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001360 v = _create_tuple_for_X509_NAME (name->d.dirn);
1361 if (v == NULL) {
1362 Py_DECREF(t);
1363 goto fail;
1364 }
1365 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +02001366 break;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001367
Christian Heimes824f7f32013-08-17 00:54:47 +02001368 case GEN_EMAIL:
1369 case GEN_DNS:
1370 case GEN_URI:
1371 /* GENERAL_NAME_print() doesn't handle NULL bytes in ASN1_string
1372 correctly, CVE-2013-4238 */
1373 t = PyTuple_New(2);
1374 if (t == NULL)
1375 goto fail;
1376 switch (gntype) {
1377 case GEN_EMAIL:
1378 v = PyUnicode_FromString("email");
1379 as = name->d.rfc822Name;
1380 break;
1381 case GEN_DNS:
1382 v = PyUnicode_FromString("DNS");
1383 as = name->d.dNSName;
1384 break;
1385 case GEN_URI:
1386 v = PyUnicode_FromString("URI");
1387 as = name->d.uniformResourceIdentifier;
1388 break;
1389 }
1390 if (v == NULL) {
1391 Py_DECREF(t);
1392 goto fail;
1393 }
1394 PyTuple_SET_ITEM(t, 0, v);
Christian Heimesa871f692020-06-01 08:58:14 +02001395 v = PyUnicode_FromStringAndSize((char *)ASN1_STRING_get0_data(as),
Christian Heimes824f7f32013-08-17 00:54:47 +02001396 ASN1_STRING_length(as));
1397 if (v == NULL) {
1398 Py_DECREF(t);
1399 goto fail;
1400 }
1401 PyTuple_SET_ITEM(t, 1, v);
1402 break;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001403
Christian Heimes1c03abd2016-09-06 23:25:35 +02001404 case GEN_RID:
1405 t = PyTuple_New(2);
1406 if (t == NULL)
1407 goto fail;
1408
1409 v = PyUnicode_FromString("Registered ID");
1410 if (v == NULL) {
1411 Py_DECREF(t);
1412 goto fail;
1413 }
1414 PyTuple_SET_ITEM(t, 0, v);
1415
1416 len = i2t_ASN1_OBJECT(buf, sizeof(buf)-1, name->d.rid);
1417 if (len < 0) {
1418 Py_DECREF(t);
1419 _setSSLError(NULL, 0, __FILE__, __LINE__);
1420 goto fail;
1421 } else if (len >= (int)sizeof(buf)) {
1422 v = PyUnicode_FromString("<INVALID>");
1423 } else {
1424 v = PyUnicode_FromStringAndSize(buf, len);
1425 }
1426 if (v == NULL) {
1427 Py_DECREF(t);
1428 goto fail;
1429 }
1430 PyTuple_SET_ITEM(t, 1, v);
1431 break;
1432
Christian Heimes2b7de662019-12-07 17:59:36 +01001433 case GEN_IPADD:
1434 /* OpenSSL < 3.0.0 adds a trailing \n to IPv6. 3.0.0 removed
1435 * the trailing newline. Remove it in all versions
1436 */
1437 t = PyTuple_New(2);
1438 if (t == NULL)
1439 goto fail;
1440
1441 v = PyUnicode_FromString("IP Address");
1442 if (v == NULL) {
1443 Py_DECREF(t);
1444 goto fail;
1445 }
1446 PyTuple_SET_ITEM(t, 0, v);
1447
1448 if (name->d.ip->length == 4) {
1449 unsigned char *p = name->d.ip->data;
1450 v = PyUnicode_FromFormat(
1451 "%d.%d.%d.%d",
1452 p[0], p[1], p[2], p[3]
1453 );
1454 } else if (name->d.ip->length == 16) {
1455 /* PyUnicode_FromFormat() does not support %X */
1456 unsigned char *p = name->d.ip->data;
1457 len = sprintf(
1458 buf,
1459 "%X:%X:%X:%X:%X:%X:%X:%X",
1460 p[0] << 8 | p[1],
1461 p[2] << 8 | p[3],
1462 p[4] << 8 | p[5],
1463 p[6] << 8 | p[7],
1464 p[8] << 8 | p[9],
1465 p[10] << 8 | p[11],
1466 p[12] << 8 | p[13],
1467 p[14] << 8 | p[15]
1468 );
1469 v = PyUnicode_FromStringAndSize(buf, len);
1470 } else {
1471 v = PyUnicode_FromString("<invalid>");
1472 }
1473
1474 if (v == NULL) {
1475 Py_DECREF(t);
1476 goto fail;
1477 }
1478 PyTuple_SET_ITEM(t, 1, v);
1479 break;
1480
Christian Heimes824f7f32013-08-17 00:54:47 +02001481 default:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001482 /* for everything else, we use the OpenSSL print form */
Christian Heimes824f7f32013-08-17 00:54:47 +02001483 switch (gntype) {
1484 /* check for new general name type */
1485 case GEN_OTHERNAME:
1486 case GEN_X400:
1487 case GEN_EDIPARTY:
Christian Heimes824f7f32013-08-17 00:54:47 +02001488 case GEN_RID:
1489 break;
1490 default:
1491 if (PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
1492 "Unknown general name type %d",
1493 gntype) == -1) {
1494 goto fail;
1495 }
1496 break;
1497 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001498 (void) BIO_reset(biobuf);
1499 GENERAL_NAME_print(biobuf, name);
1500 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1501 if (len < 0) {
1502 _setSSLError(NULL, 0, __FILE__, __LINE__);
1503 goto fail;
1504 }
1505 vptr = strchr(buf, ':');
Christian Heimes1c03abd2016-09-06 23:25:35 +02001506 if (vptr == NULL) {
1507 PyErr_Format(PyExc_ValueError,
1508 "Invalid value %.200s",
1509 buf);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001510 goto fail;
Christian Heimes1c03abd2016-09-06 23:25:35 +02001511 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001512 t = PyTuple_New(2);
1513 if (t == NULL)
1514 goto fail;
1515 v = PyUnicode_FromStringAndSize(buf, (vptr - buf));
1516 if (v == NULL) {
1517 Py_DECREF(t);
1518 goto fail;
1519 }
1520 PyTuple_SET_ITEM(t, 0, v);
1521 v = PyUnicode_FromStringAndSize((vptr + 1),
1522 (len - (vptr - buf + 1)));
1523 if (v == NULL) {
1524 Py_DECREF(t);
1525 goto fail;
1526 }
1527 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +02001528 break;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001529 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001530
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001531 /* and add that rendering to the list */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001532
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001533 if (PyList_Append(peer_alt_names, t) < 0) {
1534 Py_DECREF(t);
1535 goto fail;
1536 }
1537 Py_DECREF(t);
1538 }
Antoine Pitrou116d6b92011-11-23 01:39:19 +01001539 sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001540 }
1541 BIO_free(biobuf);
1542 if (peer_alt_names != Py_None) {
1543 v = PyList_AsTuple(peer_alt_names);
1544 Py_DECREF(peer_alt_names);
1545 return v;
1546 } else {
1547 return peer_alt_names;
1548 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001549
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001550
1551 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001552 if (biobuf != NULL)
1553 BIO_free(biobuf);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001554
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001555 if (peer_alt_names != Py_None) {
1556 Py_XDECREF(peer_alt_names);
1557 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001558
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001559 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001560}
1561
1562static PyObject *
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001563_get_aia_uri(X509 *certificate, int nid) {
1564 PyObject *lst = NULL, *ostr = NULL;
1565 int i, result;
1566 AUTHORITY_INFO_ACCESS *info;
1567
1568 info = X509_get_ext_d2i(certificate, NID_info_access, NULL, NULL);
Benjamin Petersonf0c90382015-11-14 15:12:18 -08001569 if (info == NULL)
1570 return Py_None;
1571 if (sk_ACCESS_DESCRIPTION_num(info) == 0) {
1572 AUTHORITY_INFO_ACCESS_free(info);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001573 return Py_None;
1574 }
1575
1576 if ((lst = PyList_New(0)) == NULL) {
1577 goto fail;
1578 }
1579
1580 for (i = 0; i < sk_ACCESS_DESCRIPTION_num(info); i++) {
1581 ACCESS_DESCRIPTION *ad = sk_ACCESS_DESCRIPTION_value(info, i);
1582 ASN1_IA5STRING *uri;
1583
1584 if ((OBJ_obj2nid(ad->method) != nid) ||
1585 (ad->location->type != GEN_URI)) {
1586 continue;
1587 }
1588 uri = ad->location->d.uniformResourceIdentifier;
1589 ostr = PyUnicode_FromStringAndSize((char *)uri->data,
1590 uri->length);
1591 if (ostr == NULL) {
1592 goto fail;
1593 }
1594 result = PyList_Append(lst, ostr);
1595 Py_DECREF(ostr);
1596 if (result < 0) {
1597 goto fail;
1598 }
1599 }
1600 AUTHORITY_INFO_ACCESS_free(info);
1601
1602 /* convert to tuple or None */
1603 if (PyList_Size(lst) == 0) {
1604 Py_DECREF(lst);
1605 return Py_None;
1606 } else {
1607 PyObject *tup;
1608 tup = PyList_AsTuple(lst);
1609 Py_DECREF(lst);
1610 return tup;
1611 }
1612
1613 fail:
1614 AUTHORITY_INFO_ACCESS_free(info);
Christian Heimes18fc7be2013-11-21 23:57:49 +01001615 Py_XDECREF(lst);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001616 return NULL;
1617}
1618
1619static PyObject *
1620_get_crl_dp(X509 *certificate) {
1621 STACK_OF(DIST_POINT) *dps;
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001622 int i, j;
1623 PyObject *lst, *res = NULL;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001624
Christian Heimes598894f2016-09-05 23:19:05 +02001625 dps = X509_get_ext_d2i(certificate, NID_crl_distribution_points, NULL, NULL);
Christian Heimes949ec142013-11-21 16:26:51 +01001626
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001627 if (dps == NULL)
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001628 return Py_None;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001629
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001630 lst = PyList_New(0);
1631 if (lst == NULL)
1632 goto done;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001633
1634 for (i=0; i < sk_DIST_POINT_num(dps); i++) {
1635 DIST_POINT *dp;
1636 STACK_OF(GENERAL_NAME) *gns;
1637
1638 dp = sk_DIST_POINT_value(dps, i);
Christian Heimesa37f5242019-01-15 23:47:42 +01001639 if (dp->distpoint == NULL) {
1640 /* Ignore empty DP value, CVE-2019-5010 */
1641 continue;
1642 }
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001643 gns = dp->distpoint->name.fullname;
1644
1645 for (j=0; j < sk_GENERAL_NAME_num(gns); j++) {
1646 GENERAL_NAME *gn;
1647 ASN1_IA5STRING *uri;
1648 PyObject *ouri;
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001649 int err;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001650
1651 gn = sk_GENERAL_NAME_value(gns, j);
1652 if (gn->type != GEN_URI) {
1653 continue;
1654 }
1655 uri = gn->d.uniformResourceIdentifier;
1656 ouri = PyUnicode_FromStringAndSize((char *)uri->data,
1657 uri->length);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001658 if (ouri == NULL)
1659 goto done;
1660
1661 err = PyList_Append(lst, ouri);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001662 Py_DECREF(ouri);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001663 if (err < 0)
1664 goto done;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001665 }
1666 }
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001667
1668 /* Convert to tuple. */
1669 res = (PyList_GET_SIZE(lst) > 0) ? PyList_AsTuple(lst) : Py_None;
1670
1671 done:
1672 Py_XDECREF(lst);
Olivier Vielpeau2849cc32017-04-14 21:06:07 -04001673 CRL_DIST_POINTS_free(dps);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001674 return res;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001675}
1676
1677static PyObject *
Antoine Pitroufb046912010-11-09 20:21:19 +00001678_decode_certificate(X509 *certificate) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001679
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001680 PyObject *retval = NULL;
1681 BIO *biobuf = NULL;
1682 PyObject *peer;
1683 PyObject *peer_alt_names = NULL;
1684 PyObject *issuer;
1685 PyObject *version;
1686 PyObject *sn_obj;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001687 PyObject *obj;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001688 ASN1_INTEGER *serialNumber;
1689 char buf[2048];
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001690 int len, result;
Christian Heimesa871f692020-06-01 08:58:14 +02001691 const ASN1_TIME *notBefore, *notAfter;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001692 PyObject *pnotBefore, *pnotAfter;
Thomas Woutersed03b412007-08-28 21:37:11 +00001693
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001694 retval = PyDict_New();
1695 if (retval == NULL)
1696 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001697
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001698 peer = _create_tuple_for_X509_NAME(
1699 X509_get_subject_name(certificate));
1700 if (peer == NULL)
1701 goto fail0;
1702 if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) {
1703 Py_DECREF(peer);
1704 goto fail0;
1705 }
1706 Py_DECREF(peer);
Thomas Woutersed03b412007-08-28 21:37:11 +00001707
Antoine Pitroufb046912010-11-09 20:21:19 +00001708 issuer = _create_tuple_for_X509_NAME(
1709 X509_get_issuer_name(certificate));
1710 if (issuer == NULL)
1711 goto fail0;
1712 if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001713 Py_DECREF(issuer);
Antoine Pitroufb046912010-11-09 20:21:19 +00001714 goto fail0;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001715 }
Antoine Pitroufb046912010-11-09 20:21:19 +00001716 Py_DECREF(issuer);
1717
1718 version = PyLong_FromLong(X509_get_version(certificate) + 1);
Christian Heimes5962bef2013-07-26 15:51:18 +02001719 if (version == NULL)
1720 goto fail0;
Antoine Pitroufb046912010-11-09 20:21:19 +00001721 if (PyDict_SetItemString(retval, "version", version) < 0) {
1722 Py_DECREF(version);
1723 goto fail0;
1724 }
1725 Py_DECREF(version);
Guido van Rossumf06628b2007-11-21 20:01:53 +00001726
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001727 /* get a memory buffer */
1728 biobuf = BIO_new(BIO_s_mem());
Zackery Spytz4c49da02018-12-07 03:11:30 -07001729 if (biobuf == NULL) {
1730 PyErr_SetString(PySSLErrorObject, "failed to allocate BIO");
1731 goto fail0;
1732 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001733
Antoine Pitroufb046912010-11-09 20:21:19 +00001734 (void) BIO_reset(biobuf);
1735 serialNumber = X509_get_serialNumber(certificate);
1736 /* should not exceed 20 octets, 160 bits, so buf is big enough */
1737 i2a_ASN1_INTEGER(biobuf, serialNumber);
1738 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1739 if (len < 0) {
1740 _setSSLError(NULL, 0, __FILE__, __LINE__);
1741 goto fail1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001742 }
Antoine Pitroufb046912010-11-09 20:21:19 +00001743 sn_obj = PyUnicode_FromStringAndSize(buf, len);
1744 if (sn_obj == NULL)
1745 goto fail1;
1746 if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) {
1747 Py_DECREF(sn_obj);
1748 goto fail1;
1749 }
1750 Py_DECREF(sn_obj);
1751
1752 (void) BIO_reset(biobuf);
Christian Heimesa871f692020-06-01 08:58:14 +02001753 notBefore = X509_get0_notBefore(certificate);
Antoine Pitroufb046912010-11-09 20:21:19 +00001754 ASN1_TIME_print(biobuf, notBefore);
1755 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1756 if (len < 0) {
1757 _setSSLError(NULL, 0, __FILE__, __LINE__);
1758 goto fail1;
1759 }
1760 pnotBefore = PyUnicode_FromStringAndSize(buf, len);
1761 if (pnotBefore == NULL)
1762 goto fail1;
1763 if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) {
1764 Py_DECREF(pnotBefore);
1765 goto fail1;
1766 }
1767 Py_DECREF(pnotBefore);
Thomas Woutersed03b412007-08-28 21:37:11 +00001768
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001769 (void) BIO_reset(biobuf);
Christian Heimesa871f692020-06-01 08:58:14 +02001770 notAfter = X509_get0_notAfter(certificate);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001771 ASN1_TIME_print(biobuf, notAfter);
1772 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1773 if (len < 0) {
1774 _setSSLError(NULL, 0, __FILE__, __LINE__);
1775 goto fail1;
1776 }
1777 pnotAfter = PyUnicode_FromStringAndSize(buf, len);
1778 if (pnotAfter == NULL)
1779 goto fail1;
1780 if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) {
1781 Py_DECREF(pnotAfter);
1782 goto fail1;
1783 }
1784 Py_DECREF(pnotAfter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001785
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001786 /* Now look for subjectAltName */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001787
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001788 peer_alt_names = _get_peer_alt_names(certificate);
1789 if (peer_alt_names == NULL)
1790 goto fail1;
1791 else if (peer_alt_names != Py_None) {
1792 if (PyDict_SetItemString(retval, "subjectAltName",
1793 peer_alt_names) < 0) {
1794 Py_DECREF(peer_alt_names);
1795 goto fail1;
1796 }
1797 Py_DECREF(peer_alt_names);
1798 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001799
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001800 /* Authority Information Access: OCSP URIs */
1801 obj = _get_aia_uri(certificate, NID_ad_OCSP);
1802 if (obj == NULL) {
1803 goto fail1;
1804 } else if (obj != Py_None) {
1805 result = PyDict_SetItemString(retval, "OCSP", obj);
1806 Py_DECREF(obj);
1807 if (result < 0) {
1808 goto fail1;
1809 }
1810 }
1811
1812 obj = _get_aia_uri(certificate, NID_ad_ca_issuers);
1813 if (obj == NULL) {
1814 goto fail1;
1815 } else if (obj != Py_None) {
1816 result = PyDict_SetItemString(retval, "caIssuers", obj);
1817 Py_DECREF(obj);
1818 if (result < 0) {
1819 goto fail1;
1820 }
1821 }
1822
1823 /* CDP (CRL distribution points) */
1824 obj = _get_crl_dp(certificate);
1825 if (obj == NULL) {
1826 goto fail1;
1827 } else if (obj != Py_None) {
1828 result = PyDict_SetItemString(retval, "crlDistributionPoints", obj);
1829 Py_DECREF(obj);
1830 if (result < 0) {
1831 goto fail1;
1832 }
1833 }
1834
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001835 BIO_free(biobuf);
1836 return retval;
Thomas Woutersed03b412007-08-28 21:37:11 +00001837
1838 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001839 if (biobuf != NULL)
1840 BIO_free(biobuf);
Thomas Woutersed03b412007-08-28 21:37:11 +00001841 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001842 Py_XDECREF(retval);
1843 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001844}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001845
Christian Heimes9a5395a2013-06-17 15:44:12 +02001846static PyObject *
1847_certificate_to_der(X509 *certificate)
1848{
1849 unsigned char *bytes_buf = NULL;
1850 int len;
1851 PyObject *retval;
1852
1853 bytes_buf = NULL;
1854 len = i2d_X509(certificate, &bytes_buf);
1855 if (len < 0) {
1856 _setSSLError(NULL, 0, __FILE__, __LINE__);
1857 return NULL;
1858 }
1859 /* this is actually an immutable bytes sequence */
1860 retval = PyBytes_FromStringAndSize((const char *) bytes_buf, len);
1861 OPENSSL_free(bytes_buf);
1862 return retval;
1863}
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001864
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001865/*[clinic input]
1866_ssl._test_decode_cert
1867 path: object(converter="PyUnicode_FSConverter")
1868 /
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001869
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001870[clinic start generated code]*/
1871
1872static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001873_ssl__test_decode_cert_impl(PyObject *module, PyObject *path)
1874/*[clinic end generated code: output=96becb9abb23c091 input=cdeaaf02d4346628]*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001875{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001876 PyObject *retval = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001877 X509 *x=NULL;
1878 BIO *cert;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001879
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001880 if ((cert=BIO_new(BIO_s_file())) == NULL) {
1881 PyErr_SetString(PySSLErrorObject,
1882 "Can't malloc memory to read file");
1883 goto fail0;
1884 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001885
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001886 if (BIO_read_filename(cert, PyBytes_AsString(path)) <= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001887 PyErr_SetString(PySSLErrorObject,
1888 "Can't open file");
1889 goto fail0;
1890 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001891
Alex Gaynor40dad952019-08-15 08:31:28 -04001892 x = PEM_read_bio_X509(cert, NULL, NULL, NULL);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001893 if (x == NULL) {
1894 PyErr_SetString(PySSLErrorObject,
1895 "Error decoding PEM-encoded file");
1896 goto fail0;
1897 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001898
Antoine Pitroufb046912010-11-09 20:21:19 +00001899 retval = _decode_certificate(x);
Mark Dickinsonee55df52010-08-03 18:31:54 +00001900 X509_free(x);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001901
1902 fail0:
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001903 Py_DECREF(path);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001904 if (cert != NULL) BIO_free(cert);
1905 return retval;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001906}
1907
1908
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001909/*[clinic input]
Christian Heimes141c5e82018-02-24 21:10:57 +01001910_ssl._SSLSocket.getpeercert
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001911 der as binary_mode: bool = False
1912 /
1913
1914Returns the certificate for the peer.
1915
1916If no certificate was provided, returns None. If a certificate was
1917provided, but not validated, returns an empty dictionary. Otherwise
1918returns a dict containing information about the peer certificate.
1919
1920If the optional argument is True, returns a DER-encoded copy of the
1921peer certificate, or None if no certificate was provided. This will
1922return the certificate even if it wasn't validated.
1923[clinic start generated code]*/
1924
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001925static PyObject *
Christian Heimes141c5e82018-02-24 21:10:57 +01001926_ssl__SSLSocket_getpeercert_impl(PySSLSocket *self, int binary_mode)
1927/*[clinic end generated code: output=1f0ab66dfb693c88 input=c0fbe802e57629b7]*/
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001928{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001929 int verification;
Christian Heimes66dc33b2017-05-23 16:02:02 -07001930 X509 *peer_cert;
1931 PyObject *result;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001932
Christian Heimes66dc33b2017-05-23 16:02:02 -07001933 if (!SSL_is_init_finished(self->ssl)) {
Antoine Pitrou20b85552013-09-29 19:50:53 +02001934 PyErr_SetString(PyExc_ValueError,
1935 "handshake not done yet");
1936 return NULL;
1937 }
Christian Heimes66dc33b2017-05-23 16:02:02 -07001938 peer_cert = SSL_get_peer_certificate(self->ssl);
1939 if (peer_cert == NULL)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001940 Py_RETURN_NONE;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001941
Antoine Pitrou721738f2012-08-15 23:20:39 +02001942 if (binary_mode) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001943 /* return cert in DER-encoded format */
Christian Heimes66dc33b2017-05-23 16:02:02 -07001944 result = _certificate_to_der(peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001945 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00001946 verification = SSL_CTX_get_verify_mode(SSL_get_SSL_CTX(self->ssl));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001947 if ((verification & SSL_VERIFY_PEER) == 0)
Christian Heimes66dc33b2017-05-23 16:02:02 -07001948 result = PyDict_New();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001949 else
Christian Heimes66dc33b2017-05-23 16:02:02 -07001950 result = _decode_certificate(peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001951 }
Christian Heimes66dc33b2017-05-23 16:02:02 -07001952 X509_free(peer_cert);
1953 return result;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001954}
1955
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001956static PyObject *
1957cipher_to_tuple(const SSL_CIPHER *cipher)
1958{
1959 const char *cipher_name, *cipher_protocol;
1960 PyObject *v, *retval = PyTuple_New(3);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001961 if (retval == NULL)
1962 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001963
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001964 cipher_name = SSL_CIPHER_get_name(cipher);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001965 if (cipher_name == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001966 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001967 PyTuple_SET_ITEM(retval, 0, Py_None);
1968 } else {
1969 v = PyUnicode_FromString(cipher_name);
1970 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001971 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001972 PyTuple_SET_ITEM(retval, 0, v);
1973 }
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001974
1975 cipher_protocol = SSL_CIPHER_get_version(cipher);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001976 if (cipher_protocol == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001977 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001978 PyTuple_SET_ITEM(retval, 1, Py_None);
1979 } else {
1980 v = PyUnicode_FromString(cipher_protocol);
1981 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001982 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001983 PyTuple_SET_ITEM(retval, 1, v);
1984 }
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001985
1986 v = PyLong_FromLong(SSL_CIPHER_get_bits(cipher, NULL));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001987 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001988 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001989 PyTuple_SET_ITEM(retval, 2, v);
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001990
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001991 return retval;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001992
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001993 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001994 Py_DECREF(retval);
1995 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001996}
1997
Christian Heimes25bfcd52016-09-06 00:04:45 +02001998#if OPENSSL_VERSION_NUMBER >= 0x10002000UL
1999static PyObject *
2000cipher_to_dict(const SSL_CIPHER *cipher)
2001{
2002 const char *cipher_name, *cipher_protocol;
2003
2004 unsigned long cipher_id;
2005 int alg_bits, strength_bits, len;
2006 char buf[512] = {0};
2007#if OPENSSL_VERSION_1_1
2008 int aead, nid;
2009 const char *skcipher = NULL, *digest = NULL, *kx = NULL, *auth = NULL;
2010#endif
Christian Heimes25bfcd52016-09-06 00:04:45 +02002011
2012 /* can be NULL */
2013 cipher_name = SSL_CIPHER_get_name(cipher);
2014 cipher_protocol = SSL_CIPHER_get_version(cipher);
2015 cipher_id = SSL_CIPHER_get_id(cipher);
2016 SSL_CIPHER_description(cipher, buf, sizeof(buf) - 1);
Segev Finer5cff6372017-07-27 01:19:17 +03002017 /* Downcast to avoid a warning. Safe since buf is always 512 bytes */
2018 len = (int)strlen(buf);
Christian Heimes25bfcd52016-09-06 00:04:45 +02002019 if (len > 1 && buf[len-1] == '\n')
2020 buf[len-1] = '\0';
2021 strength_bits = SSL_CIPHER_get_bits(cipher, &alg_bits);
2022
2023#if OPENSSL_VERSION_1_1
2024 aead = SSL_CIPHER_is_aead(cipher);
2025 nid = SSL_CIPHER_get_cipher_nid(cipher);
2026 skcipher = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
2027 nid = SSL_CIPHER_get_digest_nid(cipher);
2028 digest = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
2029 nid = SSL_CIPHER_get_kx_nid(cipher);
2030 kx = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
2031 nid = SSL_CIPHER_get_auth_nid(cipher);
2032 auth = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
2033#endif
2034
Victor Stinner410b9882016-09-12 12:00:23 +02002035 return Py_BuildValue(
Christian Heimes25bfcd52016-09-06 00:04:45 +02002036 "{sksssssssisi"
2037#if OPENSSL_VERSION_1_1
2038 "sOssssssss"
2039#endif
2040 "}",
2041 "id", cipher_id,
2042 "name", cipher_name,
2043 "protocol", cipher_protocol,
2044 "description", buf,
2045 "strength_bits", strength_bits,
2046 "alg_bits", alg_bits
2047#if OPENSSL_VERSION_1_1
2048 ,"aead", aead ? Py_True : Py_False,
2049 "symmetric", skcipher,
2050 "digest", digest,
2051 "kea", kx,
2052 "auth", auth
2053#endif
2054 );
Christian Heimes25bfcd52016-09-06 00:04:45 +02002055}
2056#endif
2057
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002058/*[clinic input]
2059_ssl._SSLSocket.shared_ciphers
2060[clinic start generated code]*/
2061
2062static PyObject *
2063_ssl__SSLSocket_shared_ciphers_impl(PySSLSocket *self)
2064/*[clinic end generated code: output=3d174ead2e42c4fd input=0bfe149da8fe6306]*/
Benjamin Peterson4cb17812015-01-07 11:14:26 -06002065{
2066 STACK_OF(SSL_CIPHER) *ciphers;
2067 int i;
2068 PyObject *res;
2069
Christian Heimes598894f2016-09-05 23:19:05 +02002070 ciphers = SSL_get_ciphers(self->ssl);
2071 if (!ciphers)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06002072 Py_RETURN_NONE;
Benjamin Peterson4cb17812015-01-07 11:14:26 -06002073 res = PyList_New(sk_SSL_CIPHER_num(ciphers));
2074 if (!res)
2075 return NULL;
2076 for (i = 0; i < sk_SSL_CIPHER_num(ciphers); i++) {
2077 PyObject *tup = cipher_to_tuple(sk_SSL_CIPHER_value(ciphers, i));
2078 if (!tup) {
2079 Py_DECREF(res);
2080 return NULL;
2081 }
2082 PyList_SET_ITEM(res, i, tup);
2083 }
2084 return res;
2085}
2086
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002087/*[clinic input]
2088_ssl._SSLSocket.cipher
2089[clinic start generated code]*/
2090
2091static PyObject *
2092_ssl__SSLSocket_cipher_impl(PySSLSocket *self)
2093/*[clinic end generated code: output=376417c16d0e5815 input=548fb0e27243796d]*/
Benjamin Peterson4cb17812015-01-07 11:14:26 -06002094{
2095 const SSL_CIPHER *current;
2096
2097 if (self->ssl == NULL)
2098 Py_RETURN_NONE;
2099 current = SSL_get_current_cipher(self->ssl);
2100 if (current == NULL)
2101 Py_RETURN_NONE;
2102 return cipher_to_tuple(current);
2103}
2104
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002105/*[clinic input]
2106_ssl._SSLSocket.version
2107[clinic start generated code]*/
2108
2109static PyObject *
2110_ssl__SSLSocket_version_impl(PySSLSocket *self)
2111/*[clinic end generated code: output=178aed33193b2cdb input=900186a503436fd6]*/
Antoine Pitrou47e40422014-09-04 21:00:10 +02002112{
2113 const char *version;
2114
2115 if (self->ssl == NULL)
2116 Py_RETURN_NONE;
Christian Heimes68771112017-09-05 21:55:40 -07002117 if (!SSL_is_init_finished(self->ssl)) {
2118 /* handshake not finished */
2119 Py_RETURN_NONE;
2120 }
Antoine Pitrou47e40422014-09-04 21:00:10 +02002121 version = SSL_get_version(self->ssl);
2122 if (!strcmp(version, "unknown"))
2123 Py_RETURN_NONE;
2124 return PyUnicode_FromString(version);
2125}
2126
Christian Heimes29eab552018-02-25 12:31:33 +01002127#if HAVE_NPN
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002128/*[clinic input]
2129_ssl._SSLSocket.selected_npn_protocol
2130[clinic start generated code]*/
2131
2132static PyObject *
2133_ssl__SSLSocket_selected_npn_protocol_impl(PySSLSocket *self)
2134/*[clinic end generated code: output=b91d494cd207ecf6 input=c28fde139204b826]*/
2135{
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002136 const unsigned char *out;
2137 unsigned int outlen;
2138
Victor Stinner4569cd52013-06-23 14:58:43 +02002139 SSL_get0_next_proto_negotiated(self->ssl,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002140 &out, &outlen);
2141
2142 if (out == NULL)
2143 Py_RETURN_NONE;
Benjamin Petersoncca27322015-01-23 16:35:37 -05002144 return PyUnicode_FromStringAndSize((char *)out, outlen);
2145}
2146#endif
2147
Christian Heimes29eab552018-02-25 12:31:33 +01002148#if HAVE_ALPN
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002149/*[clinic input]
2150_ssl._SSLSocket.selected_alpn_protocol
2151[clinic start generated code]*/
2152
2153static PyObject *
2154_ssl__SSLSocket_selected_alpn_protocol_impl(PySSLSocket *self)
2155/*[clinic end generated code: output=ec33688b303d250f input=442de30e35bc2913]*/
2156{
Benjamin Petersoncca27322015-01-23 16:35:37 -05002157 const unsigned char *out;
2158 unsigned int outlen;
2159
2160 SSL_get0_alpn_selected(self->ssl, &out, &outlen);
2161
2162 if (out == NULL)
2163 Py_RETURN_NONE;
2164 return PyUnicode_FromStringAndSize((char *)out, outlen);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002165}
2166#endif
2167
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002168/*[clinic input]
2169_ssl._SSLSocket.compression
2170[clinic start generated code]*/
2171
2172static PyObject *
2173_ssl__SSLSocket_compression_impl(PySSLSocket *self)
2174/*[clinic end generated code: output=bd16cb1bb4646ae7 input=5d059d0a2bbc32c8]*/
2175{
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01002176#ifdef OPENSSL_NO_COMP
2177 Py_RETURN_NONE;
2178#else
2179 const COMP_METHOD *comp_method;
2180 const char *short_name;
2181
2182 if (self->ssl == NULL)
2183 Py_RETURN_NONE;
2184 comp_method = SSL_get_current_compression(self->ssl);
Christian Heimes598894f2016-09-05 23:19:05 +02002185 if (comp_method == NULL || COMP_get_type(comp_method) == NID_undef)
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01002186 Py_RETURN_NONE;
Christian Heimes281e5f82016-09-06 01:10:39 +02002187 short_name = OBJ_nid2sn(COMP_get_type(comp_method));
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01002188 if (short_name == NULL)
2189 Py_RETURN_NONE;
2190 return PyUnicode_DecodeFSDefault(short_name);
2191#endif
2192}
2193
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002194static PySSLContext *PySSL_get_context(PySSLSocket *self, void *closure) {
2195 Py_INCREF(self->ctx);
2196 return self->ctx;
2197}
2198
2199static int PySSL_set_context(PySSLSocket *self, PyObject *value,
2200 void *closure) {
2201
Christian Heimes5c36da72020-11-20 09:40:12 +01002202 if (PyObject_TypeCheck(value, PySSLContext_Type)) {
Antoine Pitrou912fbff2013-03-30 16:29:32 +01002203#if !HAVE_SNI
2204 PyErr_SetString(PyExc_NotImplementedError, "setting a socket's "
2205 "context is not supported by your OpenSSL library");
Antoine Pitrou41f8c4f2013-03-30 16:36:54 +01002206 return -1;
Antoine Pitrou912fbff2013-03-30 16:29:32 +01002207#else
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002208 Py_INCREF(value);
Serhiy Storchaka57a01d32016-04-10 18:05:40 +03002209 Py_SETREF(self->ctx, (PySSLContext *)value);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002210 SSL_set_SSL_CTX(self->ssl, self->ctx->ctx);
Christian Heimes77cde502021-03-21 16:13:09 +01002211 /* Set SSL* internal msg_callback to state of new context's state */
2212 SSL_set_msg_callback(
2213 self->ssl,
2214 self->ctx->msg_cb ? _PySSL_msg_callback : NULL
2215 );
Antoine Pitrou912fbff2013-03-30 16:29:32 +01002216#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002217 } else {
Ned Deily4531ec72018-06-11 20:26:28 -04002218 PyErr_SetString(PyExc_TypeError, "The value must be a SSLContext");
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002219 return -1;
2220 }
2221
2222 return 0;
2223}
2224
2225PyDoc_STRVAR(PySSL_set_context_doc,
2226"_setter_context(ctx)\n\
2227\
2228This changes the context associated with the SSLSocket. This is typically\n\
Christian Heimes11a14932018-02-24 02:35:08 +01002229used from within a callback function set by the sni_callback\n\
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002230on the SSLContext to change the certificate information associated with the\n\
2231SSLSocket before the cryptographic exchange handshake messages\n");
2232
2233
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002234static PyObject *
2235PySSL_get_server_side(PySSLSocket *self, void *c)
2236{
2237 return PyBool_FromLong(self->socket_type == PY_SSL_SERVER);
2238}
2239
2240PyDoc_STRVAR(PySSL_get_server_side_doc,
2241"Whether this is a server-side socket.");
2242
2243static PyObject *
2244PySSL_get_server_hostname(PySSLSocket *self, void *c)
2245{
2246 if (self->server_hostname == NULL)
2247 Py_RETURN_NONE;
2248 Py_INCREF(self->server_hostname);
2249 return self->server_hostname;
2250}
2251
2252PyDoc_STRVAR(PySSL_get_server_hostname_doc,
2253"The currently set server hostname (for SNI).");
2254
2255static PyObject *
2256PySSL_get_owner(PySSLSocket *self, void *c)
2257{
2258 PyObject *owner;
2259
2260 if (self->owner == NULL)
2261 Py_RETURN_NONE;
2262
2263 owner = PyWeakref_GetObject(self->owner);
2264 Py_INCREF(owner);
2265 return owner;
2266}
2267
2268static int
2269PySSL_set_owner(PySSLSocket *self, PyObject *value, void *c)
2270{
Serhiy Storchaka48842712016-04-06 09:45:48 +03002271 Py_XSETREF(self->owner, PyWeakref_NewRef(value, NULL));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002272 if (self->owner == NULL)
2273 return -1;
2274 return 0;
2275}
2276
2277PyDoc_STRVAR(PySSL_get_owner_doc,
2278"The Python-level owner of this object.\
2279Passed as \"self\" in servername callback.");
2280
Christian Heimesc7f70692019-05-31 11:44:05 +02002281static int
2282PySSL_traverse(PySSLSocket *self, visitproc visit, void *arg)
2283{
2284 Py_VISIT(self->exc_type);
2285 Py_VISIT(self->exc_value);
2286 Py_VISIT(self->exc_tb);
2287 return 0;
2288}
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002289
Christian Heimesc7f70692019-05-31 11:44:05 +02002290static int
2291PySSL_clear(PySSLSocket *self)
2292{
2293 Py_CLEAR(self->exc_type);
2294 Py_CLEAR(self->exc_value);
2295 Py_CLEAR(self->exc_tb);
2296 return 0;
2297}
2298
2299static void
2300PySSL_dealloc(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002301{
Christian Heimes5c36da72020-11-20 09:40:12 +01002302 PyTypeObject *tp = Py_TYPE(self);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002303 if (self->ssl)
2304 SSL_free(self->ssl);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002305 Py_XDECREF(self->Socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002306 Py_XDECREF(self->ctx);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002307 Py_XDECREF(self->server_hostname);
2308 Py_XDECREF(self->owner);
Victor Stinner32bd68c2020-12-01 10:37:39 +01002309 PyObject_Free(self);
Christian Heimes5c36da72020-11-20 09:40:12 +01002310 Py_DECREF(tp);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002311}
2312
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002313/* If the socket has a timeout, do a select()/poll() on the socket.
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002314 The argument writing indicates the direction.
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00002315 Returns one of the possibilities in the timeout_state enum (above).
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002316 */
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00002317
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002318static int
Victor Stinner14690702015-04-06 22:46:13 +02002319PySSL_select(PySocketSockObject *s, int writing, _PyTime_t timeout)
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002320{
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002321 int rc;
2322#ifdef HAVE_POLL
2323 struct pollfd pollfd;
2324 _PyTime_t ms;
2325#else
2326 int nfds;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002327 fd_set fds;
2328 struct timeval tv;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002329#endif
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002330
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002331 /* Nothing to do unless we're in timeout mode (not non-blocking) */
Victor Stinner14690702015-04-06 22:46:13 +02002332 if ((s == NULL) || (timeout == 0))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002333 return SOCKET_IS_NONBLOCKING;
Victor Stinner14690702015-04-06 22:46:13 +02002334 else if (timeout < 0) {
2335 if (s->sock_timeout > 0)
2336 return SOCKET_HAS_TIMED_OUT;
2337 else
2338 return SOCKET_IS_BLOCKING;
2339 }
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002340
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002341 /* Guard against closed socket */
Victor Stinner524714e2016-07-22 17:43:59 +02002342 if (s->sock_fd == INVALID_SOCKET)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002343 return SOCKET_HAS_BEEN_CLOSED;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002344
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002345 /* Prefer poll, if available, since you can poll() any fd
2346 * which can't be done with select(). */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002347#ifdef HAVE_POLL
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002348 pollfd.fd = s->sock_fd;
2349 pollfd.events = writing ? POLLOUT : POLLIN;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002350
Victor Stinner14690702015-04-06 22:46:13 +02002351 /* timeout is in seconds, poll() uses milliseconds */
2352 ms = (int)_PyTime_AsMilliseconds(timeout, _PyTime_ROUND_CEILING);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002353 assert(ms <= INT_MAX);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002354
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002355 PySSL_BEGIN_ALLOW_THREADS
2356 rc = poll(&pollfd, 1, (int)ms);
2357 PySSL_END_ALLOW_THREADS
2358#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002359 /* Guard against socket too large for select*/
Charles-François Nataliaa26b272011-08-28 17:51:43 +02002360 if (!_PyIsSelectable_fd(s->sock_fd))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002361 return SOCKET_TOO_LARGE_FOR_SELECT;
Neal Norwitz082b2df2006-02-07 07:04:46 +00002362
Victor Stinner14690702015-04-06 22:46:13 +02002363 _PyTime_AsTimeval_noraise(timeout, &tv, _PyTime_ROUND_CEILING);
Victor Stinnere2452312015-03-28 03:00:46 +01002364
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002365 FD_ZERO(&fds);
2366 FD_SET(s->sock_fd, &fds);
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002367
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002368 /* Wait until the socket becomes ready */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002369 PySSL_BEGIN_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002370 nfds = Py_SAFE_DOWNCAST(s->sock_fd+1, SOCKET_T, int);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002371 if (writing)
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002372 rc = select(nfds, NULL, &fds, NULL, &tv);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002373 else
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002374 rc = select(nfds, &fds, NULL, NULL, &tv);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002375 PySSL_END_ALLOW_THREADS
Bill Janssen6e027db2007-11-15 22:23:56 +00002376#endif
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002377
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002378 /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
2379 (when we are able to write or when there's something to read) */
2380 return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002381}
2382
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002383/*[clinic input]
2384_ssl._SSLSocket.write
2385 b: Py_buffer
2386 /
2387
2388Writes the bytes-like object b into the SSL object.
2389
2390Returns the number of bytes written.
2391[clinic start generated code]*/
2392
2393static PyObject *
2394_ssl__SSLSocket_write_impl(PySSLSocket *self, Py_buffer *b)
2395/*[clinic end generated code: output=aa7a6be5527358d8 input=77262d994fe5100a]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002396{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002397 int len;
2398 int sockstate;
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002399 _PySSLError err;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002400 int nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002401 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002402 _PyTime_t timeout, deadline = 0;
2403 int has_timeout;
Bill Janssen54cc54c2007-12-14 22:08:56 +00002404
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002405 if (sock != NULL) {
2406 if (((PyObject*)sock) == Py_None) {
2407 _setSSLError("Underlying socket connection gone",
2408 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2409 return NULL;
2410 }
2411 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002412 }
2413
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002414 if (b->len > INT_MAX) {
Victor Stinner6efa9652013-06-25 00:42:31 +02002415 PyErr_Format(PyExc_OverflowError,
2416 "string longer than %d bytes", INT_MAX);
2417 goto error;
2418 }
2419
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002420 if (sock != NULL) {
2421 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002422 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002423 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2424 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
2425 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002426
Victor Stinner14690702015-04-06 22:46:13 +02002427 timeout = GET_SOCKET_TIMEOUT(sock);
2428 has_timeout = (timeout > 0);
2429 if (has_timeout)
2430 deadline = _PyTime_GetMonotonicClock() + timeout;
2431
2432 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002433 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Christian Heimes03c8ddd2020-11-20 09:26:07 +01002434 PyErr_SetString(PyExc_TimeoutError,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002435 "The write operation timed out");
2436 goto error;
2437 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
2438 PyErr_SetString(PySSLErrorObject,
2439 "Underlying socket has been closed.");
2440 goto error;
2441 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
2442 PyErr_SetString(PySSLErrorObject,
2443 "Underlying socket too large for select().");
2444 goto error;
2445 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002446
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002447 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002448 PySSL_BEGIN_ALLOW_THREADS
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002449 len = SSL_write(self->ssl, b->buf, (int)b->len);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002450 err = _PySSL_errno(len <= 0, self->ssl, len);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002451 PySSL_END_ALLOW_THREADS
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002452 self->err = err;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002453
2454 if (PyErr_CheckSignals())
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002455 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002456
Victor Stinner14690702015-04-06 22:46:13 +02002457 if (has_timeout)
2458 timeout = deadline - _PyTime_GetMonotonicClock();
2459
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002460 if (err.ssl == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +02002461 sockstate = PySSL_select(sock, 0, timeout);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002462 } else if (err.ssl == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +02002463 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002464 } else {
2465 sockstate = SOCKET_OPERATION_OK;
2466 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002467
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002468 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Christian Heimes03c8ddd2020-11-20 09:26:07 +01002469 PyErr_SetString(PyExc_TimeoutError,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002470 "The write operation timed out");
2471 goto error;
2472 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
2473 PyErr_SetString(PySSLErrorObject,
2474 "Underlying socket has been closed.");
2475 goto error;
2476 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
2477 break;
2478 }
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002479 } while (err.ssl == SSL_ERROR_WANT_READ ||
2480 err.ssl == SSL_ERROR_WANT_WRITE);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002481
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002482 Py_XDECREF(sock);
Christian Heimesc7f70692019-05-31 11:44:05 +02002483 if (len <= 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002484 return PySSL_SetError(self, len, __FILE__, __LINE__);
Christian Heimesc7f70692019-05-31 11:44:05 +02002485 if (PySSL_ChainExceptions(self) < 0)
2486 return NULL;
2487 return PyLong_FromLong(len);
Antoine Pitrou7d7aede2009-11-25 18:55:32 +00002488error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002489 Py_XDECREF(sock);
Christian Heimesc7f70692019-05-31 11:44:05 +02002490 PySSL_ChainExceptions(self);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002491 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002492}
2493
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002494/*[clinic input]
2495_ssl._SSLSocket.pending
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002496
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002497Returns the number of already decrypted bytes available for read, pending on the connection.
2498[clinic start generated code]*/
2499
2500static PyObject *
2501_ssl__SSLSocket_pending_impl(PySSLSocket *self)
2502/*[clinic end generated code: output=983d9fecdc308a83 input=2b77487d6dfd597f]*/
Bill Janssen6e027db2007-11-15 22:23:56 +00002503{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002504 int count = 0;
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002505 _PySSLError err;
Bill Janssen6e027db2007-11-15 22:23:56 +00002506
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002507 PySSL_BEGIN_ALLOW_THREADS
2508 count = SSL_pending(self->ssl);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002509 err = _PySSL_errno(count < 0, self->ssl, count);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002510 PySSL_END_ALLOW_THREADS
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002511 self->err = err;
2512
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002513 if (count < 0)
2514 return PySSL_SetError(self, count, __FILE__, __LINE__);
2515 else
2516 return PyLong_FromLong(count);
Bill Janssen6e027db2007-11-15 22:23:56 +00002517}
2518
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002519/*[clinic input]
2520_ssl._SSLSocket.read
2521 size as len: int
2522 [
Larry Hastingsdbfdc382015-05-04 06:59:46 -07002523 buffer: Py_buffer(accept={rwbuffer})
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002524 ]
2525 /
Bill Janssen6e027db2007-11-15 22:23:56 +00002526
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002527Read up to size bytes from the SSL socket.
2528[clinic start generated code]*/
2529
2530static PyObject *
2531_ssl__SSLSocket_read_impl(PySSLSocket *self, int len, int group_right_1,
2532 Py_buffer *buffer)
Larry Hastingsdbfdc382015-05-04 06:59:46 -07002533/*[clinic end generated code: output=00097776cec2a0af input=ff157eb918d0905b]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002534{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002535 PyObject *dest = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002536 char *mem;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002537 int count;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002538 int sockstate;
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002539 _PySSLError err;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002540 int nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002541 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002542 _PyTime_t timeout, deadline = 0;
2543 int has_timeout;
Bill Janssen54cc54c2007-12-14 22:08:56 +00002544
Martin Panter5503d472016-03-27 05:35:19 +00002545 if (!group_right_1 && len < 0) {
2546 PyErr_SetString(PyExc_ValueError, "size should not be negative");
2547 return NULL;
2548 }
2549
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002550 if (sock != NULL) {
2551 if (((PyObject*)sock) == Py_None) {
2552 _setSSLError("Underlying socket connection gone",
2553 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2554 return NULL;
2555 }
2556 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002557 }
2558
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002559 if (!group_right_1) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002560 dest = PyBytes_FromStringAndSize(NULL, len);
2561 if (dest == NULL)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002562 goto error;
Martin Panterbed7f1a2016-07-11 00:17:13 +00002563 if (len == 0) {
2564 Py_XDECREF(sock);
2565 return dest;
2566 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002567 mem = PyBytes_AS_STRING(dest);
2568 }
2569 else {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002570 mem = buffer->buf;
2571 if (len <= 0 || len > buffer->len) {
2572 len = (int) buffer->len;
2573 if (buffer->len != len) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002574 PyErr_SetString(PyExc_OverflowError,
2575 "maximum length can't fit in a C 'int'");
2576 goto error;
2577 }
Martin Panterbed7f1a2016-07-11 00:17:13 +00002578 if (len == 0) {
2579 count = 0;
2580 goto done;
2581 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002582 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002583 }
2584
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002585 if (sock != NULL) {
2586 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002587 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002588 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2589 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
2590 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002591
Victor Stinner14690702015-04-06 22:46:13 +02002592 timeout = GET_SOCKET_TIMEOUT(sock);
2593 has_timeout = (timeout > 0);
2594 if (has_timeout)
2595 deadline = _PyTime_GetMonotonicClock() + timeout;
2596
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002597 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002598 PySSL_BEGIN_ALLOW_THREADS
2599 count = SSL_read(self->ssl, mem, len);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002600 err = _PySSL_errno(count <= 0, self->ssl, count);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002601 PySSL_END_ALLOW_THREADS
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002602 self->err = err;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002603
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002604 if (PyErr_CheckSignals())
2605 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002606
Victor Stinner14690702015-04-06 22:46:13 +02002607 if (has_timeout)
2608 timeout = deadline - _PyTime_GetMonotonicClock();
2609
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002610 if (err.ssl == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +02002611 sockstate = PySSL_select(sock, 0, timeout);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002612 } else if (err.ssl == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +02002613 sockstate = PySSL_select(sock, 1, timeout);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002614 } else if (err.ssl == SSL_ERROR_ZERO_RETURN &&
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002615 SSL_get_shutdown(self->ssl) == SSL_RECEIVED_SHUTDOWN)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002616 {
2617 count = 0;
2618 goto done;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002619 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002620 else
2621 sockstate = SOCKET_OPERATION_OK;
2622
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002623 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Christian Heimes03c8ddd2020-11-20 09:26:07 +01002624 PyErr_SetString(PyExc_TimeoutError,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002625 "The read operation timed out");
2626 goto error;
2627 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
2628 break;
2629 }
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002630 } while (err.ssl == SSL_ERROR_WANT_READ ||
2631 err.ssl == SSL_ERROR_WANT_WRITE);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002632
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002633 if (count <= 0) {
2634 PySSL_SetError(self, count, __FILE__, __LINE__);
2635 goto error;
2636 }
Christian Heimesc7f70692019-05-31 11:44:05 +02002637 if (self->exc_type != NULL)
2638 goto error;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002639
2640done:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002641 Py_XDECREF(sock);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002642 if (!group_right_1) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002643 _PyBytes_Resize(&dest, count);
2644 return dest;
2645 }
2646 else {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002647 return PyLong_FromLong(count);
2648 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002649
2650error:
Christian Heimesc7f70692019-05-31 11:44:05 +02002651 PySSL_ChainExceptions(self);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002652 Py_XDECREF(sock);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002653 if (!group_right_1)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002654 Py_XDECREF(dest);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002655 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002656}
2657
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002658/*[clinic input]
2659_ssl._SSLSocket.shutdown
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002660
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002661Does the SSL shutdown handshake with the remote end.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002662[clinic start generated code]*/
2663
2664static PyObject *
2665_ssl__SSLSocket_shutdown_impl(PySSLSocket *self)
Christian Heimes141c5e82018-02-24 21:10:57 +01002666/*[clinic end generated code: output=ca1aa7ed9d25ca42 input=11d39e69b0a2bf4a]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00002667{
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002668 _PySSLError err;
2669 int sockstate, nonblocking, ret;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002670 int zeros = 0;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002671 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002672 _PyTime_t timeout, deadline = 0;
2673 int has_timeout;
Bill Janssen40a0f662008-08-12 16:56:25 +00002674
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002675 if (sock != NULL) {
2676 /* Guard against closed socket */
Victor Stinner524714e2016-07-22 17:43:59 +02002677 if ((((PyObject*)sock) == Py_None) || (sock->sock_fd == INVALID_SOCKET)) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002678 _setSSLError("Underlying socket connection gone",
2679 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2680 return NULL;
2681 }
2682 Py_INCREF(sock);
2683
2684 /* Just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002685 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002686 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2687 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002688 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002689
Victor Stinner14690702015-04-06 22:46:13 +02002690 timeout = GET_SOCKET_TIMEOUT(sock);
2691 has_timeout = (timeout > 0);
2692 if (has_timeout)
2693 deadline = _PyTime_GetMonotonicClock() + timeout;
2694
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002695 while (1) {
2696 PySSL_BEGIN_ALLOW_THREADS
2697 /* Disable read-ahead so that unwrap can work correctly.
2698 * Otherwise OpenSSL might read in too much data,
2699 * eating clear text data that happens to be
2700 * transmitted after the SSL shutdown.
Ezio Melotti85a86292013-08-17 16:57:41 +03002701 * Should be safe to call repeatedly every time this
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002702 * function is used and the shutdown_seen_zero != 0
2703 * condition is met.
2704 */
2705 if (self->shutdown_seen_zero)
2706 SSL_set_read_ahead(self->ssl, 0);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002707 ret = SSL_shutdown(self->ssl);
2708 err = _PySSL_errno(ret < 0, self->ssl, ret);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002709 PySSL_END_ALLOW_THREADS
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002710 self->err = err;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002711
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002712 /* If err == 1, a secure shutdown with SSL_shutdown() is complete */
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002713 if (ret > 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002714 break;
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002715 if (ret == 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002716 /* Don't loop endlessly; instead preserve legacy
2717 behaviour of trying SSL_shutdown() only twice.
2718 This looks necessary for OpenSSL < 0.9.8m */
2719 if (++zeros > 1)
2720 break;
2721 /* Shutdown was sent, now try receiving */
2722 self->shutdown_seen_zero = 1;
2723 continue;
Bill Janssen40a0f662008-08-12 16:56:25 +00002724 }
2725
Victor Stinner14690702015-04-06 22:46:13 +02002726 if (has_timeout)
2727 timeout = deadline - _PyTime_GetMonotonicClock();
2728
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002729 /* Possibly retry shutdown until timeout or failure */
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002730 if (err.ssl == SSL_ERROR_WANT_READ)
Victor Stinner14690702015-04-06 22:46:13 +02002731 sockstate = PySSL_select(sock, 0, timeout);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002732 else if (err.ssl == SSL_ERROR_WANT_WRITE)
Victor Stinner14690702015-04-06 22:46:13 +02002733 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002734 else
2735 break;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002736
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002737 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002738 if (err.ssl == SSL_ERROR_WANT_READ)
Christian Heimes03c8ddd2020-11-20 09:26:07 +01002739 PyErr_SetString(PyExc_TimeoutError,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002740 "The read operation timed out");
2741 else
Christian Heimes03c8ddd2020-11-20 09:26:07 +01002742 PyErr_SetString(PyExc_TimeoutError,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002743 "The write operation timed out");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002744 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002745 }
2746 else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
2747 PyErr_SetString(PySSLErrorObject,
2748 "Underlying socket too large for select().");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002749 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002750 }
2751 else if (sockstate != SOCKET_OPERATION_OK)
2752 /* Retain the SSL error code */
2753 break;
2754 }
Nathaniel J. Smithc0da5822018-09-21 21:44:12 -07002755 if (ret < 0) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002756 Py_XDECREF(sock);
Christian Heimesc7f70692019-05-31 11:44:05 +02002757 PySSL_SetError(self, ret, __FILE__, __LINE__);
2758 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002759 }
Christian Heimesc7f70692019-05-31 11:44:05 +02002760 if (self->exc_type != NULL)
2761 goto error;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002762 if (sock)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002763 /* It's already INCREF'ed */
2764 return (PyObject *) sock;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002765 else
2766 Py_RETURN_NONE;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002767
2768error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002769 Py_XDECREF(sock);
Christian Heimesc7f70692019-05-31 11:44:05 +02002770 PySSL_ChainExceptions(self);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002771 return NULL;
Bill Janssen40a0f662008-08-12 16:56:25 +00002772}
2773
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002774/*[clinic input]
Christian Heimes141c5e82018-02-24 21:10:57 +01002775_ssl._SSLSocket.get_channel_binding
2776 cb_type: str = "tls-unique"
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002777
Christian Heimes141c5e82018-02-24 21:10:57 +01002778Get channel binding data for current connection.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002779
Christian Heimes141c5e82018-02-24 21:10:57 +01002780Raise ValueError if the requested `cb_type` is not supported. Return bytes
2781of the data or None if the data is not available (e.g. before the handshake).
2782Only 'tls-unique' channel binding data from RFC 5929 is supported.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002783[clinic start generated code]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00002784
Antoine Pitroud6494802011-07-21 01:11:30 +02002785static PyObject *
Christian Heimes141c5e82018-02-24 21:10:57 +01002786_ssl__SSLSocket_get_channel_binding_impl(PySSLSocket *self,
2787 const char *cb_type)
2788/*[clinic end generated code: output=34bac9acb6a61d31 input=08b7e43b99c17d41]*/
Antoine Pitroud6494802011-07-21 01:11:30 +02002789{
Antoine Pitroud6494802011-07-21 01:11:30 +02002790 char buf[PySSL_CB_MAXLEN];
Victor Stinner9ee02032013-06-23 15:08:23 +02002791 size_t len;
Antoine Pitroud6494802011-07-21 01:11:30 +02002792
Christian Heimes141c5e82018-02-24 21:10:57 +01002793 if (strcmp(cb_type, "tls-unique") == 0) {
2794 if (SSL_session_reused(self->ssl) ^ !self->socket_type) {
2795 /* if session is resumed XOR we are the client */
2796 len = SSL_get_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2797 }
2798 else {
2799 /* if a new session XOR we are the server */
2800 len = SSL_get_peer_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2801 }
Antoine Pitroud6494802011-07-21 01:11:30 +02002802 }
2803 else {
Christian Heimes141c5e82018-02-24 21:10:57 +01002804 PyErr_Format(
2805 PyExc_ValueError,
2806 "'%s' channel binding type not implemented",
2807 cb_type
2808 );
2809 return NULL;
Antoine Pitroud6494802011-07-21 01:11:30 +02002810 }
2811
2812 /* It cannot be negative in current OpenSSL version as of July 2011 */
Antoine Pitroud6494802011-07-21 01:11:30 +02002813 if (len == 0)
2814 Py_RETURN_NONE;
2815
Christian Heimes141c5e82018-02-24 21:10:57 +01002816 return PyBytes_FromStringAndSize(buf, len);
Antoine Pitroud6494802011-07-21 01:11:30 +02002817}
2818
Christian Heimes9fb051f2018-09-23 08:32:31 +02002819/*[clinic input]
2820_ssl._SSLSocket.verify_client_post_handshake
2821
2822Initiate TLS 1.3 post-handshake authentication
2823[clinic start generated code]*/
2824
2825static PyObject *
2826_ssl__SSLSocket_verify_client_post_handshake_impl(PySSLSocket *self)
2827/*[clinic end generated code: output=532147f3b1341425 input=6bfa874810a3d889]*/
2828{
2829#ifdef TLS1_3_VERSION
2830 int err = SSL_verify_client_post_handshake(self->ssl);
2831 if (err == 0)
2832 return _setSSLError(NULL, 0, __FILE__, __LINE__);
2833 else
2834 Py_RETURN_NONE;
2835#else
2836 PyErr_SetString(PyExc_NotImplementedError,
2837 "Post-handshake auth is not supported by your "
2838 "OpenSSL version.");
2839 return NULL;
2840#endif
2841}
2842
Christian Heimes99a65702016-09-10 23:44:53 +02002843#ifdef OPENSSL_VERSION_1_1
2844
2845static SSL_SESSION*
2846_ssl_session_dup(SSL_SESSION *session) {
2847 SSL_SESSION *newsession = NULL;
2848 int slen;
2849 unsigned char *senc = NULL, *p;
2850 const unsigned char *const_p;
2851
2852 if (session == NULL) {
2853 PyErr_SetString(PyExc_ValueError, "Invalid session");
2854 goto error;
2855 }
2856
2857 /* get length */
2858 slen = i2d_SSL_SESSION(session, NULL);
2859 if (slen == 0 || slen > 0xFF00) {
2860 PyErr_SetString(PyExc_ValueError, "i2d() failed.");
2861 goto error;
2862 }
2863 if ((senc = PyMem_Malloc(slen)) == NULL) {
2864 PyErr_NoMemory();
2865 goto error;
2866 }
2867 p = senc;
2868 if (!i2d_SSL_SESSION(session, &p)) {
2869 PyErr_SetString(PyExc_ValueError, "i2d() failed.");
2870 goto error;
2871 }
2872 const_p = senc;
2873 newsession = d2i_SSL_SESSION(NULL, &const_p, slen);
2874 if (session == NULL) {
2875 goto error;
2876 }
2877 PyMem_Free(senc);
2878 return newsession;
2879 error:
2880 if (senc != NULL) {
2881 PyMem_Free(senc);
2882 }
2883 return NULL;
2884}
2885#endif
2886
2887static PyObject *
2888PySSL_get_session(PySSLSocket *self, void *closure) {
2889 /* get_session can return sessions from a server-side connection,
2890 * it does not check for handshake done or client socket. */
2891 PySSLSession *pysess;
2892 SSL_SESSION *session;
2893
2894#ifdef OPENSSL_VERSION_1_1
2895 /* duplicate session as workaround for session bug in OpenSSL 1.1.0,
2896 * https://github.com/openssl/openssl/issues/1550 */
2897 session = SSL_get0_session(self->ssl); /* borrowed reference */
2898 if (session == NULL) {
2899 Py_RETURN_NONE;
2900 }
2901 if ((session = _ssl_session_dup(session)) == NULL) {
2902 return NULL;
2903 }
2904#else
2905 session = SSL_get1_session(self->ssl);
2906 if (session == NULL) {
2907 Py_RETURN_NONE;
2908 }
2909#endif
Christian Heimes5c36da72020-11-20 09:40:12 +01002910 pysess = PyObject_GC_New(PySSLSession, PySSLSession_Type);
Christian Heimes99a65702016-09-10 23:44:53 +02002911 if (pysess == NULL) {
2912 SSL_SESSION_free(session);
2913 return NULL;
2914 }
2915
2916 assert(self->ctx);
2917 pysess->ctx = self->ctx;
2918 Py_INCREF(pysess->ctx);
2919 pysess->session = session;
Christian Heimesa5d07652016-09-24 10:48:05 +02002920 PyObject_GC_Track(pysess);
Christian Heimes99a65702016-09-10 23:44:53 +02002921 return (PyObject *)pysess;
2922}
2923
2924static int PySSL_set_session(PySSLSocket *self, PyObject *value,
2925 void *closure)
2926 {
2927 PySSLSession *pysess;
2928#ifdef OPENSSL_VERSION_1_1
2929 SSL_SESSION *session;
2930#endif
2931 int result;
2932
2933 if (!PySSLSession_Check(value)) {
Ned Deily4531ec72018-06-11 20:26:28 -04002934 PyErr_SetString(PyExc_TypeError, "Value is not a SSLSession.");
Christian Heimes99a65702016-09-10 23:44:53 +02002935 return -1;
2936 }
2937 pysess = (PySSLSession *)value;
2938
2939 if (self->ctx->ctx != pysess->ctx->ctx) {
2940 PyErr_SetString(PyExc_ValueError,
2941 "Session refers to a different SSLContext.");
2942 return -1;
2943 }
2944 if (self->socket_type != PY_SSL_CLIENT) {
2945 PyErr_SetString(PyExc_ValueError,
2946 "Cannot set session for server-side SSLSocket.");
2947 return -1;
2948 }
Christian Heimes66dc33b2017-05-23 16:02:02 -07002949 if (SSL_is_init_finished(self->ssl)) {
Christian Heimes99a65702016-09-10 23:44:53 +02002950 PyErr_SetString(PyExc_ValueError,
2951 "Cannot set session after handshake.");
2952 return -1;
2953 }
2954#ifdef OPENSSL_VERSION_1_1
2955 /* duplicate session */
2956 if ((session = _ssl_session_dup(pysess->session)) == NULL) {
2957 return -1;
2958 }
2959 result = SSL_set_session(self->ssl, session);
2960 /* free duplicate, SSL_set_session() bumps ref count */
2961 SSL_SESSION_free(session);
2962#else
2963 result = SSL_set_session(self->ssl, pysess->session);
2964#endif
2965 if (result == 0) {
2966 _setSSLError(NULL, 0, __FILE__, __LINE__);
2967 return -1;
2968 }
2969 return 0;
2970}
2971
2972PyDoc_STRVAR(PySSL_set_session_doc,
2973"_setter_session(session)\n\
2974\
2975Get / set SSLSession.");
2976
2977static PyObject *
2978PySSL_get_session_reused(PySSLSocket *self, void *closure) {
2979 if (SSL_session_reused(self->ssl)) {
2980 Py_RETURN_TRUE;
2981 } else {
2982 Py_RETURN_FALSE;
2983 }
2984}
2985
2986PyDoc_STRVAR(PySSL_get_session_reused_doc,
2987"Was the client session reused during handshake?");
2988
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002989static PyGetSetDef ssl_getsetlist[] = {
2990 {"context", (getter) PySSL_get_context,
2991 (setter) PySSL_set_context, PySSL_set_context_doc},
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002992 {"server_side", (getter) PySSL_get_server_side, NULL,
2993 PySSL_get_server_side_doc},
2994 {"server_hostname", (getter) PySSL_get_server_hostname, NULL,
2995 PySSL_get_server_hostname_doc},
2996 {"owner", (getter) PySSL_get_owner, (setter) PySSL_set_owner,
2997 PySSL_get_owner_doc},
Christian Heimes99a65702016-09-10 23:44:53 +02002998 {"session", (getter) PySSL_get_session,
2999 (setter) PySSL_set_session, PySSL_set_session_doc},
3000 {"session_reused", (getter) PySSL_get_session_reused, NULL,
3001 PySSL_get_session_reused_doc},
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003002 {NULL}, /* sentinel */
3003};
3004
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003005static PyMethodDef PySSLMethods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003006 _SSL__SSLSOCKET_DO_HANDSHAKE_METHODDEF
3007 _SSL__SSLSOCKET_WRITE_METHODDEF
3008 _SSL__SSLSOCKET_READ_METHODDEF
3009 _SSL__SSLSOCKET_PENDING_METHODDEF
Christian Heimes141c5e82018-02-24 21:10:57 +01003010 _SSL__SSLSOCKET_GETPEERCERT_METHODDEF
3011 _SSL__SSLSOCKET_GET_CHANNEL_BINDING_METHODDEF
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003012 _SSL__SSLSOCKET_CIPHER_METHODDEF
3013 _SSL__SSLSOCKET_SHARED_CIPHERS_METHODDEF
3014 _SSL__SSLSOCKET_VERSION_METHODDEF
3015 _SSL__SSLSOCKET_SELECTED_NPN_PROTOCOL_METHODDEF
3016 _SSL__SSLSOCKET_SELECTED_ALPN_PROTOCOL_METHODDEF
3017 _SSL__SSLSOCKET_COMPRESSION_METHODDEF
3018 _SSL__SSLSOCKET_SHUTDOWN_METHODDEF
Christian Heimes9fb051f2018-09-23 08:32:31 +02003019 _SSL__SSLSOCKET_VERIFY_CLIENT_POST_HANDSHAKE_METHODDEF
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003020 {NULL, NULL}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003021};
3022
Christian Heimes5c36da72020-11-20 09:40:12 +01003023static PyType_Slot PySSLSocket_slots[] = {
3024 {Py_tp_methods, PySSLMethods},
3025 {Py_tp_getset, ssl_getsetlist},
3026 {Py_tp_dealloc, PySSL_dealloc},
3027 {Py_tp_traverse, PySSL_traverse},
3028 {Py_tp_clear, PySSL_clear},
3029 {0, 0},
3030};
3031
3032static PyType_Spec PySSLSocket_spec = {
3033 "_ssl._SSLSocket",
3034 sizeof(PySSLSocket),
3035 0,
3036 Py_TPFLAGS_DEFAULT,
3037 PySSLSocket_slots,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003038};
3039
Antoine Pitrou152efa22010-05-16 18:19:27 +00003040
3041/*
3042 * _SSLContext objects
3043 */
3044
Christian Heimes5fe668c2016-09-12 00:01:11 +02003045static int
Christian Heimes9fb051f2018-09-23 08:32:31 +02003046_set_verify_mode(PySSLContext *self, enum py_ssl_cert_requirements n)
Christian Heimes5fe668c2016-09-12 00:01:11 +02003047{
3048 int mode;
3049 int (*verify_cb)(int, X509_STORE_CTX *) = NULL;
3050
3051 switch(n) {
3052 case PY_SSL_CERT_NONE:
3053 mode = SSL_VERIFY_NONE;
3054 break;
3055 case PY_SSL_CERT_OPTIONAL:
3056 mode = SSL_VERIFY_PEER;
3057 break;
3058 case PY_SSL_CERT_REQUIRED:
3059 mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
3060 break;
3061 default:
3062 PyErr_SetString(PyExc_ValueError,
3063 "invalid value for verify_mode");
3064 return -1;
3065 }
Christian Heimesf0f59302019-07-01 08:29:17 +02003066
3067 /* bpo-37428: newPySSLSocket() sets SSL_VERIFY_POST_HANDSHAKE flag for
3068 * server sockets and SSL_set_post_handshake_auth() for client. */
3069
Christian Heimes5fe668c2016-09-12 00:01:11 +02003070 /* keep current verify cb */
Christian Heimes9fb051f2018-09-23 08:32:31 +02003071 verify_cb = SSL_CTX_get_verify_callback(self->ctx);
3072 SSL_CTX_set_verify(self->ctx, mode, verify_cb);
Christian Heimes5fe668c2016-09-12 00:01:11 +02003073 return 0;
3074}
3075
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003076/*[clinic input]
3077@classmethod
3078_ssl._SSLContext.__new__
3079 protocol as proto_version: int
3080 /
3081[clinic start generated code]*/
3082
Antoine Pitrou152efa22010-05-16 18:19:27 +00003083static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003084_ssl__SSLContext_impl(PyTypeObject *type, int proto_version)
3085/*[clinic end generated code: output=2cf0d7a0741b6bd1 input=8d58a805b95fc534]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003086{
Antoine Pitrou152efa22010-05-16 18:19:27 +00003087 PySSLContext *self;
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01003088 long options;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003089 SSL_CTX *ctx = NULL;
Christian Heimes61d478c2018-01-27 15:51:38 +01003090 X509_VERIFY_PARAM *params;
Christian Heimes358cfd42016-09-10 22:43:48 +02003091 int result;
Berker Peksagdfcb0412016-04-14 16:48:48 +03003092#if defined(SSL_MODE_RELEASE_BUFFERS)
Benjamin Peterson3b1a8b32016-01-07 21:37:37 -08003093 unsigned long libver;
Berker Peksagdfcb0412016-04-14 16:48:48 +03003094#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00003095
Antoine Pitrou152efa22010-05-16 18:19:27 +00003096 PySSL_BEGIN_ALLOW_THREADS
Christian Heimes6e8cda92020-05-16 03:33:05 +02003097 switch(proto_version) {
3098#if defined(SSL3_VERSION) && !defined(OPENSSL_NO_SSL3)
3099 case PY_SSL_VERSION_SSL3:
Antoine Pitrou152efa22010-05-16 18:19:27 +00003100 ctx = SSL_CTX_new(SSLv3_method());
Christian Heimes6e8cda92020-05-16 03:33:05 +02003101 break;
Benjamin Petersone32467c2014-12-05 21:59:35 -05003102#endif
Christian Heimesa871f692020-06-01 08:58:14 +02003103#if (defined(TLS1_VERSION) && \
3104 !defined(OPENSSL_NO_TLS1) && \
3105 !defined(OPENSSL_NO_TLS1_METHOD))
Christian Heimes6e8cda92020-05-16 03:33:05 +02003106 case PY_SSL_VERSION_TLS1:
3107 ctx = SSL_CTX_new(TLSv1_method());
3108 break;
Victor Stinner3de49192011-05-09 00:42:58 +02003109#endif
Christian Heimesa871f692020-06-01 08:58:14 +02003110#if (defined(TLS1_1_VERSION) && \
3111 !defined(OPENSSL_NO_TLS1_1) && \
3112 !defined(OPENSSL_NO_TLS1_1_METHOD))
Christian Heimes6e8cda92020-05-16 03:33:05 +02003113 case PY_SSL_VERSION_TLS1_1:
3114 ctx = SSL_CTX_new(TLSv1_1_method());
3115 break;
3116#endif
Christian Heimesa871f692020-06-01 08:58:14 +02003117#if (defined(TLS1_2_VERSION) && \
3118 !defined(OPENSSL_NO_TLS1_2) && \
3119 !defined(OPENSSL_NO_TLS1_2_METHOD))
Christian Heimes6e8cda92020-05-16 03:33:05 +02003120 case PY_SSL_VERSION_TLS1_2:
3121 ctx = SSL_CTX_new(TLSv1_2_method());
3122 break;
3123#endif
3124 case PY_SSL_VERSION_TLS:
3125 /* SSLv23 */
Christian Heimes598894f2016-09-05 23:19:05 +02003126 ctx = SSL_CTX_new(TLS_method());
Christian Heimes6e8cda92020-05-16 03:33:05 +02003127 break;
3128 case PY_SSL_VERSION_TLS_CLIENT:
Christian Heimes5fe668c2016-09-12 00:01:11 +02003129 ctx = SSL_CTX_new(TLS_client_method());
Christian Heimes6e8cda92020-05-16 03:33:05 +02003130 break;
3131 case PY_SSL_VERSION_TLS_SERVER:
Christian Heimes5fe668c2016-09-12 00:01:11 +02003132 ctx = SSL_CTX_new(TLS_server_method());
Christian Heimes6e8cda92020-05-16 03:33:05 +02003133 break;
3134 default:
Antoine Pitrou152efa22010-05-16 18:19:27 +00003135 proto_version = -1;
Christian Heimes6e8cda92020-05-16 03:33:05 +02003136 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003137 PySSL_END_ALLOW_THREADS
3138
3139 if (proto_version == -1) {
3140 PyErr_SetString(PyExc_ValueError,
Christian Heimes6e8cda92020-05-16 03:33:05 +02003141 "invalid or unsupported protocol version");
Antoine Pitrou152efa22010-05-16 18:19:27 +00003142 return NULL;
3143 }
3144 if (ctx == NULL) {
Christian Heimes17c9ac92017-09-07 14:14:00 -07003145 _setSSLError(NULL, 0, __FILE__, __LINE__);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003146 return NULL;
3147 }
3148
3149 assert(type != NULL && type->tp_alloc != NULL);
3150 self = (PySSLContext *) type->tp_alloc(type, 0);
3151 if (self == NULL) {
3152 SSL_CTX_free(ctx);
3153 return NULL;
3154 }
3155 self->ctx = ctx;
Christian Heimes61d478c2018-01-27 15:51:38 +01003156 self->hostflags = X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS;
Christian Heimes11a14932018-02-24 02:35:08 +01003157 self->protocol = proto_version;
Christian Heimesc7f70692019-05-31 11:44:05 +02003158 self->msg_cb = NULL;
3159#ifdef HAVE_OPENSSL_KEYLOG
3160 self->keylog_filename = NULL;
3161 self->keylog_bio = NULL;
3162#endif
Christian Heimes29eab552018-02-25 12:31:33 +01003163#if HAVE_NPN
Christian Heimes5cb31c92012-09-20 12:42:54 +02003164 self->npn_protocols = NULL;
3165#endif
Christian Heimes29eab552018-02-25 12:31:33 +01003166#if HAVE_ALPN
Benjamin Petersoncca27322015-01-23 16:35:37 -05003167 self->alpn_protocols = NULL;
3168#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003169#ifndef OPENSSL_NO_TLSEXT
Christian Heimes11a14932018-02-24 02:35:08 +01003170 self->set_sni_cb = NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003171#endif
Christian Heimes1aa9a752013-12-02 02:41:19 +01003172 /* Don't check host name by default */
Christian Heimes5fe668c2016-09-12 00:01:11 +02003173 if (proto_version == PY_SSL_VERSION_TLS_CLIENT) {
3174 self->check_hostname = 1;
Christian Heimes9fb051f2018-09-23 08:32:31 +02003175 if (_set_verify_mode(self, PY_SSL_CERT_REQUIRED) == -1) {
Christian Heimes5fe668c2016-09-12 00:01:11 +02003176 Py_DECREF(self);
3177 return NULL;
3178 }
3179 } else {
3180 self->check_hostname = 0;
Christian Heimes9fb051f2018-09-23 08:32:31 +02003181 if (_set_verify_mode(self, PY_SSL_CERT_NONE) == -1) {
Christian Heimes5fe668c2016-09-12 00:01:11 +02003182 Py_DECREF(self);
3183 return NULL;
3184 }
3185 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003186 /* Defaults */
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01003187 options = SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
3188 if (proto_version != PY_SSL_VERSION_SSL2)
3189 options |= SSL_OP_NO_SSLv2;
Benjamin Petersona9dcdab2015-11-11 22:38:41 -08003190 if (proto_version != PY_SSL_VERSION_SSL3)
3191 options |= SSL_OP_NO_SSLv3;
Christian Heimes358cfd42016-09-10 22:43:48 +02003192 /* Minimal security flags for server and client side context.
3193 * Client sockets ignore server-side parameters. */
3194#ifdef SSL_OP_NO_COMPRESSION
3195 options |= SSL_OP_NO_COMPRESSION;
3196#endif
3197#ifdef SSL_OP_CIPHER_SERVER_PREFERENCE
3198 options |= SSL_OP_CIPHER_SERVER_PREFERENCE;
3199#endif
3200#ifdef SSL_OP_SINGLE_DH_USE
3201 options |= SSL_OP_SINGLE_DH_USE;
3202#endif
3203#ifdef SSL_OP_SINGLE_ECDH_USE
3204 options |= SSL_OP_SINGLE_ECDH_USE;
3205#endif
Christian Heimes6f37ebc2021-04-09 17:59:21 +02003206#ifdef SSL_OP_IGNORE_UNEXPECTED_EOF
3207 /* Make OpenSSL 3.0.0 behave like 1.1.1 */
3208 options |= SSL_OP_IGNORE_UNEXPECTED_EOF;
3209#endif
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01003210 SSL_CTX_set_options(self->ctx, options);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003211
Semen Zhydenko1295e112017-10-15 21:28:31 +02003212 /* A bare minimum cipher list without completely broken cipher suites.
Christian Heimes358cfd42016-09-10 22:43:48 +02003213 * It's far from perfect but gives users a better head start. */
3214 if (proto_version != PY_SSL_VERSION_SSL2) {
Christian Heimes892d66e2018-01-29 14:10:18 +01003215#if PY_SSL_DEFAULT_CIPHERS == 2
3216 /* stick to OpenSSL's default settings */
3217 result = 1;
3218#else
3219 result = SSL_CTX_set_cipher_list(ctx, PY_SSL_DEFAULT_CIPHER_STRING);
3220#endif
Christian Heimes358cfd42016-09-10 22:43:48 +02003221 } else {
3222 /* SSLv2 needs MD5 */
3223 result = SSL_CTX_set_cipher_list(ctx, "HIGH:!aNULL:!eNULL");
3224 }
3225 if (result == 0) {
3226 Py_DECREF(self);
3227 ERR_clear_error();
3228 PyErr_SetString(PySSLErrorObject,
3229 "No cipher can be selected.");
3230 return NULL;
3231 }
3232
Benjamin Peterson3b1a8b32016-01-07 21:37:37 -08003233#if defined(SSL_MODE_RELEASE_BUFFERS)
3234 /* Set SSL_MODE_RELEASE_BUFFERS. This potentially greatly reduces memory
3235 usage for no cost at all. However, don't do this for OpenSSL versions
3236 between 1.0.1 and 1.0.1h or 1.0.0 and 1.0.0m, which are affected by CVE
3237 2014-0198. I can't find exactly which beta fixed this CVE, so be
3238 conservative and assume it wasn't fixed until release. We do this check
3239 at runtime to avoid problems from the dynamic linker.
3240 See #25672 for more on this. */
Christian Heimesa871f692020-06-01 08:58:14 +02003241 libver = OpenSSL_version_num();
Benjamin Peterson3b1a8b32016-01-07 21:37:37 -08003242 if (!(libver >= 0x10001000UL && libver < 0x1000108fUL) &&
3243 !(libver >= 0x10000000UL && libver < 0x100000dfUL)) {
3244 SSL_CTX_set_mode(self->ctx, SSL_MODE_RELEASE_BUFFERS);
3245 }
3246#endif
3247
3248
Donald Stufft8ae264c2017-03-02 11:45:29 -05003249#if !defined(OPENSSL_NO_ECDH) && !defined(OPENSSL_VERSION_1_1)
Antoine Pitrou0bebbc32014-03-22 18:13:50 +01003250 /* Allow automatic ECDH curve selection (on OpenSSL 1.0.2+), or use
3251 prime256v1 by default. This is Apache mod_ssl's initialization
Christian Heimes598894f2016-09-05 23:19:05 +02003252 policy, so we should be safe. OpenSSL 1.1 has it enabled by default.
3253 */
Donald Stufft8ae264c2017-03-02 11:45:29 -05003254#if defined(SSL_CTX_set_ecdh_auto)
Antoine Pitrou0bebbc32014-03-22 18:13:50 +01003255 SSL_CTX_set_ecdh_auto(self->ctx, 1);
3256#else
3257 {
3258 EC_KEY *key = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
3259 SSL_CTX_set_tmp_ecdh(self->ctx, key);
3260 EC_KEY_free(key);
3261 }
3262#endif
3263#endif
3264
Antoine Pitroufc113ee2010-10-13 12:46:13 +00003265#define SID_CTX "Python"
3266 SSL_CTX_set_session_id_context(self->ctx, (const unsigned char *) SID_CTX,
3267 sizeof(SID_CTX));
3268#undef SID_CTX
3269
Christian Heimes61d478c2018-01-27 15:51:38 +01003270 params = SSL_CTX_get0_param(self->ctx);
Benjamin Petersonfdb19712015-03-04 22:11:12 -05003271#ifdef X509_V_FLAG_TRUSTED_FIRST
Christian Heimes61d478c2018-01-27 15:51:38 +01003272 /* Improve trust chain building when cross-signed intermediate
3273 certificates are present. See https://bugs.python.org/issue23476. */
3274 X509_VERIFY_PARAM_set_flags(params, X509_V_FLAG_TRUSTED_FIRST);
Benjamin Petersonfdb19712015-03-04 22:11:12 -05003275#endif
Christian Heimes61d478c2018-01-27 15:51:38 +01003276 X509_VERIFY_PARAM_set_hostflags(params, self->hostflags);
Benjamin Petersonfdb19712015-03-04 22:11:12 -05003277
Christian Heimes9fb051f2018-09-23 08:32:31 +02003278#ifdef TLS1_3_VERSION
3279 self->post_handshake_auth = 0;
3280 SSL_CTX_set_post_handshake_auth(self->ctx, self->post_handshake_auth);
3281#endif
3282
Antoine Pitrou152efa22010-05-16 18:19:27 +00003283 return (PyObject *)self;
3284}
3285
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003286static int
3287context_traverse(PySSLContext *self, visitproc visit, void *arg)
3288{
3289#ifndef OPENSSL_NO_TLSEXT
Christian Heimes11a14932018-02-24 02:35:08 +01003290 Py_VISIT(self->set_sni_cb);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003291#endif
Christian Heimesc7f70692019-05-31 11:44:05 +02003292 Py_VISIT(self->msg_cb);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003293 return 0;
3294}
3295
3296static int
3297context_clear(PySSLContext *self)
3298{
3299#ifndef OPENSSL_NO_TLSEXT
Christian Heimes11a14932018-02-24 02:35:08 +01003300 Py_CLEAR(self->set_sni_cb);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003301#endif
Christian Heimesc7f70692019-05-31 11:44:05 +02003302 Py_CLEAR(self->msg_cb);
3303#ifdef HAVE_OPENSSL_KEYLOG
3304 Py_CLEAR(self->keylog_filename);
3305 if (self->keylog_bio != NULL) {
3306 PySSL_BEGIN_ALLOW_THREADS
3307 BIO_free_all(self->keylog_bio);
3308 PySSL_END_ALLOW_THREADS
3309 self->keylog_bio = NULL;
3310 }
3311#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003312 return 0;
3313}
3314
Antoine Pitrou152efa22010-05-16 18:19:27 +00003315static void
3316context_dealloc(PySSLContext *self)
3317{
Christian Heimes5c36da72020-11-20 09:40:12 +01003318 PyTypeObject *tp = Py_TYPE(self);
INADA Naokia6296d32017-08-24 14:55:17 +09003319 /* bpo-31095: UnTrack is needed before calling any callbacks */
3320 PyObject_GC_UnTrack(self);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003321 context_clear(self);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003322 SSL_CTX_free(self->ctx);
Christian Heimes29eab552018-02-25 12:31:33 +01003323#if HAVE_NPN
Victor Stinner00d7abd2020-12-01 09:56:42 +01003324 PyMem_Free(self->npn_protocols);
Benjamin Petersoncca27322015-01-23 16:35:37 -05003325#endif
Christian Heimes29eab552018-02-25 12:31:33 +01003326#if HAVE_ALPN
Victor Stinner00d7abd2020-12-01 09:56:42 +01003327 PyMem_Free(self->alpn_protocols);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003328#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00003329 Py_TYPE(self)->tp_free(self);
Christian Heimes5c36da72020-11-20 09:40:12 +01003330 Py_DECREF(tp);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003331}
3332
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003333/*[clinic input]
3334_ssl._SSLContext.set_ciphers
3335 cipherlist: str
3336 /
3337[clinic start generated code]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003338
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003339static PyObject *
3340_ssl__SSLContext_set_ciphers_impl(PySSLContext *self, const char *cipherlist)
3341/*[clinic end generated code: output=3a3162f3557c0f3f input=a7ac931b9f3ca7fc]*/
3342{
3343 int ret = SSL_CTX_set_cipher_list(self->ctx, cipherlist);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003344 if (ret == 0) {
Antoine Pitrou65ec8ae2010-05-16 19:56:32 +00003345 /* Clearing the error queue is necessary on some OpenSSL versions,
3346 otherwise the error will be reported again when another SSL call
3347 is done. */
3348 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00003349 PyErr_SetString(PySSLErrorObject,
3350 "No cipher can be selected.");
3351 return NULL;
3352 }
3353 Py_RETURN_NONE;
3354}
3355
Christian Heimes25bfcd52016-09-06 00:04:45 +02003356#if OPENSSL_VERSION_NUMBER >= 0x10002000UL
3357/*[clinic input]
3358_ssl._SSLContext.get_ciphers
3359[clinic start generated code]*/
3360
3361static PyObject *
3362_ssl__SSLContext_get_ciphers_impl(PySSLContext *self)
3363/*[clinic end generated code: output=a56e4d68a406dfc4 input=a2aadc9af89b79c5]*/
3364{
3365 SSL *ssl = NULL;
3366 STACK_OF(SSL_CIPHER) *sk = NULL;
Christian Heimes99a65702016-09-10 23:44:53 +02003367 const SSL_CIPHER *cipher;
Christian Heimes25bfcd52016-09-06 00:04:45 +02003368 int i=0;
3369 PyObject *result = NULL, *dct;
3370
3371 ssl = SSL_new(self->ctx);
3372 if (ssl == NULL) {
3373 _setSSLError(NULL, 0, __FILE__, __LINE__);
3374 goto exit;
3375 }
3376 sk = SSL_get_ciphers(ssl);
3377
3378 result = PyList_New(sk_SSL_CIPHER_num(sk));
3379 if (result == NULL) {
3380 goto exit;
3381 }
3382
3383 for (i = 0; i < sk_SSL_CIPHER_num(sk); i++) {
3384 cipher = sk_SSL_CIPHER_value(sk, i);
3385 dct = cipher_to_dict(cipher);
3386 if (dct == NULL) {
3387 Py_CLEAR(result);
3388 goto exit;
3389 }
3390 PyList_SET_ITEM(result, i, dct);
3391 }
3392
3393 exit:
3394 if (ssl != NULL)
3395 SSL_free(ssl);
3396 return result;
3397
3398}
3399#endif
3400
3401
Christian Heimes29eab552018-02-25 12:31:33 +01003402#if HAVE_NPN || HAVE_ALPN
Benjamin Petersoncca27322015-01-23 16:35:37 -05003403static int
Benjamin Peterson88615022015-01-23 17:30:26 -05003404do_protocol_selection(int alpn, unsigned char **out, unsigned char *outlen,
3405 const unsigned char *server_protocols, unsigned int server_protocols_len,
3406 const unsigned char *client_protocols, unsigned int client_protocols_len)
Benjamin Petersoncca27322015-01-23 16:35:37 -05003407{
Benjamin Peterson88615022015-01-23 17:30:26 -05003408 int ret;
3409 if (client_protocols == NULL) {
3410 client_protocols = (unsigned char *)"";
3411 client_protocols_len = 0;
3412 }
3413 if (server_protocols == NULL) {
3414 server_protocols = (unsigned char *)"";
3415 server_protocols_len = 0;
Benjamin Petersoncca27322015-01-23 16:35:37 -05003416 }
3417
Benjamin Peterson88615022015-01-23 17:30:26 -05003418 ret = SSL_select_next_proto(out, outlen,
3419 server_protocols, server_protocols_len,
3420 client_protocols, client_protocols_len);
3421 if (alpn && ret != OPENSSL_NPN_NEGOTIATED)
3422 return SSL_TLSEXT_ERR_NOACK;
Benjamin Petersoncca27322015-01-23 16:35:37 -05003423
3424 return SSL_TLSEXT_ERR_OK;
3425}
Melvyn Sopacuab2d096b2017-09-04 23:35:15 +02003426#endif
Benjamin Petersoncca27322015-01-23 16:35:37 -05003427
Christian Heimes29eab552018-02-25 12:31:33 +01003428#if HAVE_NPN
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003429/* this callback gets passed to SSL_CTX_set_next_protos_advertise_cb */
3430static int
Victor Stinner4569cd52013-06-23 14:58:43 +02003431_advertiseNPN_cb(SSL *s,
3432 const unsigned char **data, unsigned int *len,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003433 void *args)
3434{
3435 PySSLContext *ssl_ctx = (PySSLContext *) args;
3436
3437 if (ssl_ctx->npn_protocols == NULL) {
Benjamin Petersoncca27322015-01-23 16:35:37 -05003438 *data = (unsigned char *)"";
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003439 *len = 0;
3440 } else {
Benjamin Petersoncca27322015-01-23 16:35:37 -05003441 *data = ssl_ctx->npn_protocols;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003442 *len = ssl_ctx->npn_protocols_len;
3443 }
3444
3445 return SSL_TLSEXT_ERR_OK;
3446}
3447/* this callback gets passed to SSL_CTX_set_next_proto_select_cb */
3448static int
Victor Stinner4569cd52013-06-23 14:58:43 +02003449_selectNPN_cb(SSL *s,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003450 unsigned char **out, unsigned char *outlen,
3451 const unsigned char *server, unsigned int server_len,
3452 void *args)
3453{
Benjamin Petersoncca27322015-01-23 16:35:37 -05003454 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Peterson88615022015-01-23 17:30:26 -05003455 return do_protocol_selection(0, out, outlen, server, server_len,
Benjamin Petersoncca27322015-01-23 16:35:37 -05003456 ctx->npn_protocols, ctx->npn_protocols_len);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003457}
3458#endif
3459
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003460/*[clinic input]
3461_ssl._SSLContext._set_npn_protocols
3462 protos: Py_buffer
3463 /
3464[clinic start generated code]*/
3465
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003466static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003467_ssl__SSLContext__set_npn_protocols_impl(PySSLContext *self,
3468 Py_buffer *protos)
3469/*[clinic end generated code: output=72b002c3324390c6 input=319fcb66abf95bd7]*/
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003470{
Christian Heimes29eab552018-02-25 12:31:33 +01003471#if HAVE_NPN
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003472 PyMem_Free(self->npn_protocols);
3473 self->npn_protocols = PyMem_Malloc(protos->len);
3474 if (self->npn_protocols == NULL)
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003475 return PyErr_NoMemory();
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003476 memcpy(self->npn_protocols, protos->buf, protos->len);
3477 self->npn_protocols_len = (int) protos->len;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003478
3479 /* set both server and client callbacks, because the context can
3480 * be used to create both types of sockets */
3481 SSL_CTX_set_next_protos_advertised_cb(self->ctx,
3482 _advertiseNPN_cb,
3483 self);
3484 SSL_CTX_set_next_proto_select_cb(self->ctx,
3485 _selectNPN_cb,
3486 self);
3487
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003488 Py_RETURN_NONE;
3489#else
3490 PyErr_SetString(PyExc_NotImplementedError,
3491 "The NPN extension requires OpenSSL 1.0.1 or later.");
3492 return NULL;
3493#endif
3494}
3495
Christian Heimes29eab552018-02-25 12:31:33 +01003496#if HAVE_ALPN
Benjamin Petersoncca27322015-01-23 16:35:37 -05003497static int
3498_selectALPN_cb(SSL *s,
3499 const unsigned char **out, unsigned char *outlen,
3500 const unsigned char *client_protocols, unsigned int client_protocols_len,
3501 void *args)
3502{
3503 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Peterson88615022015-01-23 17:30:26 -05003504 return do_protocol_selection(1, (unsigned char **)out, outlen,
3505 ctx->alpn_protocols, ctx->alpn_protocols_len,
3506 client_protocols, client_protocols_len);
Benjamin Petersoncca27322015-01-23 16:35:37 -05003507}
3508#endif
3509
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003510/*[clinic input]
3511_ssl._SSLContext._set_alpn_protocols
3512 protos: Py_buffer
3513 /
3514[clinic start generated code]*/
3515
Benjamin Petersoncca27322015-01-23 16:35:37 -05003516static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003517_ssl__SSLContext__set_alpn_protocols_impl(PySSLContext *self,
3518 Py_buffer *protos)
3519/*[clinic end generated code: output=87599a7f76651a9b input=9bba964595d519be]*/
Benjamin Petersoncca27322015-01-23 16:35:37 -05003520{
Christian Heimes29eab552018-02-25 12:31:33 +01003521#if HAVE_ALPN
Victor Stinner5a615592017-09-14 01:10:30 -07003522 if ((size_t)protos->len > UINT_MAX) {
Segev Finer5cff6372017-07-27 01:19:17 +03003523 PyErr_Format(PyExc_OverflowError,
Serhiy Storchakad53fe5f2019-03-13 22:59:55 +02003524 "protocols longer than %u bytes", UINT_MAX);
Segev Finer5cff6372017-07-27 01:19:17 +03003525 return NULL;
3526 }
3527
Victor Stinner00d7abd2020-12-01 09:56:42 +01003528 PyMem_Free(self->alpn_protocols);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003529 self->alpn_protocols = PyMem_Malloc(protos->len);
Benjamin Petersoncca27322015-01-23 16:35:37 -05003530 if (!self->alpn_protocols)
3531 return PyErr_NoMemory();
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003532 memcpy(self->alpn_protocols, protos->buf, protos->len);
Segev Finer5cff6372017-07-27 01:19:17 +03003533 self->alpn_protocols_len = (unsigned int)protos->len;
Benjamin Petersoncca27322015-01-23 16:35:37 -05003534
3535 if (SSL_CTX_set_alpn_protos(self->ctx, self->alpn_protocols, self->alpn_protocols_len))
3536 return PyErr_NoMemory();
3537 SSL_CTX_set_alpn_select_cb(self->ctx, _selectALPN_cb, self);
3538
Benjamin Petersoncca27322015-01-23 16:35:37 -05003539 Py_RETURN_NONE;
3540#else
3541 PyErr_SetString(PyExc_NotImplementedError,
3542 "The ALPN extension requires OpenSSL 1.0.2 or later.");
3543 return NULL;
3544#endif
3545}
3546
Antoine Pitrou152efa22010-05-16 18:19:27 +00003547static PyObject *
3548get_verify_mode(PySSLContext *self, void *c)
3549{
Christian Heimes9fb051f2018-09-23 08:32:31 +02003550 /* ignore SSL_VERIFY_CLIENT_ONCE and SSL_VERIFY_POST_HANDSHAKE */
3551 int mask = (SSL_VERIFY_NONE | SSL_VERIFY_PEER |
3552 SSL_VERIFY_FAIL_IF_NO_PEER_CERT);
3553 switch (SSL_CTX_get_verify_mode(self->ctx) & mask) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003554 case SSL_VERIFY_NONE:
3555 return PyLong_FromLong(PY_SSL_CERT_NONE);
3556 case SSL_VERIFY_PEER:
3557 return PyLong_FromLong(PY_SSL_CERT_OPTIONAL);
3558 case SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT:
3559 return PyLong_FromLong(PY_SSL_CERT_REQUIRED);
3560 }
3561 PyErr_SetString(PySSLErrorObject,
3562 "invalid return value from SSL_CTX_get_verify_mode");
3563 return NULL;
3564}
3565
3566static int
3567set_verify_mode(PySSLContext *self, PyObject *arg, void *c)
3568{
Christian Heimes5fe668c2016-09-12 00:01:11 +02003569 int n;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003570 if (!PyArg_Parse(arg, "i", &n))
3571 return -1;
Christian Heimes5fe668c2016-09-12 00:01:11 +02003572 if (n == PY_SSL_CERT_NONE && self->check_hostname) {
Christian Heimes1aa9a752013-12-02 02:41:19 +01003573 PyErr_SetString(PyExc_ValueError,
3574 "Cannot set verify_mode to CERT_NONE when "
3575 "check_hostname is enabled.");
3576 return -1;
3577 }
Christian Heimes9fb051f2018-09-23 08:32:31 +02003578 return _set_verify_mode(self, n);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003579}
3580
3581static PyObject *
Christian Heimes22587792013-11-21 23:56:13 +01003582get_verify_flags(PySSLContext *self, void *c)
3583{
Christian Heimes598894f2016-09-05 23:19:05 +02003584 X509_VERIFY_PARAM *param;
Christian Heimes22587792013-11-21 23:56:13 +01003585 unsigned long flags;
3586
Christian Heimes61d478c2018-01-27 15:51:38 +01003587 param = SSL_CTX_get0_param(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02003588 flags = X509_VERIFY_PARAM_get_flags(param);
Christian Heimes22587792013-11-21 23:56:13 +01003589 return PyLong_FromUnsignedLong(flags);
3590}
3591
3592static int
3593set_verify_flags(PySSLContext *self, PyObject *arg, void *c)
3594{
Christian Heimes598894f2016-09-05 23:19:05 +02003595 X509_VERIFY_PARAM *param;
Christian Heimes22587792013-11-21 23:56:13 +01003596 unsigned long new_flags, flags, set, clear;
3597
3598 if (!PyArg_Parse(arg, "k", &new_flags))
3599 return -1;
Christian Heimes61d478c2018-01-27 15:51:38 +01003600 param = SSL_CTX_get0_param(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02003601 flags = X509_VERIFY_PARAM_get_flags(param);
Christian Heimes22587792013-11-21 23:56:13 +01003602 clear = flags & ~new_flags;
3603 set = ~flags & new_flags;
3604 if (clear) {
Christian Heimes598894f2016-09-05 23:19:05 +02003605 if (!X509_VERIFY_PARAM_clear_flags(param, clear)) {
Christian Heimes22587792013-11-21 23:56:13 +01003606 _setSSLError(NULL, 0, __FILE__, __LINE__);
3607 return -1;
3608 }
3609 }
3610 if (set) {
Christian Heimes598894f2016-09-05 23:19:05 +02003611 if (!X509_VERIFY_PARAM_set_flags(param, set)) {
Christian Heimes22587792013-11-21 23:56:13 +01003612 _setSSLError(NULL, 0, __FILE__, __LINE__);
3613 return -1;
3614 }
3615 }
3616 return 0;
3617}
3618
Christian Heimes698dde12018-02-27 11:54:43 +01003619/* Getter and setter for protocol version */
3620#if defined(SSL_CTRL_GET_MAX_PROTO_VERSION)
3621
3622
3623static int
3624set_min_max_proto_version(PySSLContext *self, PyObject *arg, int what)
3625{
3626 long v;
3627 int result;
3628
3629 if (!PyArg_Parse(arg, "l", &v))
3630 return -1;
3631 if (v > INT_MAX) {
3632 PyErr_SetString(PyExc_OverflowError, "Option is too long");
3633 return -1;
3634 }
3635
3636 switch(self->protocol) {
3637 case PY_SSL_VERSION_TLS_CLIENT: /* fall through */
3638 case PY_SSL_VERSION_TLS_SERVER: /* fall through */
3639 case PY_SSL_VERSION_TLS:
3640 break;
3641 default:
3642 PyErr_SetString(
3643 PyExc_ValueError,
3644 "The context's protocol doesn't support modification of "
3645 "highest and lowest version."
3646 );
3647 return -1;
3648 }
3649
3650 if (what == 0) {
3651 switch(v) {
3652 case PY_PROTO_MINIMUM_SUPPORTED:
3653 v = 0;
3654 break;
3655 case PY_PROTO_MAXIMUM_SUPPORTED:
3656 /* Emulate max for set_min_proto_version */
3657 v = PY_PROTO_MAXIMUM_AVAILABLE;
3658 break;
3659 default:
3660 break;
3661 }
3662 result = SSL_CTX_set_min_proto_version(self->ctx, v);
3663 }
3664 else {
3665 switch(v) {
3666 case PY_PROTO_MAXIMUM_SUPPORTED:
3667 v = 0;
3668 break;
3669 case PY_PROTO_MINIMUM_SUPPORTED:
3670 /* Emulate max for set_min_proto_version */
3671 v = PY_PROTO_MINIMUM_AVAILABLE;
3672 break;
3673 default:
3674 break;
3675 }
3676 result = SSL_CTX_set_max_proto_version(self->ctx, v);
3677 }
3678 if (result == 0) {
3679 PyErr_Format(PyExc_ValueError,
3680 "Unsupported protocol version 0x%x", v);
3681 return -1;
3682 }
3683 return 0;
3684}
3685
3686static PyObject *
3687get_minimum_version(PySSLContext *self, void *c)
3688{
3689 int v = SSL_CTX_ctrl(self->ctx, SSL_CTRL_GET_MIN_PROTO_VERSION, 0, NULL);
3690 if (v == 0) {
3691 v = PY_PROTO_MINIMUM_SUPPORTED;
3692 }
3693 return PyLong_FromLong(v);
3694}
3695
3696static int
3697set_minimum_version(PySSLContext *self, PyObject *arg, void *c)
3698{
3699 return set_min_max_proto_version(self, arg, 0);
3700}
3701
3702static PyObject *
3703get_maximum_version(PySSLContext *self, void *c)
3704{
3705 int v = SSL_CTX_ctrl(self->ctx, SSL_CTRL_GET_MAX_PROTO_VERSION, 0, NULL);
3706 if (v == 0) {
3707 v = PY_PROTO_MAXIMUM_SUPPORTED;
3708 }
3709 return PyLong_FromLong(v);
3710}
3711
3712static int
3713set_maximum_version(PySSLContext *self, PyObject *arg, void *c)
3714{
3715 return set_min_max_proto_version(self, arg, 1);
3716}
3717#endif /* SSL_CTRL_GET_MAX_PROTO_VERSION */
3718
Christian Heimes78c7d522019-06-03 21:00:10 +02003719#if (OPENSSL_VERSION_NUMBER >= 0x10101000L) && !defined(LIBRESSL_VERSION_NUMBER)
3720static PyObject *
3721get_num_tickets(PySSLContext *self, void *c)
3722{
Victor Stinner76611c72019-07-09 13:30:52 +02003723 return PyLong_FromSize_t(SSL_CTX_get_num_tickets(self->ctx));
Christian Heimes78c7d522019-06-03 21:00:10 +02003724}
3725
3726static int
3727set_num_tickets(PySSLContext *self, PyObject *arg, void *c)
3728{
3729 long num;
3730 if (!PyArg_Parse(arg, "l", &num))
3731 return -1;
3732 if (num < 0) {
3733 PyErr_SetString(PyExc_ValueError, "value must be non-negative");
3734 return -1;
3735 }
3736 if (self->protocol != PY_SSL_VERSION_TLS_SERVER) {
3737 PyErr_SetString(PyExc_ValueError,
3738 "SSLContext is not a server context.");
3739 return -1;
3740 }
3741 if (SSL_CTX_set_num_tickets(self->ctx, num) != 1) {
3742 PyErr_SetString(PyExc_ValueError, "failed to set num tickets.");
3743 return -1;
3744 }
3745 return 0;
3746}
3747
3748PyDoc_STRVAR(PySSLContext_num_tickets_doc,
3749"Control the number of TLSv1.3 session tickets");
3750#endif /* OpenSSL 1.1.1 */
3751
matthewhughes9348e836bb2020-07-17 09:59:15 +01003752#if (OPENSSL_VERSION_NUMBER >= 0x10100000L) && !defined(LIBRESSL_VERSION_NUMBER)
3753static PyObject *
3754get_security_level(PySSLContext *self, void *c)
3755{
3756 return PyLong_FromLong(SSL_CTX_get_security_level(self->ctx));
3757}
3758PyDoc_STRVAR(PySSLContext_security_level_doc, "The current security level");
3759#endif /* OpenSSL 1.1.0 */
3760
Christian Heimes22587792013-11-21 23:56:13 +01003761static PyObject *
Antoine Pitroub5218772010-05-21 09:56:06 +00003762get_options(PySSLContext *self, void *c)
3763{
3764 return PyLong_FromLong(SSL_CTX_get_options(self->ctx));
3765}
3766
3767static int
3768set_options(PySSLContext *self, PyObject *arg, void *c)
3769{
3770 long new_opts, opts, set, clear;
3771 if (!PyArg_Parse(arg, "l", &new_opts))
3772 return -1;
3773 opts = SSL_CTX_get_options(self->ctx);
3774 clear = opts & ~new_opts;
3775 set = ~opts & new_opts;
3776 if (clear) {
3777#ifdef HAVE_SSL_CTX_CLEAR_OPTIONS
3778 SSL_CTX_clear_options(self->ctx, clear);
3779#else
3780 PyErr_SetString(PyExc_ValueError,
3781 "can't clear options before OpenSSL 0.9.8m");
3782 return -1;
3783#endif
3784 }
3785 if (set)
3786 SSL_CTX_set_options(self->ctx, set);
3787 return 0;
3788}
3789
Christian Heimes1aa9a752013-12-02 02:41:19 +01003790static PyObject *
Christian Heimes61d478c2018-01-27 15:51:38 +01003791get_host_flags(PySSLContext *self, void *c)
3792{
3793 return PyLong_FromUnsignedLong(self->hostflags);
3794}
3795
3796static int
3797set_host_flags(PySSLContext *self, PyObject *arg, void *c)
3798{
3799 X509_VERIFY_PARAM *param;
3800 unsigned int new_flags = 0;
3801
3802 if (!PyArg_Parse(arg, "I", &new_flags))
3803 return -1;
3804
3805 param = SSL_CTX_get0_param(self->ctx);
3806 self->hostflags = new_flags;
3807 X509_VERIFY_PARAM_set_hostflags(param, new_flags);
3808 return 0;
3809}
3810
3811static PyObject *
Christian Heimes1aa9a752013-12-02 02:41:19 +01003812get_check_hostname(PySSLContext *self, void *c)
3813{
3814 return PyBool_FromLong(self->check_hostname);
3815}
3816
3817static int
3818set_check_hostname(PySSLContext *self, PyObject *arg, void *c)
3819{
3820 int check_hostname;
3821 if (!PyArg_Parse(arg, "p", &check_hostname))
3822 return -1;
3823 if (check_hostname &&
3824 SSL_CTX_get_verify_mode(self->ctx) == SSL_VERIFY_NONE) {
Christian Heimese82c0342017-09-15 20:29:57 +02003825 /* check_hostname = True sets verify_mode = CERT_REQUIRED */
Christian Heimes9fb051f2018-09-23 08:32:31 +02003826 if (_set_verify_mode(self, PY_SSL_CERT_REQUIRED) == -1) {
Christian Heimese82c0342017-09-15 20:29:57 +02003827 return -1;
3828 }
Christian Heimes1aa9a752013-12-02 02:41:19 +01003829 }
3830 self->check_hostname = check_hostname;
3831 return 0;
3832}
3833
Christian Heimes11a14932018-02-24 02:35:08 +01003834static PyObject *
Christian Heimes9fb051f2018-09-23 08:32:31 +02003835get_post_handshake_auth(PySSLContext *self, void *c) {
3836#if TLS1_3_VERSION
3837 return PyBool_FromLong(self->post_handshake_auth);
3838#else
3839 Py_RETURN_NONE;
3840#endif
3841}
3842
3843#if TLS1_3_VERSION
3844static int
3845set_post_handshake_auth(PySSLContext *self, PyObject *arg, void *c) {
Zackery Spytz842acaa2018-12-17 07:52:45 -07003846 if (arg == NULL) {
3847 PyErr_SetString(PyExc_AttributeError, "cannot delete attribute");
3848 return -1;
3849 }
Christian Heimes9fb051f2018-09-23 08:32:31 +02003850 int pha = PyObject_IsTrue(arg);
3851
3852 if (pha == -1) {
3853 return -1;
3854 }
3855 self->post_handshake_auth = pha;
3856
Christian Heimesf0f59302019-07-01 08:29:17 +02003857 /* bpo-37428: newPySSLSocket() sets SSL_VERIFY_POST_HANDSHAKE flag for
3858 * server sockets and SSL_set_post_handshake_auth() for client. */
Christian Heimes9fb051f2018-09-23 08:32:31 +02003859
3860 return 0;
3861}
3862#endif
3863
3864static PyObject *
Christian Heimes11a14932018-02-24 02:35:08 +01003865get_protocol(PySSLContext *self, void *c) {
3866 return PyLong_FromLong(self->protocol);
3867}
Christian Heimes1aa9a752013-12-02 02:41:19 +01003868
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003869typedef struct {
3870 PyThreadState *thread_state;
3871 PyObject *callable;
3872 char *password;
Victor Stinner9ee02032013-06-23 15:08:23 +02003873 int size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003874 int error;
3875} _PySSLPasswordInfo;
3876
3877static int
3878_pwinfo_set(_PySSLPasswordInfo *pw_info, PyObject* password,
3879 const char *bad_type_error)
3880{
3881 /* Set the password and size fields of a _PySSLPasswordInfo struct
3882 from a unicode, bytes, or byte array object.
3883 The password field will be dynamically allocated and must be freed
3884 by the caller */
3885 PyObject *password_bytes = NULL;
3886 const char *data = NULL;
3887 Py_ssize_t size;
3888
3889 if (PyUnicode_Check(password)) {
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03003890 password_bytes = PyUnicode_AsUTF8String(password);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003891 if (!password_bytes) {
3892 goto error;
3893 }
3894 data = PyBytes_AS_STRING(password_bytes);
3895 size = PyBytes_GET_SIZE(password_bytes);
3896 } else if (PyBytes_Check(password)) {
3897 data = PyBytes_AS_STRING(password);
3898 size = PyBytes_GET_SIZE(password);
3899 } else if (PyByteArray_Check(password)) {
3900 data = PyByteArray_AS_STRING(password);
3901 size = PyByteArray_GET_SIZE(password);
3902 } else {
3903 PyErr_SetString(PyExc_TypeError, bad_type_error);
3904 goto error;
3905 }
3906
Victor Stinner9ee02032013-06-23 15:08:23 +02003907 if (size > (Py_ssize_t)INT_MAX) {
3908 PyErr_Format(PyExc_ValueError,
3909 "password cannot be longer than %d bytes", INT_MAX);
3910 goto error;
3911 }
3912
Victor Stinner11ebff22013-07-07 17:07:52 +02003913 PyMem_Free(pw_info->password);
3914 pw_info->password = PyMem_Malloc(size);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003915 if (!pw_info->password) {
3916 PyErr_SetString(PyExc_MemoryError,
3917 "unable to allocate password buffer");
3918 goto error;
3919 }
3920 memcpy(pw_info->password, data, size);
Victor Stinner9ee02032013-06-23 15:08:23 +02003921 pw_info->size = (int)size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003922
3923 Py_XDECREF(password_bytes);
3924 return 1;
3925
3926error:
3927 Py_XDECREF(password_bytes);
3928 return 0;
3929}
3930
3931static int
3932_password_callback(char *buf, int size, int rwflag, void *userdata)
3933{
3934 _PySSLPasswordInfo *pw_info = (_PySSLPasswordInfo*) userdata;
3935 PyObject *fn_ret = NULL;
3936
3937 PySSL_END_ALLOW_THREADS_S(pw_info->thread_state);
3938
Christian Heimesd3b73f32021-04-09 15:23:38 +02003939 if (pw_info->error) {
3940 /* already failed previously. OpenSSL 3.0.0-alpha14 invokes the
3941 * callback multiple times which can lead to fatal Python error in
3942 * exception check. */
3943 goto error;
3944 }
3945
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003946 if (pw_info->callable) {
Victor Stinnerf17c3de2016-12-06 18:46:19 +01003947 fn_ret = _PyObject_CallNoArg(pw_info->callable);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003948 if (!fn_ret) {
3949 /* TODO: It would be nice to move _ctypes_add_traceback() into the
3950 core python API, so we could use it to add a frame here */
3951 goto error;
3952 }
3953
3954 if (!_pwinfo_set(pw_info, fn_ret,
3955 "password callback must return a string")) {
3956 goto error;
3957 }
3958 Py_CLEAR(fn_ret);
3959 }
3960
3961 if (pw_info->size > size) {
3962 PyErr_Format(PyExc_ValueError,
3963 "password cannot be longer than %d bytes", size);
3964 goto error;
3965 }
3966
3967 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
3968 memcpy(buf, pw_info->password, pw_info->size);
3969 return pw_info->size;
3970
3971error:
3972 Py_XDECREF(fn_ret);
3973 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
3974 pw_info->error = 1;
3975 return -1;
3976}
3977
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003978/*[clinic input]
3979_ssl._SSLContext.load_cert_chain
3980 certfile: object
Serhiy Storchaka279f4462019-09-14 12:24:05 +03003981 keyfile: object = None
3982 password: object = None
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003983
3984[clinic start generated code]*/
3985
Antoine Pitroub5218772010-05-21 09:56:06 +00003986static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003987_ssl__SSLContext_load_cert_chain_impl(PySSLContext *self, PyObject *certfile,
3988 PyObject *keyfile, PyObject *password)
Serhiy Storchaka279f4462019-09-14 12:24:05 +03003989/*[clinic end generated code: output=9480bc1c380e2095 input=30bc7e967ea01a58]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003990{
Antoine Pitrou152efa22010-05-16 18:19:27 +00003991 PyObject *certfile_bytes = NULL, *keyfile_bytes = NULL;
Christian Heimes598894f2016-09-05 23:19:05 +02003992 pem_password_cb *orig_passwd_cb = SSL_CTX_get_default_passwd_cb(self->ctx);
3993 void *orig_passwd_userdata = SSL_CTX_get_default_passwd_cb_userdata(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003994 _PySSLPasswordInfo pw_info = { NULL, NULL, NULL, 0, 0 };
Antoine Pitrou152efa22010-05-16 18:19:27 +00003995 int r;
3996
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003997 errno = 0;
Antoine Pitrou67e8e562010-09-01 20:55:41 +00003998 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00003999 if (keyfile == Py_None)
4000 keyfile = NULL;
4001 if (!PyUnicode_FSConverter(certfile, &certfile_bytes)) {
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03004002 if (PyErr_ExceptionMatches(PyExc_TypeError)) {
4003 PyErr_SetString(PyExc_TypeError,
4004 "certfile should be a valid filesystem path");
4005 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00004006 return NULL;
4007 }
4008 if (keyfile && !PyUnicode_FSConverter(keyfile, &keyfile_bytes)) {
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03004009 if (PyErr_ExceptionMatches(PyExc_TypeError)) {
4010 PyErr_SetString(PyExc_TypeError,
4011 "keyfile should be a valid filesystem path");
4012 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00004013 goto error;
4014 }
Serhiy Storchaka279f4462019-09-14 12:24:05 +03004015 if (password != Py_None) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02004016 if (PyCallable_Check(password)) {
4017 pw_info.callable = password;
4018 } else if (!_pwinfo_set(&pw_info, password,
4019 "password should be a string or callable")) {
4020 goto error;
4021 }
4022 SSL_CTX_set_default_passwd_cb(self->ctx, _password_callback);
4023 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, &pw_info);
4024 }
4025 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00004026 r = SSL_CTX_use_certificate_chain_file(self->ctx,
4027 PyBytes_AS_STRING(certfile_bytes));
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02004028 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00004029 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02004030 if (pw_info.error) {
4031 ERR_clear_error();
4032 /* the password callback has already set the error information */
4033 }
4034 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00004035 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03004036 PyErr_SetFromErrno(PyExc_OSError);
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00004037 }
4038 else {
4039 _setSSLError(NULL, 0, __FILE__, __LINE__);
4040 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00004041 goto error;
4042 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02004043 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou9c254862011-04-03 18:15:34 +02004044 r = SSL_CTX_use_PrivateKey_file(self->ctx,
Antoine Pitrou152efa22010-05-16 18:19:27 +00004045 PyBytes_AS_STRING(keyfile ? keyfile_bytes : certfile_bytes),
4046 SSL_FILETYPE_PEM);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02004047 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
4048 Py_CLEAR(keyfile_bytes);
4049 Py_CLEAR(certfile_bytes);
Antoine Pitrou152efa22010-05-16 18:19:27 +00004050 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02004051 if (pw_info.error) {
4052 ERR_clear_error();
4053 /* the password callback has already set the error information */
4054 }
4055 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00004056 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03004057 PyErr_SetFromErrno(PyExc_OSError);
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00004058 }
4059 else {
4060 _setSSLError(NULL, 0, __FILE__, __LINE__);
4061 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02004062 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004063 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02004064 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00004065 r = SSL_CTX_check_private_key(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02004066 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00004067 if (r != 1) {
4068 _setSSLError(NULL, 0, __FILE__, __LINE__);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02004069 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004070 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02004071 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
4072 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02004073 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00004074 Py_RETURN_NONE;
4075
4076error:
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02004077 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
4078 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02004079 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00004080 Py_XDECREF(keyfile_bytes);
4081 Py_XDECREF(certfile_bytes);
4082 return NULL;
4083}
4084
Christian Heimesefff7062013-11-21 03:35:02 +01004085/* internal helper function, returns -1 on error
4086 */
4087static int
Serhiy Storchaka8f87eef2020-04-12 14:58:27 +03004088_add_ca_certs(PySSLContext *self, const void *data, Py_ssize_t len,
Christian Heimesefff7062013-11-21 03:35:02 +01004089 int filetype)
4090{
4091 BIO *biobuf = NULL;
4092 X509_STORE *store;
4093 int retval = 0, err, loaded = 0;
4094
4095 assert(filetype == SSL_FILETYPE_ASN1 || filetype == SSL_FILETYPE_PEM);
4096
4097 if (len <= 0) {
4098 PyErr_SetString(PyExc_ValueError,
4099 "Empty certificate data");
4100 return -1;
4101 } else if (len > INT_MAX) {
4102 PyErr_SetString(PyExc_OverflowError,
4103 "Certificate data is too long.");
4104 return -1;
4105 }
4106
Christian Heimes1dbf61f2013-11-22 00:34:18 +01004107 biobuf = BIO_new_mem_buf(data, (int)len);
Christian Heimesefff7062013-11-21 03:35:02 +01004108 if (biobuf == NULL) {
4109 _setSSLError("Can't allocate buffer", 0, __FILE__, __LINE__);
4110 return -1;
4111 }
4112
4113 store = SSL_CTX_get_cert_store(self->ctx);
4114 assert(store != NULL);
4115
4116 while (1) {
4117 X509 *cert = NULL;
4118 int r;
4119
4120 if (filetype == SSL_FILETYPE_ASN1) {
4121 cert = d2i_X509_bio(biobuf, NULL);
4122 } else {
4123 cert = PEM_read_bio_X509(biobuf, NULL,
Christian Heimes598894f2016-09-05 23:19:05 +02004124 SSL_CTX_get_default_passwd_cb(self->ctx),
4125 SSL_CTX_get_default_passwd_cb_userdata(self->ctx)
4126 );
Christian Heimesefff7062013-11-21 03:35:02 +01004127 }
4128 if (cert == NULL) {
4129 break;
4130 }
4131 r = X509_STORE_add_cert(store, cert);
4132 X509_free(cert);
4133 if (!r) {
4134 err = ERR_peek_last_error();
4135 if ((ERR_GET_LIB(err) == ERR_LIB_X509) &&
4136 (ERR_GET_REASON(err) == X509_R_CERT_ALREADY_IN_HASH_TABLE)) {
4137 /* cert already in hash table, not an error */
4138 ERR_clear_error();
4139 } else {
4140 break;
4141 }
4142 }
4143 loaded++;
4144 }
4145
4146 err = ERR_peek_last_error();
4147 if ((filetype == SSL_FILETYPE_ASN1) &&
4148 (loaded > 0) &&
4149 (ERR_GET_LIB(err) == ERR_LIB_ASN1) &&
4150 (ERR_GET_REASON(err) == ASN1_R_HEADER_TOO_LONG)) {
4151 /* EOF ASN1 file, not an error */
4152 ERR_clear_error();
4153 retval = 0;
4154 } else if ((filetype == SSL_FILETYPE_PEM) &&
4155 (loaded > 0) &&
4156 (ERR_GET_LIB(err) == ERR_LIB_PEM) &&
4157 (ERR_GET_REASON(err) == PEM_R_NO_START_LINE)) {
4158 /* EOF PEM file, not an error */
4159 ERR_clear_error();
4160 retval = 0;
4161 } else {
4162 _setSSLError(NULL, 0, __FILE__, __LINE__);
4163 retval = -1;
4164 }
4165
4166 BIO_free(biobuf);
4167 return retval;
4168}
4169
4170
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004171/*[clinic input]
4172_ssl._SSLContext.load_verify_locations
Serhiy Storchaka279f4462019-09-14 12:24:05 +03004173 cafile: object = None
4174 capath: object = None
4175 cadata: object = None
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004176
4177[clinic start generated code]*/
4178
Antoine Pitrou152efa22010-05-16 18:19:27 +00004179static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004180_ssl__SSLContext_load_verify_locations_impl(PySSLContext *self,
4181 PyObject *cafile,
4182 PyObject *capath,
4183 PyObject *cadata)
Serhiy Storchaka279f4462019-09-14 12:24:05 +03004184/*[clinic end generated code: output=454c7e41230ca551 input=42ecfe258233e194]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004185{
Antoine Pitrou152efa22010-05-16 18:19:27 +00004186 PyObject *cafile_bytes = NULL, *capath_bytes = NULL;
4187 const char *cafile_buf = NULL, *capath_buf = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01004188 int r = 0, ok = 1;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004189
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00004190 errno = 0;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004191 if (cafile == Py_None)
4192 cafile = NULL;
4193 if (capath == Py_None)
4194 capath = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01004195 if (cadata == Py_None)
4196 cadata = NULL;
4197
4198 if (cafile == NULL && capath == NULL && cadata == NULL) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00004199 PyErr_SetString(PyExc_TypeError,
Christian Heimesefff7062013-11-21 03:35:02 +01004200 "cafile, capath and cadata cannot be all omitted");
4201 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004202 }
4203 if (cafile && !PyUnicode_FSConverter(cafile, &cafile_bytes)) {
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03004204 if (PyErr_ExceptionMatches(PyExc_TypeError)) {
4205 PyErr_SetString(PyExc_TypeError,
4206 "cafile should be a valid filesystem path");
4207 }
Christian Heimesefff7062013-11-21 03:35:02 +01004208 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004209 }
4210 if (capath && !PyUnicode_FSConverter(capath, &capath_bytes)) {
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03004211 if (PyErr_ExceptionMatches(PyExc_TypeError)) {
4212 PyErr_SetString(PyExc_TypeError,
4213 "capath should be a valid filesystem path");
4214 }
Christian Heimesefff7062013-11-21 03:35:02 +01004215 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004216 }
Christian Heimesefff7062013-11-21 03:35:02 +01004217
4218 /* validata cadata type and load cadata */
4219 if (cadata) {
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03004220 if (PyUnicode_Check(cadata)) {
4221 PyObject *cadata_ascii = PyUnicode_AsASCIIString(cadata);
4222 if (cadata_ascii == NULL) {
4223 if (PyErr_ExceptionMatches(PyExc_UnicodeEncodeError)) {
4224 goto invalid_cadata;
4225 }
4226 goto error;
4227 }
4228 r = _add_ca_certs(self,
4229 PyBytes_AS_STRING(cadata_ascii),
4230 PyBytes_GET_SIZE(cadata_ascii),
4231 SSL_FILETYPE_PEM);
4232 Py_DECREF(cadata_ascii);
4233 if (r == -1) {
4234 goto error;
4235 }
4236 }
4237 else if (PyObject_CheckBuffer(cadata)) {
4238 Py_buffer buf;
4239 if (PyObject_GetBuffer(cadata, &buf, PyBUF_SIMPLE)) {
4240 goto error;
4241 }
Christian Heimesefff7062013-11-21 03:35:02 +01004242 if (!PyBuffer_IsContiguous(&buf, 'C') || buf.ndim > 1) {
4243 PyBuffer_Release(&buf);
4244 PyErr_SetString(PyExc_TypeError,
4245 "cadata should be a contiguous buffer with "
4246 "a single dimension");
4247 goto error;
4248 }
4249 r = _add_ca_certs(self, buf.buf, buf.len, SSL_FILETYPE_ASN1);
4250 PyBuffer_Release(&buf);
4251 if (r == -1) {
4252 goto error;
4253 }
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03004254 }
4255 else {
4256 invalid_cadata:
4257 PyErr_SetString(PyExc_TypeError,
4258 "cadata should be an ASCII string or a "
4259 "bytes-like object");
4260 goto error;
Christian Heimesefff7062013-11-21 03:35:02 +01004261 }
4262 }
4263
4264 /* load cafile or capath */
4265 if (cafile || capath) {
4266 if (cafile)
4267 cafile_buf = PyBytes_AS_STRING(cafile_bytes);
4268 if (capath)
4269 capath_buf = PyBytes_AS_STRING(capath_bytes);
4270 PySSL_BEGIN_ALLOW_THREADS
4271 r = SSL_CTX_load_verify_locations(self->ctx, cafile_buf, capath_buf);
4272 PySSL_END_ALLOW_THREADS
4273 if (r != 1) {
Christian Heimesefff7062013-11-21 03:35:02 +01004274 if (errno != 0) {
4275 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03004276 PyErr_SetFromErrno(PyExc_OSError);
Christian Heimesefff7062013-11-21 03:35:02 +01004277 }
4278 else {
4279 _setSSLError(NULL, 0, __FILE__, __LINE__);
4280 }
4281 goto error;
4282 }
4283 }
4284 goto end;
4285
4286 error:
4287 ok = 0;
4288 end:
Antoine Pitrou152efa22010-05-16 18:19:27 +00004289 Py_XDECREF(cafile_bytes);
4290 Py_XDECREF(capath_bytes);
Christian Heimesefff7062013-11-21 03:35:02 +01004291 if (ok) {
4292 Py_RETURN_NONE;
4293 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00004294 return NULL;
4295 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00004296}
4297
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004298/*[clinic input]
4299_ssl._SSLContext.load_dh_params
4300 path as filepath: object
4301 /
4302
4303[clinic start generated code]*/
4304
Antoine Pitrou152efa22010-05-16 18:19:27 +00004305static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004306_ssl__SSLContext_load_dh_params(PySSLContext *self, PyObject *filepath)
4307/*[clinic end generated code: output=1c8e57a38e055af0 input=c8871f3c796ae1d6]*/
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004308{
4309 FILE *f;
4310 DH *dh;
4311
Victor Stinnerdaf45552013-08-28 00:53:59 +02004312 f = _Py_fopen_obj(filepath, "rb");
Victor Stinnere42ccd22015-03-18 01:39:23 +01004313 if (f == NULL)
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004314 return NULL;
Victor Stinnere42ccd22015-03-18 01:39:23 +01004315
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004316 errno = 0;
4317 PySSL_BEGIN_ALLOW_THREADS
4318 dh = PEM_read_DHparams(f, NULL, NULL, NULL);
Antoine Pitrou457a2292013-01-12 21:43:45 +01004319 fclose(f);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004320 PySSL_END_ALLOW_THREADS
4321 if (dh == NULL) {
4322 if (errno != 0) {
4323 ERR_clear_error();
4324 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
4325 }
4326 else {
4327 _setSSLError(NULL, 0, __FILE__, __LINE__);
4328 }
4329 return NULL;
4330 }
Zackery Spytzaebc0492020-07-07 22:21:58 -06004331 if (!SSL_CTX_set_tmp_dh(self->ctx, dh)) {
4332 DH_free(dh);
4333 return _setSSLError(NULL, 0, __FILE__, __LINE__);
4334 }
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004335 DH_free(dh);
4336 Py_RETURN_NONE;
4337}
4338
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004339/*[clinic input]
4340_ssl._SSLContext._wrap_socket
4341 sock: object(subclass_of="PySocketModule.Sock_Type")
4342 server_side: int
4343 server_hostname as hostname_obj: object = None
Christian Heimes141c5e82018-02-24 21:10:57 +01004344 *
4345 owner: object = None
4346 session: object = None
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004347
4348[clinic start generated code]*/
4349
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004350static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004351_ssl__SSLContext__wrap_socket_impl(PySSLContext *self, PyObject *sock,
Christian Heimes141c5e82018-02-24 21:10:57 +01004352 int server_side, PyObject *hostname_obj,
4353 PyObject *owner, PyObject *session)
4354/*[clinic end generated code: output=f103f238633940b4 input=957d5006183d1894]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004355{
Antoine Pitroud5323212010-10-22 18:19:07 +00004356 char *hostname = NULL;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004357 PyObject *res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004358
Antoine Pitroud5323212010-10-22 18:19:07 +00004359 /* server_hostname is either None (or absent), or to be encoded
Christian Heimesd02ac252018-03-25 12:36:13 +02004360 as IDN A-label (ASCII str) without NULL bytes. */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004361 if (hostname_obj != Py_None) {
Christian Heimes11a14932018-02-24 02:35:08 +01004362 if (!PyArg_Parse(hostname_obj, "es", "ascii", &hostname))
Antoine Pitroud5323212010-10-22 18:19:07 +00004363 return NULL;
Antoine Pitroud5323212010-10-22 18:19:07 +00004364 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00004365
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004366 res = (PyObject *) newPySSLSocket(self, (PySocketSockObject *)sock,
4367 server_side, hostname,
Christian Heimes141c5e82018-02-24 21:10:57 +01004368 owner, session,
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004369 NULL, NULL);
Antoine Pitroud5323212010-10-22 18:19:07 +00004370 if (hostname != NULL)
4371 PyMem_Free(hostname);
4372 return res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004373}
4374
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004375/*[clinic input]
4376_ssl._SSLContext._wrap_bio
Christian Heimes5c36da72020-11-20 09:40:12 +01004377 incoming: object(subclass_of="PySSLMemoryBIO_Type", type="PySSLMemoryBIO *")
4378 outgoing: object(subclass_of="PySSLMemoryBIO_Type", type="PySSLMemoryBIO *")
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004379 server_side: int
4380 server_hostname as hostname_obj: object = None
Christian Heimes141c5e82018-02-24 21:10:57 +01004381 *
4382 owner: object = None
4383 session: object = None
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004384
4385[clinic start generated code]*/
4386
Antoine Pitroub0182c82010-10-12 20:09:02 +00004387static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004388_ssl__SSLContext__wrap_bio_impl(PySSLContext *self, PySSLMemoryBIO *incoming,
4389 PySSLMemoryBIO *outgoing, int server_side,
Christian Heimes141c5e82018-02-24 21:10:57 +01004390 PyObject *hostname_obj, PyObject *owner,
4391 PyObject *session)
Christian Heimes5c36da72020-11-20 09:40:12 +01004392/*[clinic end generated code: output=5c5d6d9b41f99332 input=63867b8f3e1a1aa3]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004393{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004394 char *hostname = NULL;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004395 PyObject *res;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004396
4397 /* server_hostname is either None (or absent), or to be encoded
Christian Heimesd02ac252018-03-25 12:36:13 +02004398 as IDN A-label (ASCII str) without NULL bytes. */
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004399 if (hostname_obj != Py_None) {
Christian Heimes11a14932018-02-24 02:35:08 +01004400 if (!PyArg_Parse(hostname_obj, "es", "ascii", &hostname))
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004401 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004402 }
4403
4404 res = (PyObject *) newPySSLSocket(self, NULL, server_side, hostname,
Christian Heimes141c5e82018-02-24 21:10:57 +01004405 owner, session,
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004406 incoming, outgoing);
4407
4408 PyMem_Free(hostname);
4409 return res;
4410}
4411
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004412/*[clinic input]
4413_ssl._SSLContext.session_stats
4414[clinic start generated code]*/
4415
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004416static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004417_ssl__SSLContext_session_stats_impl(PySSLContext *self)
4418/*[clinic end generated code: output=0d96411c42893bfb input=7e0a81fb11102c8b]*/
Antoine Pitroub0182c82010-10-12 20:09:02 +00004419{
4420 int r;
4421 PyObject *value, *stats = PyDict_New();
4422 if (!stats)
4423 return NULL;
4424
4425#define ADD_STATS(SSL_NAME, KEY_NAME) \
4426 value = PyLong_FromLong(SSL_CTX_sess_ ## SSL_NAME (self->ctx)); \
4427 if (value == NULL) \
4428 goto error; \
4429 r = PyDict_SetItemString(stats, KEY_NAME, value); \
4430 Py_DECREF(value); \
4431 if (r < 0) \
4432 goto error;
4433
4434 ADD_STATS(number, "number");
4435 ADD_STATS(connect, "connect");
4436 ADD_STATS(connect_good, "connect_good");
4437 ADD_STATS(connect_renegotiate, "connect_renegotiate");
4438 ADD_STATS(accept, "accept");
4439 ADD_STATS(accept_good, "accept_good");
4440 ADD_STATS(accept_renegotiate, "accept_renegotiate");
4441 ADD_STATS(accept, "accept");
4442 ADD_STATS(hits, "hits");
4443 ADD_STATS(misses, "misses");
4444 ADD_STATS(timeouts, "timeouts");
4445 ADD_STATS(cache_full, "cache_full");
4446
4447#undef ADD_STATS
4448
4449 return stats;
4450
4451error:
4452 Py_DECREF(stats);
4453 return NULL;
4454}
4455
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004456/*[clinic input]
4457_ssl._SSLContext.set_default_verify_paths
4458[clinic start generated code]*/
4459
Antoine Pitrou664c2d12010-11-17 20:29:42 +00004460static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004461_ssl__SSLContext_set_default_verify_paths_impl(PySSLContext *self)
4462/*[clinic end generated code: output=0bee74e6e09deaaa input=35f3408021463d74]*/
Antoine Pitrou664c2d12010-11-17 20:29:42 +00004463{
4464 if (!SSL_CTX_set_default_verify_paths(self->ctx)) {
4465 _setSSLError(NULL, 0, __FILE__, __LINE__);
4466 return NULL;
4467 }
4468 Py_RETURN_NONE;
4469}
4470
Antoine Pitrou501da612011-12-21 09:27:41 +01004471#ifndef OPENSSL_NO_ECDH
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004472/*[clinic input]
4473_ssl._SSLContext.set_ecdh_curve
4474 name: object
4475 /
4476
4477[clinic start generated code]*/
4478
Antoine Pitrou923df6f2011-12-19 17:16:51 +01004479static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004480_ssl__SSLContext_set_ecdh_curve(PySSLContext *self, PyObject *name)
4481/*[clinic end generated code: output=23022c196e40d7d2 input=c2bafb6f6e34726b]*/
Antoine Pitrou923df6f2011-12-19 17:16:51 +01004482{
4483 PyObject *name_bytes;
4484 int nid;
4485 EC_KEY *key;
4486
4487 if (!PyUnicode_FSConverter(name, &name_bytes))
4488 return NULL;
4489 assert(PyBytes_Check(name_bytes));
4490 nid = OBJ_sn2nid(PyBytes_AS_STRING(name_bytes));
4491 Py_DECREF(name_bytes);
4492 if (nid == 0) {
4493 PyErr_Format(PyExc_ValueError,
4494 "unknown elliptic curve name %R", name);
4495 return NULL;
4496 }
4497 key = EC_KEY_new_by_curve_name(nid);
4498 if (key == NULL) {
4499 _setSSLError(NULL, 0, __FILE__, __LINE__);
4500 return NULL;
4501 }
4502 SSL_CTX_set_tmp_ecdh(self->ctx, key);
4503 EC_KEY_free(key);
4504 Py_RETURN_NONE;
4505}
Antoine Pitrou501da612011-12-21 09:27:41 +01004506#endif
Antoine Pitrou923df6f2011-12-19 17:16:51 +01004507
Antoine Pitrou912fbff2013-03-30 16:29:32 +01004508#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004509static int
4510_servername_callback(SSL *s, int *al, void *args)
4511{
4512 int ret;
4513 PySSLContext *ssl_ctx = (PySSLContext *) args;
4514 PySSLSocket *ssl;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004515 PyObject *result;
4516 /* The high-level ssl.SSLSocket object */
4517 PyObject *ssl_socket;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004518 const char *servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
Stefan Krah20d60802013-01-17 17:07:17 +01004519 PyGILState_STATE gstate = PyGILState_Ensure();
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004520
Christian Heimes11a14932018-02-24 02:35:08 +01004521 if (ssl_ctx->set_sni_cb == NULL) {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004522 /* remove race condition in this the call back while if removing the
4523 * callback is in progress */
4524 PyGILState_Release(gstate);
Antoine Pitrou5dd12a52013-01-06 15:25:36 +01004525 return SSL_TLSEXT_ERR_OK;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004526 }
4527
4528 ssl = SSL_get_app_data(s);
4529 assert(PySSLSocket_Check(ssl));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004530
Serhiy Storchakaf51d7152015-11-02 14:40:41 +02004531 /* The servername callback expects an argument that represents the current
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004532 * SSL connection and that has a .context attribute that can be changed to
4533 * identify the requested hostname. Since the official API is the Python
4534 * level API we want to pass the callback a Python level object rather than
4535 * a _ssl.SSLSocket instance. If there's an "owner" (typically an
4536 * SSLObject) that will be passed. Otherwise if there's a socket then that
4537 * will be passed. If both do not exist only then the C-level object is
4538 * passed. */
4539 if (ssl->owner)
4540 ssl_socket = PyWeakref_GetObject(ssl->owner);
4541 else if (ssl->Socket)
4542 ssl_socket = PyWeakref_GetObject(ssl->Socket);
4543 else
4544 ssl_socket = (PyObject *) ssl;
4545
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004546 Py_INCREF(ssl_socket);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004547 if (ssl_socket == Py_None)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004548 goto error;
Victor Stinner7e001512013-06-25 00:44:31 +02004549
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004550 if (servername == NULL) {
Christian Heimes11a14932018-02-24 02:35:08 +01004551 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_sni_cb, ssl_socket,
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004552 Py_None, ssl_ctx, NULL);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004553 }
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004554 else {
Christian Heimes11a14932018-02-24 02:35:08 +01004555 PyObject *servername_bytes;
4556 PyObject *servername_str;
4557
4558 servername_bytes = PyBytes_FromString(servername);
4559 if (servername_bytes == NULL) {
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004560 PyErr_WriteUnraisable((PyObject *) ssl_ctx);
4561 goto error;
4562 }
Christian Heimes11a14932018-02-24 02:35:08 +01004563 /* server_hostname was encoded to an A-label by our caller; put it
4564 * back into a str object, but still as an A-label (bpo-28414)
4565 */
4566 servername_str = PyUnicode_FromEncodedObject(servername_bytes, "ascii", NULL);
Christian Heimes11a14932018-02-24 02:35:08 +01004567 if (servername_str == NULL) {
4568 PyErr_WriteUnraisable(servername_bytes);
Zackery Spytzee96f322020-07-09 04:00:21 -06004569 Py_DECREF(servername_bytes);
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004570 goto error;
4571 }
Zackery Spytzee96f322020-07-09 04:00:21 -06004572 Py_DECREF(servername_bytes);
Christian Heimes11a14932018-02-24 02:35:08 +01004573 result = PyObject_CallFunctionObjArgs(
4574 ssl_ctx->set_sni_cb, ssl_socket, servername_str,
4575 ssl_ctx, NULL);
4576 Py_DECREF(servername_str);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004577 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004578 Py_DECREF(ssl_socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004579
4580 if (result == NULL) {
Christian Heimes11a14932018-02-24 02:35:08 +01004581 PyErr_WriteUnraisable(ssl_ctx->set_sni_cb);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004582 *al = SSL_AD_HANDSHAKE_FAILURE;
4583 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
4584 }
4585 else {
Christian Heimes11a14932018-02-24 02:35:08 +01004586 /* Result may be None, a SSLContext or an integer
4587 * None and SSLContext are OK, integer or other values are an error.
4588 */
4589 if (result == Py_None) {
4590 ret = SSL_TLSEXT_ERR_OK;
4591 } else {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004592 *al = (int) PyLong_AsLong(result);
4593 if (PyErr_Occurred()) {
4594 PyErr_WriteUnraisable(result);
4595 *al = SSL_AD_INTERNAL_ERROR;
4596 }
4597 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
4598 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004599 Py_DECREF(result);
4600 }
4601
4602 PyGILState_Release(gstate);
4603 return ret;
4604
4605error:
4606 Py_DECREF(ssl_socket);
4607 *al = SSL_AD_INTERNAL_ERROR;
4608 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
4609 PyGILState_Release(gstate);
4610 return ret;
4611}
Antoine Pitroua5963382013-03-30 16:39:00 +01004612#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004613
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004614static PyObject *
Christian Heimes11a14932018-02-24 02:35:08 +01004615get_sni_callback(PySSLContext *self, void *c)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004616{
Christian Heimes11a14932018-02-24 02:35:08 +01004617 PyObject *cb = self->set_sni_cb;
4618 if (cb == NULL) {
4619 Py_RETURN_NONE;
4620 }
4621 Py_INCREF(cb);
4622 return cb;
4623}
4624
4625static int
4626set_sni_callback(PySSLContext *self, PyObject *arg, void *c)
4627{
4628 if (self->protocol == PY_SSL_VERSION_TLS_CLIENT) {
4629 PyErr_SetString(PyExc_ValueError,
4630 "sni_callback cannot be set on TLS_CLIENT context");
4631 return -1;
4632 }
Antoine Pitrou912fbff2013-03-30 16:29:32 +01004633#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Christian Heimes11a14932018-02-24 02:35:08 +01004634 Py_CLEAR(self->set_sni_cb);
4635 if (arg == Py_None) {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004636 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
4637 }
4638 else {
Christian Heimes11a14932018-02-24 02:35:08 +01004639 if (!PyCallable_Check(arg)) {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004640 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
4641 PyErr_SetString(PyExc_TypeError,
4642 "not a callable object");
Christian Heimes11a14932018-02-24 02:35:08 +01004643 return -1;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004644 }
Christian Heimes11a14932018-02-24 02:35:08 +01004645 Py_INCREF(arg);
4646 self->set_sni_cb = arg;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004647 SSL_CTX_set_tlsext_servername_callback(self->ctx, _servername_callback);
4648 SSL_CTX_set_tlsext_servername_arg(self->ctx, self);
4649 }
Christian Heimes11a14932018-02-24 02:35:08 +01004650 return 0;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004651#else
4652 PyErr_SetString(PyExc_NotImplementedError,
4653 "The TLS extension servername callback, "
4654 "SSL_CTX_set_tlsext_servername_callback, "
4655 "is not in the current OpenSSL library.");
Christian Heimes11a14932018-02-24 02:35:08 +01004656 return -1;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004657#endif
4658}
4659
Christian Heimes11a14932018-02-24 02:35:08 +01004660PyDoc_STRVAR(PySSLContext_sni_callback_doc,
4661"Set a callback that will be called when a server name is provided by the SSL/TLS client in the SNI extension.\n\
4662\n\
4663If the argument is None then the callback is disabled. The method is called\n\
4664with the SSLSocket, the server name as a string, and the SSLContext object.\n\
4665See RFC 6066 for details of the SNI extension.");
4666
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004667/*[clinic input]
4668_ssl._SSLContext.cert_store_stats
4669
4670Returns quantities of loaded X.509 certificates.
4671
4672X.509 certificates with a CA extension and certificate revocation lists
4673inside the context's cert store.
4674
4675NOTE: Certificates in a capath directory aren't loaded unless they have
4676been used at least once.
4677[clinic start generated code]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004678
4679static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004680_ssl__SSLContext_cert_store_stats_impl(PySSLContext *self)
4681/*[clinic end generated code: output=5f356f4d9cca874d input=eb40dd0f6d0e40cf]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004682{
4683 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02004684 STACK_OF(X509_OBJECT) *objs;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004685 X509_OBJECT *obj;
Christian Heimes598894f2016-09-05 23:19:05 +02004686 int x509 = 0, crl = 0, ca = 0, i;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004687
4688 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02004689 objs = X509_STORE_get0_objects(store);
4690 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
4691 obj = sk_X509_OBJECT_value(objs, i);
4692 switch (X509_OBJECT_get_type(obj)) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004693 case X509_LU_X509:
4694 x509++;
Christian Heimes598894f2016-09-05 23:19:05 +02004695 if (X509_check_ca(X509_OBJECT_get0_X509(obj))) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004696 ca++;
4697 }
4698 break;
4699 case X509_LU_CRL:
4700 crl++;
4701 break;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004702 default:
4703 /* Ignore X509_LU_FAIL, X509_LU_RETRY, X509_LU_PKEY.
4704 * As far as I can tell they are internal states and never
4705 * stored in a cert store */
4706 break;
4707 }
4708 }
4709 return Py_BuildValue("{sisisi}", "x509", x509, "crl", crl,
4710 "x509_ca", ca);
4711}
4712
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004713/*[clinic input]
4714_ssl._SSLContext.get_ca_certs
4715 binary_form: bool = False
4716
4717Returns a list of dicts with information of loaded CA certs.
4718
4719If the optional argument is True, returns a DER-encoded copy of the CA
4720certificate.
4721
4722NOTE: Certificates in a capath directory aren't loaded unless they have
4723been used at least once.
4724[clinic start generated code]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004725
4726static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004727_ssl__SSLContext_get_ca_certs_impl(PySSLContext *self, int binary_form)
4728/*[clinic end generated code: output=0d58f148f37e2938 input=6887b5a09b7f9076]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004729{
4730 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02004731 STACK_OF(X509_OBJECT) *objs;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004732 PyObject *ci = NULL, *rlist = NULL;
4733 int i;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004734
4735 if ((rlist = PyList_New(0)) == NULL) {
4736 return NULL;
4737 }
4738
4739 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02004740 objs = X509_STORE_get0_objects(store);
4741 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004742 X509_OBJECT *obj;
4743 X509 *cert;
4744
Christian Heimes598894f2016-09-05 23:19:05 +02004745 obj = sk_X509_OBJECT_value(objs, i);
4746 if (X509_OBJECT_get_type(obj) != X509_LU_X509) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004747 /* not a x509 cert */
4748 continue;
4749 }
4750 /* CA for any purpose */
Christian Heimes598894f2016-09-05 23:19:05 +02004751 cert = X509_OBJECT_get0_X509(obj);
Christian Heimes9a5395a2013-06-17 15:44:12 +02004752 if (!X509_check_ca(cert)) {
4753 continue;
4754 }
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004755 if (binary_form) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004756 ci = _certificate_to_der(cert);
4757 } else {
4758 ci = _decode_certificate(cert);
4759 }
4760 if (ci == NULL) {
4761 goto error;
4762 }
4763 if (PyList_Append(rlist, ci) == -1) {
4764 goto error;
4765 }
4766 Py_CLEAR(ci);
4767 }
4768 return rlist;
4769
4770 error:
4771 Py_XDECREF(ci);
4772 Py_XDECREF(rlist);
4773 return NULL;
4774}
4775
4776
Antoine Pitrou152efa22010-05-16 18:19:27 +00004777static PyGetSetDef context_getsetlist[] = {
Christian Heimes1aa9a752013-12-02 02:41:19 +01004778 {"check_hostname", (getter) get_check_hostname,
4779 (setter) set_check_hostname, NULL},
Christian Heimes61d478c2018-01-27 15:51:38 +01004780 {"_host_flags", (getter) get_host_flags,
4781 (setter) set_host_flags, NULL},
Christian Heimes698dde12018-02-27 11:54:43 +01004782#if SSL_CTRL_GET_MAX_PROTO_VERSION
4783 {"minimum_version", (getter) get_minimum_version,
4784 (setter) set_minimum_version, NULL},
4785 {"maximum_version", (getter) get_maximum_version,
4786 (setter) set_maximum_version, NULL},
4787#endif
Christian Heimesc7f70692019-05-31 11:44:05 +02004788#ifdef HAVE_OPENSSL_KEYLOG
4789 {"keylog_filename", (getter) _PySSLContext_get_keylog_filename,
4790 (setter) _PySSLContext_set_keylog_filename, NULL},
4791#endif
4792 {"_msg_callback", (getter) _PySSLContext_get_msg_callback,
4793 (setter) _PySSLContext_set_msg_callback, NULL},
Christian Heimes11a14932018-02-24 02:35:08 +01004794 {"sni_callback", (getter) get_sni_callback,
Christian Heimes698dde12018-02-27 11:54:43 +01004795 (setter) set_sni_callback, PySSLContext_sni_callback_doc},
Christian Heimes78c7d522019-06-03 21:00:10 +02004796#if (OPENSSL_VERSION_NUMBER >= 0x10101000L) && !defined(LIBRESSL_VERSION_NUMBER)
4797 {"num_tickets", (getter) get_num_tickets,
4798 (setter) set_num_tickets, PySSLContext_num_tickets_doc},
4799#endif
Antoine Pitroub5218772010-05-21 09:56:06 +00004800 {"options", (getter) get_options,
4801 (setter) set_options, NULL},
Christian Heimes9fb051f2018-09-23 08:32:31 +02004802 {"post_handshake_auth", (getter) get_post_handshake_auth,
4803#ifdef TLS1_3_VERSION
4804 (setter) set_post_handshake_auth,
4805#else
4806 NULL,
4807#endif
4808 NULL},
Christian Heimes11a14932018-02-24 02:35:08 +01004809 {"protocol", (getter) get_protocol,
4810 NULL, NULL},
Christian Heimes22587792013-11-21 23:56:13 +01004811 {"verify_flags", (getter) get_verify_flags,
4812 (setter) set_verify_flags, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00004813 {"verify_mode", (getter) get_verify_mode,
4814 (setter) set_verify_mode, NULL},
matthewhughes9348e836bb2020-07-17 09:59:15 +01004815#if (OPENSSL_VERSION_NUMBER >= 0x10100000L) && !defined(LIBRESSL_VERSION_NUMBER)
4816 {"security_level", (getter) get_security_level,
4817 NULL, PySSLContext_security_level_doc},
4818#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00004819 {NULL}, /* sentinel */
4820};
4821
4822static struct PyMethodDef context_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004823 _SSL__SSLCONTEXT__WRAP_SOCKET_METHODDEF
4824 _SSL__SSLCONTEXT__WRAP_BIO_METHODDEF
4825 _SSL__SSLCONTEXT_SET_CIPHERS_METHODDEF
4826 _SSL__SSLCONTEXT__SET_ALPN_PROTOCOLS_METHODDEF
4827 _SSL__SSLCONTEXT__SET_NPN_PROTOCOLS_METHODDEF
4828 _SSL__SSLCONTEXT_LOAD_CERT_CHAIN_METHODDEF
4829 _SSL__SSLCONTEXT_LOAD_DH_PARAMS_METHODDEF
4830 _SSL__SSLCONTEXT_LOAD_VERIFY_LOCATIONS_METHODDEF
4831 _SSL__SSLCONTEXT_SESSION_STATS_METHODDEF
4832 _SSL__SSLCONTEXT_SET_DEFAULT_VERIFY_PATHS_METHODDEF
4833 _SSL__SSLCONTEXT_SET_ECDH_CURVE_METHODDEF
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004834 _SSL__SSLCONTEXT_CERT_STORE_STATS_METHODDEF
4835 _SSL__SSLCONTEXT_GET_CA_CERTS_METHODDEF
Christian Heimes25bfcd52016-09-06 00:04:45 +02004836 _SSL__SSLCONTEXT_GET_CIPHERS_METHODDEF
Antoine Pitrou152efa22010-05-16 18:19:27 +00004837 {NULL, NULL} /* sentinel */
4838};
4839
Christian Heimes5c36da72020-11-20 09:40:12 +01004840static PyType_Slot PySSLContext_slots[] = {
4841 {Py_tp_methods, context_methods},
4842 {Py_tp_getset, context_getsetlist},
4843 {Py_tp_new, _ssl__SSLContext},
4844 {Py_tp_dealloc, context_dealloc},
4845 {Py_tp_traverse, context_traverse},
4846 {Py_tp_clear, context_clear},
4847 {0, 0},
4848};
4849
4850static PyType_Spec PySSLContext_spec = {
4851 "_ssl._SSLContext",
4852 sizeof(PySSLContext),
4853 0,
4854 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
4855 PySSLContext_slots,
Antoine Pitrou152efa22010-05-16 18:19:27 +00004856};
4857
4858
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004859/*
4860 * MemoryBIO objects
4861 */
4862
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004863/*[clinic input]
4864@classmethod
4865_ssl.MemoryBIO.__new__
4866
4867[clinic start generated code]*/
4868
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004869static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004870_ssl_MemoryBIO_impl(PyTypeObject *type)
4871/*[clinic end generated code: output=8820a58db78330ac input=26d22e4909ecb1b5]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004872{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004873 BIO *bio;
4874 PySSLMemoryBIO *self;
4875
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004876 bio = BIO_new(BIO_s_mem());
4877 if (bio == NULL) {
4878 PyErr_SetString(PySSLErrorObject,
4879 "failed to allocate BIO");
4880 return NULL;
4881 }
4882 /* Since our BIO is non-blocking an empty read() does not indicate EOF,
4883 * just that no data is currently available. The SSL routines should retry
4884 * the read, which we can achieve by calling BIO_set_retry_read(). */
4885 BIO_set_retry_read(bio);
4886 BIO_set_mem_eof_return(bio, -1);
4887
4888 assert(type != NULL && type->tp_alloc != NULL);
4889 self = (PySSLMemoryBIO *) type->tp_alloc(type, 0);
4890 if (self == NULL) {
4891 BIO_free(bio);
4892 return NULL;
4893 }
4894 self->bio = bio;
4895 self->eof_written = 0;
4896
4897 return (PyObject *) self;
4898}
4899
4900static void
4901memory_bio_dealloc(PySSLMemoryBIO *self)
4902{
Christian Heimes5c36da72020-11-20 09:40:12 +01004903 PyTypeObject *tp = Py_TYPE(self);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004904 BIO_free(self->bio);
4905 Py_TYPE(self)->tp_free(self);
Christian Heimes5c36da72020-11-20 09:40:12 +01004906 Py_DECREF(tp);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004907}
4908
4909static PyObject *
4910memory_bio_get_pending(PySSLMemoryBIO *self, void *c)
4911{
Segev Finer5cff6372017-07-27 01:19:17 +03004912 return PyLong_FromSize_t(BIO_ctrl_pending(self->bio));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004913}
4914
4915PyDoc_STRVAR(PySSL_memory_bio_pending_doc,
4916"The number of bytes pending in the memory BIO.");
4917
4918static PyObject *
4919memory_bio_get_eof(PySSLMemoryBIO *self, void *c)
4920{
4921 return PyBool_FromLong((BIO_ctrl_pending(self->bio) == 0)
4922 && self->eof_written);
4923}
4924
4925PyDoc_STRVAR(PySSL_memory_bio_eof_doc,
4926"Whether the memory BIO is at EOF.");
4927
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004928/*[clinic input]
4929_ssl.MemoryBIO.read
4930 size as len: int = -1
4931 /
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004932
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004933Read up to size bytes from the memory BIO.
4934
4935If size is not specified, read the entire buffer.
4936If the return value is an empty bytes instance, this means either
4937EOF or that no data is available. Use the "eof" property to
4938distinguish between the two.
4939[clinic start generated code]*/
4940
4941static PyObject *
4942_ssl_MemoryBIO_read_impl(PySSLMemoryBIO *self, int len)
4943/*[clinic end generated code: output=a657aa1e79cd01b3 input=574d7be06a902366]*/
4944{
4945 int avail, nbytes;
4946 PyObject *result;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004947
Segev Finer5cff6372017-07-27 01:19:17 +03004948 avail = (int)Py_MIN(BIO_ctrl_pending(self->bio), INT_MAX);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004949 if ((len < 0) || (len > avail))
4950 len = avail;
4951
4952 result = PyBytes_FromStringAndSize(NULL, len);
4953 if ((result == NULL) || (len == 0))
4954 return result;
4955
4956 nbytes = BIO_read(self->bio, PyBytes_AS_STRING(result), len);
Zackery Spytz365ad2e2018-10-06 11:41:45 -06004957 if (nbytes < 0) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004958 Py_DECREF(result);
Zackery Spytz365ad2e2018-10-06 11:41:45 -06004959 _setSSLError(NULL, 0, __FILE__, __LINE__);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004960 return NULL;
4961 }
4962
Zackery Spytz365ad2e2018-10-06 11:41:45 -06004963 /* There should never be any short reads but check anyway. */
4964 if (nbytes < len) {
4965 _PyBytes_Resize(&result, nbytes);
4966 }
4967
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004968 return result;
4969}
4970
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004971/*[clinic input]
4972_ssl.MemoryBIO.write
4973 b: Py_buffer
4974 /
4975
4976Writes the bytes b into the memory BIO.
4977
4978Returns the number of bytes written.
4979[clinic start generated code]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004980
4981static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004982_ssl_MemoryBIO_write_impl(PySSLMemoryBIO *self, Py_buffer *b)
4983/*[clinic end generated code: output=156ec59110d75935 input=e45757b3e17c4808]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004984{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004985 int nbytes;
4986
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004987 if (b->len > INT_MAX) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004988 PyErr_Format(PyExc_OverflowError,
4989 "string longer than %d bytes", INT_MAX);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004990 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004991 }
4992
4993 if (self->eof_written) {
4994 PyErr_SetString(PySSLErrorObject,
4995 "cannot write() after write_eof()");
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004996 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004997 }
4998
Segev Finer5cff6372017-07-27 01:19:17 +03004999 nbytes = BIO_write(self->bio, b->buf, (int)b->len);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005000 if (nbytes < 0) {
5001 _setSSLError(NULL, 0, __FILE__, __LINE__);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005002 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005003 }
5004
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005005 return PyLong_FromLong(nbytes);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005006}
5007
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005008/*[clinic input]
5009_ssl.MemoryBIO.write_eof
5010
5011Write an EOF marker to the memory BIO.
5012
5013When all data has been read, the "eof" property will be True.
5014[clinic start generated code]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005015
5016static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005017_ssl_MemoryBIO_write_eof_impl(PySSLMemoryBIO *self)
5018/*[clinic end generated code: output=d4106276ccd1ed34 input=56a945f1d29e8bd6]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005019{
5020 self->eof_written = 1;
5021 /* After an EOF is written, a zero return from read() should be a real EOF
5022 * i.e. it should not be retried. Clear the SHOULD_RETRY flag. */
5023 BIO_clear_retry_flags(self->bio);
5024 BIO_set_mem_eof_return(self->bio, 0);
5025
5026 Py_RETURN_NONE;
5027}
5028
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005029static PyGetSetDef memory_bio_getsetlist[] = {
5030 {"pending", (getter) memory_bio_get_pending, NULL,
5031 PySSL_memory_bio_pending_doc},
5032 {"eof", (getter) memory_bio_get_eof, NULL,
5033 PySSL_memory_bio_eof_doc},
5034 {NULL}, /* sentinel */
5035};
5036
5037static struct PyMethodDef memory_bio_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005038 _SSL_MEMORYBIO_READ_METHODDEF
5039 _SSL_MEMORYBIO_WRITE_METHODDEF
5040 _SSL_MEMORYBIO_WRITE_EOF_METHODDEF
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005041 {NULL, NULL} /* sentinel */
5042};
5043
Christian Heimes5c36da72020-11-20 09:40:12 +01005044static PyType_Slot PySSLMemoryBIO_slots[] = {
5045 {Py_tp_methods, memory_bio_methods},
5046 {Py_tp_getset, memory_bio_getsetlist},
5047 {Py_tp_new, _ssl_MemoryBIO},
5048 {Py_tp_dealloc, memory_bio_dealloc},
5049 {0, 0},
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005050};
5051
Christian Heimes5c36da72020-11-20 09:40:12 +01005052static PyType_Spec PySSLMemoryBIO_spec = {
5053 "_ssl.MemoryBIO",
5054 sizeof(PySSLMemoryBIO),
5055 0,
5056 Py_TPFLAGS_DEFAULT,
5057 PySSLMemoryBIO_slots,
5058};
Antoine Pitrou152efa22010-05-16 18:19:27 +00005059
Christian Heimes99a65702016-09-10 23:44:53 +02005060/*
5061 * SSL Session object
5062 */
5063
5064static void
5065PySSLSession_dealloc(PySSLSession *self)
5066{
Christian Heimes5c36da72020-11-20 09:40:12 +01005067 PyTypeObject *tp = Py_TYPE(self);
INADA Naokia6296d32017-08-24 14:55:17 +09005068 /* bpo-31095: UnTrack is needed before calling any callbacks */
Christian Heimesa5d07652016-09-24 10:48:05 +02005069 PyObject_GC_UnTrack(self);
Christian Heimes99a65702016-09-10 23:44:53 +02005070 Py_XDECREF(self->ctx);
5071 if (self->session != NULL) {
5072 SSL_SESSION_free(self->session);
5073 }
Christian Heimesa5d07652016-09-24 10:48:05 +02005074 PyObject_GC_Del(self);
Christian Heimes5c36da72020-11-20 09:40:12 +01005075 Py_DECREF(tp);
Christian Heimes99a65702016-09-10 23:44:53 +02005076}
5077
5078static PyObject *
5079PySSLSession_richcompare(PyObject *left, PyObject *right, int op)
5080{
5081 int result;
5082
5083 if (left == NULL || right == NULL) {
5084 PyErr_BadInternalCall();
5085 return NULL;
5086 }
5087
5088 if (!PySSLSession_Check(left) || !PySSLSession_Check(right)) {
5089 Py_RETURN_NOTIMPLEMENTED;
5090 }
5091
5092 if (left == right) {
5093 result = 0;
5094 } else {
5095 const unsigned char *left_id, *right_id;
5096 unsigned int left_len, right_len;
5097 left_id = SSL_SESSION_get_id(((PySSLSession *)left)->session,
5098 &left_len);
5099 right_id = SSL_SESSION_get_id(((PySSLSession *)right)->session,
5100 &right_len);
5101 if (left_len == right_len) {
5102 result = memcmp(left_id, right_id, left_len);
5103 } else {
5104 result = 1;
5105 }
5106 }
5107
5108 switch (op) {
5109 case Py_EQ:
5110 if (result == 0) {
5111 Py_RETURN_TRUE;
5112 } else {
5113 Py_RETURN_FALSE;
5114 }
5115 break;
5116 case Py_NE:
5117 if (result != 0) {
5118 Py_RETURN_TRUE;
5119 } else {
5120 Py_RETURN_FALSE;
5121 }
5122 break;
5123 case Py_LT:
5124 case Py_LE:
5125 case Py_GT:
5126 case Py_GE:
5127 Py_RETURN_NOTIMPLEMENTED;
5128 break;
5129 default:
5130 PyErr_BadArgument();
5131 return NULL;
5132 }
5133}
5134
5135static int
5136PySSLSession_traverse(PySSLSession *self, visitproc visit, void *arg)
5137{
5138 Py_VISIT(self->ctx);
5139 return 0;
5140}
5141
5142static int
5143PySSLSession_clear(PySSLSession *self)
5144{
5145 Py_CLEAR(self->ctx);
5146 return 0;
5147}
5148
5149
5150static PyObject *
5151PySSLSession_get_time(PySSLSession *self, void *closure) {
5152 return PyLong_FromLong(SSL_SESSION_get_time(self->session));
5153}
5154
5155PyDoc_STRVAR(PySSLSession_get_time_doc,
5156"Session creation time (seconds since epoch).");
5157
5158
5159static PyObject *
5160PySSLSession_get_timeout(PySSLSession *self, void *closure) {
5161 return PyLong_FromLong(SSL_SESSION_get_timeout(self->session));
5162}
5163
5164PyDoc_STRVAR(PySSLSession_get_timeout_doc,
5165"Session timeout (delta in seconds).");
5166
5167
5168static PyObject *
5169PySSLSession_get_ticket_lifetime_hint(PySSLSession *self, void *closure) {
5170 unsigned long hint = SSL_SESSION_get_ticket_lifetime_hint(self->session);
5171 return PyLong_FromUnsignedLong(hint);
5172}
5173
5174PyDoc_STRVAR(PySSLSession_get_ticket_lifetime_hint_doc,
5175"Ticket life time hint.");
5176
5177
5178static PyObject *
5179PySSLSession_get_session_id(PySSLSession *self, void *closure) {
5180 const unsigned char *id;
5181 unsigned int len;
5182 id = SSL_SESSION_get_id(self->session, &len);
5183 return PyBytes_FromStringAndSize((const char *)id, len);
5184}
5185
5186PyDoc_STRVAR(PySSLSession_get_session_id_doc,
5187"Session id");
5188
5189
5190static PyObject *
5191PySSLSession_get_has_ticket(PySSLSession *self, void *closure) {
5192 if (SSL_SESSION_has_ticket(self->session)) {
5193 Py_RETURN_TRUE;
5194 } else {
5195 Py_RETURN_FALSE;
5196 }
5197}
5198
5199PyDoc_STRVAR(PySSLSession_get_has_ticket_doc,
5200"Does the session contain a ticket?");
5201
5202
5203static PyGetSetDef PySSLSession_getsetlist[] = {
5204 {"has_ticket", (getter) PySSLSession_get_has_ticket, NULL,
5205 PySSLSession_get_has_ticket_doc},
5206 {"id", (getter) PySSLSession_get_session_id, NULL,
5207 PySSLSession_get_session_id_doc},
5208 {"ticket_lifetime_hint", (getter) PySSLSession_get_ticket_lifetime_hint,
5209 NULL, PySSLSession_get_ticket_lifetime_hint_doc},
5210 {"time", (getter) PySSLSession_get_time, NULL,
5211 PySSLSession_get_time_doc},
5212 {"timeout", (getter) PySSLSession_get_timeout, NULL,
5213 PySSLSession_get_timeout_doc},
5214 {NULL}, /* sentinel */
5215};
5216
Christian Heimes5c36da72020-11-20 09:40:12 +01005217static PyType_Slot PySSLSession_slots[] = {
5218 {Py_tp_getset,PySSLSession_getsetlist},
5219 {Py_tp_richcompare, PySSLSession_richcompare},
5220 {Py_tp_dealloc, PySSLSession_dealloc},
5221 {Py_tp_traverse, PySSLSession_traverse},
5222 {Py_tp_clear, PySSLSession_clear},
5223 {0, 0},
5224};
5225
5226static PyType_Spec PySSLSession_spec = {
5227 "_ssl.SSLSession",
5228 sizeof(PySSLSession),
5229 0,
5230 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,
5231 PySSLSession_slots,
Christian Heimes99a65702016-09-10 23:44:53 +02005232};
5233
5234
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005235/* helper routines for seeding the SSL PRNG */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005236/*[clinic input]
5237_ssl.RAND_add
Larry Hastingsdbfdc382015-05-04 06:59:46 -07005238 string as view: Py_buffer(accept={str, buffer})
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005239 entropy: double
5240 /
5241
5242Mix string into the OpenSSL PRNG state.
5243
5244entropy (a float) is a lower bound on the entropy contained in
Chandan Kumar63c2c8a2017-06-09 15:13:58 +05305245string. See RFC 4086.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005246[clinic start generated code]*/
5247
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005248static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005249_ssl_RAND_add_impl(PyObject *module, Py_buffer *view, double entropy)
Serhiy Storchaka5f31d5c2017-06-10 13:13:51 +03005250/*[clinic end generated code: output=e6dd48df9c9024e9 input=5c33017422828f5c]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005251{
Serhiy Storchaka8490f5a2015-03-20 09:00:36 +02005252 const char *buf;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02005253 Py_ssize_t len, written;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005254
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005255 buf = (const char *)view->buf;
5256 len = view->len;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02005257 do {
5258 written = Py_MIN(len, INT_MAX);
5259 RAND_add(buf, (int)written, entropy);
5260 buf += written;
5261 len -= written;
5262 } while (len);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02005263 Py_RETURN_NONE;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005264}
5265
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005266static PyObject *
Victor Stinner99c8b162011-05-24 12:05:19 +02005267PySSL_RAND(int len, int pseudo)
5268{
5269 int ok;
5270 PyObject *bytes;
5271 unsigned long err;
5272 const char *errstr;
5273 PyObject *v;
5274
Victor Stinner1e81a392013-12-19 16:47:04 +01005275 if (len < 0) {
5276 PyErr_SetString(PyExc_ValueError, "num must be positive");
5277 return NULL;
5278 }
5279
Victor Stinner99c8b162011-05-24 12:05:19 +02005280 bytes = PyBytes_FromStringAndSize(NULL, len);
5281 if (bytes == NULL)
5282 return NULL;
5283 if (pseudo) {
Christian Heimesa871f692020-06-01 08:58:14 +02005284#ifdef PY_OPENSSL_1_1_API
5285 ok = RAND_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
5286#else
Victor Stinner99c8b162011-05-24 12:05:19 +02005287 ok = RAND_pseudo_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
Christian Heimesa871f692020-06-01 08:58:14 +02005288#endif
Victor Stinner99c8b162011-05-24 12:05:19 +02005289 if (ok == 0 || ok == 1)
5290 return Py_BuildValue("NO", bytes, ok == 1 ? Py_True : Py_False);
5291 }
5292 else {
5293 ok = RAND_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
5294 if (ok == 1)
5295 return bytes;
5296 }
5297 Py_DECREF(bytes);
5298
5299 err = ERR_get_error();
5300 errstr = ERR_reason_error_string(err);
5301 v = Py_BuildValue("(ks)", err, errstr);
5302 if (v != NULL) {
5303 PyErr_SetObject(PySSLErrorObject, v);
5304 Py_DECREF(v);
5305 }
5306 return NULL;
5307}
5308
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005309/*[clinic input]
5310_ssl.RAND_bytes
5311 n: int
5312 /
5313
5314Generate n cryptographically strong pseudo-random bytes.
5315[clinic start generated code]*/
5316
Victor Stinner99c8b162011-05-24 12:05:19 +02005317static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005318_ssl_RAND_bytes_impl(PyObject *module, int n)
5319/*[clinic end generated code: output=977da635e4838bc7 input=678ddf2872dfebfc]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02005320{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005321 return PySSL_RAND(n, 0);
Victor Stinner99c8b162011-05-24 12:05:19 +02005322}
5323
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005324/*[clinic input]
5325_ssl.RAND_pseudo_bytes
5326 n: int
5327 /
5328
5329Generate n pseudo-random bytes.
5330
5331Return a pair (bytes, is_cryptographic). is_cryptographic is True
5332if the bytes generated are cryptographically strong.
5333[clinic start generated code]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02005334
5335static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005336_ssl_RAND_pseudo_bytes_impl(PyObject *module, int n)
5337/*[clinic end generated code: output=b1509e937000e52d input=58312bd53f9bbdd0]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02005338{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005339 return PySSL_RAND(n, 1);
Victor Stinner99c8b162011-05-24 12:05:19 +02005340}
5341
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005342/*[clinic input]
5343_ssl.RAND_status
5344
5345Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.
5346
5347It is necessary to seed the PRNG with RAND_add() on some platforms before
5348using the ssl() function.
5349[clinic start generated code]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02005350
5351static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005352_ssl_RAND_status_impl(PyObject *module)
5353/*[clinic end generated code: output=7e0aaa2d39fdc1ad input=8a774b02d1dc81f3]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005354{
Christian Heimes217cfd12007-12-02 14:31:20 +00005355 return PyLong_FromLong(RAND_status());
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005356}
5357
Benjamin Petersonb8a2f512016-07-06 23:55:15 -07005358#ifndef OPENSSL_NO_EGD
Christian Heimesa5d07652016-09-24 10:48:05 +02005359/* LCOV_EXCL_START */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005360/*[clinic input]
5361_ssl.RAND_egd
5362 path: object(converter="PyUnicode_FSConverter")
5363 /
5364
5365Queries the entropy gather daemon (EGD) on the socket named by 'path'.
5366
5367Returns number of bytes read. Raises SSLError if connection to EGD
5368fails or if it does not provide enough data to seed PRNG.
5369[clinic start generated code]*/
5370
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005371static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005372_ssl_RAND_egd_impl(PyObject *module, PyObject *path)
5373/*[clinic end generated code: output=02a67c7c367f52fa input=1aeb7eb948312195]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005374{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005375 int bytes = RAND_egd(PyBytes_AsString(path));
Victor Stinnerf9faaad2010-05-16 21:36:37 +00005376 Py_DECREF(path);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005377 if (bytes == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00005378 PyErr_SetString(PySSLErrorObject,
5379 "EGD connection failed or EGD did not return "
5380 "enough data to seed the PRNG");
5381 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005382 }
Christian Heimes217cfd12007-12-02 14:31:20 +00005383 return PyLong_FromLong(bytes);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005384}
Christian Heimesa5d07652016-09-24 10:48:05 +02005385/* LCOV_EXCL_STOP */
Benjamin Petersonb8a2f512016-07-06 23:55:15 -07005386#endif /* OPENSSL_NO_EGD */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005387
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005388
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005389
5390/*[clinic input]
5391_ssl.get_default_verify_paths
5392
5393Return search paths and environment vars that are used by SSLContext's set_default_verify_paths() to load default CAs.
5394
5395The values are 'cert_file_env', 'cert_file', 'cert_dir_env', 'cert_dir'.
5396[clinic start generated code]*/
Christian Heimes6d7ad132013-06-09 18:02:55 +02005397
5398static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005399_ssl_get_default_verify_paths_impl(PyObject *module)
5400/*[clinic end generated code: output=e5b62a466271928b input=5210c953d98c3eb5]*/
Christian Heimes6d7ad132013-06-09 18:02:55 +02005401{
5402 PyObject *ofile_env = NULL;
5403 PyObject *ofile = NULL;
5404 PyObject *odir_env = NULL;
5405 PyObject *odir = NULL;
5406
Benjamin Petersond113c962015-07-18 10:59:13 -07005407#define CONVERT(info, target) { \
Christian Heimes6d7ad132013-06-09 18:02:55 +02005408 const char *tmp = (info); \
5409 target = NULL; \
5410 if (!tmp) { Py_INCREF(Py_None); target = Py_None; } \
5411 else if ((target = PyUnicode_DecodeFSDefault(tmp)) == NULL) { \
5412 target = PyBytes_FromString(tmp); } \
5413 if (!target) goto error; \
Benjamin Peterson025a1fd2015-11-14 15:12:38 -08005414 }
Christian Heimes6d7ad132013-06-09 18:02:55 +02005415
Benjamin Petersond113c962015-07-18 10:59:13 -07005416 CONVERT(X509_get_default_cert_file_env(), ofile_env);
5417 CONVERT(X509_get_default_cert_file(), ofile);
5418 CONVERT(X509_get_default_cert_dir_env(), odir_env);
5419 CONVERT(X509_get_default_cert_dir(), odir);
5420#undef CONVERT
Christian Heimes6d7ad132013-06-09 18:02:55 +02005421
Christian Heimes200bb1b2013-06-14 15:14:29 +02005422 return Py_BuildValue("NNNN", ofile_env, ofile, odir_env, odir);
Christian Heimes6d7ad132013-06-09 18:02:55 +02005423
5424 error:
5425 Py_XDECREF(ofile_env);
5426 Py_XDECREF(ofile);
5427 Py_XDECREF(odir_env);
5428 Py_XDECREF(odir);
5429 return NULL;
5430}
5431
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005432static PyObject*
5433asn1obj2py(ASN1_OBJECT *obj)
5434{
5435 int nid;
5436 const char *ln, *sn;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005437
5438 nid = OBJ_obj2nid(obj);
5439 if (nid == NID_undef) {
5440 PyErr_Format(PyExc_ValueError, "Unknown object");
5441 return NULL;
5442 }
5443 sn = OBJ_nid2sn(nid);
5444 ln = OBJ_nid2ln(nid);
Serhiy Storchakae503ca52017-09-05 01:28:53 +03005445 return Py_BuildValue("issN", nid, sn, ln, _asn1obj2py(obj, 1));
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005446}
5447
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005448/*[clinic input]
5449_ssl.txt2obj
5450 txt: str
5451 name: bool = False
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005452
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005453Lookup NID, short name, long name and OID of an ASN1_OBJECT.
5454
5455By default objects are looked up by OID. With name=True short and
5456long name are also matched.
5457[clinic start generated code]*/
5458
5459static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005460_ssl_txt2obj_impl(PyObject *module, const char *txt, int name)
5461/*[clinic end generated code: output=c38e3991347079c1 input=1c1e7d0aa7c48602]*/
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005462{
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005463 PyObject *result = NULL;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005464 ASN1_OBJECT *obj;
5465
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005466 obj = OBJ_txt2obj(txt, name ? 0 : 1);
5467 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01005468 PyErr_Format(PyExc_ValueError, "unknown object '%.100s'", txt);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005469 return NULL;
5470 }
5471 result = asn1obj2py(obj);
5472 ASN1_OBJECT_free(obj);
5473 return result;
5474}
5475
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005476/*[clinic input]
5477_ssl.nid2obj
5478 nid: int
5479 /
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005480
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005481Lookup NID, short name, long name and OID of an ASN1_OBJECT by NID.
5482[clinic start generated code]*/
5483
5484static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005485_ssl_nid2obj_impl(PyObject *module, int nid)
5486/*[clinic end generated code: output=4a98ab691cd4f84a input=51787a3bee7d8f98]*/
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005487{
5488 PyObject *result = NULL;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005489 ASN1_OBJECT *obj;
5490
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005491 if (nid < NID_undef) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01005492 PyErr_SetString(PyExc_ValueError, "NID must be positive.");
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005493 return NULL;
5494 }
5495 obj = OBJ_nid2obj(nid);
5496 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01005497 PyErr_Format(PyExc_ValueError, "unknown NID %i", nid);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005498 return NULL;
5499 }
5500 result = asn1obj2py(obj);
5501 ASN1_OBJECT_free(obj);
5502 return result;
5503}
5504
Christian Heimes46bebee2013-06-09 19:03:31 +02005505#ifdef _MSC_VER
Christian Heimes44109d72013-11-22 01:51:30 +01005506
5507static PyObject*
5508certEncodingType(DWORD encodingType)
5509{
5510 static PyObject *x509_asn = NULL;
5511 static PyObject *pkcs_7_asn = NULL;
5512
5513 if (x509_asn == NULL) {
5514 x509_asn = PyUnicode_InternFromString("x509_asn");
5515 if (x509_asn == NULL)
5516 return NULL;
5517 }
5518 if (pkcs_7_asn == NULL) {
5519 pkcs_7_asn = PyUnicode_InternFromString("pkcs_7_asn");
5520 if (pkcs_7_asn == NULL)
5521 return NULL;
5522 }
5523 switch(encodingType) {
5524 case X509_ASN_ENCODING:
5525 Py_INCREF(x509_asn);
5526 return x509_asn;
5527 case PKCS_7_ASN_ENCODING:
5528 Py_INCREF(pkcs_7_asn);
5529 return pkcs_7_asn;
5530 default:
5531 return PyLong_FromLong(encodingType);
5532 }
5533}
5534
5535static PyObject*
5536parseKeyUsage(PCCERT_CONTEXT pCertCtx, DWORD flags)
5537{
5538 CERT_ENHKEY_USAGE *usage;
5539 DWORD size, error, i;
5540 PyObject *retval;
5541
5542 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, NULL, &size)) {
5543 error = GetLastError();
5544 if (error == CRYPT_E_NOT_FOUND) {
5545 Py_RETURN_TRUE;
5546 }
5547 return PyErr_SetFromWindowsErr(error);
5548 }
5549
5550 usage = (CERT_ENHKEY_USAGE*)PyMem_Malloc(size);
5551 if (usage == NULL) {
5552 return PyErr_NoMemory();
5553 }
5554
5555 /* Now get the actual enhanced usage property */
5556 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, usage, &size)) {
5557 PyMem_Free(usage);
5558 error = GetLastError();
5559 if (error == CRYPT_E_NOT_FOUND) {
5560 Py_RETURN_TRUE;
5561 }
5562 return PyErr_SetFromWindowsErr(error);
5563 }
Christian Heimes915cd3f2019-09-09 18:06:55 +02005564 retval = PyFrozenSet_New(NULL);
Christian Heimes44109d72013-11-22 01:51:30 +01005565 if (retval == NULL) {
5566 goto error;
5567 }
5568 for (i = 0; i < usage->cUsageIdentifier; ++i) {
5569 if (usage->rgpszUsageIdentifier[i]) {
5570 PyObject *oid;
5571 int err;
5572 oid = PyUnicode_FromString(usage->rgpszUsageIdentifier[i]);
5573 if (oid == NULL) {
5574 Py_CLEAR(retval);
5575 goto error;
5576 }
5577 err = PySet_Add(retval, oid);
5578 Py_DECREF(oid);
5579 if (err == -1) {
5580 Py_CLEAR(retval);
5581 goto error;
5582 }
5583 }
5584 }
5585 error:
5586 PyMem_Free(usage);
5587 return retval;
5588}
5589
kctherookied93fbbf2019-03-29 00:59:06 +07005590static HCERTSTORE
5591ssl_collect_certificates(const char *store_name)
5592{
5593/* this function collects the system certificate stores listed in
5594 * system_stores into a collection certificate store for being
5595 * enumerated. The store must be readable to be added to the
5596 * store collection.
5597 */
5598
5599 HCERTSTORE hCollectionStore = NULL, hSystemStore = NULL;
5600 static DWORD system_stores[] = {
5601 CERT_SYSTEM_STORE_LOCAL_MACHINE,
5602 CERT_SYSTEM_STORE_LOCAL_MACHINE_ENTERPRISE,
5603 CERT_SYSTEM_STORE_LOCAL_MACHINE_GROUP_POLICY,
5604 CERT_SYSTEM_STORE_CURRENT_USER,
5605 CERT_SYSTEM_STORE_CURRENT_USER_GROUP_POLICY,
5606 CERT_SYSTEM_STORE_SERVICES,
5607 CERT_SYSTEM_STORE_USERS};
5608 size_t i, storesAdded;
5609 BOOL result;
5610
5611 hCollectionStore = CertOpenStore(CERT_STORE_PROV_COLLECTION, 0,
5612 (HCRYPTPROV)NULL, 0, NULL);
5613 if (!hCollectionStore) {
5614 return NULL;
5615 }
5616 storesAdded = 0;
5617 for (i = 0; i < sizeof(system_stores) / sizeof(DWORD); i++) {
5618 hSystemStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0,
5619 (HCRYPTPROV)NULL,
5620 CERT_STORE_READONLY_FLAG |
5621 system_stores[i], store_name);
5622 if (hSystemStore) {
5623 result = CertAddStoreToCollection(hCollectionStore, hSystemStore,
5624 CERT_PHYSICAL_STORE_ADD_ENABLE_FLAG, 0);
5625 if (result) {
5626 ++storesAdded;
5627 }
neoneneed701292019-09-09 21:33:43 +09005628 CertCloseStore(hSystemStore, 0); /* flag must be 0 */
kctherookied93fbbf2019-03-29 00:59:06 +07005629 }
5630 }
5631 if (storesAdded == 0) {
5632 CertCloseStore(hCollectionStore, CERT_CLOSE_STORE_FORCE_FLAG);
5633 return NULL;
5634 }
5635
5636 return hCollectionStore;
5637}
5638
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005639/*[clinic input]
5640_ssl.enum_certificates
5641 store_name: str
5642
5643Retrieve certificates from Windows' cert store.
5644
5645store_name may be one of 'CA', 'ROOT' or 'MY'. The system may provide
5646more cert storages, too. The function returns a list of (bytes,
5647encoding_type, trust) tuples. The encoding_type flag can be interpreted
5648with X509_ASN_ENCODING or PKCS_7_ASN_ENCODING. The trust setting is either
5649a set of OIDs or the boolean True.
5650[clinic start generated code]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00005651
Christian Heimes46bebee2013-06-09 19:03:31 +02005652static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005653_ssl_enum_certificates_impl(PyObject *module, const char *store_name)
5654/*[clinic end generated code: output=5134dc8bb3a3c893 input=915f60d70461ea4e]*/
Christian Heimes46bebee2013-06-09 19:03:31 +02005655{
kctherookied93fbbf2019-03-29 00:59:06 +07005656 HCERTSTORE hCollectionStore = NULL;
Christian Heimes44109d72013-11-22 01:51:30 +01005657 PCCERT_CONTEXT pCertCtx = NULL;
5658 PyObject *keyusage = NULL, *cert = NULL, *enc = NULL, *tup = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02005659 PyObject *result = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02005660
Christian Heimes915cd3f2019-09-09 18:06:55 +02005661 result = PySet_New(NULL);
Christian Heimes44109d72013-11-22 01:51:30 +01005662 if (result == NULL) {
5663 return NULL;
5664 }
kctherookied93fbbf2019-03-29 00:59:06 +07005665 hCollectionStore = ssl_collect_certificates(store_name);
5666 if (hCollectionStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02005667 Py_DECREF(result);
5668 return PyErr_SetFromWindowsErr(GetLastError());
5669 }
5670
kctherookied93fbbf2019-03-29 00:59:06 +07005671 while (pCertCtx = CertEnumCertificatesInStore(hCollectionStore, pCertCtx)) {
Christian Heimes44109d72013-11-22 01:51:30 +01005672 cert = PyBytes_FromStringAndSize((const char*)pCertCtx->pbCertEncoded,
5673 pCertCtx->cbCertEncoded);
5674 if (!cert) {
5675 Py_CLEAR(result);
5676 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02005677 }
Christian Heimes44109d72013-11-22 01:51:30 +01005678 if ((enc = certEncodingType(pCertCtx->dwCertEncodingType)) == NULL) {
5679 Py_CLEAR(result);
5680 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02005681 }
Christian Heimes44109d72013-11-22 01:51:30 +01005682 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG);
5683 if (keyusage == Py_True) {
5684 Py_DECREF(keyusage);
5685 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_EXT_ONLY_ENHKEY_USAGE_FLAG);
Christian Heimes46bebee2013-06-09 19:03:31 +02005686 }
Christian Heimes44109d72013-11-22 01:51:30 +01005687 if (keyusage == NULL) {
5688 Py_CLEAR(result);
5689 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02005690 }
Christian Heimes44109d72013-11-22 01:51:30 +01005691 if ((tup = PyTuple_New(3)) == NULL) {
5692 Py_CLEAR(result);
5693 break;
5694 }
5695 PyTuple_SET_ITEM(tup, 0, cert);
5696 cert = NULL;
5697 PyTuple_SET_ITEM(tup, 1, enc);
5698 enc = NULL;
5699 PyTuple_SET_ITEM(tup, 2, keyusage);
5700 keyusage = NULL;
Christian Heimes915cd3f2019-09-09 18:06:55 +02005701 if (PySet_Add(result, tup) == -1) {
5702 Py_CLEAR(result);
5703 Py_CLEAR(tup);
5704 break;
Christian Heimes44109d72013-11-22 01:51:30 +01005705 }
5706 Py_CLEAR(tup);
5707 }
5708 if (pCertCtx) {
5709 /* loop ended with an error, need to clean up context manually */
5710 CertFreeCertificateContext(pCertCtx);
Christian Heimes46bebee2013-06-09 19:03:31 +02005711 }
5712
5713 /* In error cases cert, enc and tup may not be NULL */
5714 Py_XDECREF(cert);
5715 Py_XDECREF(enc);
Christian Heimes44109d72013-11-22 01:51:30 +01005716 Py_XDECREF(keyusage);
Christian Heimes46bebee2013-06-09 19:03:31 +02005717 Py_XDECREF(tup);
5718
kctherookied93fbbf2019-03-29 00:59:06 +07005719 /* CERT_CLOSE_STORE_FORCE_FLAG forces freeing of memory for all contexts
5720 associated with the store, in this case our collection store and the
5721 associated system stores. */
5722 if (!CertCloseStore(hCollectionStore, CERT_CLOSE_STORE_FORCE_FLAG)) {
Christian Heimes46bebee2013-06-09 19:03:31 +02005723 /* This error case might shadow another exception.*/
Christian Heimes44109d72013-11-22 01:51:30 +01005724 Py_XDECREF(result);
5725 return PyErr_SetFromWindowsErr(GetLastError());
5726 }
kctherookied93fbbf2019-03-29 00:59:06 +07005727
Christian Heimes915cd3f2019-09-09 18:06:55 +02005728 /* convert set to list */
5729 if (result == NULL) {
5730 return NULL;
5731 } else {
5732 PyObject *lst = PySequence_List(result);
5733 Py_DECREF(result);
5734 return lst;
5735 }
Christian Heimes44109d72013-11-22 01:51:30 +01005736}
5737
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005738/*[clinic input]
5739_ssl.enum_crls
5740 store_name: str
5741
5742Retrieve CRLs from Windows' cert store.
5743
5744store_name may be one of 'CA', 'ROOT' or 'MY'. The system may provide
5745more cert storages, too. The function returns a list of (bytes,
5746encoding_type) tuples. The encoding_type flag can be interpreted with
5747X509_ASN_ENCODING or PKCS_7_ASN_ENCODING.
5748[clinic start generated code]*/
Christian Heimes44109d72013-11-22 01:51:30 +01005749
5750static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005751_ssl_enum_crls_impl(PyObject *module, const char *store_name)
5752/*[clinic end generated code: output=bce467f60ccd03b6 input=a1f1d7629f1c5d3d]*/
Christian Heimes44109d72013-11-22 01:51:30 +01005753{
kctherookied93fbbf2019-03-29 00:59:06 +07005754 HCERTSTORE hCollectionStore = NULL;
Christian Heimes44109d72013-11-22 01:51:30 +01005755 PCCRL_CONTEXT pCrlCtx = NULL;
5756 PyObject *crl = NULL, *enc = NULL, *tup = NULL;
5757 PyObject *result = NULL;
5758
Christian Heimes915cd3f2019-09-09 18:06:55 +02005759 result = PySet_New(NULL);
Christian Heimes44109d72013-11-22 01:51:30 +01005760 if (result == NULL) {
5761 return NULL;
5762 }
kctherookied93fbbf2019-03-29 00:59:06 +07005763 hCollectionStore = ssl_collect_certificates(store_name);
5764 if (hCollectionStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02005765 Py_DECREF(result);
5766 return PyErr_SetFromWindowsErr(GetLastError());
5767 }
Christian Heimes44109d72013-11-22 01:51:30 +01005768
kctherookied93fbbf2019-03-29 00:59:06 +07005769 while (pCrlCtx = CertEnumCRLsInStore(hCollectionStore, pCrlCtx)) {
Christian Heimes44109d72013-11-22 01:51:30 +01005770 crl = PyBytes_FromStringAndSize((const char*)pCrlCtx->pbCrlEncoded,
5771 pCrlCtx->cbCrlEncoded);
5772 if (!crl) {
5773 Py_CLEAR(result);
5774 break;
5775 }
5776 if ((enc = certEncodingType(pCrlCtx->dwCertEncodingType)) == NULL) {
5777 Py_CLEAR(result);
5778 break;
5779 }
5780 if ((tup = PyTuple_New(2)) == NULL) {
5781 Py_CLEAR(result);
5782 break;
5783 }
5784 PyTuple_SET_ITEM(tup, 0, crl);
5785 crl = NULL;
5786 PyTuple_SET_ITEM(tup, 1, enc);
5787 enc = NULL;
5788
Christian Heimes915cd3f2019-09-09 18:06:55 +02005789 if (PySet_Add(result, tup) == -1) {
5790 Py_CLEAR(result);
5791 Py_CLEAR(tup);
5792 break;
Christian Heimes44109d72013-11-22 01:51:30 +01005793 }
5794 Py_CLEAR(tup);
Christian Heimes46bebee2013-06-09 19:03:31 +02005795 }
Christian Heimes44109d72013-11-22 01:51:30 +01005796 if (pCrlCtx) {
5797 /* loop ended with an error, need to clean up context manually */
5798 CertFreeCRLContext(pCrlCtx);
5799 }
5800
5801 /* In error cases cert, enc and tup may not be NULL */
5802 Py_XDECREF(crl);
5803 Py_XDECREF(enc);
5804 Py_XDECREF(tup);
5805
kctherookied93fbbf2019-03-29 00:59:06 +07005806 /* CERT_CLOSE_STORE_FORCE_FLAG forces freeing of memory for all contexts
5807 associated with the store, in this case our collection store and the
5808 associated system stores. */
5809 if (!CertCloseStore(hCollectionStore, CERT_CLOSE_STORE_FORCE_FLAG)) {
Christian Heimes44109d72013-11-22 01:51:30 +01005810 /* This error case might shadow another exception.*/
5811 Py_XDECREF(result);
5812 return PyErr_SetFromWindowsErr(GetLastError());
5813 }
Christian Heimes915cd3f2019-09-09 18:06:55 +02005814 /* convert set to list */
5815 if (result == NULL) {
5816 return NULL;
5817 } else {
5818 PyObject *lst = PySequence_List(result);
5819 Py_DECREF(result);
5820 return lst;
5821 }
Christian Heimes46bebee2013-06-09 19:03:31 +02005822}
Christian Heimes44109d72013-11-22 01:51:30 +01005823
5824#endif /* _MSC_VER */
Bill Janssen40a0f662008-08-12 16:56:25 +00005825
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005826/* List of functions exported by this module. */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005827static PyMethodDef PySSL_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005828 _SSL__TEST_DECODE_CERT_METHODDEF
5829 _SSL_RAND_ADD_METHODDEF
5830 _SSL_RAND_BYTES_METHODDEF
5831 _SSL_RAND_PSEUDO_BYTES_METHODDEF
5832 _SSL_RAND_EGD_METHODDEF
5833 _SSL_RAND_STATUS_METHODDEF
5834 _SSL_GET_DEFAULT_VERIFY_PATHS_METHODDEF
5835 _SSL_ENUM_CERTIFICATES_METHODDEF
5836 _SSL_ENUM_CRLS_METHODDEF
5837 _SSL_TXT2OBJ_METHODDEF
5838 _SSL_NID2OBJ_METHODDEF
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005839 {NULL, NULL} /* Sentinel */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005840};
5841
5842
Christian Heimes598894f2016-09-05 23:19:05 +02005843#ifdef HAVE_OPENSSL_CRYPTO_LOCK
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005844
5845/* an implementation of OpenSSL threading operations in terms
Christian Heimes598894f2016-09-05 23:19:05 +02005846 * of the Python C thread library
5847 * Only used up to 1.0.2. OpenSSL 1.1.0+ has its own locking code.
5848 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005849
5850static PyThread_type_lock *_ssl_locks = NULL;
5851
Christian Heimes4d98ca92013-08-19 17:36:29 +02005852#if OPENSSL_VERSION_NUMBER >= 0x10000000
5853/* use new CRYPTO_THREADID API. */
5854static void
5855_ssl_threadid_callback(CRYPTO_THREADID *id)
5856{
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +02005857 CRYPTO_THREADID_set_numeric(id, PyThread_get_thread_ident());
Christian Heimes4d98ca92013-08-19 17:36:29 +02005858}
5859#else
5860/* deprecated CRYPTO_set_id_callback() API. */
5861static unsigned long
5862_ssl_thread_id_function (void) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005863 return PyThread_get_thread_ident();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005864}
Christian Heimes4d98ca92013-08-19 17:36:29 +02005865#endif
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005866
Bill Janssen6e027db2007-11-15 22:23:56 +00005867static void _ssl_thread_locking_function
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005868 (int mode, int n, const char *file, int line) {
5869 /* this function is needed to perform locking on shared data
5870 structures. (Note that OpenSSL uses a number of global data
5871 structures that will be implicitly shared whenever multiple
5872 threads use OpenSSL.) Multi-threaded applications will
5873 crash at random if it is not set.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005874
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005875 locking_function() must be able to handle up to
5876 CRYPTO_num_locks() different mutex locks. It sets the n-th
5877 lock if mode & CRYPTO_LOCK, and releases it otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005878
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005879 file and line are the file number of the function setting the
5880 lock. They can be useful for debugging.
5881 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005882
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005883 if ((_ssl_locks == NULL) ||
5884 (n < 0) || ((unsigned)n >= _ssl_locks_count))
5885 return;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005886
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005887 if (mode & CRYPTO_LOCK) {
5888 PyThread_acquire_lock(_ssl_locks[n], 1);
5889 } else {
5890 PyThread_release_lock(_ssl_locks[n]);
5891 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005892}
5893
5894static int _setup_ssl_threads(void) {
5895
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005896 unsigned int i;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005897
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005898 if (_ssl_locks == NULL) {
5899 _ssl_locks_count = CRYPTO_num_locks();
Christian Heimesf6365e32016-09-13 20:48:13 +02005900 _ssl_locks = PyMem_Calloc(_ssl_locks_count,
5901 sizeof(PyThread_type_lock));
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02005902 if (_ssl_locks == NULL) {
5903 PyErr_NoMemory();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005904 return 0;
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02005905 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005906 for (i = 0; i < _ssl_locks_count; i++) {
5907 _ssl_locks[i] = PyThread_allocate_lock();
5908 if (_ssl_locks[i] == NULL) {
5909 unsigned int j;
5910 for (j = 0; j < i; j++) {
5911 PyThread_free_lock(_ssl_locks[j]);
5912 }
Victor Stinnerb6404912013-07-07 16:21:41 +02005913 PyMem_Free(_ssl_locks);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005914 return 0;
5915 }
5916 }
5917 CRYPTO_set_locking_callback(_ssl_thread_locking_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02005918#if OPENSSL_VERSION_NUMBER >= 0x10000000
5919 CRYPTO_THREADID_set_callback(_ssl_threadid_callback);
5920#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005921 CRYPTO_set_id_callback(_ssl_thread_id_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02005922#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005923 }
5924 return 1;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005925}
5926
Antoine Pitroua6a4dc82017-09-07 18:56:24 +02005927#endif /* HAVE_OPENSSL_CRYPTO_LOCK for OpenSSL < 1.1.0 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005928
Christian Heimes5c36da72020-11-20 09:40:12 +01005929static int
5930sslmodule_init_types(PyObject *module)
5931{
5932 PySSLContext_Type = (PyTypeObject *)PyType_FromModuleAndSpec(
5933 module, &PySSLContext_spec, NULL
5934 );
5935 if (PySSLContext_Type == NULL)
5936 return -1;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005937
Christian Heimes5c36da72020-11-20 09:40:12 +01005938 PySSLSocket_Type = (PyTypeObject *)PyType_FromModuleAndSpec(
5939 module, &PySSLSocket_spec, NULL
5940 );
5941 if (PySSLSocket_Type == NULL)
5942 return -1;
Martin v. Löwis1a214512008-06-11 05:26:20 +00005943
Christian Heimes5c36da72020-11-20 09:40:12 +01005944 PySSLMemoryBIO_Type = (PyTypeObject *)PyType_FromModuleAndSpec(
5945 module, &PySSLMemoryBIO_spec, NULL
5946 );
5947 if (PySSLMemoryBIO_Type == NULL)
5948 return -1;
Martin v. Löwis1a214512008-06-11 05:26:20 +00005949
Christian Heimes5c36da72020-11-20 09:40:12 +01005950 PySSLSession_Type = (PyTypeObject *)PyType_FromModuleAndSpec(
5951 module, &PySSLSession_spec, NULL
5952 );
5953 if (PySSLSession_Type == NULL)
5954 return -1;
5955
5956 if (PyModule_AddType(module, PySSLContext_Type))
5957 return -1;
5958 if (PyModule_AddType(module, PySSLSocket_Type))
5959 return -1;
5960 if (PyModule_AddType(module, PySSLMemoryBIO_Type))
5961 return -1;
5962 if (PyModule_AddType(module, PySSLSession_Type))
5963 return -1;
5964
5965 return 0;
5966}
5967
5968static int
5969sslmodule_init_exceptions(PyObject *module)
5970{
5971 PyObject *bases = NULL;
5972
5973#define add_exception(exc, name, doc, base) \
5974do { \
5975 (exc) = PyErr_NewExceptionWithDoc("ssl." name, (doc), (base), NULL); \
5976 if ((exc) == NULL) goto error; \
5977 if (PyModule_AddObjectRef(module, name, exc) < 0) goto error; \
5978} while(0)
5979
Serhiy Storchaka686c2032020-11-22 13:25:02 +02005980 PySSLErrorObject = PyType_FromSpecWithBases(&sslerror_type_spec, PyExc_OSError);
Christian Heimes5c36da72020-11-20 09:40:12 +01005981 if (PySSLErrorObject == NULL) {
5982 goto error;
5983 }
5984 if (PyModule_AddObjectRef(module, "SSLError", PySSLErrorObject) < 0) {
5985 goto error;
5986 }
5987
5988 /* ssl.CertificateError used to be a subclass of ValueError */
5989 bases = PyTuple_Pack(2, PySSLErrorObject, PyExc_ValueError);
5990 if (bases == NULL) {
5991 goto error;
5992 }
5993 add_exception(
5994 PySSLCertVerificationErrorObject,
5995 "SSLCertVerificationError",
5996 SSLCertVerificationError_doc,
5997 bases
5998 );
5999 Py_CLEAR(bases);
6000
6001 add_exception(
6002 PySSLZeroReturnErrorObject,
6003 "SSLZeroReturnError",
6004 SSLZeroReturnError_doc,
6005 PySSLErrorObject
6006 );
6007
6008 add_exception(
6009 PySSLWantWriteErrorObject,
6010 "SSLWantWriteError",
6011 SSLWantWriteError_doc,
6012 PySSLErrorObject
6013 );
6014
6015 add_exception(
6016 PySSLWantReadErrorObject,
6017 "SSLWantReadError",
6018 SSLWantReadError_doc,
6019 PySSLErrorObject
6020 );
6021
6022 add_exception(
6023 PySSLSyscallErrorObject,
6024 "SSLSyscallError",
6025 SSLSyscallError_doc,
6026 PySSLErrorObject
6027 );
6028
6029 add_exception(
6030 PySSLEOFErrorObject,
6031 "SSLEOFError",
6032 SSLEOFError_doc,
6033 PySSLErrorObject
6034 );
6035#undef add_exception
6036
6037 return 0;
6038 error:
6039 Py_XDECREF(bases);
6040 return -1;
6041}
6042
6043static int
6044sslmodule_init_socketapi(PyObject *module)
6045{
6046 PySocketModule_APIObject *socket_api;
6047
6048 /* Load _socket module and its C API */
6049 socket_api = PySocketModule_ImportModuleAndAPI();
6050 if (socket_api == NULL)
6051 return -1;
6052 PySocketModule = *socket_api;
6053
6054 return 0;
6055}
6056
6057static int
6058sslmodule_init_errorcodes(PyObject *module)
6059{
6060 struct py_ssl_error_code *errcode;
6061 struct py_ssl_library_code *libcode;
6062
6063 /* Mappings for error codes */
6064 err_codes_to_names = PyDict_New();
6065 if (err_codes_to_names == NULL)
6066 return -1;
6067 err_names_to_codes = PyDict_New();
6068 if (err_names_to_codes == NULL)
6069 return -1;
6070 lib_codes_to_names = PyDict_New();
6071 if (lib_codes_to_names == NULL)
6072 return -1;
6073
6074 errcode = error_codes;
6075 while (errcode->mnemonic != NULL) {
6076 PyObject *mnemo, *key;
6077 mnemo = PyUnicode_FromString(errcode->mnemonic);
6078 key = Py_BuildValue("ii", errcode->library, errcode->reason);
6079 if (mnemo == NULL || key == NULL)
6080 return -1;
6081 if (PyDict_SetItem(err_codes_to_names, key, mnemo))
6082 return -1;
6083 if (PyDict_SetItem(err_names_to_codes, mnemo, key))
6084 return -1;
6085 Py_DECREF(key);
6086 Py_DECREF(mnemo);
6087 errcode++;
6088 }
6089
6090 libcode = library_codes;
6091 while (libcode->library != NULL) {
6092 PyObject *mnemo, *key;
6093 key = PyLong_FromLong(libcode->code);
6094 mnemo = PyUnicode_FromString(libcode->library);
6095 if (key == NULL || mnemo == NULL)
6096 return -1;
6097 if (PyDict_SetItem(lib_codes_to_names, key, mnemo))
6098 return -1;
6099 Py_DECREF(key);
6100 Py_DECREF(mnemo);
6101 libcode++;
6102 }
6103
6104 if (PyModule_AddObject(module, "err_codes_to_names", err_codes_to_names))
6105 return -1;
6106 if (PyModule_AddObject(module, "err_names_to_codes", err_names_to_codes))
6107 return -1;
6108 if (PyModule_AddObject(module, "lib_codes_to_names", lib_codes_to_names))
6109 return -1;
6110
6111 return 0;
6112}
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02006113
6114static void
6115parse_openssl_version(unsigned long libver,
6116 unsigned int *major, unsigned int *minor,
6117 unsigned int *fix, unsigned int *patch,
6118 unsigned int *status)
6119{
6120 *status = libver & 0xF;
6121 libver >>= 4;
6122 *patch = libver & 0xFF;
6123 libver >>= 8;
6124 *fix = libver & 0xFF;
6125 libver >>= 8;
6126 *minor = libver & 0xFF;
6127 libver >>= 8;
6128 *major = libver & 0xFF;
6129}
6130
Christian Heimes5c36da72020-11-20 09:40:12 +01006131static int
6132sslmodule_init_versioninfo(PyObject *m)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00006133{
Christian Heimes5c36da72020-11-20 09:40:12 +01006134 PyObject *r;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006135 unsigned long libver;
6136 unsigned int major, minor, fix, patch, status;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00006137
Christian Heimes5c36da72020-11-20 09:40:12 +01006138 /* OpenSSL version */
6139 /* SSLeay() gives us the version of the library linked against,
6140 which could be different from the headers version.
6141 */
6142 libver = OpenSSL_version_num();
6143 r = PyLong_FromUnsignedLong(libver);
6144 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r))
6145 return -1;
Christian Heimes99a65702016-09-10 23:44:53 +02006146
Christian Heimes5c36da72020-11-20 09:40:12 +01006147 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
6148 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
6149 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r))
6150 return -1;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00006151
Christian Heimes5c36da72020-11-20 09:40:12 +01006152 r = PyUnicode_FromString(OpenSSL_version(OPENSSL_VERSION));
6153 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r))
6154 return -1;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00006155
Christian Heimes5c36da72020-11-20 09:40:12 +01006156 libver = OPENSSL_VERSION_NUMBER;
6157 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
6158 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
6159 if (r == NULL || PyModule_AddObject(m, "_OPENSSL_API_VERSION", r))
6160 return -1;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00006161
Christian Heimes5c36da72020-11-20 09:40:12 +01006162 return 0;
6163}
Christian Heimesc941e622017-09-05 15:47:11 +02006164
Christian Heimes5c36da72020-11-20 09:40:12 +01006165static int
6166sslmodule_init_constants(PyObject *m)
6167{
Christian Heimes892d66e2018-01-29 14:10:18 +01006168 PyModule_AddStringConstant(m, "_DEFAULT_CIPHERS",
6169 PY_SSL_DEFAULT_CIPHER_STRING);
6170
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006171 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
6172 PY_SSL_ERROR_ZERO_RETURN);
6173 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
6174 PY_SSL_ERROR_WANT_READ);
6175 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
6176 PY_SSL_ERROR_WANT_WRITE);
6177 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
6178 PY_SSL_ERROR_WANT_X509_LOOKUP);
6179 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
6180 PY_SSL_ERROR_SYSCALL);
6181 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
6182 PY_SSL_ERROR_SSL);
6183 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
6184 PY_SSL_ERROR_WANT_CONNECT);
6185 /* non ssl.h errorcodes */
6186 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
6187 PY_SSL_ERROR_EOF);
6188 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
6189 PY_SSL_ERROR_INVALID_ERROR_CODE);
6190 /* cert requirements */
6191 PyModule_AddIntConstant(m, "CERT_NONE",
6192 PY_SSL_CERT_NONE);
6193 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
6194 PY_SSL_CERT_OPTIONAL);
6195 PyModule_AddIntConstant(m, "CERT_REQUIRED",
6196 PY_SSL_CERT_REQUIRED);
Christian Heimes22587792013-11-21 23:56:13 +01006197 /* CRL verification for verification_flags */
6198 PyModule_AddIntConstant(m, "VERIFY_DEFAULT",
6199 0);
6200 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_LEAF",
6201 X509_V_FLAG_CRL_CHECK);
6202 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_CHAIN",
6203 X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
6204 PyModule_AddIntConstant(m, "VERIFY_X509_STRICT",
6205 X509_V_FLAG_X509_STRICT);
Chris Burre0b4aa02021-03-18 09:24:01 +01006206 PyModule_AddIntConstant(m, "VERIFY_ALLOW_PROXY_CERTS",
6207 X509_V_FLAG_ALLOW_PROXY_CERTS);
Benjamin Peterson990fcaa2015-03-04 22:49:41 -05006208#ifdef X509_V_FLAG_TRUSTED_FIRST
6209 PyModule_AddIntConstant(m, "VERIFY_X509_TRUSTED_FIRST",
6210 X509_V_FLAG_TRUSTED_FIRST);
6211#endif
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00006212
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01006213 /* Alert Descriptions from ssl.h */
6214 /* note RESERVED constants no longer intended for use have been removed */
6215 /* http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-6 */
6216
6217#define ADD_AD_CONSTANT(s) \
6218 PyModule_AddIntConstant(m, "ALERT_DESCRIPTION_"#s, \
6219 SSL_AD_##s)
6220
6221 ADD_AD_CONSTANT(CLOSE_NOTIFY);
6222 ADD_AD_CONSTANT(UNEXPECTED_MESSAGE);
6223 ADD_AD_CONSTANT(BAD_RECORD_MAC);
6224 ADD_AD_CONSTANT(RECORD_OVERFLOW);
6225 ADD_AD_CONSTANT(DECOMPRESSION_FAILURE);
6226 ADD_AD_CONSTANT(HANDSHAKE_FAILURE);
6227 ADD_AD_CONSTANT(BAD_CERTIFICATE);
6228 ADD_AD_CONSTANT(UNSUPPORTED_CERTIFICATE);
6229 ADD_AD_CONSTANT(CERTIFICATE_REVOKED);
6230 ADD_AD_CONSTANT(CERTIFICATE_EXPIRED);
6231 ADD_AD_CONSTANT(CERTIFICATE_UNKNOWN);
6232 ADD_AD_CONSTANT(ILLEGAL_PARAMETER);
6233 ADD_AD_CONSTANT(UNKNOWN_CA);
6234 ADD_AD_CONSTANT(ACCESS_DENIED);
6235 ADD_AD_CONSTANT(DECODE_ERROR);
6236 ADD_AD_CONSTANT(DECRYPT_ERROR);
6237 ADD_AD_CONSTANT(PROTOCOL_VERSION);
6238 ADD_AD_CONSTANT(INSUFFICIENT_SECURITY);
6239 ADD_AD_CONSTANT(INTERNAL_ERROR);
6240 ADD_AD_CONSTANT(USER_CANCELLED);
6241 ADD_AD_CONSTANT(NO_RENEGOTIATION);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01006242 /* Not all constants are in old OpenSSL versions */
Antoine Pitrou912fbff2013-03-30 16:29:32 +01006243#ifdef SSL_AD_UNSUPPORTED_EXTENSION
6244 ADD_AD_CONSTANT(UNSUPPORTED_EXTENSION);
6245#endif
6246#ifdef SSL_AD_CERTIFICATE_UNOBTAINABLE
6247 ADD_AD_CONSTANT(CERTIFICATE_UNOBTAINABLE);
6248#endif
6249#ifdef SSL_AD_UNRECOGNIZED_NAME
6250 ADD_AD_CONSTANT(UNRECOGNIZED_NAME);
6251#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01006252#ifdef SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE
6253 ADD_AD_CONSTANT(BAD_CERTIFICATE_STATUS_RESPONSE);
6254#endif
6255#ifdef SSL_AD_BAD_CERTIFICATE_HASH_VALUE
6256 ADD_AD_CONSTANT(BAD_CERTIFICATE_HASH_VALUE);
6257#endif
6258#ifdef SSL_AD_UNKNOWN_PSK_IDENTITY
6259 ADD_AD_CONSTANT(UNKNOWN_PSK_IDENTITY);
6260#endif
6261
6262#undef ADD_AD_CONSTANT
6263
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006264 /* protocol versions */
Victor Stinner3de49192011-05-09 00:42:58 +02006265#ifndef OPENSSL_NO_SSL2
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006266 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
6267 PY_SSL_VERSION_SSL2);
Victor Stinner3de49192011-05-09 00:42:58 +02006268#endif
Benjamin Petersone32467c2014-12-05 21:59:35 -05006269#ifndef OPENSSL_NO_SSL3
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006270 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
6271 PY_SSL_VERSION_SSL3);
Benjamin Petersone32467c2014-12-05 21:59:35 -05006272#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006273 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
Christian Heimes598894f2016-09-05 23:19:05 +02006274 PY_SSL_VERSION_TLS);
6275 PyModule_AddIntConstant(m, "PROTOCOL_TLS",
6276 PY_SSL_VERSION_TLS);
Christian Heimes5fe668c2016-09-12 00:01:11 +02006277 PyModule_AddIntConstant(m, "PROTOCOL_TLS_CLIENT",
6278 PY_SSL_VERSION_TLS_CLIENT);
6279 PyModule_AddIntConstant(m, "PROTOCOL_TLS_SERVER",
6280 PY_SSL_VERSION_TLS_SERVER);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006281 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
6282 PY_SSL_VERSION_TLS1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01006283 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_1",
6284 PY_SSL_VERSION_TLS1_1);
6285 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_2",
6286 PY_SSL_VERSION_TLS1_2);
Antoine Pitrou04f6a322010-04-05 21:40:07 +00006287
Antoine Pitroub5218772010-05-21 09:56:06 +00006288 /* protocol options */
Antoine Pitrou3f366312012-01-27 09:50:45 +01006289 PyModule_AddIntConstant(m, "OP_ALL",
6290 SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
Antoine Pitroub5218772010-05-21 09:56:06 +00006291 PyModule_AddIntConstant(m, "OP_NO_SSLv2", SSL_OP_NO_SSLv2);
6292 PyModule_AddIntConstant(m, "OP_NO_SSLv3", SSL_OP_NO_SSLv3);
6293 PyModule_AddIntConstant(m, "OP_NO_TLSv1", SSL_OP_NO_TLSv1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01006294 PyModule_AddIntConstant(m, "OP_NO_TLSv1_1", SSL_OP_NO_TLSv1_1);
6295 PyModule_AddIntConstant(m, "OP_NO_TLSv1_2", SSL_OP_NO_TLSv1_2);
Christian Heimescb5b68a2017-09-07 18:07:00 -07006296#ifdef SSL_OP_NO_TLSv1_3
6297 PyModule_AddIntConstant(m, "OP_NO_TLSv1_3", SSL_OP_NO_TLSv1_3);
6298#else
6299 PyModule_AddIntConstant(m, "OP_NO_TLSv1_3", 0);
6300#endif
Antoine Pitrou6db49442011-12-19 13:27:11 +01006301 PyModule_AddIntConstant(m, "OP_CIPHER_SERVER_PREFERENCE",
6302 SSL_OP_CIPHER_SERVER_PREFERENCE);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01006303 PyModule_AddIntConstant(m, "OP_SINGLE_DH_USE", SSL_OP_SINGLE_DH_USE);
Christian Heimes99a65702016-09-10 23:44:53 +02006304 PyModule_AddIntConstant(m, "OP_NO_TICKET", SSL_OP_NO_TICKET);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01006305#ifdef SSL_OP_SINGLE_ECDH_USE
Antoine Pitrou923df6f2011-12-19 17:16:51 +01006306 PyModule_AddIntConstant(m, "OP_SINGLE_ECDH_USE", SSL_OP_SINGLE_ECDH_USE);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01006307#endif
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01006308#ifdef SSL_OP_NO_COMPRESSION
6309 PyModule_AddIntConstant(m, "OP_NO_COMPRESSION",
6310 SSL_OP_NO_COMPRESSION);
6311#endif
Christian Heimes05d9fe32018-02-27 08:55:39 +01006312#ifdef SSL_OP_ENABLE_MIDDLEBOX_COMPAT
6313 PyModule_AddIntConstant(m, "OP_ENABLE_MIDDLEBOX_COMPAT",
6314 SSL_OP_ENABLE_MIDDLEBOX_COMPAT);
6315#endif
Christian Heimes67c48012018-05-15 16:25:40 -04006316#ifdef SSL_OP_NO_RENEGOTIATION
6317 PyModule_AddIntConstant(m, "OP_NO_RENEGOTIATION",
6318 SSL_OP_NO_RENEGOTIATION);
6319#endif
Christian Heimes6f37ebc2021-04-09 17:59:21 +02006320#ifdef SSL_OP_IGNORE_UNEXPECTED_EOF
6321 PyModule_AddIntConstant(m, "OP_IGNORE_UNEXPECTED_EOF",
6322 SSL_OP_IGNORE_UNEXPECTED_EOF);
6323#endif
Antoine Pitroub5218772010-05-21 09:56:06 +00006324
Christian Heimes61d478c2018-01-27 15:51:38 +01006325#ifdef X509_CHECK_FLAG_ALWAYS_CHECK_SUBJECT
6326 PyModule_AddIntConstant(m, "HOSTFLAG_ALWAYS_CHECK_SUBJECT",
6327 X509_CHECK_FLAG_ALWAYS_CHECK_SUBJECT);
6328#endif
6329#ifdef X509_CHECK_FLAG_NEVER_CHECK_SUBJECT
6330 PyModule_AddIntConstant(m, "HOSTFLAG_NEVER_CHECK_SUBJECT",
6331 X509_CHECK_FLAG_NEVER_CHECK_SUBJECT);
6332#endif
6333#ifdef X509_CHECK_FLAG_NO_WILDCARDS
6334 PyModule_AddIntConstant(m, "HOSTFLAG_NO_WILDCARDS",
6335 X509_CHECK_FLAG_NO_WILDCARDS);
6336#endif
6337#ifdef X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS
6338 PyModule_AddIntConstant(m, "HOSTFLAG_NO_PARTIAL_WILDCARDS",
6339 X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS);
6340#endif
6341#ifdef X509_CHECK_FLAG_MULTI_LABEL_WILDCARDS
6342 PyModule_AddIntConstant(m, "HOSTFLAG_MULTI_LABEL_WILDCARDS",
6343 X509_CHECK_FLAG_MULTI_LABEL_WILDCARDS);
6344#endif
6345#ifdef X509_CHECK_FLAG_SINGLE_LABEL_SUBDOMAINS
6346 PyModule_AddIntConstant(m, "HOSTFLAG_SINGLE_LABEL_SUBDOMAINS",
6347 X509_CHECK_FLAG_SINGLE_LABEL_SUBDOMAINS);
6348#endif
6349
Christian Heimes698dde12018-02-27 11:54:43 +01006350 /* protocol versions */
6351 PyModule_AddIntConstant(m, "PROTO_MINIMUM_SUPPORTED",
6352 PY_PROTO_MINIMUM_SUPPORTED);
6353 PyModule_AddIntConstant(m, "PROTO_MAXIMUM_SUPPORTED",
6354 PY_PROTO_MAXIMUM_SUPPORTED);
6355 PyModule_AddIntConstant(m, "PROTO_SSLv3", PY_PROTO_SSLv3);
6356 PyModule_AddIntConstant(m, "PROTO_TLSv1", PY_PROTO_TLSv1);
6357 PyModule_AddIntConstant(m, "PROTO_TLSv1_1", PY_PROTO_TLSv1_1);
6358 PyModule_AddIntConstant(m, "PROTO_TLSv1_2", PY_PROTO_TLSv1_2);
6359 PyModule_AddIntConstant(m, "PROTO_TLSv1_3", PY_PROTO_TLSv1_3);
Antoine Pitroud5323212010-10-22 18:19:07 +00006360
Victor Stinnerb37672d2018-11-22 03:37:50 +01006361#define addbool(m, key, value) \
6362 do { \
6363 PyObject *bool_obj = (value) ? Py_True : Py_False; \
6364 Py_INCREF(bool_obj); \
6365 PyModule_AddObject((m), (key), bool_obj); \
6366 } while (0)
Christian Heimes698dde12018-02-27 11:54:43 +01006367
6368#if HAVE_SNI
6369 addbool(m, "HAS_SNI", 1);
Antoine Pitrou501da612011-12-21 09:27:41 +01006370#else
Christian Heimes698dde12018-02-27 11:54:43 +01006371 addbool(m, "HAS_SNI", 0);
Antoine Pitrou501da612011-12-21 09:27:41 +01006372#endif
Christian Heimes698dde12018-02-27 11:54:43 +01006373
6374 addbool(m, "HAS_TLS_UNIQUE", 1);
6375
6376#ifndef OPENSSL_NO_ECDH
6377 addbool(m, "HAS_ECDH", 1);
6378#else
6379 addbool(m, "HAS_ECDH", 0);
6380#endif
Antoine Pitrou501da612011-12-21 09:27:41 +01006381
Christian Heimes29eab552018-02-25 12:31:33 +01006382#if HAVE_NPN
Christian Heimes698dde12018-02-27 11:54:43 +01006383 addbool(m, "HAS_NPN", 1);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01006384#else
Christian Heimes698dde12018-02-27 11:54:43 +01006385 addbool(m, "HAS_NPN", 0);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01006386#endif
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01006387
Christian Heimes29eab552018-02-25 12:31:33 +01006388#if HAVE_ALPN
Christian Heimes698dde12018-02-27 11:54:43 +01006389 addbool(m, "HAS_ALPN", 1);
Benjamin Petersoncca27322015-01-23 16:35:37 -05006390#else
Christian Heimes698dde12018-02-27 11:54:43 +01006391 addbool(m, "HAS_ALPN", 0);
Benjamin Petersoncca27322015-01-23 16:35:37 -05006392#endif
Christian Heimes698dde12018-02-27 11:54:43 +01006393
6394#if defined(SSL2_VERSION) && !defined(OPENSSL_NO_SSL2)
6395 addbool(m, "HAS_SSLv2", 1);
6396#else
6397 addbool(m, "HAS_SSLv2", 0);
6398#endif
6399
6400#if defined(SSL3_VERSION) && !defined(OPENSSL_NO_SSL3)
6401 addbool(m, "HAS_SSLv3", 1);
6402#else
6403 addbool(m, "HAS_SSLv3", 0);
6404#endif
6405
6406#if defined(TLS1_VERSION) && !defined(OPENSSL_NO_TLS1)
6407 addbool(m, "HAS_TLSv1", 1);
6408#else
6409 addbool(m, "HAS_TLSv1", 0);
6410#endif
6411
6412#if defined(TLS1_1_VERSION) && !defined(OPENSSL_NO_TLS1_1)
6413 addbool(m, "HAS_TLSv1_1", 1);
6414#else
6415 addbool(m, "HAS_TLSv1_1", 0);
6416#endif
6417
6418#if defined(TLS1_2_VERSION) && !defined(OPENSSL_NO_TLS1_2)
6419 addbool(m, "HAS_TLSv1_2", 1);
6420#else
6421 addbool(m, "HAS_TLSv1_2", 0);
6422#endif
Benjamin Petersoncca27322015-01-23 16:35:37 -05006423
Christian Heimescb5b68a2017-09-07 18:07:00 -07006424#if defined(TLS1_3_VERSION) && !defined(OPENSSL_NO_TLS1_3)
Christian Heimes698dde12018-02-27 11:54:43 +01006425 addbool(m, "HAS_TLSv1_3", 1);
Christian Heimescb5b68a2017-09-07 18:07:00 -07006426#else
Christian Heimes698dde12018-02-27 11:54:43 +01006427 addbool(m, "HAS_TLSv1_3", 0);
Christian Heimescb5b68a2017-09-07 18:07:00 -07006428#endif
Christian Heimescb5b68a2017-09-07 18:07:00 -07006429
Christian Heimes5c36da72020-11-20 09:40:12 +01006430 return 0;
6431}
6432
6433static int
6434sslmodule_legacy(PyObject *module)
6435{
6436#ifndef OPENSSL_VERSION_1_1
6437 /* Load all algorithms and initialize cpuid */
6438 OPENSSL_add_all_algorithms_noconf();
6439 /* Init OpenSSL */
6440 SSL_load_error_strings();
6441 SSL_library_init();
6442#endif
6443
6444#ifdef HAVE_OPENSSL_CRYPTO_LOCK
6445 /* note that this will start threading if not already started */
6446 if (!_setup_ssl_threads()) {
Pablo Galindo93a0ef72020-12-02 06:07:56 +00006447 return 0;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02006448 }
Christian Heimes5c36da72020-11-20 09:40:12 +01006449#elif OPENSSL_VERSION_1_1
6450 /* OpenSSL 1.1.0 builtin thread support is enabled */
6451 _ssl_locks_count++;
6452#endif
6453 return 0;
6454}
6455
6456PyDoc_STRVAR(module_doc,
6457"Implementation module for SSL socket operations. See the socket module\n\
6458for documentation.");
6459
6460
6461static struct PyModuleDef _sslmodule = {
6462 PyModuleDef_HEAD_INIT,
6463 "_ssl",
6464 module_doc,
6465 -1,
6466 PySSL_methods,
6467 NULL,
6468 NULL,
6469 NULL,
6470 NULL
6471};
6472
6473PyMODINIT_FUNC
6474PyInit__ssl(void)
6475{
6476 PyObject *m;
6477
6478 m = PyModule_Create(&_sslmodule);
6479 if (m == NULL)
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02006480 return NULL;
6481
Christian Heimes5c36da72020-11-20 09:40:12 +01006482 if (sslmodule_init_types(m) != 0)
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02006483 return NULL;
Christian Heimes5c36da72020-11-20 09:40:12 +01006484 if (sslmodule_init_exceptions(m) != 0)
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02006485 return NULL;
Christian Heimes5c36da72020-11-20 09:40:12 +01006486 if (sslmodule_init_socketapi(m) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006487 return NULL;
Christian Heimes5c36da72020-11-20 09:40:12 +01006488 if (sslmodule_init_errorcodes(m) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006489 return NULL;
Christian Heimes5c36da72020-11-20 09:40:12 +01006490 if (sslmodule_init_constants(m) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006491 return NULL;
Christian Heimes5c36da72020-11-20 09:40:12 +01006492 if (sslmodule_init_versioninfo(m) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006493 return NULL;
Christian Heimes5c36da72020-11-20 09:40:12 +01006494 if (sslmodule_legacy(m) != 0)
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02006495 return NULL;
6496
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006497 return m;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00006498}