blob: 3ee61e3e631eb1ec1e1882ac7d2f7c7cffd1ad79 [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
Victor Stinner2e57b4e2014-07-01 16:37:17 +020017#define PY_SSIZE_T_CLEAN
18
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000019#include "Python.h"
Thomas Woutersed03b412007-08-28 21:37:11 +000020
Steve Dower68d663c2017-07-17 11:15:48 +020021/* Redefined below for Windows debug builds after important #includes */
22#define _PySSL_FIX_ERRNO
Christian Heimesf77b4b22013-08-21 13:26:05 +020023
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +020024#define PySSL_BEGIN_ALLOW_THREADS_S(save) \
25 do { if (_ssl_locks_count>0) { (save) = PyEval_SaveThread(); } } while (0)
26#define PySSL_END_ALLOW_THREADS_S(save) \
Steve Dower68d663c2017-07-17 11:15:48 +020027 do { if (_ssl_locks_count>0) { PyEval_RestoreThread(save); } _PySSL_FIX_ERRNO; } while (0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +000028#define PySSL_BEGIN_ALLOW_THREADS { \
Antoine Pitroucbb82eb2010-05-05 15:57:33 +000029 PyThreadState *_save = NULL; \
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +020030 PySSL_BEGIN_ALLOW_THREADS_S(_save);
31#define PySSL_BLOCK_THREADS PySSL_END_ALLOW_THREADS_S(_save);
32#define PySSL_UNBLOCK_THREADS PySSL_BEGIN_ALLOW_THREADS_S(_save);
33#define PySSL_END_ALLOW_THREADS PySSL_END_ALLOW_THREADS_S(_save); }
Thomas Wouters1b7f8912007-09-19 03:06:30 +000034
Antoine Pitrou2463e5f2013-03-28 22:24:43 +010035/* Include symbols from _socket module */
36#include "socketmodule.h"
37
38static PySocketModule_APIObject PySocketModule;
39
40#if defined(HAVE_POLL_H)
41#include <poll.h>
42#elif defined(HAVE_SYS_POLL_H)
43#include <sys/poll.h>
44#endif
45
Christian Heimes598894f2016-09-05 23:19:05 +020046/* Don't warn about deprecated functions */
47#ifdef __GNUC__
48#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
49#endif
50#ifdef __clang__
51#pragma clang diagnostic ignored "-Wdeprecated-declarations"
52#endif
53
Antoine Pitrou2463e5f2013-03-28 22:24:43 +010054/* Include OpenSSL header files */
55#include "openssl/rsa.h"
56#include "openssl/crypto.h"
57#include "openssl/x509.h"
58#include "openssl/x509v3.h"
59#include "openssl/pem.h"
60#include "openssl/ssl.h"
61#include "openssl/err.h"
62#include "openssl/rand.h"
Antoine Pitroub1fdf472014-10-05 20:41:53 +020063#include "openssl/bio.h"
Alexandru Ardeleanb3a271f2018-09-17 14:53:31 +030064#include "openssl/dh.h"
Antoine Pitrou2463e5f2013-03-28 22:24:43 +010065
Christian Heimesff5be6e2018-01-20 13:19:21 +010066#ifndef HAVE_X509_VERIFY_PARAM_SET1_HOST
Christian Heimes61d478c2018-01-27 15:51:38 +010067# ifdef LIBRESSL_VERSION_NUMBER
68# error "LibreSSL is missing X509_VERIFY_PARAM_set1_host(), see https://github.com/libressl-portable/portable/issues/381"
69# elif OPENSSL_VERSION_NUMBER > 0x1000200fL
Christian Heimesff5be6e2018-01-20 13:19:21 +010070# define HAVE_X509_VERIFY_PARAM_SET1_HOST
Christian Heimes61d478c2018-01-27 15:51:38 +010071# else
72# error "libssl is too old and does not support X509_VERIFY_PARAM_set1_host()"
Christian Heimesff5be6e2018-01-20 13:19:21 +010073# endif
74#endif
75
Christian Heimesc087a262020-05-15 20:55:25 +020076#ifndef OPENSSL_THREADS
77# error "OPENSSL_THREADS is not defined, Python requires thread-safe OpenSSL"
78#endif
79
Antoine Pitrou2463e5f2013-03-28 22:24:43 +010080/* SSL error object */
81static PyObject *PySSLErrorObject;
Christian Heimesb3ad0e52017-09-08 12:00:19 -070082static PyObject *PySSLCertVerificationErrorObject;
Antoine Pitrou2463e5f2013-03-28 22:24:43 +010083static PyObject *PySSLZeroReturnErrorObject;
84static PyObject *PySSLWantReadErrorObject;
85static PyObject *PySSLWantWriteErrorObject;
86static PyObject *PySSLSyscallErrorObject;
87static PyObject *PySSLEOFErrorObject;
88
89/* Error mappings */
90static PyObject *err_codes_to_names;
91static PyObject *err_names_to_codes;
92static PyObject *lib_codes_to_names;
93
94struct py_ssl_error_code {
95 const char *mnemonic;
96 int library, reason;
97};
98struct py_ssl_library_code {
99 const char *library;
100 int code;
101};
102
Steve Dower68d663c2017-07-17 11:15:48 +0200103#if defined(MS_WINDOWS) && defined(Py_DEBUG)
104/* Debug builds on Windows rely on getting errno directly from OpenSSL.
105 * However, because it uses a different CRT, we need to transfer the
106 * value of errno from OpenSSL into our debug CRT.
107 *
108 * Don't be fooled - this is horribly ugly code. The only reasonable
109 * alternative is to do both debug and release builds of OpenSSL, which
110 * requires much uglier code to transform their automatically generated
111 * makefile. This is the lesser of all the evils.
112 */
113
114static void _PySSLFixErrno(void) {
115 HMODULE ucrtbase = GetModuleHandleW(L"ucrtbase.dll");
116 if (!ucrtbase) {
117 /* If ucrtbase.dll is not loaded but the SSL DLLs are, we likely
118 * have a catastrophic failure, but this function is not the
119 * place to raise it. */
120 return;
121 }
122
123 typedef int *(__stdcall *errno_func)(void);
124 errno_func ssl_errno = (errno_func)GetProcAddress(ucrtbase, "_errno");
125 if (ssl_errno) {
126 errno = *ssl_errno();
127 *ssl_errno() = 0;
128 } else {
129 errno = ENOTRECOVERABLE;
130 }
131}
132
133#undef _PySSL_FIX_ERRNO
134#define _PySSL_FIX_ERRNO _PySSLFixErrno()
135#endif
136
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100137/* Include generated data (error codes) */
Christian Heimes150af752021-04-09 17:02:00 +0200138#if (OPENSSL_VERSION_NUMBER >= 0x30000000L)
139#include "_ssl_data_300.h"
140#elif (OPENSSL_VERSION_NUMBER >= 0x10101000L) && !defined(LIBRESSL_VERSION_NUMBER)
141#include "_ssl_data_111.h"
142#else
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100143#include "_ssl_data.h"
Christian Heimes150af752021-04-09 17:02:00 +0200144#endif
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100145
Christian Heimes598894f2016-09-05 23:19:05 +0200146#if (OPENSSL_VERSION_NUMBER >= 0x10100000L) && !defined(LIBRESSL_VERSION_NUMBER)
147# define OPENSSL_VERSION_1_1 1
Christian Heimes4ca07392018-03-24 15:41:37 +0100148# define PY_OPENSSL_1_1_API 1
149#endif
150
Christian Heimesa871f692020-06-01 08:58:14 +0200151/* OpenSSL API compat */
152#ifdef OPENSSL_API_COMPAT
153#if OPENSSL_API_COMPAT >= 0x10100000L
154
155/* OpenSSL API 1.1.0+ does not include version methods */
156#ifndef OPENSSL_NO_TLS1_METHOD
157#define OPENSSL_NO_TLS1_METHOD 1
158#endif
159#ifndef OPENSSL_NO_TLS1_1_METHOD
160#define OPENSSL_NO_TLS1_1_METHOD 1
161#endif
162#ifndef OPENSSL_NO_TLS1_2_METHOD
163#define OPENSSL_NO_TLS1_2_METHOD 1
164#endif
165
166#endif /* >= 1.1.0 compcat */
167#endif /* OPENSSL_API_COMPAT */
168
Christian Heimes4ca07392018-03-24 15:41:37 +0100169/* LibreSSL 2.7.0 provides necessary OpenSSL 1.1.0 APIs */
170#if defined(LIBRESSL_VERSION_NUMBER) && LIBRESSL_VERSION_NUMBER >= 0x2070000fL
171# define PY_OPENSSL_1_1_API 1
Christian Heimes598894f2016-09-05 23:19:05 +0200172#endif
173
Christian Heimes470fba12013-11-28 15:12:15 +0100174/* SNI support (client- and server-side) appeared in OpenSSL 1.0.0 and 0.9.8f
Antoine Pitrou912fbff2013-03-30 16:29:32 +0100175 * This includes the SSL_set_SSL_CTX() function.
176 */
177#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
178# define HAVE_SNI 1
179#else
180# define HAVE_SNI 0
181#endif
182
Benjamin Petersond3308222015-09-27 00:09:02 -0700183#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
Christian Heimes29eab552018-02-25 12:31:33 +0100184# define HAVE_ALPN 1
185#else
186# define HAVE_ALPN 0
Benjamin Petersoncca27322015-01-23 16:35:37 -0500187#endif
188
Christian Heimes6cdb7952018-02-24 22:12:40 +0100189/* We cannot rely on OPENSSL_NO_NEXTPROTONEG because LibreSSL 2.6.1 dropped
190 * NPN support but did not set OPENSSL_NO_NEXTPROTONEG for compatibility
191 * reasons. The check for TLSEXT_TYPE_next_proto_neg works with
192 * OpenSSL 1.0.1+ and LibreSSL.
Christian Heimes29eab552018-02-25 12:31:33 +0100193 * OpenSSL 1.1.1-pre1 dropped NPN but still has TLSEXT_TYPE_next_proto_neg.
Christian Heimes6cdb7952018-02-24 22:12:40 +0100194 */
195#ifdef OPENSSL_NO_NEXTPROTONEG
Christian Heimes29eab552018-02-25 12:31:33 +0100196# define HAVE_NPN 0
197#elif (OPENSSL_VERSION_NUMBER >= 0x10101000L) && !defined(LIBRESSL_VERSION_NUMBER)
198# define HAVE_NPN 0
Christian Heimes6cdb7952018-02-24 22:12:40 +0100199#elif defined(TLSEXT_TYPE_next_proto_neg)
Christian Heimes29eab552018-02-25 12:31:33 +0100200# define HAVE_NPN 1
Christian Heimes6cdb7952018-02-24 22:12:40 +0100201#else
Christian Heimes29eab552018-02-25 12:31:33 +0100202# define HAVE_NPN 0
203#endif
Christian Heimes6cdb7952018-02-24 22:12:40 +0100204
Christian Heimesc7f70692019-05-31 11:44:05 +0200205#if (OPENSSL_VERSION_NUMBER >= 0x10101000L) && !defined(LIBRESSL_VERSION_NUMBER)
206#define HAVE_OPENSSL_KEYLOG 1
207#endif
208
Victor Stinner524714e2016-07-22 17:43:59 +0200209#ifndef INVALID_SOCKET /* MS defines this */
210#define INVALID_SOCKET (-1)
211#endif
212
Christian Heimes4ca07392018-03-24 15:41:37 +0100213/* OpenSSL 1.0.2 and LibreSSL needs extra code for locking */
214#ifndef OPENSSL_VERSION_1_1
215#define HAVE_OPENSSL_CRYPTO_LOCK
216#endif
217
218#if defined(OPENSSL_VERSION_1_1) && !defined(OPENSSL_NO_SSL2)
Christian Heimes598894f2016-09-05 23:19:05 +0200219#define OPENSSL_NO_SSL2
220#endif
Christian Heimes4ca07392018-03-24 15:41:37 +0100221
222#ifndef PY_OPENSSL_1_1_API
223/* OpenSSL 1.1 API shims for OpenSSL < 1.1.0 and LibreSSL < 2.7.0 */
Christian Heimes598894f2016-09-05 23:19:05 +0200224
225#define TLS_method SSLv23_method
Christian Heimes5fe668c2016-09-12 00:01:11 +0200226#define TLS_client_method SSLv23_client_method
227#define TLS_server_method SSLv23_server_method
Christian Heimesa871f692020-06-01 08:58:14 +0200228#define ASN1_STRING_get0_data ASN1_STRING_data
229#define X509_get0_notBefore X509_get_notBefore
230#define X509_get0_notAfter X509_get_notAfter
231#define OpenSSL_version_num SSLeay
232#define OpenSSL_version SSLeay_version
233#define OPENSSL_VERSION SSLEAY_VERSION
Christian Heimes598894f2016-09-05 23:19:05 +0200234
235static int X509_NAME_ENTRY_set(const X509_NAME_ENTRY *ne)
236{
237 return ne->set;
238}
239
240#ifndef OPENSSL_NO_COMP
Christian Heimesa5d07652016-09-24 10:48:05 +0200241/* LCOV_EXCL_START */
Christian Heimes598894f2016-09-05 23:19:05 +0200242static int COMP_get_type(const COMP_METHOD *meth)
243{
244 return meth->type;
245}
Christian Heimes1a63b9f2016-09-24 12:07:21 +0200246/* LCOV_EXCL_STOP */
Christian Heimes598894f2016-09-05 23:19:05 +0200247#endif
248
249static pem_password_cb *SSL_CTX_get_default_passwd_cb(SSL_CTX *ctx)
250{
251 return ctx->default_passwd_callback;
252}
253
254static void *SSL_CTX_get_default_passwd_cb_userdata(SSL_CTX *ctx)
255{
256 return ctx->default_passwd_callback_userdata;
257}
258
259static int X509_OBJECT_get_type(X509_OBJECT *x)
260{
261 return x->type;
262}
263
264static X509 *X509_OBJECT_get0_X509(X509_OBJECT *x)
265{
266 return x->data.x509;
267}
268
269static int BIO_up_ref(BIO *b)
270{
271 CRYPTO_add(&b->references, 1, CRYPTO_LOCK_BIO);
272 return 1;
273}
274
275static STACK_OF(X509_OBJECT) *X509_STORE_get0_objects(X509_STORE *store) {
276 return store->objs;
277}
278
Christian Heimes99a65702016-09-10 23:44:53 +0200279static int
280SSL_SESSION_has_ticket(const SSL_SESSION *s)
281{
282 return (s->tlsext_ticklen > 0) ? 1 : 0;
283}
284
285static unsigned long
286SSL_SESSION_get_ticket_lifetime_hint(const SSL_SESSION *s)
287{
288 return s->tlsext_tick_lifetime_hint;
289}
290
Christian Heimes4ca07392018-03-24 15:41:37 +0100291#endif /* OpenSSL < 1.1.0 or LibreSSL < 2.7.0 */
Christian Heimes598894f2016-09-05 23:19:05 +0200292
Christian Heimes892d66e2018-01-29 14:10:18 +0100293/* Default cipher suites */
294#ifndef PY_SSL_DEFAULT_CIPHERS
295#define PY_SSL_DEFAULT_CIPHERS 1
296#endif
297
298#if PY_SSL_DEFAULT_CIPHERS == 0
299 #ifndef PY_SSL_DEFAULT_CIPHER_STRING
300 #error "Py_SSL_DEFAULT_CIPHERS 0 needs Py_SSL_DEFAULT_CIPHER_STRING"
301 #endif
302#elif PY_SSL_DEFAULT_CIPHERS == 1
Stéphane Wirtel07fbbfd2018-10-05 16:17:18 +0200303/* Python custom selection of sensible cipher suites
Christian Heimes892d66e2018-01-29 14:10:18 +0100304 * DEFAULT: OpenSSL's default cipher list. Since 1.0.2 the list is in sensible order.
305 * !aNULL:!eNULL: really no NULL ciphers
306 * !MD5:!3DES:!DES:!RC4:!IDEA:!SEED: no weak or broken algorithms on old OpenSSL versions.
307 * !aDSS: no authentication with discrete logarithm DSA algorithm
308 * !SRP:!PSK: no secure remote password or pre-shared key authentication
309 */
310 #define PY_SSL_DEFAULT_CIPHER_STRING "DEFAULT:!aNULL:!eNULL:!MD5:!3DES:!DES:!RC4:!IDEA:!SEED:!aDSS:!SRP:!PSK"
311#elif PY_SSL_DEFAULT_CIPHERS == 2
312/* Ignored in SSLContext constructor, only used to as _ssl.DEFAULT_CIPHER_STRING */
313 #define PY_SSL_DEFAULT_CIPHER_STRING SSL_DEFAULT_CIPHER_LIST
314#else
315 #error "Unsupported PY_SSL_DEFAULT_CIPHERS"
316#endif
317
Christian Heimes598894f2016-09-05 23:19:05 +0200318
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000319enum py_ssl_error {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000320 /* these mirror ssl.h */
321 PY_SSL_ERROR_NONE,
322 PY_SSL_ERROR_SSL,
323 PY_SSL_ERROR_WANT_READ,
324 PY_SSL_ERROR_WANT_WRITE,
325 PY_SSL_ERROR_WANT_X509_LOOKUP,
326 PY_SSL_ERROR_SYSCALL, /* look at error stack/return value/errno */
327 PY_SSL_ERROR_ZERO_RETURN,
328 PY_SSL_ERROR_WANT_CONNECT,
329 /* start of non ssl.h errorcodes */
330 PY_SSL_ERROR_EOF, /* special case of SSL_ERROR_SYSCALL */
331 PY_SSL_ERROR_NO_SOCKET, /* socket has been GC'd */
332 PY_SSL_ERROR_INVALID_ERROR_CODE
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000333};
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000334
Thomas Woutersed03b412007-08-28 21:37:11 +0000335enum py_ssl_server_or_client {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000336 PY_SSL_CLIENT,
337 PY_SSL_SERVER
Thomas Woutersed03b412007-08-28 21:37:11 +0000338};
339
340enum py_ssl_cert_requirements {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000341 PY_SSL_CERT_NONE,
342 PY_SSL_CERT_OPTIONAL,
343 PY_SSL_CERT_REQUIRED
Thomas Woutersed03b412007-08-28 21:37:11 +0000344};
345
346enum py_ssl_version {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000347 PY_SSL_VERSION_SSL2,
Victor Stinner3de49192011-05-09 00:42:58 +0200348 PY_SSL_VERSION_SSL3=1,
Christian Heimes5fe668c2016-09-12 00:01:11 +0200349 PY_SSL_VERSION_TLS, /* SSLv23 */
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100350 PY_SSL_VERSION_TLS1,
351 PY_SSL_VERSION_TLS1_1,
Christian Heimes5fe668c2016-09-12 00:01:11 +0200352 PY_SSL_VERSION_TLS1_2,
Christian Heimes5fe668c2016-09-12 00:01:11 +0200353 PY_SSL_VERSION_TLS_CLIENT=0x10,
354 PY_SSL_VERSION_TLS_SERVER,
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100355};
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200356
Christian Heimes698dde12018-02-27 11:54:43 +0100357enum py_proto_version {
358 PY_PROTO_MINIMUM_SUPPORTED = -2,
359 PY_PROTO_SSLv3 = SSL3_VERSION,
360 PY_PROTO_TLSv1 = TLS1_VERSION,
361 PY_PROTO_TLSv1_1 = TLS1_1_VERSION,
362 PY_PROTO_TLSv1_2 = TLS1_2_VERSION,
363#ifdef TLS1_3_VERSION
364 PY_PROTO_TLSv1_3 = TLS1_3_VERSION,
365#else
366 PY_PROTO_TLSv1_3 = 0x304,
367#endif
368 PY_PROTO_MAXIMUM_SUPPORTED = -1,
369
370/* OpenSSL has no dedicated API to set the minimum version to the maximum
371 * available version, and the other way around. We have to figure out the
372 * minimum and maximum available version on our own and hope for the best.
373 */
374#if defined(SSL3_VERSION) && !defined(OPENSSL_NO_SSL3)
375 PY_PROTO_MINIMUM_AVAILABLE = PY_PROTO_SSLv3,
376#elif defined(TLS1_VERSION) && !defined(OPENSSL_NO_TLS1)
377 PY_PROTO_MINIMUM_AVAILABLE = PY_PROTO_TLSv1,
378#elif defined(TLS1_1_VERSION) && !defined(OPENSSL_NO_TLS1_1)
379 PY_PROTO_MINIMUM_AVAILABLE = PY_PROTO_TLSv1_1,
380#elif defined(TLS1_2_VERSION) && !defined(OPENSSL_NO_TLS1_2)
381 PY_PROTO_MINIMUM_AVAILABLE = PY_PROTO_TLSv1_2,
382#elif defined(TLS1_3_VERSION) && !defined(OPENSSL_NO_TLS1_3)
383 PY_PROTO_MINIMUM_AVAILABLE = PY_PROTO_TLSv1_3,
384#else
385 #error "PY_PROTO_MINIMUM_AVAILABLE not found"
386#endif
387
388#if defined(TLS1_3_VERSION) && !defined(OPENSSL_NO_TLS1_3)
389 PY_PROTO_MAXIMUM_AVAILABLE = PY_PROTO_TLSv1_3,
390#elif defined(TLS1_2_VERSION) && !defined(OPENSSL_NO_TLS1_2)
391 PY_PROTO_MAXIMUM_AVAILABLE = PY_PROTO_TLSv1_2,
392#elif defined(TLS1_1_VERSION) && !defined(OPENSSL_NO_TLS1_1)
393 PY_PROTO_MAXIMUM_AVAILABLE = PY_PROTO_TLSv1_1,
394#elif defined(TLS1_VERSION) && !defined(OPENSSL_NO_TLS1)
395 PY_PROTO_MAXIMUM_AVAILABLE = PY_PROTO_TLSv1,
396#elif defined(SSL3_VERSION) && !defined(OPENSSL_NO_SSL3)
397 PY_PROTO_MAXIMUM_AVAILABLE = PY_PROTO_SSLv3,
398#else
399 #error "PY_PROTO_MAXIMUM_AVAILABLE not found"
400#endif
401};
402
403
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000404/* serves as a flag to see whether we've initialized the SSL thread support. */
405/* 0 means no, greater than 0 means yes */
406
407static unsigned int _ssl_locks_count = 0;
408
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000409/* SSL socket object */
410
411#define X509_NAME_MAXLEN 256
412
Gregory P. Smithbd4dacb2010-10-13 03:53:21 +0000413/* SSL_CTX_clear_options() and SSL_clear_options() were first added in
414 * OpenSSL 0.9.8m but do not appear in some 0.9.9-dev versions such the
415 * 0.9.9 from "May 2008" that NetBSD 5.0 uses. */
416#if OPENSSL_VERSION_NUMBER >= 0x009080dfL && OPENSSL_VERSION_NUMBER != 0x00909000L
Antoine Pitroub5218772010-05-21 09:56:06 +0000417# define HAVE_SSL_CTX_CLEAR_OPTIONS
418#else
419# undef HAVE_SSL_CTX_CLEAR_OPTIONS
420#endif
421
Antoine Pitroud6494802011-07-21 01:11:30 +0200422/* In case of 'tls-unique' it will be 12 bytes for TLS, 36 bytes for
423 * older SSL, but let's be safe */
424#define PySSL_CB_MAXLEN 128
425
Antoine Pitroua9bf2ac2012-02-17 18:47:54 +0100426
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000427typedef struct {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000428 PyObject_HEAD
Antoine Pitrou152efa22010-05-16 18:19:27 +0000429 SSL_CTX *ctx;
Christian Heimes29eab552018-02-25 12:31:33 +0100430#if HAVE_NPN
Benjamin Petersoncca27322015-01-23 16:35:37 -0500431 unsigned char *npn_protocols;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100432 int npn_protocols_len;
433#endif
Christian Heimes29eab552018-02-25 12:31:33 +0100434#if HAVE_ALPN
Benjamin Petersoncca27322015-01-23 16:35:37 -0500435 unsigned char *alpn_protocols;
Segev Finer5cff6372017-07-27 01:19:17 +0300436 unsigned int alpn_protocols_len;
Benjamin Petersoncca27322015-01-23 16:35:37 -0500437#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100438#ifndef OPENSSL_NO_TLSEXT
Christian Heimes11a14932018-02-24 02:35:08 +0100439 PyObject *set_sni_cb;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100440#endif
Christian Heimes1aa9a752013-12-02 02:41:19 +0100441 int check_hostname;
Christian Heimes61d478c2018-01-27 15:51:38 +0100442 /* OpenSSL has no API to get hostflags from X509_VERIFY_PARAM* struct.
443 * We have to maintain our own copy. OpenSSL's hostflags default to 0.
444 */
445 unsigned int hostflags;
Christian Heimes11a14932018-02-24 02:35:08 +0100446 int protocol;
Christian Heimes9fb051f2018-09-23 08:32:31 +0200447#ifdef TLS1_3_VERSION
448 int post_handshake_auth;
449#endif
Christian Heimesc7f70692019-05-31 11:44:05 +0200450 PyObject *msg_cb;
451#ifdef HAVE_OPENSSL_KEYLOG
452 PyObject *keylog_filename;
453 BIO *keylog_bio;
454#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +0000455} PySSLContext;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000456
Antoine Pitrou152efa22010-05-16 18:19:27 +0000457typedef struct {
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700458 int ssl; /* last seen error from SSL */
459 int c; /* last seen error from libc */
460#ifdef MS_WINDOWS
461 int ws; /* last seen error from winsock */
462#endif
463} _PySSLError;
464
465typedef struct {
Antoine Pitrou152efa22010-05-16 18:19:27 +0000466 PyObject_HEAD
467 PyObject *Socket; /* weakref to socket on which we're layered */
468 SSL *ssl;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100469 PySSLContext *ctx; /* weakref to SSL context */
Antoine Pitrou20b85552013-09-29 19:50:53 +0200470 char shutdown_seen_zero;
Antoine Pitroud6494802011-07-21 01:11:30 +0200471 enum py_ssl_server_or_client socket_type;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200472 PyObject *owner; /* Python level "owner" passed to servername callback */
473 PyObject *server_hostname;
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700474 _PySSLError err; /* last seen error from various sources */
Christian Heimesc7f70692019-05-31 11:44:05 +0200475 /* Some SSL callbacks don't have error reporting. Callback wrappers
476 * store exception information on the socket. The handshake, read, write,
477 * and shutdown methods check for chained exceptions.
478 */
479 PyObject *exc_type;
480 PyObject *exc_value;
481 PyObject *exc_tb;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000482} PySSLSocket;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000483
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200484typedef struct {
485 PyObject_HEAD
486 BIO *bio;
487 int eof_written;
488} PySSLMemoryBIO;
489
Christian Heimes99a65702016-09-10 23:44:53 +0200490typedef struct {
491 PyObject_HEAD
492 SSL_SESSION *session;
493 PySSLContext *ctx;
494} PySSLSession;
495
Christian Heimes5c36da72020-11-20 09:40:12 +0100496static PyTypeObject *PySSLContext_Type;
497static PyTypeObject *PySSLSocket_Type;
498static PyTypeObject *PySSLMemoryBIO_Type;
499static PyTypeObject *PySSLSession_Type;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000500
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700501static inline _PySSLError _PySSL_errno(int failed, const SSL *ssl, int retcode)
502{
503 _PySSLError err = { 0 };
504 if (failed) {
Steve Dowere6eb48c2017-09-08 15:16:15 -0700505#ifdef MS_WINDOWS
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700506 err.ws = WSAGetLastError();
507 _PySSL_FIX_ERRNO;
Steve Dowere6eb48c2017-09-08 15:16:15 -0700508#endif
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700509 err.c = errno;
510 err.ssl = SSL_get_error(ssl, retcode);
511 }
512 return err;
513}
Steve Dowere6eb48c2017-09-08 15:16:15 -0700514
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +0300515/*[clinic input]
516module _ssl
Christian Heimes5c36da72020-11-20 09:40:12 +0100517class _ssl._SSLContext "PySSLContext *" "PySSLContext_Type"
518class _ssl._SSLSocket "PySSLSocket *" "PySSLSocket_Type"
519class _ssl.MemoryBIO "PySSLMemoryBIO *" "PySSLMemoryBIO_Type"
520class _ssl.SSLSession "PySSLSession *" "PySSLSession_Type"
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +0300521[clinic start generated code]*/
Christian Heimes5c36da72020-11-20 09:40:12 +0100522/*[clinic end generated code: output=da39a3ee5e6b4b0d input=cc4883756da17954]*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +0300523
524#include "clinic/_ssl.c.h"
525
Victor Stinner14690702015-04-06 22:46:13 +0200526static int PySSL_select(PySocketSockObject *s, int writing, _PyTime_t timeout);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000527
Christian Heimes141c5e82018-02-24 21:10:57 +0100528static int PySSL_set_owner(PySSLSocket *, PyObject *, void *);
529static int PySSL_set_session(PySSLSocket *, PyObject *, void *);
Christian Heimes5c36da72020-11-20 09:40:12 +0100530#define PySSLSocket_Check(v) Py_IS_TYPE(v, PySSLSocket_Type)
531#define PySSLMemoryBIO_Check(v) Py_IS_TYPE(v, PySSLMemoryBIO_Type)
532#define PySSLSession_Check(v) Py_IS_TYPE(v, PySSLSession_Type)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000533
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000534typedef enum {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000535 SOCKET_IS_NONBLOCKING,
536 SOCKET_IS_BLOCKING,
537 SOCKET_HAS_TIMED_OUT,
538 SOCKET_HAS_BEEN_CLOSED,
539 SOCKET_TOO_LARGE_FOR_SELECT,
540 SOCKET_OPERATION_OK
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000541} timeout_state;
542
Thomas Woutersed03b412007-08-28 21:37:11 +0000543/* Wrap error strings with filename and line # */
Thomas Woutersed03b412007-08-28 21:37:11 +0000544#define ERRSTR1(x,y,z) (x ":" y ": " z)
Victor Stinner45e8e2f2014-05-14 17:24:35 +0200545#define ERRSTR(x) ERRSTR1("_ssl.c", Py_STRINGIFY(__LINE__), x)
Thomas Woutersed03b412007-08-28 21:37:11 +0000546
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200547/* Get the socket from a PySSLSocket, if it has one */
548#define GET_SOCKET(obj) ((obj)->Socket ? \
549 (PySocketSockObject *) PyWeakref_GetObject((obj)->Socket) : NULL)
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200550
Victor Stinner14690702015-04-06 22:46:13 +0200551/* If sock is NULL, use a timeout of 0 second */
552#define GET_SOCKET_TIMEOUT(sock) \
553 ((sock != NULL) ? (sock)->sock_timeout : 0)
554
Christian Heimesc7f70692019-05-31 11:44:05 +0200555#include "_ssl/debughelpers.c"
556
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200557/*
558 * SSL errors.
559 */
560
561PyDoc_STRVAR(SSLError_doc,
562"An error occurred in the SSL implementation.");
563
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700564PyDoc_STRVAR(SSLCertVerificationError_doc,
565"A certificate could not be verified.");
566
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200567PyDoc_STRVAR(SSLZeroReturnError_doc,
568"SSL/TLS session closed cleanly.");
569
570PyDoc_STRVAR(SSLWantReadError_doc,
571"Non-blocking SSL socket needs to read more data\n"
572"before the requested operation can be completed.");
573
574PyDoc_STRVAR(SSLWantWriteError_doc,
575"Non-blocking SSL socket needs to write more data\n"
576"before the requested operation can be completed.");
577
578PyDoc_STRVAR(SSLSyscallError_doc,
579"System error when attempting SSL operation.");
580
581PyDoc_STRVAR(SSLEOFError_doc,
582"SSL/TLS connection terminated abruptly.");
583
584static PyObject *
585SSLError_str(PyOSErrorObject *self)
586{
587 if (self->strerror != NULL && PyUnicode_Check(self->strerror)) {
588 Py_INCREF(self->strerror);
589 return self->strerror;
590 }
591 else
592 return PyObject_Str(self->args);
593}
594
595static PyType_Slot sslerror_type_slots[] = {
Inada Naoki926b0cb2019-04-17 08:39:46 +0900596 {Py_tp_doc, (void*)SSLError_doc},
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200597 {Py_tp_str, SSLError_str},
598 {0, 0},
599};
600
601static PyType_Spec sslerror_type_spec = {
602 "ssl.SSLError",
603 sizeof(PyOSErrorObject),
604 0,
605 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
606 sslerror_type_slots
607};
608
609static void
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700610fill_and_set_sslerror(PySSLSocket *sslsock, PyObject *type, int ssl_errno,
611 const char *errstr, int lineno, unsigned long errcode)
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200612{
613 PyObject *err_value = NULL, *reason_obj = NULL, *lib_obj = NULL;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700614 PyObject *verify_obj = NULL, *verify_code_obj = NULL;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200615 PyObject *init_value, *msg, *key;
616 _Py_IDENTIFIER(reason);
617 _Py_IDENTIFIER(library);
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700618 _Py_IDENTIFIER(verify_message);
619 _Py_IDENTIFIER(verify_code);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200620
621 if (errcode != 0) {
622 int lib, reason;
623
624 lib = ERR_GET_LIB(errcode);
625 reason = ERR_GET_REASON(errcode);
626 key = Py_BuildValue("ii", lib, reason);
627 if (key == NULL)
628 goto fail;
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +0300629 reason_obj = PyDict_GetItemWithError(err_codes_to_names, key);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200630 Py_DECREF(key);
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +0300631 if (reason_obj == NULL && PyErr_Occurred()) {
632 goto fail;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200633 }
634 key = PyLong_FromLong(lib);
635 if (key == NULL)
636 goto fail;
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +0300637 lib_obj = PyDict_GetItemWithError(lib_codes_to_names, key);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200638 Py_DECREF(key);
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +0300639 if (lib_obj == NULL && PyErr_Occurred()) {
640 goto fail;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200641 }
642 if (errstr == NULL)
643 errstr = ERR_reason_error_string(errcode);
644 }
645 if (errstr == NULL)
646 errstr = "unknown error";
647
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700648 /* verify code for cert validation error */
649 if ((sslsock != NULL) && (type == PySSLCertVerificationErrorObject)) {
650 const char *verify_str = NULL;
651 long verify_code;
652
653 verify_code = SSL_get_verify_result(sslsock->ssl);
654 verify_code_obj = PyLong_FromLong(verify_code);
655 if (verify_code_obj == NULL) {
656 goto fail;
657 }
658
659 switch (verify_code) {
Christian Heimes09153602017-09-08 14:47:58 -0700660#ifdef X509_V_ERR_HOSTNAME_MISMATCH
661 /* OpenSSL >= 1.0.2, LibreSSL >= 2.5.3 */
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700662 case X509_V_ERR_HOSTNAME_MISMATCH:
663 verify_obj = PyUnicode_FromFormat(
664 "Hostname mismatch, certificate is not valid for '%S'.",
665 sslsock->server_hostname
666 );
667 break;
Christian Heimes09153602017-09-08 14:47:58 -0700668#endif
669#ifdef X509_V_ERR_IP_ADDRESS_MISMATCH
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700670 case X509_V_ERR_IP_ADDRESS_MISMATCH:
671 verify_obj = PyUnicode_FromFormat(
672 "IP address mismatch, certificate is not valid for '%S'.",
673 sslsock->server_hostname
674 );
675 break;
Christian Heimes09153602017-09-08 14:47:58 -0700676#endif
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700677 default:
678 verify_str = X509_verify_cert_error_string(verify_code);
679 if (verify_str != NULL) {
680 verify_obj = PyUnicode_FromString(verify_str);
681 } else {
682 verify_obj = Py_None;
683 Py_INCREF(verify_obj);
684 }
685 break;
686 }
687 if (verify_obj == NULL) {
688 goto fail;
689 }
690 }
691
692 if (verify_obj && reason_obj && lib_obj)
693 msg = PyUnicode_FromFormat("[%S: %S] %s: %S (_ssl.c:%d)",
694 lib_obj, reason_obj, errstr, verify_obj,
695 lineno);
696 else if (reason_obj && lib_obj)
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200697 msg = PyUnicode_FromFormat("[%S: %S] %s (_ssl.c:%d)",
698 lib_obj, reason_obj, errstr, lineno);
699 else if (lib_obj)
700 msg = PyUnicode_FromFormat("[%S] %s (_ssl.c:%d)",
701 lib_obj, errstr, lineno);
702 else
703 msg = PyUnicode_FromFormat("%s (_ssl.c:%d)", errstr, lineno);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200704 if (msg == NULL)
705 goto fail;
Victor Stinnerba9be472013-10-31 15:00:24 +0100706
Paul Monsonfb7e7502019-05-15 15:38:55 -0700707 init_value = Py_BuildValue("iN", ERR_GET_REASON(ssl_errno), msg);
Victor Stinnerba9be472013-10-31 15:00:24 +0100708 if (init_value == NULL)
709 goto fail;
710
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200711 err_value = PyObject_CallObject(type, init_value);
712 Py_DECREF(init_value);
713 if (err_value == NULL)
714 goto fail;
Victor Stinnerba9be472013-10-31 15:00:24 +0100715
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200716 if (reason_obj == NULL)
717 reason_obj = Py_None;
718 if (_PyObject_SetAttrId(err_value, &PyId_reason, reason_obj))
719 goto fail;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700720
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200721 if (lib_obj == NULL)
722 lib_obj = Py_None;
723 if (_PyObject_SetAttrId(err_value, &PyId_library, lib_obj))
724 goto fail;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700725
726 if ((sslsock != NULL) && (type == PySSLCertVerificationErrorObject)) {
727 /* Only set verify code / message for SSLCertVerificationError */
728 if (_PyObject_SetAttrId(err_value, &PyId_verify_code,
729 verify_code_obj))
730 goto fail;
731 if (_PyObject_SetAttrId(err_value, &PyId_verify_message, verify_obj))
732 goto fail;
733 }
734
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200735 PyErr_SetObject(type, err_value);
736fail:
737 Py_XDECREF(err_value);
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700738 Py_XDECREF(verify_code_obj);
739 Py_XDECREF(verify_obj);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200740}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000741
Christian Heimesc7f70692019-05-31 11:44:05 +0200742static int
743PySSL_ChainExceptions(PySSLSocket *sslsock) {
744 if (sslsock->exc_type == NULL)
745 return 0;
746
747 _PyErr_ChainExceptions(sslsock->exc_type, sslsock->exc_value, sslsock->exc_tb);
748 sslsock->exc_type = NULL;
749 sslsock->exc_value = NULL;
750 sslsock->exc_tb = NULL;
751 return -1;
752}
753
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000754static PyObject *
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700755PySSL_SetError(PySSLSocket *sslsock, int ret, const char *filename, int lineno)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000756{
Antoine Pitrou41032a62011-10-27 23:56:55 +0200757 PyObject *type = PySSLErrorObject;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200758 char *errstr = NULL;
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700759 _PySSLError err;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000760 enum py_ssl_error p = PY_SSL_ERROR_NONE;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200761 unsigned long e = 0;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000762
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000763 assert(ret <= 0);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200764 e = ERR_peek_last_error();
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000765
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700766 if (sslsock->ssl != NULL) {
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700767 err = sslsock->err;
Thomas Woutersed03b412007-08-28 21:37:11 +0000768
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700769 switch (err.ssl) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000770 case SSL_ERROR_ZERO_RETURN:
Antoine Pitrou41032a62011-10-27 23:56:55 +0200771 errstr = "TLS/SSL connection has been closed (EOF)";
772 type = PySSLZeroReturnErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000773 p = PY_SSL_ERROR_ZERO_RETURN;
774 break;
775 case SSL_ERROR_WANT_READ:
776 errstr = "The operation did not complete (read)";
Antoine Pitrou41032a62011-10-27 23:56:55 +0200777 type = PySSLWantReadErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000778 p = PY_SSL_ERROR_WANT_READ;
779 break;
780 case SSL_ERROR_WANT_WRITE:
781 p = PY_SSL_ERROR_WANT_WRITE;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200782 type = PySSLWantWriteErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000783 errstr = "The operation did not complete (write)";
784 break;
785 case SSL_ERROR_WANT_X509_LOOKUP:
786 p = PY_SSL_ERROR_WANT_X509_LOOKUP;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000787 errstr = "The operation did not complete (X509 lookup)";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000788 break;
789 case SSL_ERROR_WANT_CONNECT:
790 p = PY_SSL_ERROR_WANT_CONNECT;
791 errstr = "The operation did not complete (connect)";
792 break;
793 case SSL_ERROR_SYSCALL:
794 {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000795 if (e == 0) {
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700796 PySocketSockObject *s = GET_SOCKET(sslsock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000797 if (ret == 0 || (((PyObject *)s) == Py_None)) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000798 p = PY_SSL_ERROR_EOF;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200799 type = PySSLEOFErrorObject;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000800 errstr = "EOF occurred in violation of protocol";
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200801 } else if (s && ret == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000802 /* underlying BIO reported an I/O error */
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000803 ERR_clear_error();
Steve Dowere6eb48c2017-09-08 15:16:15 -0700804#ifdef MS_WINDOWS
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700805 if (err.ws) {
806 return PyErr_SetFromWindowsErr(err.ws);
807 }
Steve Dowere6eb48c2017-09-08 15:16:15 -0700808#endif
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700809 if (err.c) {
810 errno = err.c;
Steve Dowere6eb48c2017-09-08 15:16:15 -0700811 return PyErr_SetFromErrno(PyExc_OSError);
812 }
Dima Tisnek495bd032020-08-16 02:01:19 +0900813 else {
814 p = PY_SSL_ERROR_EOF;
815 type = PySSLEOFErrorObject;
816 errstr = "EOF occurred in violation of protocol";
817 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000818 } else { /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000819 p = PY_SSL_ERROR_SYSCALL;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200820 type = PySSLSyscallErrorObject;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000821 errstr = "Some I/O error occurred";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000822 }
823 } else {
824 p = PY_SSL_ERROR_SYSCALL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000825 }
826 break;
827 }
828 case SSL_ERROR_SSL:
829 {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000830 p = PY_SSL_ERROR_SSL;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700831 if (e == 0) {
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200832 /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000833 errstr = "A failure in the SSL library occurred";
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700834 }
835 if (ERR_GET_LIB(e) == ERR_LIB_SSL &&
836 ERR_GET_REASON(e) == SSL_R_CERTIFICATE_VERIFY_FAILED) {
837 type = PySSLCertVerificationErrorObject;
838 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000839 break;
840 }
841 default:
842 p = PY_SSL_ERROR_INVALID_ERROR_CODE;
843 errstr = "Invalid error code";
844 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000845 }
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700846 fill_and_set_sslerror(sslsock, type, p, errstr, lineno, e);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000847 ERR_clear_error();
Christian Heimesc7f70692019-05-31 11:44:05 +0200848 PySSL_ChainExceptions(sslsock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000849 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000850}
851
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000852static PyObject *
Serhiy Storchakaef1585e2015-12-25 20:01:53 +0200853_setSSLError (const char *errstr, int errcode, const char *filename, int lineno) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000854
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200855 if (errstr == NULL)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000856 errcode = ERR_peek_last_error();
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200857 else
858 errcode = 0;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700859 fill_and_set_sslerror(NULL, PySSLErrorObject, errcode, errstr, lineno, errcode);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000860 ERR_clear_error();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000861 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000862}
863
Christian Heimes61d478c2018-01-27 15:51:38 +0100864/*
865 * SSL objects
866 */
867
868static int
869_ssl_configure_hostname(PySSLSocket *self, const char* server_hostname)
870{
871 int retval = -1;
872 ASN1_OCTET_STRING *ip;
873 PyObject *hostname;
874 size_t len;
875
876 assert(server_hostname);
877
878 /* Disable OpenSSL's special mode with leading dot in hostname:
879 * When name starts with a dot (e.g ".example.com"), it will be
880 * matched by a certificate valid for any sub-domain of name.
881 */
882 len = strlen(server_hostname);
883 if (len == 0 || *server_hostname == '.') {
884 PyErr_SetString(
885 PyExc_ValueError,
886 "server_hostname cannot be an empty string or start with a "
887 "leading dot.");
888 return retval;
889 }
890
891 /* inet_pton is not available on all platforms. */
892 ip = a2i_IPADDRESS(server_hostname);
893 if (ip == NULL) {
894 ERR_clear_error();
895 }
896
Christian Heimes11a14932018-02-24 02:35:08 +0100897 hostname = PyUnicode_Decode(server_hostname, len, "ascii", "strict");
Christian Heimes61d478c2018-01-27 15:51:38 +0100898 if (hostname == NULL) {
899 goto error;
900 }
901 self->server_hostname = hostname;
902
903 /* Only send SNI extension for non-IP hostnames */
904 if (ip == NULL) {
905 if (!SSL_set_tlsext_host_name(self->ssl, server_hostname)) {
906 _setSSLError(NULL, 0, __FILE__, __LINE__);
Zackery Spytzc32f2972020-10-25 12:02:30 -0600907 goto error;
Christian Heimes61d478c2018-01-27 15:51:38 +0100908 }
909 }
910 if (self->ctx->check_hostname) {
911 X509_VERIFY_PARAM *param = SSL_get0_param(self->ssl);
912 if (ip == NULL) {
Christian Heimesd02ac252018-03-25 12:36:13 +0200913 if (!X509_VERIFY_PARAM_set1_host(param, server_hostname,
914 strlen(server_hostname))) {
Christian Heimes61d478c2018-01-27 15:51:38 +0100915 _setSSLError(NULL, 0, __FILE__, __LINE__);
916 goto error;
917 }
918 } else {
Christian Heimesa871f692020-06-01 08:58:14 +0200919 if (!X509_VERIFY_PARAM_set1_ip(param, ASN1_STRING_get0_data(ip),
Christian Heimes61d478c2018-01-27 15:51:38 +0100920 ASN1_STRING_length(ip))) {
921 _setSSLError(NULL, 0, __FILE__, __LINE__);
922 goto error;
923 }
924 }
925 }
926 retval = 0;
927 error:
928 if (ip != NULL) {
929 ASN1_OCTET_STRING_free(ip);
930 }
931 return retval;
932}
933
Antoine Pitrou152efa22010-05-16 18:19:27 +0000934static PySSLSocket *
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100935newPySSLSocket(PySSLContext *sslctx, PySocketSockObject *sock,
Antoine Pitroud5323212010-10-22 18:19:07 +0000936 enum py_ssl_server_or_client socket_type,
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200937 char *server_hostname,
Christian Heimes141c5e82018-02-24 21:10:57 +0100938 PyObject *owner, PyObject *session,
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200939 PySSLMemoryBIO *inbio, PySSLMemoryBIO *outbio)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000940{
Antoine Pitrou152efa22010-05-16 18:19:27 +0000941 PySSLSocket *self;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100942 SSL_CTX *ctx = sslctx->ctx;
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700943 _PySSLError err = { 0 };
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000944
Christian Heimes5c36da72020-11-20 09:40:12 +0100945 self = PyObject_New(PySSLSocket, PySSLSocket_Type);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000946 if (self == NULL)
947 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000948
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000949 self->ssl = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000950 self->Socket = NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100951 self->ctx = sslctx;
Nathaniel J. Smith65ece7c2017-06-07 23:30:43 -0700952 Py_INCREF(sslctx);
Antoine Pitrou860aee72013-09-29 19:52:45 +0200953 self->shutdown_seen_zero = 0;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200954 self->owner = NULL;
Benjamin Peterson81b9ecd2016-08-15 21:55:37 -0700955 self->server_hostname = NULL;
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700956 self->err = err;
Christian Heimesc7f70692019-05-31 11:44:05 +0200957 self->exc_type = NULL;
958 self->exc_value = NULL;
959 self->exc_tb = NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200960
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000961 /* Make sure the SSL error state is initialized */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000962 ERR_clear_error();
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000963
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000964 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitrou152efa22010-05-16 18:19:27 +0000965 self->ssl = SSL_new(ctx);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000966 PySSL_END_ALLOW_THREADS
Zackery Spytz4c49da02018-12-07 03:11:30 -0700967 if (self->ssl == NULL) {
968 Py_DECREF(self);
969 _setSSLError(NULL, 0, __FILE__, __LINE__);
970 return NULL;
971 }
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
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01003206 SSL_CTX_set_options(self->ctx, options);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003207
Semen Zhydenko1295e112017-10-15 21:28:31 +02003208 /* A bare minimum cipher list without completely broken cipher suites.
Christian Heimes358cfd42016-09-10 22:43:48 +02003209 * It's far from perfect but gives users a better head start. */
3210 if (proto_version != PY_SSL_VERSION_SSL2) {
Christian Heimes892d66e2018-01-29 14:10:18 +01003211#if PY_SSL_DEFAULT_CIPHERS == 2
3212 /* stick to OpenSSL's default settings */
3213 result = 1;
3214#else
3215 result = SSL_CTX_set_cipher_list(ctx, PY_SSL_DEFAULT_CIPHER_STRING);
3216#endif
Christian Heimes358cfd42016-09-10 22:43:48 +02003217 } else {
3218 /* SSLv2 needs MD5 */
3219 result = SSL_CTX_set_cipher_list(ctx, "HIGH:!aNULL:!eNULL");
3220 }
3221 if (result == 0) {
3222 Py_DECREF(self);
3223 ERR_clear_error();
3224 PyErr_SetString(PySSLErrorObject,
3225 "No cipher can be selected.");
3226 return NULL;
3227 }
3228
Benjamin Peterson3b1a8b32016-01-07 21:37:37 -08003229#if defined(SSL_MODE_RELEASE_BUFFERS)
3230 /* Set SSL_MODE_RELEASE_BUFFERS. This potentially greatly reduces memory
3231 usage for no cost at all. However, don't do this for OpenSSL versions
3232 between 1.0.1 and 1.0.1h or 1.0.0 and 1.0.0m, which are affected by CVE
3233 2014-0198. I can't find exactly which beta fixed this CVE, so be
3234 conservative and assume it wasn't fixed until release. We do this check
3235 at runtime to avoid problems from the dynamic linker.
3236 See #25672 for more on this. */
Christian Heimesa871f692020-06-01 08:58:14 +02003237 libver = OpenSSL_version_num();
Benjamin Peterson3b1a8b32016-01-07 21:37:37 -08003238 if (!(libver >= 0x10001000UL && libver < 0x1000108fUL) &&
3239 !(libver >= 0x10000000UL && libver < 0x100000dfUL)) {
3240 SSL_CTX_set_mode(self->ctx, SSL_MODE_RELEASE_BUFFERS);
3241 }
3242#endif
3243
3244
Donald Stufft8ae264c2017-03-02 11:45:29 -05003245#if !defined(OPENSSL_NO_ECDH) && !defined(OPENSSL_VERSION_1_1)
Antoine Pitrou0bebbc32014-03-22 18:13:50 +01003246 /* Allow automatic ECDH curve selection (on OpenSSL 1.0.2+), or use
3247 prime256v1 by default. This is Apache mod_ssl's initialization
Christian Heimes598894f2016-09-05 23:19:05 +02003248 policy, so we should be safe. OpenSSL 1.1 has it enabled by default.
3249 */
Donald Stufft8ae264c2017-03-02 11:45:29 -05003250#if defined(SSL_CTX_set_ecdh_auto)
Antoine Pitrou0bebbc32014-03-22 18:13:50 +01003251 SSL_CTX_set_ecdh_auto(self->ctx, 1);
3252#else
3253 {
3254 EC_KEY *key = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
3255 SSL_CTX_set_tmp_ecdh(self->ctx, key);
3256 EC_KEY_free(key);
3257 }
3258#endif
3259#endif
3260
Antoine Pitroufc113ee2010-10-13 12:46:13 +00003261#define SID_CTX "Python"
3262 SSL_CTX_set_session_id_context(self->ctx, (const unsigned char *) SID_CTX,
3263 sizeof(SID_CTX));
3264#undef SID_CTX
3265
Christian Heimes61d478c2018-01-27 15:51:38 +01003266 params = SSL_CTX_get0_param(self->ctx);
Benjamin Petersonfdb19712015-03-04 22:11:12 -05003267#ifdef X509_V_FLAG_TRUSTED_FIRST
Christian Heimes61d478c2018-01-27 15:51:38 +01003268 /* Improve trust chain building when cross-signed intermediate
3269 certificates are present. See https://bugs.python.org/issue23476. */
3270 X509_VERIFY_PARAM_set_flags(params, X509_V_FLAG_TRUSTED_FIRST);
Benjamin Petersonfdb19712015-03-04 22:11:12 -05003271#endif
Christian Heimes61d478c2018-01-27 15:51:38 +01003272 X509_VERIFY_PARAM_set_hostflags(params, self->hostflags);
Benjamin Petersonfdb19712015-03-04 22:11:12 -05003273
Christian Heimes9fb051f2018-09-23 08:32:31 +02003274#ifdef TLS1_3_VERSION
3275 self->post_handshake_auth = 0;
3276 SSL_CTX_set_post_handshake_auth(self->ctx, self->post_handshake_auth);
3277#endif
3278
Antoine Pitrou152efa22010-05-16 18:19:27 +00003279 return (PyObject *)self;
3280}
3281
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003282static int
3283context_traverse(PySSLContext *self, visitproc visit, void *arg)
3284{
3285#ifndef OPENSSL_NO_TLSEXT
Christian Heimes11a14932018-02-24 02:35:08 +01003286 Py_VISIT(self->set_sni_cb);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003287#endif
Christian Heimesc7f70692019-05-31 11:44:05 +02003288 Py_VISIT(self->msg_cb);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003289 return 0;
3290}
3291
3292static int
3293context_clear(PySSLContext *self)
3294{
3295#ifndef OPENSSL_NO_TLSEXT
Christian Heimes11a14932018-02-24 02:35:08 +01003296 Py_CLEAR(self->set_sni_cb);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003297#endif
Christian Heimesc7f70692019-05-31 11:44:05 +02003298 Py_CLEAR(self->msg_cb);
3299#ifdef HAVE_OPENSSL_KEYLOG
3300 Py_CLEAR(self->keylog_filename);
3301 if (self->keylog_bio != NULL) {
3302 PySSL_BEGIN_ALLOW_THREADS
3303 BIO_free_all(self->keylog_bio);
3304 PySSL_END_ALLOW_THREADS
3305 self->keylog_bio = NULL;
3306 }
3307#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003308 return 0;
3309}
3310
Antoine Pitrou152efa22010-05-16 18:19:27 +00003311static void
3312context_dealloc(PySSLContext *self)
3313{
Christian Heimes5c36da72020-11-20 09:40:12 +01003314 PyTypeObject *tp = Py_TYPE(self);
INADA Naokia6296d32017-08-24 14:55:17 +09003315 /* bpo-31095: UnTrack is needed before calling any callbacks */
3316 PyObject_GC_UnTrack(self);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003317 context_clear(self);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003318 SSL_CTX_free(self->ctx);
Christian Heimes29eab552018-02-25 12:31:33 +01003319#if HAVE_NPN
Victor Stinner00d7abd2020-12-01 09:56:42 +01003320 PyMem_Free(self->npn_protocols);
Benjamin Petersoncca27322015-01-23 16:35:37 -05003321#endif
Christian Heimes29eab552018-02-25 12:31:33 +01003322#if HAVE_ALPN
Victor Stinner00d7abd2020-12-01 09:56:42 +01003323 PyMem_Free(self->alpn_protocols);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003324#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00003325 Py_TYPE(self)->tp_free(self);
Christian Heimes5c36da72020-11-20 09:40:12 +01003326 Py_DECREF(tp);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003327}
3328
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003329/*[clinic input]
3330_ssl._SSLContext.set_ciphers
3331 cipherlist: str
3332 /
3333[clinic start generated code]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003334
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003335static PyObject *
3336_ssl__SSLContext_set_ciphers_impl(PySSLContext *self, const char *cipherlist)
3337/*[clinic end generated code: output=3a3162f3557c0f3f input=a7ac931b9f3ca7fc]*/
3338{
3339 int ret = SSL_CTX_set_cipher_list(self->ctx, cipherlist);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003340 if (ret == 0) {
Antoine Pitrou65ec8ae2010-05-16 19:56:32 +00003341 /* Clearing the error queue is necessary on some OpenSSL versions,
3342 otherwise the error will be reported again when another SSL call
3343 is done. */
3344 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00003345 PyErr_SetString(PySSLErrorObject,
3346 "No cipher can be selected.");
3347 return NULL;
3348 }
3349 Py_RETURN_NONE;
3350}
3351
Christian Heimes25bfcd52016-09-06 00:04:45 +02003352#if OPENSSL_VERSION_NUMBER >= 0x10002000UL
3353/*[clinic input]
3354_ssl._SSLContext.get_ciphers
3355[clinic start generated code]*/
3356
3357static PyObject *
3358_ssl__SSLContext_get_ciphers_impl(PySSLContext *self)
3359/*[clinic end generated code: output=a56e4d68a406dfc4 input=a2aadc9af89b79c5]*/
3360{
3361 SSL *ssl = NULL;
3362 STACK_OF(SSL_CIPHER) *sk = NULL;
Christian Heimes99a65702016-09-10 23:44:53 +02003363 const SSL_CIPHER *cipher;
Christian Heimes25bfcd52016-09-06 00:04:45 +02003364 int i=0;
3365 PyObject *result = NULL, *dct;
3366
3367 ssl = SSL_new(self->ctx);
3368 if (ssl == NULL) {
3369 _setSSLError(NULL, 0, __FILE__, __LINE__);
3370 goto exit;
3371 }
3372 sk = SSL_get_ciphers(ssl);
3373
3374 result = PyList_New(sk_SSL_CIPHER_num(sk));
3375 if (result == NULL) {
3376 goto exit;
3377 }
3378
3379 for (i = 0; i < sk_SSL_CIPHER_num(sk); i++) {
3380 cipher = sk_SSL_CIPHER_value(sk, i);
3381 dct = cipher_to_dict(cipher);
3382 if (dct == NULL) {
3383 Py_CLEAR(result);
3384 goto exit;
3385 }
3386 PyList_SET_ITEM(result, i, dct);
3387 }
3388
3389 exit:
3390 if (ssl != NULL)
3391 SSL_free(ssl);
3392 return result;
3393
3394}
3395#endif
3396
3397
Christian Heimes29eab552018-02-25 12:31:33 +01003398#if HAVE_NPN || HAVE_ALPN
Benjamin Petersoncca27322015-01-23 16:35:37 -05003399static int
Benjamin Peterson88615022015-01-23 17:30:26 -05003400do_protocol_selection(int alpn, unsigned char **out, unsigned char *outlen,
3401 const unsigned char *server_protocols, unsigned int server_protocols_len,
3402 const unsigned char *client_protocols, unsigned int client_protocols_len)
Benjamin Petersoncca27322015-01-23 16:35:37 -05003403{
Benjamin Peterson88615022015-01-23 17:30:26 -05003404 int ret;
3405 if (client_protocols == NULL) {
3406 client_protocols = (unsigned char *)"";
3407 client_protocols_len = 0;
3408 }
3409 if (server_protocols == NULL) {
3410 server_protocols = (unsigned char *)"";
3411 server_protocols_len = 0;
Benjamin Petersoncca27322015-01-23 16:35:37 -05003412 }
3413
Benjamin Peterson88615022015-01-23 17:30:26 -05003414 ret = SSL_select_next_proto(out, outlen,
3415 server_protocols, server_protocols_len,
3416 client_protocols, client_protocols_len);
3417 if (alpn && ret != OPENSSL_NPN_NEGOTIATED)
3418 return SSL_TLSEXT_ERR_NOACK;
Benjamin Petersoncca27322015-01-23 16:35:37 -05003419
3420 return SSL_TLSEXT_ERR_OK;
3421}
Melvyn Sopacuab2d096b2017-09-04 23:35:15 +02003422#endif
Benjamin Petersoncca27322015-01-23 16:35:37 -05003423
Christian Heimes29eab552018-02-25 12:31:33 +01003424#if HAVE_NPN
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003425/* this callback gets passed to SSL_CTX_set_next_protos_advertise_cb */
3426static int
Victor Stinner4569cd52013-06-23 14:58:43 +02003427_advertiseNPN_cb(SSL *s,
3428 const unsigned char **data, unsigned int *len,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003429 void *args)
3430{
3431 PySSLContext *ssl_ctx = (PySSLContext *) args;
3432
3433 if (ssl_ctx->npn_protocols == NULL) {
Benjamin Petersoncca27322015-01-23 16:35:37 -05003434 *data = (unsigned char *)"";
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003435 *len = 0;
3436 } else {
Benjamin Petersoncca27322015-01-23 16:35:37 -05003437 *data = ssl_ctx->npn_protocols;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003438 *len = ssl_ctx->npn_protocols_len;
3439 }
3440
3441 return SSL_TLSEXT_ERR_OK;
3442}
3443/* this callback gets passed to SSL_CTX_set_next_proto_select_cb */
3444static int
Victor Stinner4569cd52013-06-23 14:58:43 +02003445_selectNPN_cb(SSL *s,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003446 unsigned char **out, unsigned char *outlen,
3447 const unsigned char *server, unsigned int server_len,
3448 void *args)
3449{
Benjamin Petersoncca27322015-01-23 16:35:37 -05003450 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Peterson88615022015-01-23 17:30:26 -05003451 return do_protocol_selection(0, out, outlen, server, server_len,
Benjamin Petersoncca27322015-01-23 16:35:37 -05003452 ctx->npn_protocols, ctx->npn_protocols_len);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003453}
3454#endif
3455
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003456/*[clinic input]
3457_ssl._SSLContext._set_npn_protocols
3458 protos: Py_buffer
3459 /
3460[clinic start generated code]*/
3461
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003462static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003463_ssl__SSLContext__set_npn_protocols_impl(PySSLContext *self,
3464 Py_buffer *protos)
3465/*[clinic end generated code: output=72b002c3324390c6 input=319fcb66abf95bd7]*/
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003466{
Christian Heimes29eab552018-02-25 12:31:33 +01003467#if HAVE_NPN
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003468 PyMem_Free(self->npn_protocols);
3469 self->npn_protocols = PyMem_Malloc(protos->len);
3470 if (self->npn_protocols == NULL)
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003471 return PyErr_NoMemory();
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003472 memcpy(self->npn_protocols, protos->buf, protos->len);
3473 self->npn_protocols_len = (int) protos->len;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003474
3475 /* set both server and client callbacks, because the context can
3476 * be used to create both types of sockets */
3477 SSL_CTX_set_next_protos_advertised_cb(self->ctx,
3478 _advertiseNPN_cb,
3479 self);
3480 SSL_CTX_set_next_proto_select_cb(self->ctx,
3481 _selectNPN_cb,
3482 self);
3483
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003484 Py_RETURN_NONE;
3485#else
3486 PyErr_SetString(PyExc_NotImplementedError,
3487 "The NPN extension requires OpenSSL 1.0.1 or later.");
3488 return NULL;
3489#endif
3490}
3491
Christian Heimes29eab552018-02-25 12:31:33 +01003492#if HAVE_ALPN
Benjamin Petersoncca27322015-01-23 16:35:37 -05003493static int
3494_selectALPN_cb(SSL *s,
3495 const unsigned char **out, unsigned char *outlen,
3496 const unsigned char *client_protocols, unsigned int client_protocols_len,
3497 void *args)
3498{
3499 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Peterson88615022015-01-23 17:30:26 -05003500 return do_protocol_selection(1, (unsigned char **)out, outlen,
3501 ctx->alpn_protocols, ctx->alpn_protocols_len,
3502 client_protocols, client_protocols_len);
Benjamin Petersoncca27322015-01-23 16:35:37 -05003503}
3504#endif
3505
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003506/*[clinic input]
3507_ssl._SSLContext._set_alpn_protocols
3508 protos: Py_buffer
3509 /
3510[clinic start generated code]*/
3511
Benjamin Petersoncca27322015-01-23 16:35:37 -05003512static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003513_ssl__SSLContext__set_alpn_protocols_impl(PySSLContext *self,
3514 Py_buffer *protos)
3515/*[clinic end generated code: output=87599a7f76651a9b input=9bba964595d519be]*/
Benjamin Petersoncca27322015-01-23 16:35:37 -05003516{
Christian Heimes29eab552018-02-25 12:31:33 +01003517#if HAVE_ALPN
Victor Stinner5a615592017-09-14 01:10:30 -07003518 if ((size_t)protos->len > UINT_MAX) {
Segev Finer5cff6372017-07-27 01:19:17 +03003519 PyErr_Format(PyExc_OverflowError,
Serhiy Storchakad53fe5f2019-03-13 22:59:55 +02003520 "protocols longer than %u bytes", UINT_MAX);
Segev Finer5cff6372017-07-27 01:19:17 +03003521 return NULL;
3522 }
3523
Victor Stinner00d7abd2020-12-01 09:56:42 +01003524 PyMem_Free(self->alpn_protocols);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003525 self->alpn_protocols = PyMem_Malloc(protos->len);
Benjamin Petersoncca27322015-01-23 16:35:37 -05003526 if (!self->alpn_protocols)
3527 return PyErr_NoMemory();
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003528 memcpy(self->alpn_protocols, protos->buf, protos->len);
Segev Finer5cff6372017-07-27 01:19:17 +03003529 self->alpn_protocols_len = (unsigned int)protos->len;
Benjamin Petersoncca27322015-01-23 16:35:37 -05003530
3531 if (SSL_CTX_set_alpn_protos(self->ctx, self->alpn_protocols, self->alpn_protocols_len))
3532 return PyErr_NoMemory();
3533 SSL_CTX_set_alpn_select_cb(self->ctx, _selectALPN_cb, self);
3534
Benjamin Petersoncca27322015-01-23 16:35:37 -05003535 Py_RETURN_NONE;
3536#else
3537 PyErr_SetString(PyExc_NotImplementedError,
3538 "The ALPN extension requires OpenSSL 1.0.2 or later.");
3539 return NULL;
3540#endif
3541}
3542
Antoine Pitrou152efa22010-05-16 18:19:27 +00003543static PyObject *
3544get_verify_mode(PySSLContext *self, void *c)
3545{
Christian Heimes9fb051f2018-09-23 08:32:31 +02003546 /* ignore SSL_VERIFY_CLIENT_ONCE and SSL_VERIFY_POST_HANDSHAKE */
3547 int mask = (SSL_VERIFY_NONE | SSL_VERIFY_PEER |
3548 SSL_VERIFY_FAIL_IF_NO_PEER_CERT);
3549 switch (SSL_CTX_get_verify_mode(self->ctx) & mask) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003550 case SSL_VERIFY_NONE:
3551 return PyLong_FromLong(PY_SSL_CERT_NONE);
3552 case SSL_VERIFY_PEER:
3553 return PyLong_FromLong(PY_SSL_CERT_OPTIONAL);
3554 case SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT:
3555 return PyLong_FromLong(PY_SSL_CERT_REQUIRED);
3556 }
3557 PyErr_SetString(PySSLErrorObject,
3558 "invalid return value from SSL_CTX_get_verify_mode");
3559 return NULL;
3560}
3561
3562static int
3563set_verify_mode(PySSLContext *self, PyObject *arg, void *c)
3564{
Christian Heimes5fe668c2016-09-12 00:01:11 +02003565 int n;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003566 if (!PyArg_Parse(arg, "i", &n))
3567 return -1;
Christian Heimes5fe668c2016-09-12 00:01:11 +02003568 if (n == PY_SSL_CERT_NONE && self->check_hostname) {
Christian Heimes1aa9a752013-12-02 02:41:19 +01003569 PyErr_SetString(PyExc_ValueError,
3570 "Cannot set verify_mode to CERT_NONE when "
3571 "check_hostname is enabled.");
3572 return -1;
3573 }
Christian Heimes9fb051f2018-09-23 08:32:31 +02003574 return _set_verify_mode(self, n);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003575}
3576
3577static PyObject *
Christian Heimes22587792013-11-21 23:56:13 +01003578get_verify_flags(PySSLContext *self, void *c)
3579{
Christian Heimes598894f2016-09-05 23:19:05 +02003580 X509_VERIFY_PARAM *param;
Christian Heimes22587792013-11-21 23:56:13 +01003581 unsigned long flags;
3582
Christian Heimes61d478c2018-01-27 15:51:38 +01003583 param = SSL_CTX_get0_param(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02003584 flags = X509_VERIFY_PARAM_get_flags(param);
Christian Heimes22587792013-11-21 23:56:13 +01003585 return PyLong_FromUnsignedLong(flags);
3586}
3587
3588static int
3589set_verify_flags(PySSLContext *self, PyObject *arg, void *c)
3590{
Christian Heimes598894f2016-09-05 23:19:05 +02003591 X509_VERIFY_PARAM *param;
Christian Heimes22587792013-11-21 23:56:13 +01003592 unsigned long new_flags, flags, set, clear;
3593
3594 if (!PyArg_Parse(arg, "k", &new_flags))
3595 return -1;
Christian Heimes61d478c2018-01-27 15:51:38 +01003596 param = SSL_CTX_get0_param(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02003597 flags = X509_VERIFY_PARAM_get_flags(param);
Christian Heimes22587792013-11-21 23:56:13 +01003598 clear = flags & ~new_flags;
3599 set = ~flags & new_flags;
3600 if (clear) {
Christian Heimes598894f2016-09-05 23:19:05 +02003601 if (!X509_VERIFY_PARAM_clear_flags(param, clear)) {
Christian Heimes22587792013-11-21 23:56:13 +01003602 _setSSLError(NULL, 0, __FILE__, __LINE__);
3603 return -1;
3604 }
3605 }
3606 if (set) {
Christian Heimes598894f2016-09-05 23:19:05 +02003607 if (!X509_VERIFY_PARAM_set_flags(param, set)) {
Christian Heimes22587792013-11-21 23:56:13 +01003608 _setSSLError(NULL, 0, __FILE__, __LINE__);
3609 return -1;
3610 }
3611 }
3612 return 0;
3613}
3614
Christian Heimes698dde12018-02-27 11:54:43 +01003615/* Getter and setter for protocol version */
3616#if defined(SSL_CTRL_GET_MAX_PROTO_VERSION)
3617
3618
3619static int
3620set_min_max_proto_version(PySSLContext *self, PyObject *arg, int what)
3621{
3622 long v;
3623 int result;
3624
3625 if (!PyArg_Parse(arg, "l", &v))
3626 return -1;
3627 if (v > INT_MAX) {
3628 PyErr_SetString(PyExc_OverflowError, "Option is too long");
3629 return -1;
3630 }
3631
3632 switch(self->protocol) {
3633 case PY_SSL_VERSION_TLS_CLIENT: /* fall through */
3634 case PY_SSL_VERSION_TLS_SERVER: /* fall through */
3635 case PY_SSL_VERSION_TLS:
3636 break;
3637 default:
3638 PyErr_SetString(
3639 PyExc_ValueError,
3640 "The context's protocol doesn't support modification of "
3641 "highest and lowest version."
3642 );
3643 return -1;
3644 }
3645
3646 if (what == 0) {
3647 switch(v) {
3648 case PY_PROTO_MINIMUM_SUPPORTED:
3649 v = 0;
3650 break;
3651 case PY_PROTO_MAXIMUM_SUPPORTED:
3652 /* Emulate max for set_min_proto_version */
3653 v = PY_PROTO_MAXIMUM_AVAILABLE;
3654 break;
3655 default:
3656 break;
3657 }
3658 result = SSL_CTX_set_min_proto_version(self->ctx, v);
3659 }
3660 else {
3661 switch(v) {
3662 case PY_PROTO_MAXIMUM_SUPPORTED:
3663 v = 0;
3664 break;
3665 case PY_PROTO_MINIMUM_SUPPORTED:
3666 /* Emulate max for set_min_proto_version */
3667 v = PY_PROTO_MINIMUM_AVAILABLE;
3668 break;
3669 default:
3670 break;
3671 }
3672 result = SSL_CTX_set_max_proto_version(self->ctx, v);
3673 }
3674 if (result == 0) {
3675 PyErr_Format(PyExc_ValueError,
3676 "Unsupported protocol version 0x%x", v);
3677 return -1;
3678 }
3679 return 0;
3680}
3681
3682static PyObject *
3683get_minimum_version(PySSLContext *self, void *c)
3684{
3685 int v = SSL_CTX_ctrl(self->ctx, SSL_CTRL_GET_MIN_PROTO_VERSION, 0, NULL);
3686 if (v == 0) {
3687 v = PY_PROTO_MINIMUM_SUPPORTED;
3688 }
3689 return PyLong_FromLong(v);
3690}
3691
3692static int
3693set_minimum_version(PySSLContext *self, PyObject *arg, void *c)
3694{
3695 return set_min_max_proto_version(self, arg, 0);
3696}
3697
3698static PyObject *
3699get_maximum_version(PySSLContext *self, void *c)
3700{
3701 int v = SSL_CTX_ctrl(self->ctx, SSL_CTRL_GET_MAX_PROTO_VERSION, 0, NULL);
3702 if (v == 0) {
3703 v = PY_PROTO_MAXIMUM_SUPPORTED;
3704 }
3705 return PyLong_FromLong(v);
3706}
3707
3708static int
3709set_maximum_version(PySSLContext *self, PyObject *arg, void *c)
3710{
3711 return set_min_max_proto_version(self, arg, 1);
3712}
3713#endif /* SSL_CTRL_GET_MAX_PROTO_VERSION */
3714
Christian Heimes78c7d522019-06-03 21:00:10 +02003715#if (OPENSSL_VERSION_NUMBER >= 0x10101000L) && !defined(LIBRESSL_VERSION_NUMBER)
3716static PyObject *
3717get_num_tickets(PySSLContext *self, void *c)
3718{
Victor Stinner76611c72019-07-09 13:30:52 +02003719 return PyLong_FromSize_t(SSL_CTX_get_num_tickets(self->ctx));
Christian Heimes78c7d522019-06-03 21:00:10 +02003720}
3721
3722static int
3723set_num_tickets(PySSLContext *self, PyObject *arg, void *c)
3724{
3725 long num;
3726 if (!PyArg_Parse(arg, "l", &num))
3727 return -1;
3728 if (num < 0) {
3729 PyErr_SetString(PyExc_ValueError, "value must be non-negative");
3730 return -1;
3731 }
3732 if (self->protocol != PY_SSL_VERSION_TLS_SERVER) {
3733 PyErr_SetString(PyExc_ValueError,
3734 "SSLContext is not a server context.");
3735 return -1;
3736 }
3737 if (SSL_CTX_set_num_tickets(self->ctx, num) != 1) {
3738 PyErr_SetString(PyExc_ValueError, "failed to set num tickets.");
3739 return -1;
3740 }
3741 return 0;
3742}
3743
3744PyDoc_STRVAR(PySSLContext_num_tickets_doc,
3745"Control the number of TLSv1.3 session tickets");
3746#endif /* OpenSSL 1.1.1 */
3747
matthewhughes9348e836bb2020-07-17 09:59:15 +01003748#if (OPENSSL_VERSION_NUMBER >= 0x10100000L) && !defined(LIBRESSL_VERSION_NUMBER)
3749static PyObject *
3750get_security_level(PySSLContext *self, void *c)
3751{
3752 return PyLong_FromLong(SSL_CTX_get_security_level(self->ctx));
3753}
3754PyDoc_STRVAR(PySSLContext_security_level_doc, "The current security level");
3755#endif /* OpenSSL 1.1.0 */
3756
Christian Heimes22587792013-11-21 23:56:13 +01003757static PyObject *
Antoine Pitroub5218772010-05-21 09:56:06 +00003758get_options(PySSLContext *self, void *c)
3759{
3760 return PyLong_FromLong(SSL_CTX_get_options(self->ctx));
3761}
3762
3763static int
3764set_options(PySSLContext *self, PyObject *arg, void *c)
3765{
3766 long new_opts, opts, set, clear;
3767 if (!PyArg_Parse(arg, "l", &new_opts))
3768 return -1;
3769 opts = SSL_CTX_get_options(self->ctx);
3770 clear = opts & ~new_opts;
3771 set = ~opts & new_opts;
3772 if (clear) {
3773#ifdef HAVE_SSL_CTX_CLEAR_OPTIONS
3774 SSL_CTX_clear_options(self->ctx, clear);
3775#else
3776 PyErr_SetString(PyExc_ValueError,
3777 "can't clear options before OpenSSL 0.9.8m");
3778 return -1;
3779#endif
3780 }
3781 if (set)
3782 SSL_CTX_set_options(self->ctx, set);
3783 return 0;
3784}
3785
Christian Heimes1aa9a752013-12-02 02:41:19 +01003786static PyObject *
Christian Heimes61d478c2018-01-27 15:51:38 +01003787get_host_flags(PySSLContext *self, void *c)
3788{
3789 return PyLong_FromUnsignedLong(self->hostflags);
3790}
3791
3792static int
3793set_host_flags(PySSLContext *self, PyObject *arg, void *c)
3794{
3795 X509_VERIFY_PARAM *param;
3796 unsigned int new_flags = 0;
3797
3798 if (!PyArg_Parse(arg, "I", &new_flags))
3799 return -1;
3800
3801 param = SSL_CTX_get0_param(self->ctx);
3802 self->hostflags = new_flags;
3803 X509_VERIFY_PARAM_set_hostflags(param, new_flags);
3804 return 0;
3805}
3806
3807static PyObject *
Christian Heimes1aa9a752013-12-02 02:41:19 +01003808get_check_hostname(PySSLContext *self, void *c)
3809{
3810 return PyBool_FromLong(self->check_hostname);
3811}
3812
3813static int
3814set_check_hostname(PySSLContext *self, PyObject *arg, void *c)
3815{
3816 int check_hostname;
3817 if (!PyArg_Parse(arg, "p", &check_hostname))
3818 return -1;
3819 if (check_hostname &&
3820 SSL_CTX_get_verify_mode(self->ctx) == SSL_VERIFY_NONE) {
Christian Heimese82c0342017-09-15 20:29:57 +02003821 /* check_hostname = True sets verify_mode = CERT_REQUIRED */
Christian Heimes9fb051f2018-09-23 08:32:31 +02003822 if (_set_verify_mode(self, PY_SSL_CERT_REQUIRED) == -1) {
Christian Heimese82c0342017-09-15 20:29:57 +02003823 return -1;
3824 }
Christian Heimes1aa9a752013-12-02 02:41:19 +01003825 }
3826 self->check_hostname = check_hostname;
3827 return 0;
3828}
3829
Christian Heimes11a14932018-02-24 02:35:08 +01003830static PyObject *
Christian Heimes9fb051f2018-09-23 08:32:31 +02003831get_post_handshake_auth(PySSLContext *self, void *c) {
3832#if TLS1_3_VERSION
3833 return PyBool_FromLong(self->post_handshake_auth);
3834#else
3835 Py_RETURN_NONE;
3836#endif
3837}
3838
3839#if TLS1_3_VERSION
3840static int
3841set_post_handshake_auth(PySSLContext *self, PyObject *arg, void *c) {
Zackery Spytz842acaa2018-12-17 07:52:45 -07003842 if (arg == NULL) {
3843 PyErr_SetString(PyExc_AttributeError, "cannot delete attribute");
3844 return -1;
3845 }
Christian Heimes9fb051f2018-09-23 08:32:31 +02003846 int pha = PyObject_IsTrue(arg);
3847
3848 if (pha == -1) {
3849 return -1;
3850 }
3851 self->post_handshake_auth = pha;
3852
Christian Heimesf0f59302019-07-01 08:29:17 +02003853 /* bpo-37428: newPySSLSocket() sets SSL_VERIFY_POST_HANDSHAKE flag for
3854 * server sockets and SSL_set_post_handshake_auth() for client. */
Christian Heimes9fb051f2018-09-23 08:32:31 +02003855
3856 return 0;
3857}
3858#endif
3859
3860static PyObject *
Christian Heimes11a14932018-02-24 02:35:08 +01003861get_protocol(PySSLContext *self, void *c) {
3862 return PyLong_FromLong(self->protocol);
3863}
Christian Heimes1aa9a752013-12-02 02:41:19 +01003864
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003865typedef struct {
3866 PyThreadState *thread_state;
3867 PyObject *callable;
3868 char *password;
Victor Stinner9ee02032013-06-23 15:08:23 +02003869 int size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003870 int error;
3871} _PySSLPasswordInfo;
3872
3873static int
3874_pwinfo_set(_PySSLPasswordInfo *pw_info, PyObject* password,
3875 const char *bad_type_error)
3876{
3877 /* Set the password and size fields of a _PySSLPasswordInfo struct
3878 from a unicode, bytes, or byte array object.
3879 The password field will be dynamically allocated and must be freed
3880 by the caller */
3881 PyObject *password_bytes = NULL;
3882 const char *data = NULL;
3883 Py_ssize_t size;
3884
3885 if (PyUnicode_Check(password)) {
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03003886 password_bytes = PyUnicode_AsUTF8String(password);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003887 if (!password_bytes) {
3888 goto error;
3889 }
3890 data = PyBytes_AS_STRING(password_bytes);
3891 size = PyBytes_GET_SIZE(password_bytes);
3892 } else if (PyBytes_Check(password)) {
3893 data = PyBytes_AS_STRING(password);
3894 size = PyBytes_GET_SIZE(password);
3895 } else if (PyByteArray_Check(password)) {
3896 data = PyByteArray_AS_STRING(password);
3897 size = PyByteArray_GET_SIZE(password);
3898 } else {
3899 PyErr_SetString(PyExc_TypeError, bad_type_error);
3900 goto error;
3901 }
3902
Victor Stinner9ee02032013-06-23 15:08:23 +02003903 if (size > (Py_ssize_t)INT_MAX) {
3904 PyErr_Format(PyExc_ValueError,
3905 "password cannot be longer than %d bytes", INT_MAX);
3906 goto error;
3907 }
3908
Victor Stinner11ebff22013-07-07 17:07:52 +02003909 PyMem_Free(pw_info->password);
3910 pw_info->password = PyMem_Malloc(size);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003911 if (!pw_info->password) {
3912 PyErr_SetString(PyExc_MemoryError,
3913 "unable to allocate password buffer");
3914 goto error;
3915 }
3916 memcpy(pw_info->password, data, size);
Victor Stinner9ee02032013-06-23 15:08:23 +02003917 pw_info->size = (int)size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003918
3919 Py_XDECREF(password_bytes);
3920 return 1;
3921
3922error:
3923 Py_XDECREF(password_bytes);
3924 return 0;
3925}
3926
3927static int
3928_password_callback(char *buf, int size, int rwflag, void *userdata)
3929{
3930 _PySSLPasswordInfo *pw_info = (_PySSLPasswordInfo*) userdata;
3931 PyObject *fn_ret = NULL;
3932
3933 PySSL_END_ALLOW_THREADS_S(pw_info->thread_state);
3934
Christian Heimesd3b73f32021-04-09 15:23:38 +02003935 if (pw_info->error) {
3936 /* already failed previously. OpenSSL 3.0.0-alpha14 invokes the
3937 * callback multiple times which can lead to fatal Python error in
3938 * exception check. */
3939 goto error;
3940 }
3941
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003942 if (pw_info->callable) {
Victor Stinnerf17c3de2016-12-06 18:46:19 +01003943 fn_ret = _PyObject_CallNoArg(pw_info->callable);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003944 if (!fn_ret) {
3945 /* TODO: It would be nice to move _ctypes_add_traceback() into the
3946 core python API, so we could use it to add a frame here */
3947 goto error;
3948 }
3949
3950 if (!_pwinfo_set(pw_info, fn_ret,
3951 "password callback must return a string")) {
3952 goto error;
3953 }
3954 Py_CLEAR(fn_ret);
3955 }
3956
3957 if (pw_info->size > size) {
3958 PyErr_Format(PyExc_ValueError,
3959 "password cannot be longer than %d bytes", size);
3960 goto error;
3961 }
3962
3963 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
3964 memcpy(buf, pw_info->password, pw_info->size);
3965 return pw_info->size;
3966
3967error:
3968 Py_XDECREF(fn_ret);
3969 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
3970 pw_info->error = 1;
3971 return -1;
3972}
3973
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003974/*[clinic input]
3975_ssl._SSLContext.load_cert_chain
3976 certfile: object
Serhiy Storchaka279f4462019-09-14 12:24:05 +03003977 keyfile: object = None
3978 password: object = None
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003979
3980[clinic start generated code]*/
3981
Antoine Pitroub5218772010-05-21 09:56:06 +00003982static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003983_ssl__SSLContext_load_cert_chain_impl(PySSLContext *self, PyObject *certfile,
3984 PyObject *keyfile, PyObject *password)
Serhiy Storchaka279f4462019-09-14 12:24:05 +03003985/*[clinic end generated code: output=9480bc1c380e2095 input=30bc7e967ea01a58]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003986{
Antoine Pitrou152efa22010-05-16 18:19:27 +00003987 PyObject *certfile_bytes = NULL, *keyfile_bytes = NULL;
Christian Heimes598894f2016-09-05 23:19:05 +02003988 pem_password_cb *orig_passwd_cb = SSL_CTX_get_default_passwd_cb(self->ctx);
3989 void *orig_passwd_userdata = SSL_CTX_get_default_passwd_cb_userdata(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003990 _PySSLPasswordInfo pw_info = { NULL, NULL, NULL, 0, 0 };
Antoine Pitrou152efa22010-05-16 18:19:27 +00003991 int r;
3992
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003993 errno = 0;
Antoine Pitrou67e8e562010-09-01 20:55:41 +00003994 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00003995 if (keyfile == Py_None)
3996 keyfile = NULL;
3997 if (!PyUnicode_FSConverter(certfile, &certfile_bytes)) {
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03003998 if (PyErr_ExceptionMatches(PyExc_TypeError)) {
3999 PyErr_SetString(PyExc_TypeError,
4000 "certfile should be a valid filesystem path");
4001 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00004002 return NULL;
4003 }
4004 if (keyfile && !PyUnicode_FSConverter(keyfile, &keyfile_bytes)) {
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03004005 if (PyErr_ExceptionMatches(PyExc_TypeError)) {
4006 PyErr_SetString(PyExc_TypeError,
4007 "keyfile should be a valid filesystem path");
4008 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00004009 goto error;
4010 }
Serhiy Storchaka279f4462019-09-14 12:24:05 +03004011 if (password != Py_None) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02004012 if (PyCallable_Check(password)) {
4013 pw_info.callable = password;
4014 } else if (!_pwinfo_set(&pw_info, password,
4015 "password should be a string or callable")) {
4016 goto error;
4017 }
4018 SSL_CTX_set_default_passwd_cb(self->ctx, _password_callback);
4019 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, &pw_info);
4020 }
4021 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00004022 r = SSL_CTX_use_certificate_chain_file(self->ctx,
4023 PyBytes_AS_STRING(certfile_bytes));
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02004024 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00004025 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02004026 if (pw_info.error) {
4027 ERR_clear_error();
4028 /* the password callback has already set the error information */
4029 }
4030 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00004031 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03004032 PyErr_SetFromErrno(PyExc_OSError);
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00004033 }
4034 else {
4035 _setSSLError(NULL, 0, __FILE__, __LINE__);
4036 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00004037 goto error;
4038 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02004039 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou9c254862011-04-03 18:15:34 +02004040 r = SSL_CTX_use_PrivateKey_file(self->ctx,
Antoine Pitrou152efa22010-05-16 18:19:27 +00004041 PyBytes_AS_STRING(keyfile ? keyfile_bytes : certfile_bytes),
4042 SSL_FILETYPE_PEM);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02004043 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
4044 Py_CLEAR(keyfile_bytes);
4045 Py_CLEAR(certfile_bytes);
Antoine Pitrou152efa22010-05-16 18:19:27 +00004046 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02004047 if (pw_info.error) {
4048 ERR_clear_error();
4049 /* the password callback has already set the error information */
4050 }
4051 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00004052 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03004053 PyErr_SetFromErrno(PyExc_OSError);
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00004054 }
4055 else {
4056 _setSSLError(NULL, 0, __FILE__, __LINE__);
4057 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02004058 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004059 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02004060 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00004061 r = SSL_CTX_check_private_key(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02004062 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00004063 if (r != 1) {
4064 _setSSLError(NULL, 0, __FILE__, __LINE__);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02004065 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004066 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02004067 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
4068 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02004069 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00004070 Py_RETURN_NONE;
4071
4072error:
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02004073 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
4074 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02004075 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00004076 Py_XDECREF(keyfile_bytes);
4077 Py_XDECREF(certfile_bytes);
4078 return NULL;
4079}
4080
Christian Heimesefff7062013-11-21 03:35:02 +01004081/* internal helper function, returns -1 on error
4082 */
4083static int
Serhiy Storchaka8f87eef2020-04-12 14:58:27 +03004084_add_ca_certs(PySSLContext *self, const void *data, Py_ssize_t len,
Christian Heimesefff7062013-11-21 03:35:02 +01004085 int filetype)
4086{
4087 BIO *biobuf = NULL;
4088 X509_STORE *store;
4089 int retval = 0, err, loaded = 0;
4090
4091 assert(filetype == SSL_FILETYPE_ASN1 || filetype == SSL_FILETYPE_PEM);
4092
4093 if (len <= 0) {
4094 PyErr_SetString(PyExc_ValueError,
4095 "Empty certificate data");
4096 return -1;
4097 } else if (len > INT_MAX) {
4098 PyErr_SetString(PyExc_OverflowError,
4099 "Certificate data is too long.");
4100 return -1;
4101 }
4102
Christian Heimes1dbf61f2013-11-22 00:34:18 +01004103 biobuf = BIO_new_mem_buf(data, (int)len);
Christian Heimesefff7062013-11-21 03:35:02 +01004104 if (biobuf == NULL) {
4105 _setSSLError("Can't allocate buffer", 0, __FILE__, __LINE__);
4106 return -1;
4107 }
4108
4109 store = SSL_CTX_get_cert_store(self->ctx);
4110 assert(store != NULL);
4111
4112 while (1) {
4113 X509 *cert = NULL;
4114 int r;
4115
4116 if (filetype == SSL_FILETYPE_ASN1) {
4117 cert = d2i_X509_bio(biobuf, NULL);
4118 } else {
4119 cert = PEM_read_bio_X509(biobuf, NULL,
Christian Heimes598894f2016-09-05 23:19:05 +02004120 SSL_CTX_get_default_passwd_cb(self->ctx),
4121 SSL_CTX_get_default_passwd_cb_userdata(self->ctx)
4122 );
Christian Heimesefff7062013-11-21 03:35:02 +01004123 }
4124 if (cert == NULL) {
4125 break;
4126 }
4127 r = X509_STORE_add_cert(store, cert);
4128 X509_free(cert);
4129 if (!r) {
4130 err = ERR_peek_last_error();
4131 if ((ERR_GET_LIB(err) == ERR_LIB_X509) &&
4132 (ERR_GET_REASON(err) == X509_R_CERT_ALREADY_IN_HASH_TABLE)) {
4133 /* cert already in hash table, not an error */
4134 ERR_clear_error();
4135 } else {
4136 break;
4137 }
4138 }
4139 loaded++;
4140 }
4141
4142 err = ERR_peek_last_error();
4143 if ((filetype == SSL_FILETYPE_ASN1) &&
4144 (loaded > 0) &&
4145 (ERR_GET_LIB(err) == ERR_LIB_ASN1) &&
4146 (ERR_GET_REASON(err) == ASN1_R_HEADER_TOO_LONG)) {
4147 /* EOF ASN1 file, not an error */
4148 ERR_clear_error();
4149 retval = 0;
4150 } else if ((filetype == SSL_FILETYPE_PEM) &&
4151 (loaded > 0) &&
4152 (ERR_GET_LIB(err) == ERR_LIB_PEM) &&
4153 (ERR_GET_REASON(err) == PEM_R_NO_START_LINE)) {
4154 /* EOF PEM file, not an error */
4155 ERR_clear_error();
4156 retval = 0;
4157 } else {
4158 _setSSLError(NULL, 0, __FILE__, __LINE__);
4159 retval = -1;
4160 }
4161
4162 BIO_free(biobuf);
4163 return retval;
4164}
4165
4166
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004167/*[clinic input]
4168_ssl._SSLContext.load_verify_locations
Serhiy Storchaka279f4462019-09-14 12:24:05 +03004169 cafile: object = None
4170 capath: object = None
4171 cadata: object = None
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004172
4173[clinic start generated code]*/
4174
Antoine Pitrou152efa22010-05-16 18:19:27 +00004175static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004176_ssl__SSLContext_load_verify_locations_impl(PySSLContext *self,
4177 PyObject *cafile,
4178 PyObject *capath,
4179 PyObject *cadata)
Serhiy Storchaka279f4462019-09-14 12:24:05 +03004180/*[clinic end generated code: output=454c7e41230ca551 input=42ecfe258233e194]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004181{
Antoine Pitrou152efa22010-05-16 18:19:27 +00004182 PyObject *cafile_bytes = NULL, *capath_bytes = NULL;
4183 const char *cafile_buf = NULL, *capath_buf = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01004184 int r = 0, ok = 1;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004185
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00004186 errno = 0;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004187 if (cafile == Py_None)
4188 cafile = NULL;
4189 if (capath == Py_None)
4190 capath = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01004191 if (cadata == Py_None)
4192 cadata = NULL;
4193
4194 if (cafile == NULL && capath == NULL && cadata == NULL) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00004195 PyErr_SetString(PyExc_TypeError,
Christian Heimesefff7062013-11-21 03:35:02 +01004196 "cafile, capath and cadata cannot be all omitted");
4197 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004198 }
4199 if (cafile && !PyUnicode_FSConverter(cafile, &cafile_bytes)) {
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03004200 if (PyErr_ExceptionMatches(PyExc_TypeError)) {
4201 PyErr_SetString(PyExc_TypeError,
4202 "cafile should be a valid filesystem path");
4203 }
Christian Heimesefff7062013-11-21 03:35:02 +01004204 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004205 }
4206 if (capath && !PyUnicode_FSConverter(capath, &capath_bytes)) {
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03004207 if (PyErr_ExceptionMatches(PyExc_TypeError)) {
4208 PyErr_SetString(PyExc_TypeError,
4209 "capath should be a valid filesystem path");
4210 }
Christian Heimesefff7062013-11-21 03:35:02 +01004211 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004212 }
Christian Heimesefff7062013-11-21 03:35:02 +01004213
4214 /* validata cadata type and load cadata */
4215 if (cadata) {
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03004216 if (PyUnicode_Check(cadata)) {
4217 PyObject *cadata_ascii = PyUnicode_AsASCIIString(cadata);
4218 if (cadata_ascii == NULL) {
4219 if (PyErr_ExceptionMatches(PyExc_UnicodeEncodeError)) {
4220 goto invalid_cadata;
4221 }
4222 goto error;
4223 }
4224 r = _add_ca_certs(self,
4225 PyBytes_AS_STRING(cadata_ascii),
4226 PyBytes_GET_SIZE(cadata_ascii),
4227 SSL_FILETYPE_PEM);
4228 Py_DECREF(cadata_ascii);
4229 if (r == -1) {
4230 goto error;
4231 }
4232 }
4233 else if (PyObject_CheckBuffer(cadata)) {
4234 Py_buffer buf;
4235 if (PyObject_GetBuffer(cadata, &buf, PyBUF_SIMPLE)) {
4236 goto error;
4237 }
Christian Heimesefff7062013-11-21 03:35:02 +01004238 if (!PyBuffer_IsContiguous(&buf, 'C') || buf.ndim > 1) {
4239 PyBuffer_Release(&buf);
4240 PyErr_SetString(PyExc_TypeError,
4241 "cadata should be a contiguous buffer with "
4242 "a single dimension");
4243 goto error;
4244 }
4245 r = _add_ca_certs(self, buf.buf, buf.len, SSL_FILETYPE_ASN1);
4246 PyBuffer_Release(&buf);
4247 if (r == -1) {
4248 goto error;
4249 }
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03004250 }
4251 else {
4252 invalid_cadata:
4253 PyErr_SetString(PyExc_TypeError,
4254 "cadata should be an ASCII string or a "
4255 "bytes-like object");
4256 goto error;
Christian Heimesefff7062013-11-21 03:35:02 +01004257 }
4258 }
4259
4260 /* load cafile or capath */
4261 if (cafile || capath) {
4262 if (cafile)
4263 cafile_buf = PyBytes_AS_STRING(cafile_bytes);
4264 if (capath)
4265 capath_buf = PyBytes_AS_STRING(capath_bytes);
4266 PySSL_BEGIN_ALLOW_THREADS
4267 r = SSL_CTX_load_verify_locations(self->ctx, cafile_buf, capath_buf);
4268 PySSL_END_ALLOW_THREADS
4269 if (r != 1) {
Christian Heimesefff7062013-11-21 03:35:02 +01004270 if (errno != 0) {
4271 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03004272 PyErr_SetFromErrno(PyExc_OSError);
Christian Heimesefff7062013-11-21 03:35:02 +01004273 }
4274 else {
4275 _setSSLError(NULL, 0, __FILE__, __LINE__);
4276 }
4277 goto error;
4278 }
4279 }
4280 goto end;
4281
4282 error:
4283 ok = 0;
4284 end:
Antoine Pitrou152efa22010-05-16 18:19:27 +00004285 Py_XDECREF(cafile_bytes);
4286 Py_XDECREF(capath_bytes);
Christian Heimesefff7062013-11-21 03:35:02 +01004287 if (ok) {
4288 Py_RETURN_NONE;
4289 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00004290 return NULL;
4291 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00004292}
4293
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004294/*[clinic input]
4295_ssl._SSLContext.load_dh_params
4296 path as filepath: object
4297 /
4298
4299[clinic start generated code]*/
4300
Antoine Pitrou152efa22010-05-16 18:19:27 +00004301static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004302_ssl__SSLContext_load_dh_params(PySSLContext *self, PyObject *filepath)
4303/*[clinic end generated code: output=1c8e57a38e055af0 input=c8871f3c796ae1d6]*/
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004304{
4305 FILE *f;
4306 DH *dh;
4307
Victor Stinnerdaf45552013-08-28 00:53:59 +02004308 f = _Py_fopen_obj(filepath, "rb");
Victor Stinnere42ccd22015-03-18 01:39:23 +01004309 if (f == NULL)
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004310 return NULL;
Victor Stinnere42ccd22015-03-18 01:39:23 +01004311
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004312 errno = 0;
4313 PySSL_BEGIN_ALLOW_THREADS
4314 dh = PEM_read_DHparams(f, NULL, NULL, NULL);
Antoine Pitrou457a2292013-01-12 21:43:45 +01004315 fclose(f);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004316 PySSL_END_ALLOW_THREADS
4317 if (dh == NULL) {
4318 if (errno != 0) {
4319 ERR_clear_error();
4320 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
4321 }
4322 else {
4323 _setSSLError(NULL, 0, __FILE__, __LINE__);
4324 }
4325 return NULL;
4326 }
Zackery Spytzaebc0492020-07-07 22:21:58 -06004327 if (!SSL_CTX_set_tmp_dh(self->ctx, dh)) {
4328 DH_free(dh);
4329 return _setSSLError(NULL, 0, __FILE__, __LINE__);
4330 }
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004331 DH_free(dh);
4332 Py_RETURN_NONE;
4333}
4334
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004335/*[clinic input]
4336_ssl._SSLContext._wrap_socket
4337 sock: object(subclass_of="PySocketModule.Sock_Type")
4338 server_side: int
4339 server_hostname as hostname_obj: object = None
Christian Heimes141c5e82018-02-24 21:10:57 +01004340 *
4341 owner: object = None
4342 session: object = None
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004343
4344[clinic start generated code]*/
4345
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004346static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004347_ssl__SSLContext__wrap_socket_impl(PySSLContext *self, PyObject *sock,
Christian Heimes141c5e82018-02-24 21:10:57 +01004348 int server_side, PyObject *hostname_obj,
4349 PyObject *owner, PyObject *session)
4350/*[clinic end generated code: output=f103f238633940b4 input=957d5006183d1894]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004351{
Antoine Pitroud5323212010-10-22 18:19:07 +00004352 char *hostname = NULL;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004353 PyObject *res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004354
Antoine Pitroud5323212010-10-22 18:19:07 +00004355 /* server_hostname is either None (or absent), or to be encoded
Christian Heimesd02ac252018-03-25 12:36:13 +02004356 as IDN A-label (ASCII str) without NULL bytes. */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004357 if (hostname_obj != Py_None) {
Christian Heimes11a14932018-02-24 02:35:08 +01004358 if (!PyArg_Parse(hostname_obj, "es", "ascii", &hostname))
Antoine Pitroud5323212010-10-22 18:19:07 +00004359 return NULL;
Antoine Pitroud5323212010-10-22 18:19:07 +00004360 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00004361
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004362 res = (PyObject *) newPySSLSocket(self, (PySocketSockObject *)sock,
4363 server_side, hostname,
Christian Heimes141c5e82018-02-24 21:10:57 +01004364 owner, session,
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004365 NULL, NULL);
Antoine Pitroud5323212010-10-22 18:19:07 +00004366 if (hostname != NULL)
4367 PyMem_Free(hostname);
4368 return res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004369}
4370
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004371/*[clinic input]
4372_ssl._SSLContext._wrap_bio
Christian Heimes5c36da72020-11-20 09:40:12 +01004373 incoming: object(subclass_of="PySSLMemoryBIO_Type", type="PySSLMemoryBIO *")
4374 outgoing: object(subclass_of="PySSLMemoryBIO_Type", type="PySSLMemoryBIO *")
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004375 server_side: int
4376 server_hostname as hostname_obj: object = None
Christian Heimes141c5e82018-02-24 21:10:57 +01004377 *
4378 owner: object = None
4379 session: object = None
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004380
4381[clinic start generated code]*/
4382
Antoine Pitroub0182c82010-10-12 20:09:02 +00004383static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004384_ssl__SSLContext__wrap_bio_impl(PySSLContext *self, PySSLMemoryBIO *incoming,
4385 PySSLMemoryBIO *outgoing, int server_side,
Christian Heimes141c5e82018-02-24 21:10:57 +01004386 PyObject *hostname_obj, PyObject *owner,
4387 PyObject *session)
Christian Heimes5c36da72020-11-20 09:40:12 +01004388/*[clinic end generated code: output=5c5d6d9b41f99332 input=63867b8f3e1a1aa3]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004389{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004390 char *hostname = NULL;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004391 PyObject *res;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004392
4393 /* server_hostname is either None (or absent), or to be encoded
Christian Heimesd02ac252018-03-25 12:36:13 +02004394 as IDN A-label (ASCII str) without NULL bytes. */
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004395 if (hostname_obj != Py_None) {
Christian Heimes11a14932018-02-24 02:35:08 +01004396 if (!PyArg_Parse(hostname_obj, "es", "ascii", &hostname))
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004397 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004398 }
4399
4400 res = (PyObject *) newPySSLSocket(self, NULL, server_side, hostname,
Christian Heimes141c5e82018-02-24 21:10:57 +01004401 owner, session,
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004402 incoming, outgoing);
4403
4404 PyMem_Free(hostname);
4405 return res;
4406}
4407
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004408/*[clinic input]
4409_ssl._SSLContext.session_stats
4410[clinic start generated code]*/
4411
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004412static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004413_ssl__SSLContext_session_stats_impl(PySSLContext *self)
4414/*[clinic end generated code: output=0d96411c42893bfb input=7e0a81fb11102c8b]*/
Antoine Pitroub0182c82010-10-12 20:09:02 +00004415{
4416 int r;
4417 PyObject *value, *stats = PyDict_New();
4418 if (!stats)
4419 return NULL;
4420
4421#define ADD_STATS(SSL_NAME, KEY_NAME) \
4422 value = PyLong_FromLong(SSL_CTX_sess_ ## SSL_NAME (self->ctx)); \
4423 if (value == NULL) \
4424 goto error; \
4425 r = PyDict_SetItemString(stats, KEY_NAME, value); \
4426 Py_DECREF(value); \
4427 if (r < 0) \
4428 goto error;
4429
4430 ADD_STATS(number, "number");
4431 ADD_STATS(connect, "connect");
4432 ADD_STATS(connect_good, "connect_good");
4433 ADD_STATS(connect_renegotiate, "connect_renegotiate");
4434 ADD_STATS(accept, "accept");
4435 ADD_STATS(accept_good, "accept_good");
4436 ADD_STATS(accept_renegotiate, "accept_renegotiate");
4437 ADD_STATS(accept, "accept");
4438 ADD_STATS(hits, "hits");
4439 ADD_STATS(misses, "misses");
4440 ADD_STATS(timeouts, "timeouts");
4441 ADD_STATS(cache_full, "cache_full");
4442
4443#undef ADD_STATS
4444
4445 return stats;
4446
4447error:
4448 Py_DECREF(stats);
4449 return NULL;
4450}
4451
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004452/*[clinic input]
4453_ssl._SSLContext.set_default_verify_paths
4454[clinic start generated code]*/
4455
Antoine Pitrou664c2d12010-11-17 20:29:42 +00004456static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004457_ssl__SSLContext_set_default_verify_paths_impl(PySSLContext *self)
4458/*[clinic end generated code: output=0bee74e6e09deaaa input=35f3408021463d74]*/
Antoine Pitrou664c2d12010-11-17 20:29:42 +00004459{
4460 if (!SSL_CTX_set_default_verify_paths(self->ctx)) {
4461 _setSSLError(NULL, 0, __FILE__, __LINE__);
4462 return NULL;
4463 }
4464 Py_RETURN_NONE;
4465}
4466
Antoine Pitrou501da612011-12-21 09:27:41 +01004467#ifndef OPENSSL_NO_ECDH
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004468/*[clinic input]
4469_ssl._SSLContext.set_ecdh_curve
4470 name: object
4471 /
4472
4473[clinic start generated code]*/
4474
Antoine Pitrou923df6f2011-12-19 17:16:51 +01004475static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004476_ssl__SSLContext_set_ecdh_curve(PySSLContext *self, PyObject *name)
4477/*[clinic end generated code: output=23022c196e40d7d2 input=c2bafb6f6e34726b]*/
Antoine Pitrou923df6f2011-12-19 17:16:51 +01004478{
4479 PyObject *name_bytes;
4480 int nid;
4481 EC_KEY *key;
4482
4483 if (!PyUnicode_FSConverter(name, &name_bytes))
4484 return NULL;
4485 assert(PyBytes_Check(name_bytes));
4486 nid = OBJ_sn2nid(PyBytes_AS_STRING(name_bytes));
4487 Py_DECREF(name_bytes);
4488 if (nid == 0) {
4489 PyErr_Format(PyExc_ValueError,
4490 "unknown elliptic curve name %R", name);
4491 return NULL;
4492 }
4493 key = EC_KEY_new_by_curve_name(nid);
4494 if (key == NULL) {
4495 _setSSLError(NULL, 0, __FILE__, __LINE__);
4496 return NULL;
4497 }
4498 SSL_CTX_set_tmp_ecdh(self->ctx, key);
4499 EC_KEY_free(key);
4500 Py_RETURN_NONE;
4501}
Antoine Pitrou501da612011-12-21 09:27:41 +01004502#endif
Antoine Pitrou923df6f2011-12-19 17:16:51 +01004503
Antoine Pitrou912fbff2013-03-30 16:29:32 +01004504#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004505static int
4506_servername_callback(SSL *s, int *al, void *args)
4507{
4508 int ret;
4509 PySSLContext *ssl_ctx = (PySSLContext *) args;
4510 PySSLSocket *ssl;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004511 PyObject *result;
4512 /* The high-level ssl.SSLSocket object */
4513 PyObject *ssl_socket;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004514 const char *servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
Stefan Krah20d60802013-01-17 17:07:17 +01004515 PyGILState_STATE gstate = PyGILState_Ensure();
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004516
Christian Heimes11a14932018-02-24 02:35:08 +01004517 if (ssl_ctx->set_sni_cb == NULL) {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004518 /* remove race condition in this the call back while if removing the
4519 * callback is in progress */
4520 PyGILState_Release(gstate);
Antoine Pitrou5dd12a52013-01-06 15:25:36 +01004521 return SSL_TLSEXT_ERR_OK;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004522 }
4523
4524 ssl = SSL_get_app_data(s);
4525 assert(PySSLSocket_Check(ssl));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004526
Serhiy Storchakaf51d7152015-11-02 14:40:41 +02004527 /* The servername callback expects an argument that represents the current
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004528 * SSL connection and that has a .context attribute that can be changed to
4529 * identify the requested hostname. Since the official API is the Python
4530 * level API we want to pass the callback a Python level object rather than
4531 * a _ssl.SSLSocket instance. If there's an "owner" (typically an
4532 * SSLObject) that will be passed. Otherwise if there's a socket then that
4533 * will be passed. If both do not exist only then the C-level object is
4534 * passed. */
4535 if (ssl->owner)
4536 ssl_socket = PyWeakref_GetObject(ssl->owner);
4537 else if (ssl->Socket)
4538 ssl_socket = PyWeakref_GetObject(ssl->Socket);
4539 else
4540 ssl_socket = (PyObject *) ssl;
4541
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004542 Py_INCREF(ssl_socket);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004543 if (ssl_socket == Py_None)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004544 goto error;
Victor Stinner7e001512013-06-25 00:44:31 +02004545
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004546 if (servername == NULL) {
Christian Heimes11a14932018-02-24 02:35:08 +01004547 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_sni_cb, ssl_socket,
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004548 Py_None, ssl_ctx, NULL);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004549 }
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004550 else {
Christian Heimes11a14932018-02-24 02:35:08 +01004551 PyObject *servername_bytes;
4552 PyObject *servername_str;
4553
4554 servername_bytes = PyBytes_FromString(servername);
4555 if (servername_bytes == NULL) {
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004556 PyErr_WriteUnraisable((PyObject *) ssl_ctx);
4557 goto error;
4558 }
Christian Heimes11a14932018-02-24 02:35:08 +01004559 /* server_hostname was encoded to an A-label by our caller; put it
4560 * back into a str object, but still as an A-label (bpo-28414)
4561 */
4562 servername_str = PyUnicode_FromEncodedObject(servername_bytes, "ascii", NULL);
Christian Heimes11a14932018-02-24 02:35:08 +01004563 if (servername_str == NULL) {
4564 PyErr_WriteUnraisable(servername_bytes);
Zackery Spytzee96f322020-07-09 04:00:21 -06004565 Py_DECREF(servername_bytes);
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004566 goto error;
4567 }
Zackery Spytzee96f322020-07-09 04:00:21 -06004568 Py_DECREF(servername_bytes);
Christian Heimes11a14932018-02-24 02:35:08 +01004569 result = PyObject_CallFunctionObjArgs(
4570 ssl_ctx->set_sni_cb, ssl_socket, servername_str,
4571 ssl_ctx, NULL);
4572 Py_DECREF(servername_str);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004573 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004574 Py_DECREF(ssl_socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004575
4576 if (result == NULL) {
Christian Heimes11a14932018-02-24 02:35:08 +01004577 PyErr_WriteUnraisable(ssl_ctx->set_sni_cb);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004578 *al = SSL_AD_HANDSHAKE_FAILURE;
4579 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
4580 }
4581 else {
Christian Heimes11a14932018-02-24 02:35:08 +01004582 /* Result may be None, a SSLContext or an integer
4583 * None and SSLContext are OK, integer or other values are an error.
4584 */
4585 if (result == Py_None) {
4586 ret = SSL_TLSEXT_ERR_OK;
4587 } else {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004588 *al = (int) PyLong_AsLong(result);
4589 if (PyErr_Occurred()) {
4590 PyErr_WriteUnraisable(result);
4591 *al = SSL_AD_INTERNAL_ERROR;
4592 }
4593 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
4594 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004595 Py_DECREF(result);
4596 }
4597
4598 PyGILState_Release(gstate);
4599 return ret;
4600
4601error:
4602 Py_DECREF(ssl_socket);
4603 *al = SSL_AD_INTERNAL_ERROR;
4604 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
4605 PyGILState_Release(gstate);
4606 return ret;
4607}
Antoine Pitroua5963382013-03-30 16:39:00 +01004608#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004609
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004610static PyObject *
Christian Heimes11a14932018-02-24 02:35:08 +01004611get_sni_callback(PySSLContext *self, void *c)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004612{
Christian Heimes11a14932018-02-24 02:35:08 +01004613 PyObject *cb = self->set_sni_cb;
4614 if (cb == NULL) {
4615 Py_RETURN_NONE;
4616 }
4617 Py_INCREF(cb);
4618 return cb;
4619}
4620
4621static int
4622set_sni_callback(PySSLContext *self, PyObject *arg, void *c)
4623{
4624 if (self->protocol == PY_SSL_VERSION_TLS_CLIENT) {
4625 PyErr_SetString(PyExc_ValueError,
4626 "sni_callback cannot be set on TLS_CLIENT context");
4627 return -1;
4628 }
Antoine Pitrou912fbff2013-03-30 16:29:32 +01004629#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Christian Heimes11a14932018-02-24 02:35:08 +01004630 Py_CLEAR(self->set_sni_cb);
4631 if (arg == Py_None) {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004632 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
4633 }
4634 else {
Christian Heimes11a14932018-02-24 02:35:08 +01004635 if (!PyCallable_Check(arg)) {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004636 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
4637 PyErr_SetString(PyExc_TypeError,
4638 "not a callable object");
Christian Heimes11a14932018-02-24 02:35:08 +01004639 return -1;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004640 }
Christian Heimes11a14932018-02-24 02:35:08 +01004641 Py_INCREF(arg);
4642 self->set_sni_cb = arg;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004643 SSL_CTX_set_tlsext_servername_callback(self->ctx, _servername_callback);
4644 SSL_CTX_set_tlsext_servername_arg(self->ctx, self);
4645 }
Christian Heimes11a14932018-02-24 02:35:08 +01004646 return 0;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004647#else
4648 PyErr_SetString(PyExc_NotImplementedError,
4649 "The TLS extension servername callback, "
4650 "SSL_CTX_set_tlsext_servername_callback, "
4651 "is not in the current OpenSSL library.");
Christian Heimes11a14932018-02-24 02:35:08 +01004652 return -1;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004653#endif
4654}
4655
Christian Heimes11a14932018-02-24 02:35:08 +01004656PyDoc_STRVAR(PySSLContext_sni_callback_doc,
4657"Set a callback that will be called when a server name is provided by the SSL/TLS client in the SNI extension.\n\
4658\n\
4659If the argument is None then the callback is disabled. The method is called\n\
4660with the SSLSocket, the server name as a string, and the SSLContext object.\n\
4661See RFC 6066 for details of the SNI extension.");
4662
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004663/*[clinic input]
4664_ssl._SSLContext.cert_store_stats
4665
4666Returns quantities of loaded X.509 certificates.
4667
4668X.509 certificates with a CA extension and certificate revocation lists
4669inside the context's cert store.
4670
4671NOTE: Certificates in a capath directory aren't loaded unless they have
4672been used at least once.
4673[clinic start generated code]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004674
4675static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004676_ssl__SSLContext_cert_store_stats_impl(PySSLContext *self)
4677/*[clinic end generated code: output=5f356f4d9cca874d input=eb40dd0f6d0e40cf]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004678{
4679 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02004680 STACK_OF(X509_OBJECT) *objs;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004681 X509_OBJECT *obj;
Christian Heimes598894f2016-09-05 23:19:05 +02004682 int x509 = 0, crl = 0, ca = 0, i;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004683
4684 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02004685 objs = X509_STORE_get0_objects(store);
4686 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
4687 obj = sk_X509_OBJECT_value(objs, i);
4688 switch (X509_OBJECT_get_type(obj)) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004689 case X509_LU_X509:
4690 x509++;
Christian Heimes598894f2016-09-05 23:19:05 +02004691 if (X509_check_ca(X509_OBJECT_get0_X509(obj))) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004692 ca++;
4693 }
4694 break;
4695 case X509_LU_CRL:
4696 crl++;
4697 break;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004698 default:
4699 /* Ignore X509_LU_FAIL, X509_LU_RETRY, X509_LU_PKEY.
4700 * As far as I can tell they are internal states and never
4701 * stored in a cert store */
4702 break;
4703 }
4704 }
4705 return Py_BuildValue("{sisisi}", "x509", x509, "crl", crl,
4706 "x509_ca", ca);
4707}
4708
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004709/*[clinic input]
4710_ssl._SSLContext.get_ca_certs
4711 binary_form: bool = False
4712
4713Returns a list of dicts with information of loaded CA certs.
4714
4715If the optional argument is True, returns a DER-encoded copy of the CA
4716certificate.
4717
4718NOTE: Certificates in a capath directory aren't loaded unless they have
4719been used at least once.
4720[clinic start generated code]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004721
4722static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004723_ssl__SSLContext_get_ca_certs_impl(PySSLContext *self, int binary_form)
4724/*[clinic end generated code: output=0d58f148f37e2938 input=6887b5a09b7f9076]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004725{
4726 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02004727 STACK_OF(X509_OBJECT) *objs;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004728 PyObject *ci = NULL, *rlist = NULL;
4729 int i;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004730
4731 if ((rlist = PyList_New(0)) == NULL) {
4732 return NULL;
4733 }
4734
4735 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02004736 objs = X509_STORE_get0_objects(store);
4737 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004738 X509_OBJECT *obj;
4739 X509 *cert;
4740
Christian Heimes598894f2016-09-05 23:19:05 +02004741 obj = sk_X509_OBJECT_value(objs, i);
4742 if (X509_OBJECT_get_type(obj) != X509_LU_X509) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004743 /* not a x509 cert */
4744 continue;
4745 }
4746 /* CA for any purpose */
Christian Heimes598894f2016-09-05 23:19:05 +02004747 cert = X509_OBJECT_get0_X509(obj);
Christian Heimes9a5395a2013-06-17 15:44:12 +02004748 if (!X509_check_ca(cert)) {
4749 continue;
4750 }
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004751 if (binary_form) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004752 ci = _certificate_to_der(cert);
4753 } else {
4754 ci = _decode_certificate(cert);
4755 }
4756 if (ci == NULL) {
4757 goto error;
4758 }
4759 if (PyList_Append(rlist, ci) == -1) {
4760 goto error;
4761 }
4762 Py_CLEAR(ci);
4763 }
4764 return rlist;
4765
4766 error:
4767 Py_XDECREF(ci);
4768 Py_XDECREF(rlist);
4769 return NULL;
4770}
4771
4772
Antoine Pitrou152efa22010-05-16 18:19:27 +00004773static PyGetSetDef context_getsetlist[] = {
Christian Heimes1aa9a752013-12-02 02:41:19 +01004774 {"check_hostname", (getter) get_check_hostname,
4775 (setter) set_check_hostname, NULL},
Christian Heimes61d478c2018-01-27 15:51:38 +01004776 {"_host_flags", (getter) get_host_flags,
4777 (setter) set_host_flags, NULL},
Christian Heimes698dde12018-02-27 11:54:43 +01004778#if SSL_CTRL_GET_MAX_PROTO_VERSION
4779 {"minimum_version", (getter) get_minimum_version,
4780 (setter) set_minimum_version, NULL},
4781 {"maximum_version", (getter) get_maximum_version,
4782 (setter) set_maximum_version, NULL},
4783#endif
Christian Heimesc7f70692019-05-31 11:44:05 +02004784#ifdef HAVE_OPENSSL_KEYLOG
4785 {"keylog_filename", (getter) _PySSLContext_get_keylog_filename,
4786 (setter) _PySSLContext_set_keylog_filename, NULL},
4787#endif
4788 {"_msg_callback", (getter) _PySSLContext_get_msg_callback,
4789 (setter) _PySSLContext_set_msg_callback, NULL},
Christian Heimes11a14932018-02-24 02:35:08 +01004790 {"sni_callback", (getter) get_sni_callback,
Christian Heimes698dde12018-02-27 11:54:43 +01004791 (setter) set_sni_callback, PySSLContext_sni_callback_doc},
Christian Heimes78c7d522019-06-03 21:00:10 +02004792#if (OPENSSL_VERSION_NUMBER >= 0x10101000L) && !defined(LIBRESSL_VERSION_NUMBER)
4793 {"num_tickets", (getter) get_num_tickets,
4794 (setter) set_num_tickets, PySSLContext_num_tickets_doc},
4795#endif
Antoine Pitroub5218772010-05-21 09:56:06 +00004796 {"options", (getter) get_options,
4797 (setter) set_options, NULL},
Christian Heimes9fb051f2018-09-23 08:32:31 +02004798 {"post_handshake_auth", (getter) get_post_handshake_auth,
4799#ifdef TLS1_3_VERSION
4800 (setter) set_post_handshake_auth,
4801#else
4802 NULL,
4803#endif
4804 NULL},
Christian Heimes11a14932018-02-24 02:35:08 +01004805 {"protocol", (getter) get_protocol,
4806 NULL, NULL},
Christian Heimes22587792013-11-21 23:56:13 +01004807 {"verify_flags", (getter) get_verify_flags,
4808 (setter) set_verify_flags, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00004809 {"verify_mode", (getter) get_verify_mode,
4810 (setter) set_verify_mode, NULL},
matthewhughes9348e836bb2020-07-17 09:59:15 +01004811#if (OPENSSL_VERSION_NUMBER >= 0x10100000L) && !defined(LIBRESSL_VERSION_NUMBER)
4812 {"security_level", (getter) get_security_level,
4813 NULL, PySSLContext_security_level_doc},
4814#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00004815 {NULL}, /* sentinel */
4816};
4817
4818static struct PyMethodDef context_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004819 _SSL__SSLCONTEXT__WRAP_SOCKET_METHODDEF
4820 _SSL__SSLCONTEXT__WRAP_BIO_METHODDEF
4821 _SSL__SSLCONTEXT_SET_CIPHERS_METHODDEF
4822 _SSL__SSLCONTEXT__SET_ALPN_PROTOCOLS_METHODDEF
4823 _SSL__SSLCONTEXT__SET_NPN_PROTOCOLS_METHODDEF
4824 _SSL__SSLCONTEXT_LOAD_CERT_CHAIN_METHODDEF
4825 _SSL__SSLCONTEXT_LOAD_DH_PARAMS_METHODDEF
4826 _SSL__SSLCONTEXT_LOAD_VERIFY_LOCATIONS_METHODDEF
4827 _SSL__SSLCONTEXT_SESSION_STATS_METHODDEF
4828 _SSL__SSLCONTEXT_SET_DEFAULT_VERIFY_PATHS_METHODDEF
4829 _SSL__SSLCONTEXT_SET_ECDH_CURVE_METHODDEF
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004830 _SSL__SSLCONTEXT_CERT_STORE_STATS_METHODDEF
4831 _SSL__SSLCONTEXT_GET_CA_CERTS_METHODDEF
Christian Heimes25bfcd52016-09-06 00:04:45 +02004832 _SSL__SSLCONTEXT_GET_CIPHERS_METHODDEF
Antoine Pitrou152efa22010-05-16 18:19:27 +00004833 {NULL, NULL} /* sentinel */
4834};
4835
Christian Heimes5c36da72020-11-20 09:40:12 +01004836static PyType_Slot PySSLContext_slots[] = {
4837 {Py_tp_methods, context_methods},
4838 {Py_tp_getset, context_getsetlist},
4839 {Py_tp_new, _ssl__SSLContext},
4840 {Py_tp_dealloc, context_dealloc},
4841 {Py_tp_traverse, context_traverse},
4842 {Py_tp_clear, context_clear},
4843 {0, 0},
4844};
4845
4846static PyType_Spec PySSLContext_spec = {
4847 "_ssl._SSLContext",
4848 sizeof(PySSLContext),
4849 0,
4850 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
4851 PySSLContext_slots,
Antoine Pitrou152efa22010-05-16 18:19:27 +00004852};
4853
4854
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004855/*
4856 * MemoryBIO objects
4857 */
4858
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004859/*[clinic input]
4860@classmethod
4861_ssl.MemoryBIO.__new__
4862
4863[clinic start generated code]*/
4864
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004865static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004866_ssl_MemoryBIO_impl(PyTypeObject *type)
4867/*[clinic end generated code: output=8820a58db78330ac input=26d22e4909ecb1b5]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004868{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004869 BIO *bio;
4870 PySSLMemoryBIO *self;
4871
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004872 bio = BIO_new(BIO_s_mem());
4873 if (bio == NULL) {
4874 PyErr_SetString(PySSLErrorObject,
4875 "failed to allocate BIO");
4876 return NULL;
4877 }
4878 /* Since our BIO is non-blocking an empty read() does not indicate EOF,
4879 * just that no data is currently available. The SSL routines should retry
4880 * the read, which we can achieve by calling BIO_set_retry_read(). */
4881 BIO_set_retry_read(bio);
4882 BIO_set_mem_eof_return(bio, -1);
4883
4884 assert(type != NULL && type->tp_alloc != NULL);
4885 self = (PySSLMemoryBIO *) type->tp_alloc(type, 0);
4886 if (self == NULL) {
4887 BIO_free(bio);
4888 return NULL;
4889 }
4890 self->bio = bio;
4891 self->eof_written = 0;
4892
4893 return (PyObject *) self;
4894}
4895
4896static void
4897memory_bio_dealloc(PySSLMemoryBIO *self)
4898{
Christian Heimes5c36da72020-11-20 09:40:12 +01004899 PyTypeObject *tp = Py_TYPE(self);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004900 BIO_free(self->bio);
4901 Py_TYPE(self)->tp_free(self);
Christian Heimes5c36da72020-11-20 09:40:12 +01004902 Py_DECREF(tp);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004903}
4904
4905static PyObject *
4906memory_bio_get_pending(PySSLMemoryBIO *self, void *c)
4907{
Segev Finer5cff6372017-07-27 01:19:17 +03004908 return PyLong_FromSize_t(BIO_ctrl_pending(self->bio));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004909}
4910
4911PyDoc_STRVAR(PySSL_memory_bio_pending_doc,
4912"The number of bytes pending in the memory BIO.");
4913
4914static PyObject *
4915memory_bio_get_eof(PySSLMemoryBIO *self, void *c)
4916{
4917 return PyBool_FromLong((BIO_ctrl_pending(self->bio) == 0)
4918 && self->eof_written);
4919}
4920
4921PyDoc_STRVAR(PySSL_memory_bio_eof_doc,
4922"Whether the memory BIO is at EOF.");
4923
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004924/*[clinic input]
4925_ssl.MemoryBIO.read
4926 size as len: int = -1
4927 /
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004928
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004929Read up to size bytes from the memory BIO.
4930
4931If size is not specified, read the entire buffer.
4932If the return value is an empty bytes instance, this means either
4933EOF or that no data is available. Use the "eof" property to
4934distinguish between the two.
4935[clinic start generated code]*/
4936
4937static PyObject *
4938_ssl_MemoryBIO_read_impl(PySSLMemoryBIO *self, int len)
4939/*[clinic end generated code: output=a657aa1e79cd01b3 input=574d7be06a902366]*/
4940{
4941 int avail, nbytes;
4942 PyObject *result;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004943
Segev Finer5cff6372017-07-27 01:19:17 +03004944 avail = (int)Py_MIN(BIO_ctrl_pending(self->bio), INT_MAX);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004945 if ((len < 0) || (len > avail))
4946 len = avail;
4947
4948 result = PyBytes_FromStringAndSize(NULL, len);
4949 if ((result == NULL) || (len == 0))
4950 return result;
4951
4952 nbytes = BIO_read(self->bio, PyBytes_AS_STRING(result), len);
Zackery Spytz365ad2e2018-10-06 11:41:45 -06004953 if (nbytes < 0) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004954 Py_DECREF(result);
Zackery Spytz365ad2e2018-10-06 11:41:45 -06004955 _setSSLError(NULL, 0, __FILE__, __LINE__);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004956 return NULL;
4957 }
4958
Zackery Spytz365ad2e2018-10-06 11:41:45 -06004959 /* There should never be any short reads but check anyway. */
4960 if (nbytes < len) {
4961 _PyBytes_Resize(&result, nbytes);
4962 }
4963
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004964 return result;
4965}
4966
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004967/*[clinic input]
4968_ssl.MemoryBIO.write
4969 b: Py_buffer
4970 /
4971
4972Writes the bytes b into the memory BIO.
4973
4974Returns the number of bytes written.
4975[clinic start generated code]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004976
4977static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004978_ssl_MemoryBIO_write_impl(PySSLMemoryBIO *self, Py_buffer *b)
4979/*[clinic end generated code: output=156ec59110d75935 input=e45757b3e17c4808]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004980{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004981 int nbytes;
4982
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004983 if (b->len > INT_MAX) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004984 PyErr_Format(PyExc_OverflowError,
4985 "string longer than %d bytes", INT_MAX);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004986 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004987 }
4988
4989 if (self->eof_written) {
4990 PyErr_SetString(PySSLErrorObject,
4991 "cannot write() after write_eof()");
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004992 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004993 }
4994
Segev Finer5cff6372017-07-27 01:19:17 +03004995 nbytes = BIO_write(self->bio, b->buf, (int)b->len);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004996 if (nbytes < 0) {
4997 _setSSLError(NULL, 0, __FILE__, __LINE__);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004998 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004999 }
5000
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005001 return PyLong_FromLong(nbytes);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005002}
5003
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005004/*[clinic input]
5005_ssl.MemoryBIO.write_eof
5006
5007Write an EOF marker to the memory BIO.
5008
5009When all data has been read, the "eof" property will be True.
5010[clinic start generated code]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005011
5012static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005013_ssl_MemoryBIO_write_eof_impl(PySSLMemoryBIO *self)
5014/*[clinic end generated code: output=d4106276ccd1ed34 input=56a945f1d29e8bd6]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005015{
5016 self->eof_written = 1;
5017 /* After an EOF is written, a zero return from read() should be a real EOF
5018 * i.e. it should not be retried. Clear the SHOULD_RETRY flag. */
5019 BIO_clear_retry_flags(self->bio);
5020 BIO_set_mem_eof_return(self->bio, 0);
5021
5022 Py_RETURN_NONE;
5023}
5024
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005025static PyGetSetDef memory_bio_getsetlist[] = {
5026 {"pending", (getter) memory_bio_get_pending, NULL,
5027 PySSL_memory_bio_pending_doc},
5028 {"eof", (getter) memory_bio_get_eof, NULL,
5029 PySSL_memory_bio_eof_doc},
5030 {NULL}, /* sentinel */
5031};
5032
5033static struct PyMethodDef memory_bio_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005034 _SSL_MEMORYBIO_READ_METHODDEF
5035 _SSL_MEMORYBIO_WRITE_METHODDEF
5036 _SSL_MEMORYBIO_WRITE_EOF_METHODDEF
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005037 {NULL, NULL} /* sentinel */
5038};
5039
Christian Heimes5c36da72020-11-20 09:40:12 +01005040static PyType_Slot PySSLMemoryBIO_slots[] = {
5041 {Py_tp_methods, memory_bio_methods},
5042 {Py_tp_getset, memory_bio_getsetlist},
5043 {Py_tp_new, _ssl_MemoryBIO},
5044 {Py_tp_dealloc, memory_bio_dealloc},
5045 {0, 0},
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005046};
5047
Christian Heimes5c36da72020-11-20 09:40:12 +01005048static PyType_Spec PySSLMemoryBIO_spec = {
5049 "_ssl.MemoryBIO",
5050 sizeof(PySSLMemoryBIO),
5051 0,
5052 Py_TPFLAGS_DEFAULT,
5053 PySSLMemoryBIO_slots,
5054};
Antoine Pitrou152efa22010-05-16 18:19:27 +00005055
Christian Heimes99a65702016-09-10 23:44:53 +02005056/*
5057 * SSL Session object
5058 */
5059
5060static void
5061PySSLSession_dealloc(PySSLSession *self)
5062{
Christian Heimes5c36da72020-11-20 09:40:12 +01005063 PyTypeObject *tp = Py_TYPE(self);
INADA Naokia6296d32017-08-24 14:55:17 +09005064 /* bpo-31095: UnTrack is needed before calling any callbacks */
Christian Heimesa5d07652016-09-24 10:48:05 +02005065 PyObject_GC_UnTrack(self);
Christian Heimes99a65702016-09-10 23:44:53 +02005066 Py_XDECREF(self->ctx);
5067 if (self->session != NULL) {
5068 SSL_SESSION_free(self->session);
5069 }
Christian Heimesa5d07652016-09-24 10:48:05 +02005070 PyObject_GC_Del(self);
Christian Heimes5c36da72020-11-20 09:40:12 +01005071 Py_DECREF(tp);
Christian Heimes99a65702016-09-10 23:44:53 +02005072}
5073
5074static PyObject *
5075PySSLSession_richcompare(PyObject *left, PyObject *right, int op)
5076{
5077 int result;
5078
5079 if (left == NULL || right == NULL) {
5080 PyErr_BadInternalCall();
5081 return NULL;
5082 }
5083
5084 if (!PySSLSession_Check(left) || !PySSLSession_Check(right)) {
5085 Py_RETURN_NOTIMPLEMENTED;
5086 }
5087
5088 if (left == right) {
5089 result = 0;
5090 } else {
5091 const unsigned char *left_id, *right_id;
5092 unsigned int left_len, right_len;
5093 left_id = SSL_SESSION_get_id(((PySSLSession *)left)->session,
5094 &left_len);
5095 right_id = SSL_SESSION_get_id(((PySSLSession *)right)->session,
5096 &right_len);
5097 if (left_len == right_len) {
5098 result = memcmp(left_id, right_id, left_len);
5099 } else {
5100 result = 1;
5101 }
5102 }
5103
5104 switch (op) {
5105 case Py_EQ:
5106 if (result == 0) {
5107 Py_RETURN_TRUE;
5108 } else {
5109 Py_RETURN_FALSE;
5110 }
5111 break;
5112 case Py_NE:
5113 if (result != 0) {
5114 Py_RETURN_TRUE;
5115 } else {
5116 Py_RETURN_FALSE;
5117 }
5118 break;
5119 case Py_LT:
5120 case Py_LE:
5121 case Py_GT:
5122 case Py_GE:
5123 Py_RETURN_NOTIMPLEMENTED;
5124 break;
5125 default:
5126 PyErr_BadArgument();
5127 return NULL;
5128 }
5129}
5130
5131static int
5132PySSLSession_traverse(PySSLSession *self, visitproc visit, void *arg)
5133{
5134 Py_VISIT(self->ctx);
5135 return 0;
5136}
5137
5138static int
5139PySSLSession_clear(PySSLSession *self)
5140{
5141 Py_CLEAR(self->ctx);
5142 return 0;
5143}
5144
5145
5146static PyObject *
5147PySSLSession_get_time(PySSLSession *self, void *closure) {
5148 return PyLong_FromLong(SSL_SESSION_get_time(self->session));
5149}
5150
5151PyDoc_STRVAR(PySSLSession_get_time_doc,
5152"Session creation time (seconds since epoch).");
5153
5154
5155static PyObject *
5156PySSLSession_get_timeout(PySSLSession *self, void *closure) {
5157 return PyLong_FromLong(SSL_SESSION_get_timeout(self->session));
5158}
5159
5160PyDoc_STRVAR(PySSLSession_get_timeout_doc,
5161"Session timeout (delta in seconds).");
5162
5163
5164static PyObject *
5165PySSLSession_get_ticket_lifetime_hint(PySSLSession *self, void *closure) {
5166 unsigned long hint = SSL_SESSION_get_ticket_lifetime_hint(self->session);
5167 return PyLong_FromUnsignedLong(hint);
5168}
5169
5170PyDoc_STRVAR(PySSLSession_get_ticket_lifetime_hint_doc,
5171"Ticket life time hint.");
5172
5173
5174static PyObject *
5175PySSLSession_get_session_id(PySSLSession *self, void *closure) {
5176 const unsigned char *id;
5177 unsigned int len;
5178 id = SSL_SESSION_get_id(self->session, &len);
5179 return PyBytes_FromStringAndSize((const char *)id, len);
5180}
5181
5182PyDoc_STRVAR(PySSLSession_get_session_id_doc,
5183"Session id");
5184
5185
5186static PyObject *
5187PySSLSession_get_has_ticket(PySSLSession *self, void *closure) {
5188 if (SSL_SESSION_has_ticket(self->session)) {
5189 Py_RETURN_TRUE;
5190 } else {
5191 Py_RETURN_FALSE;
5192 }
5193}
5194
5195PyDoc_STRVAR(PySSLSession_get_has_ticket_doc,
5196"Does the session contain a ticket?");
5197
5198
5199static PyGetSetDef PySSLSession_getsetlist[] = {
5200 {"has_ticket", (getter) PySSLSession_get_has_ticket, NULL,
5201 PySSLSession_get_has_ticket_doc},
5202 {"id", (getter) PySSLSession_get_session_id, NULL,
5203 PySSLSession_get_session_id_doc},
5204 {"ticket_lifetime_hint", (getter) PySSLSession_get_ticket_lifetime_hint,
5205 NULL, PySSLSession_get_ticket_lifetime_hint_doc},
5206 {"time", (getter) PySSLSession_get_time, NULL,
5207 PySSLSession_get_time_doc},
5208 {"timeout", (getter) PySSLSession_get_timeout, NULL,
5209 PySSLSession_get_timeout_doc},
5210 {NULL}, /* sentinel */
5211};
5212
Christian Heimes5c36da72020-11-20 09:40:12 +01005213static PyType_Slot PySSLSession_slots[] = {
5214 {Py_tp_getset,PySSLSession_getsetlist},
5215 {Py_tp_richcompare, PySSLSession_richcompare},
5216 {Py_tp_dealloc, PySSLSession_dealloc},
5217 {Py_tp_traverse, PySSLSession_traverse},
5218 {Py_tp_clear, PySSLSession_clear},
5219 {0, 0},
5220};
5221
5222static PyType_Spec PySSLSession_spec = {
5223 "_ssl.SSLSession",
5224 sizeof(PySSLSession),
5225 0,
5226 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,
5227 PySSLSession_slots,
Christian Heimes99a65702016-09-10 23:44:53 +02005228};
5229
5230
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005231/* helper routines for seeding the SSL PRNG */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005232/*[clinic input]
5233_ssl.RAND_add
Larry Hastingsdbfdc382015-05-04 06:59:46 -07005234 string as view: Py_buffer(accept={str, buffer})
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005235 entropy: double
5236 /
5237
5238Mix string into the OpenSSL PRNG state.
5239
5240entropy (a float) is a lower bound on the entropy contained in
Chandan Kumar63c2c8a2017-06-09 15:13:58 +05305241string. See RFC 4086.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005242[clinic start generated code]*/
5243
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005244static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005245_ssl_RAND_add_impl(PyObject *module, Py_buffer *view, double entropy)
Serhiy Storchaka5f31d5c2017-06-10 13:13:51 +03005246/*[clinic end generated code: output=e6dd48df9c9024e9 input=5c33017422828f5c]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005247{
Serhiy Storchaka8490f5a2015-03-20 09:00:36 +02005248 const char *buf;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02005249 Py_ssize_t len, written;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005250
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005251 buf = (const char *)view->buf;
5252 len = view->len;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02005253 do {
5254 written = Py_MIN(len, INT_MAX);
5255 RAND_add(buf, (int)written, entropy);
5256 buf += written;
5257 len -= written;
5258 } while (len);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02005259 Py_RETURN_NONE;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005260}
5261
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005262static PyObject *
Victor Stinner99c8b162011-05-24 12:05:19 +02005263PySSL_RAND(int len, int pseudo)
5264{
5265 int ok;
5266 PyObject *bytes;
5267 unsigned long err;
5268 const char *errstr;
5269 PyObject *v;
5270
Victor Stinner1e81a392013-12-19 16:47:04 +01005271 if (len < 0) {
5272 PyErr_SetString(PyExc_ValueError, "num must be positive");
5273 return NULL;
5274 }
5275
Victor Stinner99c8b162011-05-24 12:05:19 +02005276 bytes = PyBytes_FromStringAndSize(NULL, len);
5277 if (bytes == NULL)
5278 return NULL;
5279 if (pseudo) {
Christian Heimesa871f692020-06-01 08:58:14 +02005280#ifdef PY_OPENSSL_1_1_API
5281 ok = RAND_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
5282#else
Victor Stinner99c8b162011-05-24 12:05:19 +02005283 ok = RAND_pseudo_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
Christian Heimesa871f692020-06-01 08:58:14 +02005284#endif
Victor Stinner99c8b162011-05-24 12:05:19 +02005285 if (ok == 0 || ok == 1)
5286 return Py_BuildValue("NO", bytes, ok == 1 ? Py_True : Py_False);
5287 }
5288 else {
5289 ok = RAND_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
5290 if (ok == 1)
5291 return bytes;
5292 }
5293 Py_DECREF(bytes);
5294
5295 err = ERR_get_error();
5296 errstr = ERR_reason_error_string(err);
5297 v = Py_BuildValue("(ks)", err, errstr);
5298 if (v != NULL) {
5299 PyErr_SetObject(PySSLErrorObject, v);
5300 Py_DECREF(v);
5301 }
5302 return NULL;
5303}
5304
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005305/*[clinic input]
5306_ssl.RAND_bytes
5307 n: int
5308 /
5309
5310Generate n cryptographically strong pseudo-random bytes.
5311[clinic start generated code]*/
5312
Victor Stinner99c8b162011-05-24 12:05:19 +02005313static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005314_ssl_RAND_bytes_impl(PyObject *module, int n)
5315/*[clinic end generated code: output=977da635e4838bc7 input=678ddf2872dfebfc]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02005316{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005317 return PySSL_RAND(n, 0);
Victor Stinner99c8b162011-05-24 12:05:19 +02005318}
5319
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005320/*[clinic input]
5321_ssl.RAND_pseudo_bytes
5322 n: int
5323 /
5324
5325Generate n pseudo-random bytes.
5326
5327Return a pair (bytes, is_cryptographic). is_cryptographic is True
5328if the bytes generated are cryptographically strong.
5329[clinic start generated code]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02005330
5331static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005332_ssl_RAND_pseudo_bytes_impl(PyObject *module, int n)
5333/*[clinic end generated code: output=b1509e937000e52d input=58312bd53f9bbdd0]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02005334{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005335 return PySSL_RAND(n, 1);
Victor Stinner99c8b162011-05-24 12:05:19 +02005336}
5337
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005338/*[clinic input]
5339_ssl.RAND_status
5340
5341Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.
5342
5343It is necessary to seed the PRNG with RAND_add() on some platforms before
5344using the ssl() function.
5345[clinic start generated code]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02005346
5347static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005348_ssl_RAND_status_impl(PyObject *module)
5349/*[clinic end generated code: output=7e0aaa2d39fdc1ad input=8a774b02d1dc81f3]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005350{
Christian Heimes217cfd12007-12-02 14:31:20 +00005351 return PyLong_FromLong(RAND_status());
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005352}
5353
Benjamin Petersonb8a2f512016-07-06 23:55:15 -07005354#ifndef OPENSSL_NO_EGD
Christian Heimesa5d07652016-09-24 10:48:05 +02005355/* LCOV_EXCL_START */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005356/*[clinic input]
5357_ssl.RAND_egd
5358 path: object(converter="PyUnicode_FSConverter")
5359 /
5360
5361Queries the entropy gather daemon (EGD) on the socket named by 'path'.
5362
5363Returns number of bytes read. Raises SSLError if connection to EGD
5364fails or if it does not provide enough data to seed PRNG.
5365[clinic start generated code]*/
5366
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005367static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005368_ssl_RAND_egd_impl(PyObject *module, PyObject *path)
5369/*[clinic end generated code: output=02a67c7c367f52fa input=1aeb7eb948312195]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005370{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005371 int bytes = RAND_egd(PyBytes_AsString(path));
Victor Stinnerf9faaad2010-05-16 21:36:37 +00005372 Py_DECREF(path);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005373 if (bytes == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00005374 PyErr_SetString(PySSLErrorObject,
5375 "EGD connection failed or EGD did not return "
5376 "enough data to seed the PRNG");
5377 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005378 }
Christian Heimes217cfd12007-12-02 14:31:20 +00005379 return PyLong_FromLong(bytes);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005380}
Christian Heimesa5d07652016-09-24 10:48:05 +02005381/* LCOV_EXCL_STOP */
Benjamin Petersonb8a2f512016-07-06 23:55:15 -07005382#endif /* OPENSSL_NO_EGD */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005383
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005384
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005385
5386/*[clinic input]
5387_ssl.get_default_verify_paths
5388
5389Return search paths and environment vars that are used by SSLContext's set_default_verify_paths() to load default CAs.
5390
5391The values are 'cert_file_env', 'cert_file', 'cert_dir_env', 'cert_dir'.
5392[clinic start generated code]*/
Christian Heimes6d7ad132013-06-09 18:02:55 +02005393
5394static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005395_ssl_get_default_verify_paths_impl(PyObject *module)
5396/*[clinic end generated code: output=e5b62a466271928b input=5210c953d98c3eb5]*/
Christian Heimes6d7ad132013-06-09 18:02:55 +02005397{
5398 PyObject *ofile_env = NULL;
5399 PyObject *ofile = NULL;
5400 PyObject *odir_env = NULL;
5401 PyObject *odir = NULL;
5402
Benjamin Petersond113c962015-07-18 10:59:13 -07005403#define CONVERT(info, target) { \
Christian Heimes6d7ad132013-06-09 18:02:55 +02005404 const char *tmp = (info); \
5405 target = NULL; \
5406 if (!tmp) { Py_INCREF(Py_None); target = Py_None; } \
5407 else if ((target = PyUnicode_DecodeFSDefault(tmp)) == NULL) { \
5408 target = PyBytes_FromString(tmp); } \
5409 if (!target) goto error; \
Benjamin Peterson025a1fd2015-11-14 15:12:38 -08005410 }
Christian Heimes6d7ad132013-06-09 18:02:55 +02005411
Benjamin Petersond113c962015-07-18 10:59:13 -07005412 CONVERT(X509_get_default_cert_file_env(), ofile_env);
5413 CONVERT(X509_get_default_cert_file(), ofile);
5414 CONVERT(X509_get_default_cert_dir_env(), odir_env);
5415 CONVERT(X509_get_default_cert_dir(), odir);
5416#undef CONVERT
Christian Heimes6d7ad132013-06-09 18:02:55 +02005417
Christian Heimes200bb1b2013-06-14 15:14:29 +02005418 return Py_BuildValue("NNNN", ofile_env, ofile, odir_env, odir);
Christian Heimes6d7ad132013-06-09 18:02:55 +02005419
5420 error:
5421 Py_XDECREF(ofile_env);
5422 Py_XDECREF(ofile);
5423 Py_XDECREF(odir_env);
5424 Py_XDECREF(odir);
5425 return NULL;
5426}
5427
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005428static PyObject*
5429asn1obj2py(ASN1_OBJECT *obj)
5430{
5431 int nid;
5432 const char *ln, *sn;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005433
5434 nid = OBJ_obj2nid(obj);
5435 if (nid == NID_undef) {
5436 PyErr_Format(PyExc_ValueError, "Unknown object");
5437 return NULL;
5438 }
5439 sn = OBJ_nid2sn(nid);
5440 ln = OBJ_nid2ln(nid);
Serhiy Storchakae503ca52017-09-05 01:28:53 +03005441 return Py_BuildValue("issN", nid, sn, ln, _asn1obj2py(obj, 1));
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005442}
5443
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005444/*[clinic input]
5445_ssl.txt2obj
5446 txt: str
5447 name: bool = False
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005448
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005449Lookup NID, short name, long name and OID of an ASN1_OBJECT.
5450
5451By default objects are looked up by OID. With name=True short and
5452long name are also matched.
5453[clinic start generated code]*/
5454
5455static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005456_ssl_txt2obj_impl(PyObject *module, const char *txt, int name)
5457/*[clinic end generated code: output=c38e3991347079c1 input=1c1e7d0aa7c48602]*/
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005458{
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005459 PyObject *result = NULL;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005460 ASN1_OBJECT *obj;
5461
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005462 obj = OBJ_txt2obj(txt, name ? 0 : 1);
5463 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01005464 PyErr_Format(PyExc_ValueError, "unknown object '%.100s'", txt);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005465 return NULL;
5466 }
5467 result = asn1obj2py(obj);
5468 ASN1_OBJECT_free(obj);
5469 return result;
5470}
5471
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005472/*[clinic input]
5473_ssl.nid2obj
5474 nid: int
5475 /
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005476
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005477Lookup NID, short name, long name and OID of an ASN1_OBJECT by NID.
5478[clinic start generated code]*/
5479
5480static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005481_ssl_nid2obj_impl(PyObject *module, int nid)
5482/*[clinic end generated code: output=4a98ab691cd4f84a input=51787a3bee7d8f98]*/
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005483{
5484 PyObject *result = NULL;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005485 ASN1_OBJECT *obj;
5486
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005487 if (nid < NID_undef) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01005488 PyErr_SetString(PyExc_ValueError, "NID must be positive.");
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005489 return NULL;
5490 }
5491 obj = OBJ_nid2obj(nid);
5492 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01005493 PyErr_Format(PyExc_ValueError, "unknown NID %i", nid);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005494 return NULL;
5495 }
5496 result = asn1obj2py(obj);
5497 ASN1_OBJECT_free(obj);
5498 return result;
5499}
5500
Christian Heimes46bebee2013-06-09 19:03:31 +02005501#ifdef _MSC_VER
Christian Heimes44109d72013-11-22 01:51:30 +01005502
5503static PyObject*
5504certEncodingType(DWORD encodingType)
5505{
5506 static PyObject *x509_asn = NULL;
5507 static PyObject *pkcs_7_asn = NULL;
5508
5509 if (x509_asn == NULL) {
5510 x509_asn = PyUnicode_InternFromString("x509_asn");
5511 if (x509_asn == NULL)
5512 return NULL;
5513 }
5514 if (pkcs_7_asn == NULL) {
5515 pkcs_7_asn = PyUnicode_InternFromString("pkcs_7_asn");
5516 if (pkcs_7_asn == NULL)
5517 return NULL;
5518 }
5519 switch(encodingType) {
5520 case X509_ASN_ENCODING:
5521 Py_INCREF(x509_asn);
5522 return x509_asn;
5523 case PKCS_7_ASN_ENCODING:
5524 Py_INCREF(pkcs_7_asn);
5525 return pkcs_7_asn;
5526 default:
5527 return PyLong_FromLong(encodingType);
5528 }
5529}
5530
5531static PyObject*
5532parseKeyUsage(PCCERT_CONTEXT pCertCtx, DWORD flags)
5533{
5534 CERT_ENHKEY_USAGE *usage;
5535 DWORD size, error, i;
5536 PyObject *retval;
5537
5538 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, NULL, &size)) {
5539 error = GetLastError();
5540 if (error == CRYPT_E_NOT_FOUND) {
5541 Py_RETURN_TRUE;
5542 }
5543 return PyErr_SetFromWindowsErr(error);
5544 }
5545
5546 usage = (CERT_ENHKEY_USAGE*)PyMem_Malloc(size);
5547 if (usage == NULL) {
5548 return PyErr_NoMemory();
5549 }
5550
5551 /* Now get the actual enhanced usage property */
5552 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, usage, &size)) {
5553 PyMem_Free(usage);
5554 error = GetLastError();
5555 if (error == CRYPT_E_NOT_FOUND) {
5556 Py_RETURN_TRUE;
5557 }
5558 return PyErr_SetFromWindowsErr(error);
5559 }
Christian Heimes915cd3f2019-09-09 18:06:55 +02005560 retval = PyFrozenSet_New(NULL);
Christian Heimes44109d72013-11-22 01:51:30 +01005561 if (retval == NULL) {
5562 goto error;
5563 }
5564 for (i = 0; i < usage->cUsageIdentifier; ++i) {
5565 if (usage->rgpszUsageIdentifier[i]) {
5566 PyObject *oid;
5567 int err;
5568 oid = PyUnicode_FromString(usage->rgpszUsageIdentifier[i]);
5569 if (oid == NULL) {
5570 Py_CLEAR(retval);
5571 goto error;
5572 }
5573 err = PySet_Add(retval, oid);
5574 Py_DECREF(oid);
5575 if (err == -1) {
5576 Py_CLEAR(retval);
5577 goto error;
5578 }
5579 }
5580 }
5581 error:
5582 PyMem_Free(usage);
5583 return retval;
5584}
5585
kctherookied93fbbf2019-03-29 00:59:06 +07005586static HCERTSTORE
5587ssl_collect_certificates(const char *store_name)
5588{
5589/* this function collects the system certificate stores listed in
5590 * system_stores into a collection certificate store for being
5591 * enumerated. The store must be readable to be added to the
5592 * store collection.
5593 */
5594
5595 HCERTSTORE hCollectionStore = NULL, hSystemStore = NULL;
5596 static DWORD system_stores[] = {
5597 CERT_SYSTEM_STORE_LOCAL_MACHINE,
5598 CERT_SYSTEM_STORE_LOCAL_MACHINE_ENTERPRISE,
5599 CERT_SYSTEM_STORE_LOCAL_MACHINE_GROUP_POLICY,
5600 CERT_SYSTEM_STORE_CURRENT_USER,
5601 CERT_SYSTEM_STORE_CURRENT_USER_GROUP_POLICY,
5602 CERT_SYSTEM_STORE_SERVICES,
5603 CERT_SYSTEM_STORE_USERS};
5604 size_t i, storesAdded;
5605 BOOL result;
5606
5607 hCollectionStore = CertOpenStore(CERT_STORE_PROV_COLLECTION, 0,
5608 (HCRYPTPROV)NULL, 0, NULL);
5609 if (!hCollectionStore) {
5610 return NULL;
5611 }
5612 storesAdded = 0;
5613 for (i = 0; i < sizeof(system_stores) / sizeof(DWORD); i++) {
5614 hSystemStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0,
5615 (HCRYPTPROV)NULL,
5616 CERT_STORE_READONLY_FLAG |
5617 system_stores[i], store_name);
5618 if (hSystemStore) {
5619 result = CertAddStoreToCollection(hCollectionStore, hSystemStore,
5620 CERT_PHYSICAL_STORE_ADD_ENABLE_FLAG, 0);
5621 if (result) {
5622 ++storesAdded;
5623 }
neoneneed701292019-09-09 21:33:43 +09005624 CertCloseStore(hSystemStore, 0); /* flag must be 0 */
kctherookied93fbbf2019-03-29 00:59:06 +07005625 }
5626 }
5627 if (storesAdded == 0) {
5628 CertCloseStore(hCollectionStore, CERT_CLOSE_STORE_FORCE_FLAG);
5629 return NULL;
5630 }
5631
5632 return hCollectionStore;
5633}
5634
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005635/*[clinic input]
5636_ssl.enum_certificates
5637 store_name: str
5638
5639Retrieve certificates from Windows' cert store.
5640
5641store_name may be one of 'CA', 'ROOT' or 'MY'. The system may provide
5642more cert storages, too. The function returns a list of (bytes,
5643encoding_type, trust) tuples. The encoding_type flag can be interpreted
5644with X509_ASN_ENCODING or PKCS_7_ASN_ENCODING. The trust setting is either
5645a set of OIDs or the boolean True.
5646[clinic start generated code]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00005647
Christian Heimes46bebee2013-06-09 19:03:31 +02005648static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005649_ssl_enum_certificates_impl(PyObject *module, const char *store_name)
5650/*[clinic end generated code: output=5134dc8bb3a3c893 input=915f60d70461ea4e]*/
Christian Heimes46bebee2013-06-09 19:03:31 +02005651{
kctherookied93fbbf2019-03-29 00:59:06 +07005652 HCERTSTORE hCollectionStore = NULL;
Christian Heimes44109d72013-11-22 01:51:30 +01005653 PCCERT_CONTEXT pCertCtx = NULL;
5654 PyObject *keyusage = NULL, *cert = NULL, *enc = NULL, *tup = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02005655 PyObject *result = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02005656
Christian Heimes915cd3f2019-09-09 18:06:55 +02005657 result = PySet_New(NULL);
Christian Heimes44109d72013-11-22 01:51:30 +01005658 if (result == NULL) {
5659 return NULL;
5660 }
kctherookied93fbbf2019-03-29 00:59:06 +07005661 hCollectionStore = ssl_collect_certificates(store_name);
5662 if (hCollectionStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02005663 Py_DECREF(result);
5664 return PyErr_SetFromWindowsErr(GetLastError());
5665 }
5666
kctherookied93fbbf2019-03-29 00:59:06 +07005667 while (pCertCtx = CertEnumCertificatesInStore(hCollectionStore, pCertCtx)) {
Christian Heimes44109d72013-11-22 01:51:30 +01005668 cert = PyBytes_FromStringAndSize((const char*)pCertCtx->pbCertEncoded,
5669 pCertCtx->cbCertEncoded);
5670 if (!cert) {
5671 Py_CLEAR(result);
5672 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02005673 }
Christian Heimes44109d72013-11-22 01:51:30 +01005674 if ((enc = certEncodingType(pCertCtx->dwCertEncodingType)) == NULL) {
5675 Py_CLEAR(result);
5676 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02005677 }
Christian Heimes44109d72013-11-22 01:51:30 +01005678 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG);
5679 if (keyusage == Py_True) {
5680 Py_DECREF(keyusage);
5681 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_EXT_ONLY_ENHKEY_USAGE_FLAG);
Christian Heimes46bebee2013-06-09 19:03:31 +02005682 }
Christian Heimes44109d72013-11-22 01:51:30 +01005683 if (keyusage == NULL) {
5684 Py_CLEAR(result);
5685 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02005686 }
Christian Heimes44109d72013-11-22 01:51:30 +01005687 if ((tup = PyTuple_New(3)) == NULL) {
5688 Py_CLEAR(result);
5689 break;
5690 }
5691 PyTuple_SET_ITEM(tup, 0, cert);
5692 cert = NULL;
5693 PyTuple_SET_ITEM(tup, 1, enc);
5694 enc = NULL;
5695 PyTuple_SET_ITEM(tup, 2, keyusage);
5696 keyusage = NULL;
Christian Heimes915cd3f2019-09-09 18:06:55 +02005697 if (PySet_Add(result, tup) == -1) {
5698 Py_CLEAR(result);
5699 Py_CLEAR(tup);
5700 break;
Christian Heimes44109d72013-11-22 01:51:30 +01005701 }
5702 Py_CLEAR(tup);
5703 }
5704 if (pCertCtx) {
5705 /* loop ended with an error, need to clean up context manually */
5706 CertFreeCertificateContext(pCertCtx);
Christian Heimes46bebee2013-06-09 19:03:31 +02005707 }
5708
5709 /* In error cases cert, enc and tup may not be NULL */
5710 Py_XDECREF(cert);
5711 Py_XDECREF(enc);
Christian Heimes44109d72013-11-22 01:51:30 +01005712 Py_XDECREF(keyusage);
Christian Heimes46bebee2013-06-09 19:03:31 +02005713 Py_XDECREF(tup);
5714
kctherookied93fbbf2019-03-29 00:59:06 +07005715 /* CERT_CLOSE_STORE_FORCE_FLAG forces freeing of memory for all contexts
5716 associated with the store, in this case our collection store and the
5717 associated system stores. */
5718 if (!CertCloseStore(hCollectionStore, CERT_CLOSE_STORE_FORCE_FLAG)) {
Christian Heimes46bebee2013-06-09 19:03:31 +02005719 /* This error case might shadow another exception.*/
Christian Heimes44109d72013-11-22 01:51:30 +01005720 Py_XDECREF(result);
5721 return PyErr_SetFromWindowsErr(GetLastError());
5722 }
kctherookied93fbbf2019-03-29 00:59:06 +07005723
Christian Heimes915cd3f2019-09-09 18:06:55 +02005724 /* convert set to list */
5725 if (result == NULL) {
5726 return NULL;
5727 } else {
5728 PyObject *lst = PySequence_List(result);
5729 Py_DECREF(result);
5730 return lst;
5731 }
Christian Heimes44109d72013-11-22 01:51:30 +01005732}
5733
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005734/*[clinic input]
5735_ssl.enum_crls
5736 store_name: str
5737
5738Retrieve CRLs from Windows' cert store.
5739
5740store_name may be one of 'CA', 'ROOT' or 'MY'. The system may provide
5741more cert storages, too. The function returns a list of (bytes,
5742encoding_type) tuples. The encoding_type flag can be interpreted with
5743X509_ASN_ENCODING or PKCS_7_ASN_ENCODING.
5744[clinic start generated code]*/
Christian Heimes44109d72013-11-22 01:51:30 +01005745
5746static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005747_ssl_enum_crls_impl(PyObject *module, const char *store_name)
5748/*[clinic end generated code: output=bce467f60ccd03b6 input=a1f1d7629f1c5d3d]*/
Christian Heimes44109d72013-11-22 01:51:30 +01005749{
kctherookied93fbbf2019-03-29 00:59:06 +07005750 HCERTSTORE hCollectionStore = NULL;
Christian Heimes44109d72013-11-22 01:51:30 +01005751 PCCRL_CONTEXT pCrlCtx = NULL;
5752 PyObject *crl = NULL, *enc = NULL, *tup = NULL;
5753 PyObject *result = NULL;
5754
Christian Heimes915cd3f2019-09-09 18:06:55 +02005755 result = PySet_New(NULL);
Christian Heimes44109d72013-11-22 01:51:30 +01005756 if (result == NULL) {
5757 return NULL;
5758 }
kctherookied93fbbf2019-03-29 00:59:06 +07005759 hCollectionStore = ssl_collect_certificates(store_name);
5760 if (hCollectionStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02005761 Py_DECREF(result);
5762 return PyErr_SetFromWindowsErr(GetLastError());
5763 }
Christian Heimes44109d72013-11-22 01:51:30 +01005764
kctherookied93fbbf2019-03-29 00:59:06 +07005765 while (pCrlCtx = CertEnumCRLsInStore(hCollectionStore, pCrlCtx)) {
Christian Heimes44109d72013-11-22 01:51:30 +01005766 crl = PyBytes_FromStringAndSize((const char*)pCrlCtx->pbCrlEncoded,
5767 pCrlCtx->cbCrlEncoded);
5768 if (!crl) {
5769 Py_CLEAR(result);
5770 break;
5771 }
5772 if ((enc = certEncodingType(pCrlCtx->dwCertEncodingType)) == NULL) {
5773 Py_CLEAR(result);
5774 break;
5775 }
5776 if ((tup = PyTuple_New(2)) == NULL) {
5777 Py_CLEAR(result);
5778 break;
5779 }
5780 PyTuple_SET_ITEM(tup, 0, crl);
5781 crl = NULL;
5782 PyTuple_SET_ITEM(tup, 1, enc);
5783 enc = NULL;
5784
Christian Heimes915cd3f2019-09-09 18:06:55 +02005785 if (PySet_Add(result, tup) == -1) {
5786 Py_CLEAR(result);
5787 Py_CLEAR(tup);
5788 break;
Christian Heimes44109d72013-11-22 01:51:30 +01005789 }
5790 Py_CLEAR(tup);
Christian Heimes46bebee2013-06-09 19:03:31 +02005791 }
Christian Heimes44109d72013-11-22 01:51:30 +01005792 if (pCrlCtx) {
5793 /* loop ended with an error, need to clean up context manually */
5794 CertFreeCRLContext(pCrlCtx);
5795 }
5796
5797 /* In error cases cert, enc and tup may not be NULL */
5798 Py_XDECREF(crl);
5799 Py_XDECREF(enc);
5800 Py_XDECREF(tup);
5801
kctherookied93fbbf2019-03-29 00:59:06 +07005802 /* CERT_CLOSE_STORE_FORCE_FLAG forces freeing of memory for all contexts
5803 associated with the store, in this case our collection store and the
5804 associated system stores. */
5805 if (!CertCloseStore(hCollectionStore, CERT_CLOSE_STORE_FORCE_FLAG)) {
Christian Heimes44109d72013-11-22 01:51:30 +01005806 /* This error case might shadow another exception.*/
5807 Py_XDECREF(result);
5808 return PyErr_SetFromWindowsErr(GetLastError());
5809 }
Christian Heimes915cd3f2019-09-09 18:06:55 +02005810 /* convert set to list */
5811 if (result == NULL) {
5812 return NULL;
5813 } else {
5814 PyObject *lst = PySequence_List(result);
5815 Py_DECREF(result);
5816 return lst;
5817 }
Christian Heimes46bebee2013-06-09 19:03:31 +02005818}
Christian Heimes44109d72013-11-22 01:51:30 +01005819
5820#endif /* _MSC_VER */
Bill Janssen40a0f662008-08-12 16:56:25 +00005821
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005822/* List of functions exported by this module. */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005823static PyMethodDef PySSL_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005824 _SSL__TEST_DECODE_CERT_METHODDEF
5825 _SSL_RAND_ADD_METHODDEF
5826 _SSL_RAND_BYTES_METHODDEF
5827 _SSL_RAND_PSEUDO_BYTES_METHODDEF
5828 _SSL_RAND_EGD_METHODDEF
5829 _SSL_RAND_STATUS_METHODDEF
5830 _SSL_GET_DEFAULT_VERIFY_PATHS_METHODDEF
5831 _SSL_ENUM_CERTIFICATES_METHODDEF
5832 _SSL_ENUM_CRLS_METHODDEF
5833 _SSL_TXT2OBJ_METHODDEF
5834 _SSL_NID2OBJ_METHODDEF
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005835 {NULL, NULL} /* Sentinel */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005836};
5837
5838
Christian Heimes598894f2016-09-05 23:19:05 +02005839#ifdef HAVE_OPENSSL_CRYPTO_LOCK
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005840
5841/* an implementation of OpenSSL threading operations in terms
Christian Heimes598894f2016-09-05 23:19:05 +02005842 * of the Python C thread library
5843 * Only used up to 1.0.2. OpenSSL 1.1.0+ has its own locking code.
5844 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005845
5846static PyThread_type_lock *_ssl_locks = NULL;
5847
Christian Heimes4d98ca92013-08-19 17:36:29 +02005848#if OPENSSL_VERSION_NUMBER >= 0x10000000
5849/* use new CRYPTO_THREADID API. */
5850static void
5851_ssl_threadid_callback(CRYPTO_THREADID *id)
5852{
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +02005853 CRYPTO_THREADID_set_numeric(id, PyThread_get_thread_ident());
Christian Heimes4d98ca92013-08-19 17:36:29 +02005854}
5855#else
5856/* deprecated CRYPTO_set_id_callback() API. */
5857static unsigned long
5858_ssl_thread_id_function (void) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005859 return PyThread_get_thread_ident();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005860}
Christian Heimes4d98ca92013-08-19 17:36:29 +02005861#endif
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005862
Bill Janssen6e027db2007-11-15 22:23:56 +00005863static void _ssl_thread_locking_function
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005864 (int mode, int n, const char *file, int line) {
5865 /* this function is needed to perform locking on shared data
5866 structures. (Note that OpenSSL uses a number of global data
5867 structures that will be implicitly shared whenever multiple
5868 threads use OpenSSL.) Multi-threaded applications will
5869 crash at random if it is not set.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005870
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005871 locking_function() must be able to handle up to
5872 CRYPTO_num_locks() different mutex locks. It sets the n-th
5873 lock if mode & CRYPTO_LOCK, and releases it otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005874
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005875 file and line are the file number of the function setting the
5876 lock. They can be useful for debugging.
5877 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005878
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005879 if ((_ssl_locks == NULL) ||
5880 (n < 0) || ((unsigned)n >= _ssl_locks_count))
5881 return;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005882
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005883 if (mode & CRYPTO_LOCK) {
5884 PyThread_acquire_lock(_ssl_locks[n], 1);
5885 } else {
5886 PyThread_release_lock(_ssl_locks[n]);
5887 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005888}
5889
5890static int _setup_ssl_threads(void) {
5891
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005892 unsigned int i;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005893
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005894 if (_ssl_locks == NULL) {
5895 _ssl_locks_count = CRYPTO_num_locks();
Christian Heimesf6365e32016-09-13 20:48:13 +02005896 _ssl_locks = PyMem_Calloc(_ssl_locks_count,
5897 sizeof(PyThread_type_lock));
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02005898 if (_ssl_locks == NULL) {
5899 PyErr_NoMemory();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005900 return 0;
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02005901 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005902 for (i = 0; i < _ssl_locks_count; i++) {
5903 _ssl_locks[i] = PyThread_allocate_lock();
5904 if (_ssl_locks[i] == NULL) {
5905 unsigned int j;
5906 for (j = 0; j < i; j++) {
5907 PyThread_free_lock(_ssl_locks[j]);
5908 }
Victor Stinnerb6404912013-07-07 16:21:41 +02005909 PyMem_Free(_ssl_locks);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005910 return 0;
5911 }
5912 }
5913 CRYPTO_set_locking_callback(_ssl_thread_locking_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02005914#if OPENSSL_VERSION_NUMBER >= 0x10000000
5915 CRYPTO_THREADID_set_callback(_ssl_threadid_callback);
5916#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005917 CRYPTO_set_id_callback(_ssl_thread_id_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02005918#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005919 }
5920 return 1;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005921}
5922
Antoine Pitroua6a4dc82017-09-07 18:56:24 +02005923#endif /* HAVE_OPENSSL_CRYPTO_LOCK for OpenSSL < 1.1.0 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005924
Christian Heimes5c36da72020-11-20 09:40:12 +01005925static int
5926sslmodule_init_types(PyObject *module)
5927{
5928 PySSLContext_Type = (PyTypeObject *)PyType_FromModuleAndSpec(
5929 module, &PySSLContext_spec, NULL
5930 );
5931 if (PySSLContext_Type == NULL)
5932 return -1;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005933
Christian Heimes5c36da72020-11-20 09:40:12 +01005934 PySSLSocket_Type = (PyTypeObject *)PyType_FromModuleAndSpec(
5935 module, &PySSLSocket_spec, NULL
5936 );
5937 if (PySSLSocket_Type == NULL)
5938 return -1;
Martin v. Löwis1a214512008-06-11 05:26:20 +00005939
Christian Heimes5c36da72020-11-20 09:40:12 +01005940 PySSLMemoryBIO_Type = (PyTypeObject *)PyType_FromModuleAndSpec(
5941 module, &PySSLMemoryBIO_spec, NULL
5942 );
5943 if (PySSLMemoryBIO_Type == NULL)
5944 return -1;
Martin v. Löwis1a214512008-06-11 05:26:20 +00005945
Christian Heimes5c36da72020-11-20 09:40:12 +01005946 PySSLSession_Type = (PyTypeObject *)PyType_FromModuleAndSpec(
5947 module, &PySSLSession_spec, NULL
5948 );
5949 if (PySSLSession_Type == NULL)
5950 return -1;
5951
5952 if (PyModule_AddType(module, PySSLContext_Type))
5953 return -1;
5954 if (PyModule_AddType(module, PySSLSocket_Type))
5955 return -1;
5956 if (PyModule_AddType(module, PySSLMemoryBIO_Type))
5957 return -1;
5958 if (PyModule_AddType(module, PySSLSession_Type))
5959 return -1;
5960
5961 return 0;
5962}
5963
5964static int
5965sslmodule_init_exceptions(PyObject *module)
5966{
5967 PyObject *bases = NULL;
5968
5969#define add_exception(exc, name, doc, base) \
5970do { \
5971 (exc) = PyErr_NewExceptionWithDoc("ssl." name, (doc), (base), NULL); \
5972 if ((exc) == NULL) goto error; \
5973 if (PyModule_AddObjectRef(module, name, exc) < 0) goto error; \
5974} while(0)
5975
Serhiy Storchaka686c2032020-11-22 13:25:02 +02005976 PySSLErrorObject = PyType_FromSpecWithBases(&sslerror_type_spec, PyExc_OSError);
Christian Heimes5c36da72020-11-20 09:40:12 +01005977 if (PySSLErrorObject == NULL) {
5978 goto error;
5979 }
5980 if (PyModule_AddObjectRef(module, "SSLError", PySSLErrorObject) < 0) {
5981 goto error;
5982 }
5983
5984 /* ssl.CertificateError used to be a subclass of ValueError */
5985 bases = PyTuple_Pack(2, PySSLErrorObject, PyExc_ValueError);
5986 if (bases == NULL) {
5987 goto error;
5988 }
5989 add_exception(
5990 PySSLCertVerificationErrorObject,
5991 "SSLCertVerificationError",
5992 SSLCertVerificationError_doc,
5993 bases
5994 );
5995 Py_CLEAR(bases);
5996
5997 add_exception(
5998 PySSLZeroReturnErrorObject,
5999 "SSLZeroReturnError",
6000 SSLZeroReturnError_doc,
6001 PySSLErrorObject
6002 );
6003
6004 add_exception(
6005 PySSLWantWriteErrorObject,
6006 "SSLWantWriteError",
6007 SSLWantWriteError_doc,
6008 PySSLErrorObject
6009 );
6010
6011 add_exception(
6012 PySSLWantReadErrorObject,
6013 "SSLWantReadError",
6014 SSLWantReadError_doc,
6015 PySSLErrorObject
6016 );
6017
6018 add_exception(
6019 PySSLSyscallErrorObject,
6020 "SSLSyscallError",
6021 SSLSyscallError_doc,
6022 PySSLErrorObject
6023 );
6024
6025 add_exception(
6026 PySSLEOFErrorObject,
6027 "SSLEOFError",
6028 SSLEOFError_doc,
6029 PySSLErrorObject
6030 );
6031#undef add_exception
6032
6033 return 0;
6034 error:
6035 Py_XDECREF(bases);
6036 return -1;
6037}
6038
6039static int
6040sslmodule_init_socketapi(PyObject *module)
6041{
6042 PySocketModule_APIObject *socket_api;
6043
6044 /* Load _socket module and its C API */
6045 socket_api = PySocketModule_ImportModuleAndAPI();
6046 if (socket_api == NULL)
6047 return -1;
6048 PySocketModule = *socket_api;
6049
6050 return 0;
6051}
6052
6053static int
6054sslmodule_init_errorcodes(PyObject *module)
6055{
6056 struct py_ssl_error_code *errcode;
6057 struct py_ssl_library_code *libcode;
6058
6059 /* Mappings for error codes */
6060 err_codes_to_names = PyDict_New();
6061 if (err_codes_to_names == NULL)
6062 return -1;
6063 err_names_to_codes = PyDict_New();
6064 if (err_names_to_codes == NULL)
6065 return -1;
6066 lib_codes_to_names = PyDict_New();
6067 if (lib_codes_to_names == NULL)
6068 return -1;
6069
6070 errcode = error_codes;
6071 while (errcode->mnemonic != NULL) {
6072 PyObject *mnemo, *key;
6073 mnemo = PyUnicode_FromString(errcode->mnemonic);
6074 key = Py_BuildValue("ii", errcode->library, errcode->reason);
6075 if (mnemo == NULL || key == NULL)
6076 return -1;
6077 if (PyDict_SetItem(err_codes_to_names, key, mnemo))
6078 return -1;
6079 if (PyDict_SetItem(err_names_to_codes, mnemo, key))
6080 return -1;
6081 Py_DECREF(key);
6082 Py_DECREF(mnemo);
6083 errcode++;
6084 }
6085
6086 libcode = library_codes;
6087 while (libcode->library != NULL) {
6088 PyObject *mnemo, *key;
6089 key = PyLong_FromLong(libcode->code);
6090 mnemo = PyUnicode_FromString(libcode->library);
6091 if (key == NULL || mnemo == NULL)
6092 return -1;
6093 if (PyDict_SetItem(lib_codes_to_names, key, mnemo))
6094 return -1;
6095 Py_DECREF(key);
6096 Py_DECREF(mnemo);
6097 libcode++;
6098 }
6099
6100 if (PyModule_AddObject(module, "err_codes_to_names", err_codes_to_names))
6101 return -1;
6102 if (PyModule_AddObject(module, "err_names_to_codes", err_names_to_codes))
6103 return -1;
6104 if (PyModule_AddObject(module, "lib_codes_to_names", lib_codes_to_names))
6105 return -1;
6106
6107 return 0;
6108}
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02006109
6110static void
6111parse_openssl_version(unsigned long libver,
6112 unsigned int *major, unsigned int *minor,
6113 unsigned int *fix, unsigned int *patch,
6114 unsigned int *status)
6115{
6116 *status = libver & 0xF;
6117 libver >>= 4;
6118 *patch = libver & 0xFF;
6119 libver >>= 8;
6120 *fix = libver & 0xFF;
6121 libver >>= 8;
6122 *minor = libver & 0xFF;
6123 libver >>= 8;
6124 *major = libver & 0xFF;
6125}
6126
Christian Heimes5c36da72020-11-20 09:40:12 +01006127static int
6128sslmodule_init_versioninfo(PyObject *m)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00006129{
Christian Heimes5c36da72020-11-20 09:40:12 +01006130 PyObject *r;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006131 unsigned long libver;
6132 unsigned int major, minor, fix, patch, status;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00006133
Christian Heimes5c36da72020-11-20 09:40:12 +01006134 /* OpenSSL version */
6135 /* SSLeay() gives us the version of the library linked against,
6136 which could be different from the headers version.
6137 */
6138 libver = OpenSSL_version_num();
6139 r = PyLong_FromUnsignedLong(libver);
6140 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r))
6141 return -1;
Christian Heimes99a65702016-09-10 23:44:53 +02006142
Christian Heimes5c36da72020-11-20 09:40:12 +01006143 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
6144 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
6145 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r))
6146 return -1;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00006147
Christian Heimes5c36da72020-11-20 09:40:12 +01006148 r = PyUnicode_FromString(OpenSSL_version(OPENSSL_VERSION));
6149 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r))
6150 return -1;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00006151
Christian Heimes5c36da72020-11-20 09:40:12 +01006152 libver = OPENSSL_VERSION_NUMBER;
6153 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
6154 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
6155 if (r == NULL || PyModule_AddObject(m, "_OPENSSL_API_VERSION", r))
6156 return -1;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00006157
Christian Heimes5c36da72020-11-20 09:40:12 +01006158 return 0;
6159}
Christian Heimesc941e622017-09-05 15:47:11 +02006160
Christian Heimes5c36da72020-11-20 09:40:12 +01006161static int
6162sslmodule_init_constants(PyObject *m)
6163{
Christian Heimes892d66e2018-01-29 14:10:18 +01006164 PyModule_AddStringConstant(m, "_DEFAULT_CIPHERS",
6165 PY_SSL_DEFAULT_CIPHER_STRING);
6166
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006167 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
6168 PY_SSL_ERROR_ZERO_RETURN);
6169 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
6170 PY_SSL_ERROR_WANT_READ);
6171 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
6172 PY_SSL_ERROR_WANT_WRITE);
6173 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
6174 PY_SSL_ERROR_WANT_X509_LOOKUP);
6175 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
6176 PY_SSL_ERROR_SYSCALL);
6177 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
6178 PY_SSL_ERROR_SSL);
6179 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
6180 PY_SSL_ERROR_WANT_CONNECT);
6181 /* non ssl.h errorcodes */
6182 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
6183 PY_SSL_ERROR_EOF);
6184 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
6185 PY_SSL_ERROR_INVALID_ERROR_CODE);
6186 /* cert requirements */
6187 PyModule_AddIntConstant(m, "CERT_NONE",
6188 PY_SSL_CERT_NONE);
6189 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
6190 PY_SSL_CERT_OPTIONAL);
6191 PyModule_AddIntConstant(m, "CERT_REQUIRED",
6192 PY_SSL_CERT_REQUIRED);
Christian Heimes22587792013-11-21 23:56:13 +01006193 /* CRL verification for verification_flags */
6194 PyModule_AddIntConstant(m, "VERIFY_DEFAULT",
6195 0);
6196 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_LEAF",
6197 X509_V_FLAG_CRL_CHECK);
6198 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_CHAIN",
6199 X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
6200 PyModule_AddIntConstant(m, "VERIFY_X509_STRICT",
6201 X509_V_FLAG_X509_STRICT);
Chris Burre0b4aa02021-03-18 09:24:01 +01006202 PyModule_AddIntConstant(m, "VERIFY_ALLOW_PROXY_CERTS",
6203 X509_V_FLAG_ALLOW_PROXY_CERTS);
Benjamin Peterson990fcaa2015-03-04 22:49:41 -05006204#ifdef X509_V_FLAG_TRUSTED_FIRST
6205 PyModule_AddIntConstant(m, "VERIFY_X509_TRUSTED_FIRST",
6206 X509_V_FLAG_TRUSTED_FIRST);
6207#endif
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00006208
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01006209 /* Alert Descriptions from ssl.h */
6210 /* note RESERVED constants no longer intended for use have been removed */
6211 /* http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-6 */
6212
6213#define ADD_AD_CONSTANT(s) \
6214 PyModule_AddIntConstant(m, "ALERT_DESCRIPTION_"#s, \
6215 SSL_AD_##s)
6216
6217 ADD_AD_CONSTANT(CLOSE_NOTIFY);
6218 ADD_AD_CONSTANT(UNEXPECTED_MESSAGE);
6219 ADD_AD_CONSTANT(BAD_RECORD_MAC);
6220 ADD_AD_CONSTANT(RECORD_OVERFLOW);
6221 ADD_AD_CONSTANT(DECOMPRESSION_FAILURE);
6222 ADD_AD_CONSTANT(HANDSHAKE_FAILURE);
6223 ADD_AD_CONSTANT(BAD_CERTIFICATE);
6224 ADD_AD_CONSTANT(UNSUPPORTED_CERTIFICATE);
6225 ADD_AD_CONSTANT(CERTIFICATE_REVOKED);
6226 ADD_AD_CONSTANT(CERTIFICATE_EXPIRED);
6227 ADD_AD_CONSTANT(CERTIFICATE_UNKNOWN);
6228 ADD_AD_CONSTANT(ILLEGAL_PARAMETER);
6229 ADD_AD_CONSTANT(UNKNOWN_CA);
6230 ADD_AD_CONSTANT(ACCESS_DENIED);
6231 ADD_AD_CONSTANT(DECODE_ERROR);
6232 ADD_AD_CONSTANT(DECRYPT_ERROR);
6233 ADD_AD_CONSTANT(PROTOCOL_VERSION);
6234 ADD_AD_CONSTANT(INSUFFICIENT_SECURITY);
6235 ADD_AD_CONSTANT(INTERNAL_ERROR);
6236 ADD_AD_CONSTANT(USER_CANCELLED);
6237 ADD_AD_CONSTANT(NO_RENEGOTIATION);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01006238 /* Not all constants are in old OpenSSL versions */
Antoine Pitrou912fbff2013-03-30 16:29:32 +01006239#ifdef SSL_AD_UNSUPPORTED_EXTENSION
6240 ADD_AD_CONSTANT(UNSUPPORTED_EXTENSION);
6241#endif
6242#ifdef SSL_AD_CERTIFICATE_UNOBTAINABLE
6243 ADD_AD_CONSTANT(CERTIFICATE_UNOBTAINABLE);
6244#endif
6245#ifdef SSL_AD_UNRECOGNIZED_NAME
6246 ADD_AD_CONSTANT(UNRECOGNIZED_NAME);
6247#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01006248#ifdef SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE
6249 ADD_AD_CONSTANT(BAD_CERTIFICATE_STATUS_RESPONSE);
6250#endif
6251#ifdef SSL_AD_BAD_CERTIFICATE_HASH_VALUE
6252 ADD_AD_CONSTANT(BAD_CERTIFICATE_HASH_VALUE);
6253#endif
6254#ifdef SSL_AD_UNKNOWN_PSK_IDENTITY
6255 ADD_AD_CONSTANT(UNKNOWN_PSK_IDENTITY);
6256#endif
6257
6258#undef ADD_AD_CONSTANT
6259
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006260 /* protocol versions */
Victor Stinner3de49192011-05-09 00:42:58 +02006261#ifndef OPENSSL_NO_SSL2
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006262 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
6263 PY_SSL_VERSION_SSL2);
Victor Stinner3de49192011-05-09 00:42:58 +02006264#endif
Benjamin Petersone32467c2014-12-05 21:59:35 -05006265#ifndef OPENSSL_NO_SSL3
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006266 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
6267 PY_SSL_VERSION_SSL3);
Benjamin Petersone32467c2014-12-05 21:59:35 -05006268#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006269 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
Christian Heimes598894f2016-09-05 23:19:05 +02006270 PY_SSL_VERSION_TLS);
6271 PyModule_AddIntConstant(m, "PROTOCOL_TLS",
6272 PY_SSL_VERSION_TLS);
Christian Heimes5fe668c2016-09-12 00:01:11 +02006273 PyModule_AddIntConstant(m, "PROTOCOL_TLS_CLIENT",
6274 PY_SSL_VERSION_TLS_CLIENT);
6275 PyModule_AddIntConstant(m, "PROTOCOL_TLS_SERVER",
6276 PY_SSL_VERSION_TLS_SERVER);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006277 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
6278 PY_SSL_VERSION_TLS1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01006279 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_1",
6280 PY_SSL_VERSION_TLS1_1);
6281 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_2",
6282 PY_SSL_VERSION_TLS1_2);
Antoine Pitrou04f6a322010-04-05 21:40:07 +00006283
Antoine Pitroub5218772010-05-21 09:56:06 +00006284 /* protocol options */
Antoine Pitrou3f366312012-01-27 09:50:45 +01006285 PyModule_AddIntConstant(m, "OP_ALL",
6286 SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
Antoine Pitroub5218772010-05-21 09:56:06 +00006287 PyModule_AddIntConstant(m, "OP_NO_SSLv2", SSL_OP_NO_SSLv2);
6288 PyModule_AddIntConstant(m, "OP_NO_SSLv3", SSL_OP_NO_SSLv3);
6289 PyModule_AddIntConstant(m, "OP_NO_TLSv1", SSL_OP_NO_TLSv1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01006290 PyModule_AddIntConstant(m, "OP_NO_TLSv1_1", SSL_OP_NO_TLSv1_1);
6291 PyModule_AddIntConstant(m, "OP_NO_TLSv1_2", SSL_OP_NO_TLSv1_2);
Christian Heimescb5b68a2017-09-07 18:07:00 -07006292#ifdef SSL_OP_NO_TLSv1_3
6293 PyModule_AddIntConstant(m, "OP_NO_TLSv1_3", SSL_OP_NO_TLSv1_3);
6294#else
6295 PyModule_AddIntConstant(m, "OP_NO_TLSv1_3", 0);
6296#endif
Antoine Pitrou6db49442011-12-19 13:27:11 +01006297 PyModule_AddIntConstant(m, "OP_CIPHER_SERVER_PREFERENCE",
6298 SSL_OP_CIPHER_SERVER_PREFERENCE);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01006299 PyModule_AddIntConstant(m, "OP_SINGLE_DH_USE", SSL_OP_SINGLE_DH_USE);
Christian Heimes99a65702016-09-10 23:44:53 +02006300 PyModule_AddIntConstant(m, "OP_NO_TICKET", SSL_OP_NO_TICKET);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01006301#ifdef SSL_OP_SINGLE_ECDH_USE
Antoine Pitrou923df6f2011-12-19 17:16:51 +01006302 PyModule_AddIntConstant(m, "OP_SINGLE_ECDH_USE", SSL_OP_SINGLE_ECDH_USE);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01006303#endif
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01006304#ifdef SSL_OP_NO_COMPRESSION
6305 PyModule_AddIntConstant(m, "OP_NO_COMPRESSION",
6306 SSL_OP_NO_COMPRESSION);
6307#endif
Christian Heimes05d9fe32018-02-27 08:55:39 +01006308#ifdef SSL_OP_ENABLE_MIDDLEBOX_COMPAT
6309 PyModule_AddIntConstant(m, "OP_ENABLE_MIDDLEBOX_COMPAT",
6310 SSL_OP_ENABLE_MIDDLEBOX_COMPAT);
6311#endif
Christian Heimes67c48012018-05-15 16:25:40 -04006312#ifdef SSL_OP_NO_RENEGOTIATION
6313 PyModule_AddIntConstant(m, "OP_NO_RENEGOTIATION",
6314 SSL_OP_NO_RENEGOTIATION);
6315#endif
Antoine Pitroub5218772010-05-21 09:56:06 +00006316
Christian Heimes61d478c2018-01-27 15:51:38 +01006317#ifdef X509_CHECK_FLAG_ALWAYS_CHECK_SUBJECT
6318 PyModule_AddIntConstant(m, "HOSTFLAG_ALWAYS_CHECK_SUBJECT",
6319 X509_CHECK_FLAG_ALWAYS_CHECK_SUBJECT);
6320#endif
6321#ifdef X509_CHECK_FLAG_NEVER_CHECK_SUBJECT
6322 PyModule_AddIntConstant(m, "HOSTFLAG_NEVER_CHECK_SUBJECT",
6323 X509_CHECK_FLAG_NEVER_CHECK_SUBJECT);
6324#endif
6325#ifdef X509_CHECK_FLAG_NO_WILDCARDS
6326 PyModule_AddIntConstant(m, "HOSTFLAG_NO_WILDCARDS",
6327 X509_CHECK_FLAG_NO_WILDCARDS);
6328#endif
6329#ifdef X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS
6330 PyModule_AddIntConstant(m, "HOSTFLAG_NO_PARTIAL_WILDCARDS",
6331 X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS);
6332#endif
6333#ifdef X509_CHECK_FLAG_MULTI_LABEL_WILDCARDS
6334 PyModule_AddIntConstant(m, "HOSTFLAG_MULTI_LABEL_WILDCARDS",
6335 X509_CHECK_FLAG_MULTI_LABEL_WILDCARDS);
6336#endif
6337#ifdef X509_CHECK_FLAG_SINGLE_LABEL_SUBDOMAINS
6338 PyModule_AddIntConstant(m, "HOSTFLAG_SINGLE_LABEL_SUBDOMAINS",
6339 X509_CHECK_FLAG_SINGLE_LABEL_SUBDOMAINS);
6340#endif
6341
Christian Heimes698dde12018-02-27 11:54:43 +01006342 /* protocol versions */
6343 PyModule_AddIntConstant(m, "PROTO_MINIMUM_SUPPORTED",
6344 PY_PROTO_MINIMUM_SUPPORTED);
6345 PyModule_AddIntConstant(m, "PROTO_MAXIMUM_SUPPORTED",
6346 PY_PROTO_MAXIMUM_SUPPORTED);
6347 PyModule_AddIntConstant(m, "PROTO_SSLv3", PY_PROTO_SSLv3);
6348 PyModule_AddIntConstant(m, "PROTO_TLSv1", PY_PROTO_TLSv1);
6349 PyModule_AddIntConstant(m, "PROTO_TLSv1_1", PY_PROTO_TLSv1_1);
6350 PyModule_AddIntConstant(m, "PROTO_TLSv1_2", PY_PROTO_TLSv1_2);
6351 PyModule_AddIntConstant(m, "PROTO_TLSv1_3", PY_PROTO_TLSv1_3);
Antoine Pitroud5323212010-10-22 18:19:07 +00006352
Victor Stinnerb37672d2018-11-22 03:37:50 +01006353#define addbool(m, key, value) \
6354 do { \
6355 PyObject *bool_obj = (value) ? Py_True : Py_False; \
6356 Py_INCREF(bool_obj); \
6357 PyModule_AddObject((m), (key), bool_obj); \
6358 } while (0)
Christian Heimes698dde12018-02-27 11:54:43 +01006359
6360#if HAVE_SNI
6361 addbool(m, "HAS_SNI", 1);
Antoine Pitrou501da612011-12-21 09:27:41 +01006362#else
Christian Heimes698dde12018-02-27 11:54:43 +01006363 addbool(m, "HAS_SNI", 0);
Antoine Pitrou501da612011-12-21 09:27:41 +01006364#endif
Christian Heimes698dde12018-02-27 11:54:43 +01006365
6366 addbool(m, "HAS_TLS_UNIQUE", 1);
6367
6368#ifndef OPENSSL_NO_ECDH
6369 addbool(m, "HAS_ECDH", 1);
6370#else
6371 addbool(m, "HAS_ECDH", 0);
6372#endif
Antoine Pitrou501da612011-12-21 09:27:41 +01006373
Christian Heimes29eab552018-02-25 12:31:33 +01006374#if HAVE_NPN
Christian Heimes698dde12018-02-27 11:54:43 +01006375 addbool(m, "HAS_NPN", 1);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01006376#else
Christian Heimes698dde12018-02-27 11:54:43 +01006377 addbool(m, "HAS_NPN", 0);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01006378#endif
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01006379
Christian Heimes29eab552018-02-25 12:31:33 +01006380#if HAVE_ALPN
Christian Heimes698dde12018-02-27 11:54:43 +01006381 addbool(m, "HAS_ALPN", 1);
Benjamin Petersoncca27322015-01-23 16:35:37 -05006382#else
Christian Heimes698dde12018-02-27 11:54:43 +01006383 addbool(m, "HAS_ALPN", 0);
Benjamin Petersoncca27322015-01-23 16:35:37 -05006384#endif
Christian Heimes698dde12018-02-27 11:54:43 +01006385
6386#if defined(SSL2_VERSION) && !defined(OPENSSL_NO_SSL2)
6387 addbool(m, "HAS_SSLv2", 1);
6388#else
6389 addbool(m, "HAS_SSLv2", 0);
6390#endif
6391
6392#if defined(SSL3_VERSION) && !defined(OPENSSL_NO_SSL3)
6393 addbool(m, "HAS_SSLv3", 1);
6394#else
6395 addbool(m, "HAS_SSLv3", 0);
6396#endif
6397
6398#if defined(TLS1_VERSION) && !defined(OPENSSL_NO_TLS1)
6399 addbool(m, "HAS_TLSv1", 1);
6400#else
6401 addbool(m, "HAS_TLSv1", 0);
6402#endif
6403
6404#if defined(TLS1_1_VERSION) && !defined(OPENSSL_NO_TLS1_1)
6405 addbool(m, "HAS_TLSv1_1", 1);
6406#else
6407 addbool(m, "HAS_TLSv1_1", 0);
6408#endif
6409
6410#if defined(TLS1_2_VERSION) && !defined(OPENSSL_NO_TLS1_2)
6411 addbool(m, "HAS_TLSv1_2", 1);
6412#else
6413 addbool(m, "HAS_TLSv1_2", 0);
6414#endif
Benjamin Petersoncca27322015-01-23 16:35:37 -05006415
Christian Heimescb5b68a2017-09-07 18:07:00 -07006416#if defined(TLS1_3_VERSION) && !defined(OPENSSL_NO_TLS1_3)
Christian Heimes698dde12018-02-27 11:54:43 +01006417 addbool(m, "HAS_TLSv1_3", 1);
Christian Heimescb5b68a2017-09-07 18:07:00 -07006418#else
Christian Heimes698dde12018-02-27 11:54:43 +01006419 addbool(m, "HAS_TLSv1_3", 0);
Christian Heimescb5b68a2017-09-07 18:07:00 -07006420#endif
Christian Heimescb5b68a2017-09-07 18:07:00 -07006421
Christian Heimes5c36da72020-11-20 09:40:12 +01006422 return 0;
6423}
6424
6425static int
6426sslmodule_legacy(PyObject *module)
6427{
6428#ifndef OPENSSL_VERSION_1_1
6429 /* Load all algorithms and initialize cpuid */
6430 OPENSSL_add_all_algorithms_noconf();
6431 /* Init OpenSSL */
6432 SSL_load_error_strings();
6433 SSL_library_init();
6434#endif
6435
6436#ifdef HAVE_OPENSSL_CRYPTO_LOCK
6437 /* note that this will start threading if not already started */
6438 if (!_setup_ssl_threads()) {
Pablo Galindo93a0ef72020-12-02 06:07:56 +00006439 return 0;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02006440 }
Christian Heimes5c36da72020-11-20 09:40:12 +01006441#elif OPENSSL_VERSION_1_1
6442 /* OpenSSL 1.1.0 builtin thread support is enabled */
6443 _ssl_locks_count++;
6444#endif
6445 return 0;
6446}
6447
6448PyDoc_STRVAR(module_doc,
6449"Implementation module for SSL socket operations. See the socket module\n\
6450for documentation.");
6451
6452
6453static struct PyModuleDef _sslmodule = {
6454 PyModuleDef_HEAD_INIT,
6455 "_ssl",
6456 module_doc,
6457 -1,
6458 PySSL_methods,
6459 NULL,
6460 NULL,
6461 NULL,
6462 NULL
6463};
6464
6465PyMODINIT_FUNC
6466PyInit__ssl(void)
6467{
6468 PyObject *m;
6469
6470 m = PyModule_Create(&_sslmodule);
6471 if (m == NULL)
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02006472 return NULL;
6473
Christian Heimes5c36da72020-11-20 09:40:12 +01006474 if (sslmodule_init_types(m) != 0)
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02006475 return NULL;
Christian Heimes5c36da72020-11-20 09:40:12 +01006476 if (sslmodule_init_exceptions(m) != 0)
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02006477 return NULL;
Christian Heimes5c36da72020-11-20 09:40:12 +01006478 if (sslmodule_init_socketapi(m) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006479 return NULL;
Christian Heimes5c36da72020-11-20 09:40:12 +01006480 if (sslmodule_init_errorcodes(m) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006481 return NULL;
Christian Heimes5c36da72020-11-20 09:40:12 +01006482 if (sslmodule_init_constants(m) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006483 return NULL;
Christian Heimes5c36da72020-11-20 09:40:12 +01006484 if (sslmodule_init_versioninfo(m) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006485 return NULL;
Christian Heimes5c36da72020-11-20 09:40:12 +01006486 if (sslmodule_legacy(m) != 0)
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02006487 return NULL;
6488
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006489 return m;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00006490}