blob: 9fbaecb80739f95bece3575a55f0b08bb48d0fe7 [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
Thomas Wouters1b7f8912007-09-19 03:06:30 +000021#include "pythread.h"
Christian Heimesf77b4b22013-08-21 13:26:05 +020022
Steve Dower68d663c2017-07-17 11:15:48 +020023/* Redefined below for Windows debug builds after important #includes */
24#define _PySSL_FIX_ERRNO
Christian Heimesf77b4b22013-08-21 13:26:05 +020025
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +020026#define PySSL_BEGIN_ALLOW_THREADS_S(save) \
27 do { if (_ssl_locks_count>0) { (save) = PyEval_SaveThread(); } } while (0)
28#define PySSL_END_ALLOW_THREADS_S(save) \
Steve Dower68d663c2017-07-17 11:15:48 +020029 do { if (_ssl_locks_count>0) { PyEval_RestoreThread(save); } _PySSL_FIX_ERRNO; } while (0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +000030#define PySSL_BEGIN_ALLOW_THREADS { \
Antoine Pitroucbb82eb2010-05-05 15:57:33 +000031 PyThreadState *_save = NULL; \
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +020032 PySSL_BEGIN_ALLOW_THREADS_S(_save);
33#define PySSL_BLOCK_THREADS PySSL_END_ALLOW_THREADS_S(_save);
34#define PySSL_UNBLOCK_THREADS PySSL_BEGIN_ALLOW_THREADS_S(_save);
35#define PySSL_END_ALLOW_THREADS PySSL_END_ALLOW_THREADS_S(_save); }
Thomas Wouters1b7f8912007-09-19 03:06:30 +000036
Antoine Pitrou2463e5f2013-03-28 22:24:43 +010037/* Include symbols from _socket module */
38#include "socketmodule.h"
39
40static PySocketModule_APIObject PySocketModule;
41
42#if defined(HAVE_POLL_H)
43#include <poll.h>
44#elif defined(HAVE_SYS_POLL_H)
45#include <sys/poll.h>
46#endif
47
Christian Heimes598894f2016-09-05 23:19:05 +020048/* Don't warn about deprecated functions */
49#ifdef __GNUC__
50#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
51#endif
52#ifdef __clang__
53#pragma clang diagnostic ignored "-Wdeprecated-declarations"
54#endif
55
Antoine Pitrou2463e5f2013-03-28 22:24:43 +010056/* Include OpenSSL header files */
57#include "openssl/rsa.h"
58#include "openssl/crypto.h"
59#include "openssl/x509.h"
60#include "openssl/x509v3.h"
61#include "openssl/pem.h"
62#include "openssl/ssl.h"
63#include "openssl/err.h"
64#include "openssl/rand.h"
Antoine Pitroub1fdf472014-10-05 20:41:53 +020065#include "openssl/bio.h"
Alexandru Ardeleanb3a271f2018-09-17 14:53:31 +030066#include "openssl/dh.h"
Antoine Pitrou2463e5f2013-03-28 22:24:43 +010067
Christian Heimesff5be6e2018-01-20 13:19:21 +010068#ifndef HAVE_X509_VERIFY_PARAM_SET1_HOST
Christian Heimes61d478c2018-01-27 15:51:38 +010069# ifdef LIBRESSL_VERSION_NUMBER
70# error "LibreSSL is missing X509_VERIFY_PARAM_set1_host(), see https://github.com/libressl-portable/portable/issues/381"
71# elif OPENSSL_VERSION_NUMBER > 0x1000200fL
Christian Heimesff5be6e2018-01-20 13:19:21 +010072# define HAVE_X509_VERIFY_PARAM_SET1_HOST
Christian Heimes61d478c2018-01-27 15:51:38 +010073# else
74# error "libssl is too old and does not support X509_VERIFY_PARAM_set1_host()"
Christian Heimesff5be6e2018-01-20 13:19:21 +010075# endif
76#endif
77
Christian Heimes387c7442020-05-15 22:36:51 +020078#ifndef OPENSSL_THREADS
79# error "OPENSSL_THREADS is not defined, Python requires thread-safe OpenSSL"
80#endif
81
Antoine Pitrou2463e5f2013-03-28 22:24:43 +010082/* SSL error object */
83static PyObject *PySSLErrorObject;
Christian Heimesb3ad0e52017-09-08 12:00:19 -070084static PyObject *PySSLCertVerificationErrorObject;
Antoine Pitrou2463e5f2013-03-28 22:24:43 +010085static PyObject *PySSLZeroReturnErrorObject;
86static PyObject *PySSLWantReadErrorObject;
87static PyObject *PySSLWantWriteErrorObject;
88static PyObject *PySSLSyscallErrorObject;
89static PyObject *PySSLEOFErrorObject;
90
91/* Error mappings */
92static PyObject *err_codes_to_names;
93static PyObject *err_names_to_codes;
94static PyObject *lib_codes_to_names;
95
96struct py_ssl_error_code {
97 const char *mnemonic;
98 int library, reason;
99};
100struct py_ssl_library_code {
101 const char *library;
102 int code;
103};
104
Steve Dower68d663c2017-07-17 11:15:48 +0200105#if defined(MS_WINDOWS) && defined(Py_DEBUG)
106/* Debug builds on Windows rely on getting errno directly from OpenSSL.
107 * However, because it uses a different CRT, we need to transfer the
108 * value of errno from OpenSSL into our debug CRT.
109 *
110 * Don't be fooled - this is horribly ugly code. The only reasonable
111 * alternative is to do both debug and release builds of OpenSSL, which
112 * requires much uglier code to transform their automatically generated
113 * makefile. This is the lesser of all the evils.
114 */
115
116static void _PySSLFixErrno(void) {
117 HMODULE ucrtbase = GetModuleHandleW(L"ucrtbase.dll");
118 if (!ucrtbase) {
119 /* If ucrtbase.dll is not loaded but the SSL DLLs are, we likely
120 * have a catastrophic failure, but this function is not the
121 * place to raise it. */
122 return;
123 }
124
125 typedef int *(__stdcall *errno_func)(void);
126 errno_func ssl_errno = (errno_func)GetProcAddress(ucrtbase, "_errno");
127 if (ssl_errno) {
128 errno = *ssl_errno();
129 *ssl_errno() = 0;
130 } else {
131 errno = ENOTRECOVERABLE;
132 }
133}
134
135#undef _PySSL_FIX_ERRNO
136#define _PySSL_FIX_ERRNO _PySSLFixErrno()
137#endif
138
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100139/* Include generated data (error codes) */
140#include "_ssl_data.h"
141
Christian Heimes598894f2016-09-05 23:19:05 +0200142#if (OPENSSL_VERSION_NUMBER >= 0x10100000L) && !defined(LIBRESSL_VERSION_NUMBER)
143# define OPENSSL_VERSION_1_1 1
Christian Heimes4ca07392018-03-24 15:41:37 +0100144# define PY_OPENSSL_1_1_API 1
145#endif
146
Miss Islington (bot)9c0ff172020-06-01 00:17:16 -0700147/* OpenSSL API compat */
148#ifdef OPENSSL_API_COMPAT
149#if OPENSSL_API_COMPAT >= 0x10100000L
150
151/* OpenSSL API 1.1.0+ does not include version methods */
152#ifndef OPENSSL_NO_TLS1_METHOD
153#define OPENSSL_NO_TLS1_METHOD 1
154#endif
155#ifndef OPENSSL_NO_TLS1_1_METHOD
156#define OPENSSL_NO_TLS1_1_METHOD 1
157#endif
158#ifndef OPENSSL_NO_TLS1_2_METHOD
159#define OPENSSL_NO_TLS1_2_METHOD 1
160#endif
161
162#endif /* >= 1.1.0 compcat */
163#endif /* OPENSSL_API_COMPAT */
164
Christian Heimes4ca07392018-03-24 15:41:37 +0100165/* LibreSSL 2.7.0 provides necessary OpenSSL 1.1.0 APIs */
166#if defined(LIBRESSL_VERSION_NUMBER) && LIBRESSL_VERSION_NUMBER >= 0x2070000fL
167# define PY_OPENSSL_1_1_API 1
Christian Heimes598894f2016-09-05 23:19:05 +0200168#endif
169
Christian Heimes470fba12013-11-28 15:12:15 +0100170/* SNI support (client- and server-side) appeared in OpenSSL 1.0.0 and 0.9.8f
Antoine Pitrou912fbff2013-03-30 16:29:32 +0100171 * This includes the SSL_set_SSL_CTX() function.
172 */
173#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
174# define HAVE_SNI 1
175#else
176# define HAVE_SNI 0
177#endif
178
Benjamin Petersond3308222015-09-27 00:09:02 -0700179#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
Christian Heimes29eab552018-02-25 12:31:33 +0100180# define HAVE_ALPN 1
181#else
182# define HAVE_ALPN 0
Benjamin Petersoncca27322015-01-23 16:35:37 -0500183#endif
184
Christian Heimes6cdb7952018-02-24 22:12:40 +0100185/* We cannot rely on OPENSSL_NO_NEXTPROTONEG because LibreSSL 2.6.1 dropped
186 * NPN support but did not set OPENSSL_NO_NEXTPROTONEG for compatibility
187 * reasons. The check for TLSEXT_TYPE_next_proto_neg works with
188 * OpenSSL 1.0.1+ and LibreSSL.
Christian Heimes29eab552018-02-25 12:31:33 +0100189 * OpenSSL 1.1.1-pre1 dropped NPN but still has TLSEXT_TYPE_next_proto_neg.
Christian Heimes6cdb7952018-02-24 22:12:40 +0100190 */
191#ifdef OPENSSL_NO_NEXTPROTONEG
Christian Heimes29eab552018-02-25 12:31:33 +0100192# define HAVE_NPN 0
193#elif (OPENSSL_VERSION_NUMBER >= 0x10101000L) && !defined(LIBRESSL_VERSION_NUMBER)
194# define HAVE_NPN 0
Christian Heimes6cdb7952018-02-24 22:12:40 +0100195#elif defined(TLSEXT_TYPE_next_proto_neg)
Christian Heimes29eab552018-02-25 12:31:33 +0100196# define HAVE_NPN 1
Christian Heimes6cdb7952018-02-24 22:12:40 +0100197#else
Christian Heimes29eab552018-02-25 12:31:33 +0100198# define HAVE_NPN 0
199#endif
Christian Heimes6cdb7952018-02-24 22:12:40 +0100200
Christian Heimesc7f70692019-05-31 11:44:05 +0200201#if (OPENSSL_VERSION_NUMBER >= 0x10101000L) && !defined(LIBRESSL_VERSION_NUMBER)
202#define HAVE_OPENSSL_KEYLOG 1
203#endif
204
Victor Stinner524714e2016-07-22 17:43:59 +0200205#ifndef INVALID_SOCKET /* MS defines this */
206#define INVALID_SOCKET (-1)
207#endif
208
Christian Heimes4ca07392018-03-24 15:41:37 +0100209/* OpenSSL 1.0.2 and LibreSSL needs extra code for locking */
210#ifndef OPENSSL_VERSION_1_1
211#define HAVE_OPENSSL_CRYPTO_LOCK
212#endif
213
214#if defined(OPENSSL_VERSION_1_1) && !defined(OPENSSL_NO_SSL2)
Christian Heimes598894f2016-09-05 23:19:05 +0200215#define OPENSSL_NO_SSL2
216#endif
Christian Heimes4ca07392018-03-24 15:41:37 +0100217
218#ifndef PY_OPENSSL_1_1_API
219/* OpenSSL 1.1 API shims for OpenSSL < 1.1.0 and LibreSSL < 2.7.0 */
Christian Heimes598894f2016-09-05 23:19:05 +0200220
221#define TLS_method SSLv23_method
Christian Heimes5fe668c2016-09-12 00:01:11 +0200222#define TLS_client_method SSLv23_client_method
223#define TLS_server_method SSLv23_server_method
Miss Islington (bot)9c0ff172020-06-01 00:17:16 -0700224#define ASN1_STRING_get0_data ASN1_STRING_data
225#define X509_get0_notBefore X509_get_notBefore
226#define X509_get0_notAfter X509_get_notAfter
227#define OpenSSL_version_num SSLeay
228#define OpenSSL_version SSLeay_version
229#define OPENSSL_VERSION SSLEAY_VERSION
Christian Heimes598894f2016-09-05 23:19:05 +0200230
231static int X509_NAME_ENTRY_set(const X509_NAME_ENTRY *ne)
232{
233 return ne->set;
234}
235
236#ifndef OPENSSL_NO_COMP
Christian Heimesa5d07652016-09-24 10:48:05 +0200237/* LCOV_EXCL_START */
Christian Heimes598894f2016-09-05 23:19:05 +0200238static int COMP_get_type(const COMP_METHOD *meth)
239{
240 return meth->type;
241}
Christian Heimes1a63b9f2016-09-24 12:07:21 +0200242/* LCOV_EXCL_STOP */
Christian Heimes598894f2016-09-05 23:19:05 +0200243#endif
244
245static pem_password_cb *SSL_CTX_get_default_passwd_cb(SSL_CTX *ctx)
246{
247 return ctx->default_passwd_callback;
248}
249
250static void *SSL_CTX_get_default_passwd_cb_userdata(SSL_CTX *ctx)
251{
252 return ctx->default_passwd_callback_userdata;
253}
254
255static int X509_OBJECT_get_type(X509_OBJECT *x)
256{
257 return x->type;
258}
259
260static X509 *X509_OBJECT_get0_X509(X509_OBJECT *x)
261{
262 return x->data.x509;
263}
264
265static int BIO_up_ref(BIO *b)
266{
267 CRYPTO_add(&b->references, 1, CRYPTO_LOCK_BIO);
268 return 1;
269}
270
271static STACK_OF(X509_OBJECT) *X509_STORE_get0_objects(X509_STORE *store) {
272 return store->objs;
273}
274
Christian Heimes99a65702016-09-10 23:44:53 +0200275static int
276SSL_SESSION_has_ticket(const SSL_SESSION *s)
277{
278 return (s->tlsext_ticklen > 0) ? 1 : 0;
279}
280
281static unsigned long
282SSL_SESSION_get_ticket_lifetime_hint(const SSL_SESSION *s)
283{
284 return s->tlsext_tick_lifetime_hint;
285}
286
Christian Heimes4ca07392018-03-24 15:41:37 +0100287#endif /* OpenSSL < 1.1.0 or LibreSSL < 2.7.0 */
Christian Heimes598894f2016-09-05 23:19:05 +0200288
Christian Heimes892d66e2018-01-29 14:10:18 +0100289/* Default cipher suites */
290#ifndef PY_SSL_DEFAULT_CIPHERS
291#define PY_SSL_DEFAULT_CIPHERS 1
292#endif
293
294#if PY_SSL_DEFAULT_CIPHERS == 0
295 #ifndef PY_SSL_DEFAULT_CIPHER_STRING
296 #error "Py_SSL_DEFAULT_CIPHERS 0 needs Py_SSL_DEFAULT_CIPHER_STRING"
297 #endif
298#elif PY_SSL_DEFAULT_CIPHERS == 1
Stéphane Wirtel07fbbfd2018-10-05 16:17:18 +0200299/* Python custom selection of sensible cipher suites
Christian Heimes892d66e2018-01-29 14:10:18 +0100300 * DEFAULT: OpenSSL's default cipher list. Since 1.0.2 the list is in sensible order.
301 * !aNULL:!eNULL: really no NULL ciphers
302 * !MD5:!3DES:!DES:!RC4:!IDEA:!SEED: no weak or broken algorithms on old OpenSSL versions.
303 * !aDSS: no authentication with discrete logarithm DSA algorithm
304 * !SRP:!PSK: no secure remote password or pre-shared key authentication
305 */
306 #define PY_SSL_DEFAULT_CIPHER_STRING "DEFAULT:!aNULL:!eNULL:!MD5:!3DES:!DES:!RC4:!IDEA:!SEED:!aDSS:!SRP:!PSK"
307#elif PY_SSL_DEFAULT_CIPHERS == 2
308/* Ignored in SSLContext constructor, only used to as _ssl.DEFAULT_CIPHER_STRING */
309 #define PY_SSL_DEFAULT_CIPHER_STRING SSL_DEFAULT_CIPHER_LIST
310#else
311 #error "Unsupported PY_SSL_DEFAULT_CIPHERS"
312#endif
313
Christian Heimes598894f2016-09-05 23:19:05 +0200314
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000315enum py_ssl_error {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000316 /* these mirror ssl.h */
317 PY_SSL_ERROR_NONE,
318 PY_SSL_ERROR_SSL,
319 PY_SSL_ERROR_WANT_READ,
320 PY_SSL_ERROR_WANT_WRITE,
321 PY_SSL_ERROR_WANT_X509_LOOKUP,
322 PY_SSL_ERROR_SYSCALL, /* look at error stack/return value/errno */
323 PY_SSL_ERROR_ZERO_RETURN,
324 PY_SSL_ERROR_WANT_CONNECT,
325 /* start of non ssl.h errorcodes */
326 PY_SSL_ERROR_EOF, /* special case of SSL_ERROR_SYSCALL */
327 PY_SSL_ERROR_NO_SOCKET, /* socket has been GC'd */
328 PY_SSL_ERROR_INVALID_ERROR_CODE
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000329};
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000330
Thomas Woutersed03b412007-08-28 21:37:11 +0000331enum py_ssl_server_or_client {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000332 PY_SSL_CLIENT,
333 PY_SSL_SERVER
Thomas Woutersed03b412007-08-28 21:37:11 +0000334};
335
336enum py_ssl_cert_requirements {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000337 PY_SSL_CERT_NONE,
338 PY_SSL_CERT_OPTIONAL,
339 PY_SSL_CERT_REQUIRED
Thomas Woutersed03b412007-08-28 21:37:11 +0000340};
341
342enum py_ssl_version {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000343 PY_SSL_VERSION_SSL2,
Victor Stinner3de49192011-05-09 00:42:58 +0200344 PY_SSL_VERSION_SSL3=1,
Christian Heimes5fe668c2016-09-12 00:01:11 +0200345 PY_SSL_VERSION_TLS, /* SSLv23 */
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100346 PY_SSL_VERSION_TLS1,
347 PY_SSL_VERSION_TLS1_1,
Christian Heimes5fe668c2016-09-12 00:01:11 +0200348 PY_SSL_VERSION_TLS1_2,
Christian Heimes5fe668c2016-09-12 00:01:11 +0200349 PY_SSL_VERSION_TLS_CLIENT=0x10,
350 PY_SSL_VERSION_TLS_SERVER,
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100351};
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200352
Christian Heimes698dde12018-02-27 11:54:43 +0100353enum py_proto_version {
354 PY_PROTO_MINIMUM_SUPPORTED = -2,
355 PY_PROTO_SSLv3 = SSL3_VERSION,
356 PY_PROTO_TLSv1 = TLS1_VERSION,
357 PY_PROTO_TLSv1_1 = TLS1_1_VERSION,
358 PY_PROTO_TLSv1_2 = TLS1_2_VERSION,
359#ifdef TLS1_3_VERSION
360 PY_PROTO_TLSv1_3 = TLS1_3_VERSION,
361#else
362 PY_PROTO_TLSv1_3 = 0x304,
363#endif
364 PY_PROTO_MAXIMUM_SUPPORTED = -1,
365
366/* OpenSSL has no dedicated API to set the minimum version to the maximum
367 * available version, and the other way around. We have to figure out the
368 * minimum and maximum available version on our own and hope for the best.
369 */
370#if defined(SSL3_VERSION) && !defined(OPENSSL_NO_SSL3)
371 PY_PROTO_MINIMUM_AVAILABLE = PY_PROTO_SSLv3,
372#elif defined(TLS1_VERSION) && !defined(OPENSSL_NO_TLS1)
373 PY_PROTO_MINIMUM_AVAILABLE = PY_PROTO_TLSv1,
374#elif defined(TLS1_1_VERSION) && !defined(OPENSSL_NO_TLS1_1)
375 PY_PROTO_MINIMUM_AVAILABLE = PY_PROTO_TLSv1_1,
376#elif defined(TLS1_2_VERSION) && !defined(OPENSSL_NO_TLS1_2)
377 PY_PROTO_MINIMUM_AVAILABLE = PY_PROTO_TLSv1_2,
378#elif defined(TLS1_3_VERSION) && !defined(OPENSSL_NO_TLS1_3)
379 PY_PROTO_MINIMUM_AVAILABLE = PY_PROTO_TLSv1_3,
380#else
381 #error "PY_PROTO_MINIMUM_AVAILABLE not found"
382#endif
383
384#if defined(TLS1_3_VERSION) && !defined(OPENSSL_NO_TLS1_3)
385 PY_PROTO_MAXIMUM_AVAILABLE = PY_PROTO_TLSv1_3,
386#elif defined(TLS1_2_VERSION) && !defined(OPENSSL_NO_TLS1_2)
387 PY_PROTO_MAXIMUM_AVAILABLE = PY_PROTO_TLSv1_2,
388#elif defined(TLS1_1_VERSION) && !defined(OPENSSL_NO_TLS1_1)
389 PY_PROTO_MAXIMUM_AVAILABLE = PY_PROTO_TLSv1_1,
390#elif defined(TLS1_VERSION) && !defined(OPENSSL_NO_TLS1)
391 PY_PROTO_MAXIMUM_AVAILABLE = PY_PROTO_TLSv1,
392#elif defined(SSL3_VERSION) && !defined(OPENSSL_NO_SSL3)
393 PY_PROTO_MAXIMUM_AVAILABLE = PY_PROTO_SSLv3,
394#else
395 #error "PY_PROTO_MAXIMUM_AVAILABLE not found"
396#endif
397};
398
399
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000400/* serves as a flag to see whether we've initialized the SSL thread support. */
401/* 0 means no, greater than 0 means yes */
402
403static unsigned int _ssl_locks_count = 0;
404
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000405/* SSL socket object */
406
407#define X509_NAME_MAXLEN 256
408
Gregory P. Smithbd4dacb2010-10-13 03:53:21 +0000409/* SSL_CTX_clear_options() and SSL_clear_options() were first added in
410 * OpenSSL 0.9.8m but do not appear in some 0.9.9-dev versions such the
411 * 0.9.9 from "May 2008" that NetBSD 5.0 uses. */
412#if OPENSSL_VERSION_NUMBER >= 0x009080dfL && OPENSSL_VERSION_NUMBER != 0x00909000L
Antoine Pitroub5218772010-05-21 09:56:06 +0000413# define HAVE_SSL_CTX_CLEAR_OPTIONS
414#else
415# undef HAVE_SSL_CTX_CLEAR_OPTIONS
416#endif
417
Antoine Pitroud6494802011-07-21 01:11:30 +0200418/* In case of 'tls-unique' it will be 12 bytes for TLS, 36 bytes for
419 * older SSL, but let's be safe */
420#define PySSL_CB_MAXLEN 128
421
Antoine Pitroua9bf2ac2012-02-17 18:47:54 +0100422
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000423typedef struct {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000424 PyObject_HEAD
Antoine Pitrou152efa22010-05-16 18:19:27 +0000425 SSL_CTX *ctx;
Christian Heimes29eab552018-02-25 12:31:33 +0100426#if HAVE_NPN
Benjamin Petersoncca27322015-01-23 16:35:37 -0500427 unsigned char *npn_protocols;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100428 int npn_protocols_len;
429#endif
Christian Heimes29eab552018-02-25 12:31:33 +0100430#if HAVE_ALPN
Benjamin Petersoncca27322015-01-23 16:35:37 -0500431 unsigned char *alpn_protocols;
Segev Finer5cff6372017-07-27 01:19:17 +0300432 unsigned int alpn_protocols_len;
Benjamin Petersoncca27322015-01-23 16:35:37 -0500433#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100434#ifndef OPENSSL_NO_TLSEXT
Christian Heimes11a14932018-02-24 02:35:08 +0100435 PyObject *set_sni_cb;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100436#endif
Christian Heimes1aa9a752013-12-02 02:41:19 +0100437 int check_hostname;
Christian Heimes61d478c2018-01-27 15:51:38 +0100438 /* OpenSSL has no API to get hostflags from X509_VERIFY_PARAM* struct.
439 * We have to maintain our own copy. OpenSSL's hostflags default to 0.
440 */
441 unsigned int hostflags;
Christian Heimes11a14932018-02-24 02:35:08 +0100442 int protocol;
Christian Heimes9fb051f2018-09-23 08:32:31 +0200443#ifdef TLS1_3_VERSION
444 int post_handshake_auth;
445#endif
Christian Heimesc7f70692019-05-31 11:44:05 +0200446 PyObject *msg_cb;
447#ifdef HAVE_OPENSSL_KEYLOG
448 PyObject *keylog_filename;
449 BIO *keylog_bio;
450#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +0000451} PySSLContext;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000452
Antoine Pitrou152efa22010-05-16 18:19:27 +0000453typedef struct {
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700454 int ssl; /* last seen error from SSL */
455 int c; /* last seen error from libc */
456#ifdef MS_WINDOWS
457 int ws; /* last seen error from winsock */
458#endif
459} _PySSLError;
460
461typedef struct {
Antoine Pitrou152efa22010-05-16 18:19:27 +0000462 PyObject_HEAD
463 PyObject *Socket; /* weakref to socket on which we're layered */
464 SSL *ssl;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100465 PySSLContext *ctx; /* weakref to SSL context */
Antoine Pitrou20b85552013-09-29 19:50:53 +0200466 char shutdown_seen_zero;
Antoine Pitroud6494802011-07-21 01:11:30 +0200467 enum py_ssl_server_or_client socket_type;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200468 PyObject *owner; /* Python level "owner" passed to servername callback */
469 PyObject *server_hostname;
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700470 _PySSLError err; /* last seen error from various sources */
Christian Heimesc7f70692019-05-31 11:44:05 +0200471 /* Some SSL callbacks don't have error reporting. Callback wrappers
472 * store exception information on the socket. The handshake, read, write,
473 * and shutdown methods check for chained exceptions.
474 */
475 PyObject *exc_type;
476 PyObject *exc_value;
477 PyObject *exc_tb;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000478} PySSLSocket;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000479
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200480typedef struct {
481 PyObject_HEAD
482 BIO *bio;
483 int eof_written;
484} PySSLMemoryBIO;
485
Christian Heimes99a65702016-09-10 23:44:53 +0200486typedef struct {
487 PyObject_HEAD
488 SSL_SESSION *session;
489 PySSLContext *ctx;
490} PySSLSession;
491
Antoine Pitrou152efa22010-05-16 18:19:27 +0000492static PyTypeObject PySSLContext_Type;
493static PyTypeObject PySSLSocket_Type;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200494static PyTypeObject PySSLMemoryBIO_Type;
Christian Heimes99a65702016-09-10 23:44:53 +0200495static PyTypeObject PySSLSession_Type;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000496
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700497static inline _PySSLError _PySSL_errno(int failed, const SSL *ssl, int retcode)
498{
499 _PySSLError err = { 0 };
500 if (failed) {
Steve Dowere6eb48c2017-09-08 15:16:15 -0700501#ifdef MS_WINDOWS
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700502 err.ws = WSAGetLastError();
503 _PySSL_FIX_ERRNO;
Steve Dowere6eb48c2017-09-08 15:16:15 -0700504#endif
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700505 err.c = errno;
506 err.ssl = SSL_get_error(ssl, retcode);
507 }
508 return err;
509}
Steve Dowere6eb48c2017-09-08 15:16:15 -0700510
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +0300511/*[clinic input]
512module _ssl
513class _ssl._SSLContext "PySSLContext *" "&PySSLContext_Type"
514class _ssl._SSLSocket "PySSLSocket *" "&PySSLSocket_Type"
515class _ssl.MemoryBIO "PySSLMemoryBIO *" "&PySSLMemoryBIO_Type"
Christian Heimes99a65702016-09-10 23:44:53 +0200516class _ssl.SSLSession "PySSLSession *" "&PySSLSession_Type"
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +0300517[clinic start generated code]*/
Christian Heimes99a65702016-09-10 23:44:53 +0200518/*[clinic end generated code: output=da39a3ee5e6b4b0d input=bdc67fafeeaa8109]*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +0300519
520#include "clinic/_ssl.c.h"
521
Victor Stinner14690702015-04-06 22:46:13 +0200522static int PySSL_select(PySocketSockObject *s, int writing, _PyTime_t timeout);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000523
Christian Heimes141c5e82018-02-24 21:10:57 +0100524static int PySSL_set_owner(PySSLSocket *, PyObject *, void *);
525static int PySSL_set_session(PySSLSocket *, PyObject *, void *);
Antoine Pitrou152efa22010-05-16 18:19:27 +0000526#define PySSLSocket_Check(v) (Py_TYPE(v) == &PySSLSocket_Type)
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200527#define PySSLMemoryBIO_Check(v) (Py_TYPE(v) == &PySSLMemoryBIO_Type)
Christian Heimes99a65702016-09-10 23:44:53 +0200528#define PySSLSession_Check(v) (Py_TYPE(v) == &PySSLSession_Type)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000529
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000530typedef enum {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000531 SOCKET_IS_NONBLOCKING,
532 SOCKET_IS_BLOCKING,
533 SOCKET_HAS_TIMED_OUT,
534 SOCKET_HAS_BEEN_CLOSED,
535 SOCKET_TOO_LARGE_FOR_SELECT,
536 SOCKET_OPERATION_OK
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000537} timeout_state;
538
Thomas Woutersed03b412007-08-28 21:37:11 +0000539/* Wrap error strings with filename and line # */
Thomas Woutersed03b412007-08-28 21:37:11 +0000540#define ERRSTR1(x,y,z) (x ":" y ": " z)
Victor Stinner45e8e2f2014-05-14 17:24:35 +0200541#define ERRSTR(x) ERRSTR1("_ssl.c", Py_STRINGIFY(__LINE__), x)
Thomas Woutersed03b412007-08-28 21:37:11 +0000542
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200543/* Get the socket from a PySSLSocket, if it has one */
544#define GET_SOCKET(obj) ((obj)->Socket ? \
545 (PySocketSockObject *) PyWeakref_GetObject((obj)->Socket) : NULL)
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200546
Victor Stinner14690702015-04-06 22:46:13 +0200547/* If sock is NULL, use a timeout of 0 second */
548#define GET_SOCKET_TIMEOUT(sock) \
549 ((sock != NULL) ? (sock)->sock_timeout : 0)
550
Christian Heimesc7f70692019-05-31 11:44:05 +0200551#include "_ssl/debughelpers.c"
552
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200553/*
554 * SSL errors.
555 */
556
557PyDoc_STRVAR(SSLError_doc,
558"An error occurred in the SSL implementation.");
559
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700560PyDoc_STRVAR(SSLCertVerificationError_doc,
561"A certificate could not be verified.");
562
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200563PyDoc_STRVAR(SSLZeroReturnError_doc,
564"SSL/TLS session closed cleanly.");
565
566PyDoc_STRVAR(SSLWantReadError_doc,
567"Non-blocking SSL socket needs to read more data\n"
568"before the requested operation can be completed.");
569
570PyDoc_STRVAR(SSLWantWriteError_doc,
571"Non-blocking SSL socket needs to write more data\n"
572"before the requested operation can be completed.");
573
574PyDoc_STRVAR(SSLSyscallError_doc,
575"System error when attempting SSL operation.");
576
577PyDoc_STRVAR(SSLEOFError_doc,
578"SSL/TLS connection terminated abruptly.");
579
580static PyObject *
581SSLError_str(PyOSErrorObject *self)
582{
583 if (self->strerror != NULL && PyUnicode_Check(self->strerror)) {
584 Py_INCREF(self->strerror);
585 return self->strerror;
586 }
587 else
588 return PyObject_Str(self->args);
589}
590
591static PyType_Slot sslerror_type_slots[] = {
592 {Py_tp_base, NULL}, /* Filled out in module init as it's not a constant */
Inada Naoki926b0cb2019-04-17 08:39:46 +0900593 {Py_tp_doc, (void*)SSLError_doc},
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200594 {Py_tp_str, SSLError_str},
595 {0, 0},
596};
597
598static PyType_Spec sslerror_type_spec = {
599 "ssl.SSLError",
600 sizeof(PyOSErrorObject),
601 0,
602 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
603 sslerror_type_slots
604};
605
606static void
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700607fill_and_set_sslerror(PySSLSocket *sslsock, PyObject *type, int ssl_errno,
608 const char *errstr, int lineno, unsigned long errcode)
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200609{
610 PyObject *err_value = NULL, *reason_obj = NULL, *lib_obj = NULL;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700611 PyObject *verify_obj = NULL, *verify_code_obj = NULL;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200612 PyObject *init_value, *msg, *key;
613 _Py_IDENTIFIER(reason);
614 _Py_IDENTIFIER(library);
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700615 _Py_IDENTIFIER(verify_message);
616 _Py_IDENTIFIER(verify_code);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200617
618 if (errcode != 0) {
619 int lib, reason;
620
621 lib = ERR_GET_LIB(errcode);
622 reason = ERR_GET_REASON(errcode);
623 key = Py_BuildValue("ii", lib, reason);
624 if (key == NULL)
625 goto fail;
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +0300626 reason_obj = PyDict_GetItemWithError(err_codes_to_names, key);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200627 Py_DECREF(key);
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +0300628 if (reason_obj == NULL && PyErr_Occurred()) {
629 goto fail;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200630 }
631 key = PyLong_FromLong(lib);
632 if (key == NULL)
633 goto fail;
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +0300634 lib_obj = PyDict_GetItemWithError(lib_codes_to_names, key);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200635 Py_DECREF(key);
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +0300636 if (lib_obj == NULL && PyErr_Occurred()) {
637 goto fail;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200638 }
639 if (errstr == NULL)
640 errstr = ERR_reason_error_string(errcode);
641 }
642 if (errstr == NULL)
643 errstr = "unknown error";
644
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700645 /* verify code for cert validation error */
646 if ((sslsock != NULL) && (type == PySSLCertVerificationErrorObject)) {
647 const char *verify_str = NULL;
648 long verify_code;
649
650 verify_code = SSL_get_verify_result(sslsock->ssl);
651 verify_code_obj = PyLong_FromLong(verify_code);
652 if (verify_code_obj == NULL) {
653 goto fail;
654 }
655
656 switch (verify_code) {
Christian Heimes09153602017-09-08 14:47:58 -0700657#ifdef X509_V_ERR_HOSTNAME_MISMATCH
658 /* OpenSSL >= 1.0.2, LibreSSL >= 2.5.3 */
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700659 case X509_V_ERR_HOSTNAME_MISMATCH:
660 verify_obj = PyUnicode_FromFormat(
661 "Hostname mismatch, certificate is not valid for '%S'.",
662 sslsock->server_hostname
663 );
664 break;
Christian Heimes09153602017-09-08 14:47:58 -0700665#endif
666#ifdef X509_V_ERR_IP_ADDRESS_MISMATCH
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700667 case X509_V_ERR_IP_ADDRESS_MISMATCH:
668 verify_obj = PyUnicode_FromFormat(
669 "IP address mismatch, certificate is not valid for '%S'.",
670 sslsock->server_hostname
671 );
672 break;
Christian Heimes09153602017-09-08 14:47:58 -0700673#endif
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700674 default:
675 verify_str = X509_verify_cert_error_string(verify_code);
676 if (verify_str != NULL) {
677 verify_obj = PyUnicode_FromString(verify_str);
678 } else {
679 verify_obj = Py_None;
680 Py_INCREF(verify_obj);
681 }
682 break;
683 }
684 if (verify_obj == NULL) {
685 goto fail;
686 }
687 }
688
689 if (verify_obj && reason_obj && lib_obj)
690 msg = PyUnicode_FromFormat("[%S: %S] %s: %S (_ssl.c:%d)",
691 lib_obj, reason_obj, errstr, verify_obj,
692 lineno);
693 else if (reason_obj && lib_obj)
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200694 msg = PyUnicode_FromFormat("[%S: %S] %s (_ssl.c:%d)",
695 lib_obj, reason_obj, errstr, lineno);
696 else if (lib_obj)
697 msg = PyUnicode_FromFormat("[%S] %s (_ssl.c:%d)",
698 lib_obj, errstr, lineno);
699 else
700 msg = PyUnicode_FromFormat("%s (_ssl.c:%d)", errstr, lineno);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200701 if (msg == NULL)
702 goto fail;
Victor Stinnerba9be472013-10-31 15:00:24 +0100703
Paul Monsonfb7e7502019-05-15 15:38:55 -0700704 init_value = Py_BuildValue("iN", ERR_GET_REASON(ssl_errno), msg);
Victor Stinnerba9be472013-10-31 15:00:24 +0100705 if (init_value == NULL)
706 goto fail;
707
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200708 err_value = PyObject_CallObject(type, init_value);
709 Py_DECREF(init_value);
710 if (err_value == NULL)
711 goto fail;
Victor Stinnerba9be472013-10-31 15:00:24 +0100712
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200713 if (reason_obj == NULL)
714 reason_obj = Py_None;
715 if (_PyObject_SetAttrId(err_value, &PyId_reason, reason_obj))
716 goto fail;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700717
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200718 if (lib_obj == NULL)
719 lib_obj = Py_None;
720 if (_PyObject_SetAttrId(err_value, &PyId_library, lib_obj))
721 goto fail;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700722
723 if ((sslsock != NULL) && (type == PySSLCertVerificationErrorObject)) {
724 /* Only set verify code / message for SSLCertVerificationError */
725 if (_PyObject_SetAttrId(err_value, &PyId_verify_code,
726 verify_code_obj))
727 goto fail;
728 if (_PyObject_SetAttrId(err_value, &PyId_verify_message, verify_obj))
729 goto fail;
730 }
731
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200732 PyErr_SetObject(type, err_value);
733fail:
734 Py_XDECREF(err_value);
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700735 Py_XDECREF(verify_code_obj);
736 Py_XDECREF(verify_obj);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200737}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000738
Christian Heimesc7f70692019-05-31 11:44:05 +0200739static int
740PySSL_ChainExceptions(PySSLSocket *sslsock) {
741 if (sslsock->exc_type == NULL)
742 return 0;
743
744 _PyErr_ChainExceptions(sslsock->exc_type, sslsock->exc_value, sslsock->exc_tb);
745 sslsock->exc_type = NULL;
746 sslsock->exc_value = NULL;
747 sslsock->exc_tb = NULL;
748 return -1;
749}
750
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000751static PyObject *
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700752PySSL_SetError(PySSLSocket *sslsock, int ret, const char *filename, int lineno)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000753{
Antoine Pitrou41032a62011-10-27 23:56:55 +0200754 PyObject *type = PySSLErrorObject;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200755 char *errstr = NULL;
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700756 _PySSLError err;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000757 enum py_ssl_error p = PY_SSL_ERROR_NONE;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200758 unsigned long e = 0;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000759
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000760 assert(ret <= 0);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200761 e = ERR_peek_last_error();
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000762
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700763 if (sslsock->ssl != NULL) {
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700764 err = sslsock->err;
Thomas Woutersed03b412007-08-28 21:37:11 +0000765
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700766 switch (err.ssl) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000767 case SSL_ERROR_ZERO_RETURN:
Antoine Pitrou41032a62011-10-27 23:56:55 +0200768 errstr = "TLS/SSL connection has been closed (EOF)";
769 type = PySSLZeroReturnErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000770 p = PY_SSL_ERROR_ZERO_RETURN;
771 break;
772 case SSL_ERROR_WANT_READ:
773 errstr = "The operation did not complete (read)";
Antoine Pitrou41032a62011-10-27 23:56:55 +0200774 type = PySSLWantReadErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000775 p = PY_SSL_ERROR_WANT_READ;
776 break;
777 case SSL_ERROR_WANT_WRITE:
778 p = PY_SSL_ERROR_WANT_WRITE;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200779 type = PySSLWantWriteErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000780 errstr = "The operation did not complete (write)";
781 break;
782 case SSL_ERROR_WANT_X509_LOOKUP:
783 p = PY_SSL_ERROR_WANT_X509_LOOKUP;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000784 errstr = "The operation did not complete (X509 lookup)";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000785 break;
786 case SSL_ERROR_WANT_CONNECT:
787 p = PY_SSL_ERROR_WANT_CONNECT;
788 errstr = "The operation did not complete (connect)";
789 break;
790 case SSL_ERROR_SYSCALL:
791 {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000792 if (e == 0) {
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700793 PySocketSockObject *s = GET_SOCKET(sslsock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000794 if (ret == 0 || (((PyObject *)s) == Py_None)) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000795 p = PY_SSL_ERROR_EOF;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200796 type = PySSLEOFErrorObject;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000797 errstr = "EOF occurred in violation of protocol";
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200798 } else if (s && ret == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000799 /* underlying BIO reported an I/O error */
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000800 ERR_clear_error();
Steve Dowere6eb48c2017-09-08 15:16:15 -0700801#ifdef MS_WINDOWS
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700802 if (err.ws) {
803 return PyErr_SetFromWindowsErr(err.ws);
804 }
Steve Dowere6eb48c2017-09-08 15:16:15 -0700805#endif
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700806 if (err.c) {
807 errno = err.c;
Steve Dowere6eb48c2017-09-08 15:16:15 -0700808 return PyErr_SetFromErrno(PyExc_OSError);
809 }
810 Py_INCREF(s);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200811 s->errorhandler();
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000812 Py_DECREF(s);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200813 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000814 } else { /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000815 p = PY_SSL_ERROR_SYSCALL;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200816 type = PySSLSyscallErrorObject;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000817 errstr = "Some I/O error occurred";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000818 }
819 } else {
820 p = PY_SSL_ERROR_SYSCALL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000821 }
822 break;
823 }
824 case SSL_ERROR_SSL:
825 {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000826 p = PY_SSL_ERROR_SSL;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700827 if (e == 0) {
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200828 /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000829 errstr = "A failure in the SSL library occurred";
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700830 }
831 if (ERR_GET_LIB(e) == ERR_LIB_SSL &&
832 ERR_GET_REASON(e) == SSL_R_CERTIFICATE_VERIFY_FAILED) {
833 type = PySSLCertVerificationErrorObject;
834 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000835 break;
836 }
837 default:
838 p = PY_SSL_ERROR_INVALID_ERROR_CODE;
839 errstr = "Invalid error code";
840 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000841 }
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700842 fill_and_set_sslerror(sslsock, type, p, errstr, lineno, e);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000843 ERR_clear_error();
Christian Heimesc7f70692019-05-31 11:44:05 +0200844 PySSL_ChainExceptions(sslsock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000845 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000846}
847
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000848static PyObject *
Serhiy Storchakaef1585e2015-12-25 20:01:53 +0200849_setSSLError (const char *errstr, int errcode, const char *filename, int lineno) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000850
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200851 if (errstr == NULL)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000852 errcode = ERR_peek_last_error();
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200853 else
854 errcode = 0;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700855 fill_and_set_sslerror(NULL, PySSLErrorObject, errcode, errstr, lineno, errcode);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000856 ERR_clear_error();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000857 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000858}
859
Christian Heimes61d478c2018-01-27 15:51:38 +0100860/*
861 * SSL objects
862 */
863
864static int
865_ssl_configure_hostname(PySSLSocket *self, const char* server_hostname)
866{
867 int retval = -1;
868 ASN1_OCTET_STRING *ip;
869 PyObject *hostname;
870 size_t len;
871
872 assert(server_hostname);
873
874 /* Disable OpenSSL's special mode with leading dot in hostname:
875 * When name starts with a dot (e.g ".example.com"), it will be
876 * matched by a certificate valid for any sub-domain of name.
877 */
878 len = strlen(server_hostname);
879 if (len == 0 || *server_hostname == '.') {
880 PyErr_SetString(
881 PyExc_ValueError,
882 "server_hostname cannot be an empty string or start with a "
883 "leading dot.");
884 return retval;
885 }
886
887 /* inet_pton is not available on all platforms. */
888 ip = a2i_IPADDRESS(server_hostname);
889 if (ip == NULL) {
890 ERR_clear_error();
891 }
892
Christian Heimes11a14932018-02-24 02:35:08 +0100893 hostname = PyUnicode_Decode(server_hostname, len, "ascii", "strict");
Christian Heimes61d478c2018-01-27 15:51:38 +0100894 if (hostname == NULL) {
895 goto error;
896 }
897 self->server_hostname = hostname;
898
899 /* Only send SNI extension for non-IP hostnames */
900 if (ip == NULL) {
901 if (!SSL_set_tlsext_host_name(self->ssl, server_hostname)) {
902 _setSSLError(NULL, 0, __FILE__, __LINE__);
903 }
904 }
905 if (self->ctx->check_hostname) {
906 X509_VERIFY_PARAM *param = SSL_get0_param(self->ssl);
907 if (ip == NULL) {
Christian Heimesd02ac252018-03-25 12:36:13 +0200908 if (!X509_VERIFY_PARAM_set1_host(param, server_hostname,
909 strlen(server_hostname))) {
Christian Heimes61d478c2018-01-27 15:51:38 +0100910 _setSSLError(NULL, 0, __FILE__, __LINE__);
911 goto error;
912 }
913 } else {
Miss Islington (bot)9c0ff172020-06-01 00:17:16 -0700914 if (!X509_VERIFY_PARAM_set1_ip(param, ASN1_STRING_get0_data(ip),
Christian Heimes61d478c2018-01-27 15:51:38 +0100915 ASN1_STRING_length(ip))) {
916 _setSSLError(NULL, 0, __FILE__, __LINE__);
917 goto error;
918 }
919 }
920 }
921 retval = 0;
922 error:
923 if (ip != NULL) {
924 ASN1_OCTET_STRING_free(ip);
925 }
926 return retval;
927}
928
Antoine Pitrou152efa22010-05-16 18:19:27 +0000929static PySSLSocket *
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100930newPySSLSocket(PySSLContext *sslctx, PySocketSockObject *sock,
Antoine Pitroud5323212010-10-22 18:19:07 +0000931 enum py_ssl_server_or_client socket_type,
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200932 char *server_hostname,
Christian Heimes141c5e82018-02-24 21:10:57 +0100933 PyObject *owner, PyObject *session,
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200934 PySSLMemoryBIO *inbio, PySSLMemoryBIO *outbio)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000935{
Antoine Pitrou152efa22010-05-16 18:19:27 +0000936 PySSLSocket *self;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100937 SSL_CTX *ctx = sslctx->ctx;
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700938 _PySSLError err = { 0 };
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000939
Antoine Pitrou152efa22010-05-16 18:19:27 +0000940 self = PyObject_New(PySSLSocket, &PySSLSocket_Type);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000941 if (self == NULL)
942 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000943
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000944 self->ssl = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000945 self->Socket = NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100946 self->ctx = sslctx;
Nathaniel J. Smith65ece7c2017-06-07 23:30:43 -0700947 Py_INCREF(sslctx);
Antoine Pitrou860aee72013-09-29 19:52:45 +0200948 self->shutdown_seen_zero = 0;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200949 self->owner = NULL;
Benjamin Peterson81b9ecd2016-08-15 21:55:37 -0700950 self->server_hostname = NULL;
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700951 self->err = err;
Christian Heimesc7f70692019-05-31 11:44:05 +0200952 self->exc_type = NULL;
953 self->exc_value = NULL;
954 self->exc_tb = NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200955
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000956 /* Make sure the SSL error state is initialized */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000957 ERR_clear_error();
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000958
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000959 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitrou152efa22010-05-16 18:19:27 +0000960 self->ssl = SSL_new(ctx);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000961 PySSL_END_ALLOW_THREADS
Zackery Spytz4c49da02018-12-07 03:11:30 -0700962 if (self->ssl == NULL) {
963 Py_DECREF(self);
964 _setSSLError(NULL, 0, __FILE__, __LINE__);
965 return NULL;
966 }
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200967 SSL_set_app_data(self->ssl, self);
968 if (sock) {
969 SSL_set_fd(self->ssl, Py_SAFE_DOWNCAST(sock->sock_fd, SOCKET_T, int));
970 } else {
971 /* BIOs are reference counted and SSL_set_bio borrows our reference.
972 * To prevent a double free in memory_bio_dealloc() we need to take an
973 * extra reference here. */
Christian Heimes598894f2016-09-05 23:19:05 +0200974 BIO_up_ref(inbio->bio);
975 BIO_up_ref(outbio->bio);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200976 SSL_set_bio(self->ssl, inbio->bio, outbio->bio);
977 }
Alex Gaynorf0422422018-05-14 11:51:45 -0400978 SSL_set_mode(self->ssl,
979 SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER | SSL_MODE_AUTO_RETRY);
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000980
Christian Heimesf22c4cf2019-07-01 09:25:48 +0200981#ifdef TLS1_3_VERSION
982 if (sslctx->post_handshake_auth == 1) {
983 if (socket_type == PY_SSL_SERVER) {
984 /* bpo-37428: OpenSSL does not ignore SSL_VERIFY_POST_HANDSHAKE.
985 * Set SSL_VERIFY_POST_HANDSHAKE flag only for server sockets and
986 * only in combination with SSL_VERIFY_PEER flag. */
987 int mode = SSL_get_verify_mode(self->ssl);
988 if (mode & SSL_VERIFY_PEER) {
989 int (*verify_cb)(int, X509_STORE_CTX *) = NULL;
990 verify_cb = SSL_get_verify_callback(self->ssl);
991 mode |= SSL_VERIFY_POST_HANDSHAKE;
992 SSL_set_verify(self->ssl, mode, verify_cb);
993 }
994 } else {
995 /* client socket */
996 SSL_set_post_handshake_auth(self->ssl, 1);
997 }
998 }
999#endif
1000
Christian Heimes61d478c2018-01-27 15:51:38 +01001001 if (server_hostname != NULL) {
1002 if (_ssl_configure_hostname(self, server_hostname) < 0) {
1003 Py_DECREF(self);
1004 return NULL;
1005 }
1006 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001007 /* If the socket is in non-blocking mode or timeout mode, set the BIO
1008 * to non-blocking mode (blocking is the default)
1009 */
Victor Stinnere2452312015-03-28 03:00:46 +01001010 if (sock && sock->sock_timeout >= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001011 BIO_set_nbio(SSL_get_rbio(self->ssl), 1);
1012 BIO_set_nbio(SSL_get_wbio(self->ssl), 1);
1013 }
Guido van Rossum4f707ac2003-01-31 18:13:18 +00001014
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001015 PySSL_BEGIN_ALLOW_THREADS
1016 if (socket_type == PY_SSL_CLIENT)
1017 SSL_set_connect_state(self->ssl);
1018 else
1019 SSL_set_accept_state(self->ssl);
1020 PySSL_END_ALLOW_THREADS
Martin v. Löwis09c35f72002-07-28 09:57:45 +00001021
Antoine Pitroud6494802011-07-21 01:11:30 +02001022 self->socket_type = socket_type;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001023 if (sock != NULL) {
1024 self->Socket = PyWeakref_NewRef((PyObject *) sock, NULL);
1025 if (self->Socket == NULL) {
1026 Py_DECREF(self);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001027 return NULL;
1028 }
Victor Stinnera9eb38f2013-10-31 16:35:38 +01001029 }
Christian Heimes141c5e82018-02-24 21:10:57 +01001030 if (owner && owner != Py_None) {
1031 if (PySSL_set_owner(self, owner, NULL) == -1) {
1032 Py_DECREF(self);
1033 return NULL;
1034 }
1035 }
1036 if (session && session != Py_None) {
1037 if (PySSL_set_session(self, session, NULL) == -1) {
1038 Py_DECREF(self);
1039 return NULL;
1040 }
1041 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001042 return self;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001043}
1044
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001045/* SSL object methods */
1046
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001047/*[clinic input]
1048_ssl._SSLSocket.do_handshake
1049[clinic start generated code]*/
1050
1051static PyObject *
1052_ssl__SSLSocket_do_handshake_impl(PySSLSocket *self)
1053/*[clinic end generated code: output=6c0898a8936548f6 input=d2d737de3df018c8]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001054{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001055 int ret;
Steve Dowerc6fd1c12018-09-17 11:34:47 -07001056 _PySSLError err;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001057 int sockstate, nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001058 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02001059 _PyTime_t timeout, deadline = 0;
1060 int has_timeout;
Antoine Pitroud3f8ab82010-04-24 21:26:44 +00001061
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001062 if (sock) {
1063 if (((PyObject*)sock) == Py_None) {
1064 _setSSLError("Underlying socket connection gone",
1065 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1066 return NULL;
1067 }
1068 Py_INCREF(sock);
1069
1070 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01001071 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001072 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1073 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001074 }
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001075
Victor Stinner14690702015-04-06 22:46:13 +02001076 timeout = GET_SOCKET_TIMEOUT(sock);
1077 has_timeout = (timeout > 0);
1078 if (has_timeout)
1079 deadline = _PyTime_GetMonotonicClock() + timeout;
1080
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001081 /* Actually negotiate SSL connection */
1082 /* XXX If SSL_do_handshake() returns 0, it's also a failure. */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001083 do {
Bill Janssen6e027db2007-11-15 22:23:56 +00001084 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001085 ret = SSL_do_handshake(self->ssl);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07001086 err = _PySSL_errno(ret < 1, self->ssl, ret);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001087 PySSL_END_ALLOW_THREADS
Steve Dowerc6fd1c12018-09-17 11:34:47 -07001088 self->err = err;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001089
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001090 if (PyErr_CheckSignals())
1091 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001092
Victor Stinner14690702015-04-06 22:46:13 +02001093 if (has_timeout)
1094 timeout = deadline - _PyTime_GetMonotonicClock();
1095
Steve Dowerc6fd1c12018-09-17 11:34:47 -07001096 if (err.ssl == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +02001097 sockstate = PySSL_select(sock, 0, timeout);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07001098 } else if (err.ssl == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +02001099 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001100 } else {
1101 sockstate = SOCKET_OPERATION_OK;
1102 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001103
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001104 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001105 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitrou525807b2010-05-12 14:05:24 +00001106 ERRSTR("The handshake operation timed out"));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001107 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001108 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1109 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +00001110 ERRSTR("Underlying socket has been closed."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001111 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001112 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1113 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +00001114 ERRSTR("Underlying socket too large for select()."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001115 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001116 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1117 break;
1118 }
Steve Dowerc6fd1c12018-09-17 11:34:47 -07001119 } while (err.ssl == SSL_ERROR_WANT_READ ||
1120 err.ssl == SSL_ERROR_WANT_WRITE);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001121 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001122 if (ret < 1)
1123 return PySSL_SetError(self, ret, __FILE__, __LINE__);
Christian Heimesc7f70692019-05-31 11:44:05 +02001124 if (PySSL_ChainExceptions(self) < 0)
1125 return NULL;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001126 Py_RETURN_NONE;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001127error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001128 Py_XDECREF(sock);
Christian Heimesc7f70692019-05-31 11:44:05 +02001129 PySSL_ChainExceptions(self);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001130 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001131}
1132
Thomas Woutersed03b412007-08-28 21:37:11 +00001133static PyObject *
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001134_asn1obj2py(const ASN1_OBJECT *name, int no_name)
1135{
1136 char buf[X509_NAME_MAXLEN];
1137 char *namebuf = buf;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001138 int buflen;
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001139 PyObject *name_obj = NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001140
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001141 buflen = OBJ_obj2txt(namebuf, X509_NAME_MAXLEN, name, no_name);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001142 if (buflen < 0) {
1143 _setSSLError(NULL, 0, __FILE__, __LINE__);
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001144 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001145 }
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001146 /* initial buffer is too small for oid + terminating null byte */
1147 if (buflen > X509_NAME_MAXLEN - 1) {
1148 /* make OBJ_obj2txt() calculate the required buflen */
1149 buflen = OBJ_obj2txt(NULL, 0, name, no_name);
1150 /* allocate len + 1 for terminating NULL byte */
1151 namebuf = PyMem_Malloc(buflen + 1);
1152 if (namebuf == NULL) {
1153 PyErr_NoMemory();
1154 return NULL;
1155 }
1156 buflen = OBJ_obj2txt(namebuf, buflen + 1, name, no_name);
1157 if (buflen < 0) {
1158 _setSSLError(NULL, 0, __FILE__, __LINE__);
1159 goto done;
1160 }
1161 }
1162 if (!buflen && no_name) {
1163 Py_INCREF(Py_None);
1164 name_obj = Py_None;
1165 }
1166 else {
1167 name_obj = PyUnicode_FromStringAndSize(namebuf, buflen);
1168 }
1169
1170 done:
1171 if (buf != namebuf) {
1172 PyMem_Free(namebuf);
1173 }
1174 return name_obj;
1175}
1176
1177static PyObject *
1178_create_tuple_for_attribute(ASN1_OBJECT *name, ASN1_STRING *value)
1179{
1180 Py_ssize_t buflen;
1181 unsigned char *valuebuf = NULL;
1182 PyObject *attr;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001183
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001184 buflen = ASN1_STRING_to_UTF8(&valuebuf, value);
1185 if (buflen < 0) {
1186 _setSSLError(NULL, 0, __FILE__, __LINE__);
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001187 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001188 }
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001189 attr = Py_BuildValue("Ns#", _asn1obj2py(name, 0), valuebuf, buflen);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001190 OPENSSL_free(valuebuf);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001191 return attr;
Thomas Woutersed03b412007-08-28 21:37:11 +00001192}
1193
1194static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001195_create_tuple_for_X509_NAME (X509_NAME *xname)
Thomas Woutersed03b412007-08-28 21:37:11 +00001196{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001197 PyObject *dn = NULL; /* tuple which represents the "distinguished name" */
1198 PyObject *rdn = NULL; /* tuple to hold a "relative distinguished name" */
1199 PyObject *rdnt;
1200 PyObject *attr = NULL; /* tuple to hold an attribute */
1201 int entry_count = X509_NAME_entry_count(xname);
1202 X509_NAME_ENTRY *entry;
1203 ASN1_OBJECT *name;
1204 ASN1_STRING *value;
1205 int index_counter;
1206 int rdn_level = -1;
1207 int retcode;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001208
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001209 dn = PyList_New(0);
1210 if (dn == NULL)
1211 return NULL;
1212 /* now create another tuple to hold the top-level RDN */
1213 rdn = PyList_New(0);
1214 if (rdn == NULL)
1215 goto fail0;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001216
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001217 for (index_counter = 0;
1218 index_counter < entry_count;
1219 index_counter++)
1220 {
1221 entry = X509_NAME_get_entry(xname, index_counter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001222
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001223 /* check to see if we've gotten to a new RDN */
1224 if (rdn_level >= 0) {
Christian Heimes598894f2016-09-05 23:19:05 +02001225 if (rdn_level != X509_NAME_ENTRY_set(entry)) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001226 /* yes, new RDN */
1227 /* add old RDN to DN */
1228 rdnt = PyList_AsTuple(rdn);
1229 Py_DECREF(rdn);
1230 if (rdnt == NULL)
1231 goto fail0;
1232 retcode = PyList_Append(dn, rdnt);
1233 Py_DECREF(rdnt);
1234 if (retcode < 0)
1235 goto fail0;
1236 /* create new RDN */
1237 rdn = PyList_New(0);
1238 if (rdn == NULL)
1239 goto fail0;
1240 }
1241 }
Christian Heimes598894f2016-09-05 23:19:05 +02001242 rdn_level = X509_NAME_ENTRY_set(entry);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001243
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001244 /* now add this attribute to the current RDN */
1245 name = X509_NAME_ENTRY_get_object(entry);
1246 value = X509_NAME_ENTRY_get_data(entry);
1247 attr = _create_tuple_for_attribute(name, value);
1248 /*
1249 fprintf(stderr, "RDN level %d, attribute %s: %s\n",
1250 entry->set,
1251 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 0)),
1252 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 1)));
1253 */
1254 if (attr == NULL)
1255 goto fail1;
1256 retcode = PyList_Append(rdn, attr);
1257 Py_DECREF(attr);
1258 if (retcode < 0)
1259 goto fail1;
1260 }
1261 /* now, there's typically a dangling RDN */
Antoine Pitrou2f5a1632012-02-15 22:25:27 +01001262 if (rdn != NULL) {
1263 if (PyList_GET_SIZE(rdn) > 0) {
1264 rdnt = PyList_AsTuple(rdn);
1265 Py_DECREF(rdn);
1266 if (rdnt == NULL)
1267 goto fail0;
1268 retcode = PyList_Append(dn, rdnt);
1269 Py_DECREF(rdnt);
1270 if (retcode < 0)
1271 goto fail0;
1272 }
1273 else {
1274 Py_DECREF(rdn);
1275 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001276 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001277
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001278 /* convert list to tuple */
1279 rdnt = PyList_AsTuple(dn);
1280 Py_DECREF(dn);
1281 if (rdnt == NULL)
1282 return NULL;
1283 return rdnt;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001284
1285 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001286 Py_XDECREF(rdn);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001287
1288 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001289 Py_XDECREF(dn);
1290 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001291}
1292
1293static PyObject *
1294_get_peer_alt_names (X509 *certificate) {
Guido van Rossumf06628b2007-11-21 20:01:53 +00001295
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001296 /* this code follows the procedure outlined in
1297 OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print()
1298 function to extract the STACK_OF(GENERAL_NAME),
1299 then iterates through the stack to add the
1300 names. */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001301
Alex Gaynorb87c0df2017-06-06 07:53:11 -04001302 int j;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001303 PyObject *peer_alt_names = Py_None;
Christian Heimes60bf2fc2013-09-05 16:04:35 +02001304 PyObject *v = NULL, *t;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001305 GENERAL_NAMES *names = NULL;
1306 GENERAL_NAME *name;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001307 BIO *biobuf = NULL;
1308 char buf[2048];
1309 char *vptr;
1310 int len;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001311
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001312 if (certificate == NULL)
1313 return peer_alt_names;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001314
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001315 /* get a memory buffer */
1316 biobuf = BIO_new(BIO_s_mem());
Zackery Spytz4c49da02018-12-07 03:11:30 -07001317 if (biobuf == NULL) {
1318 PyErr_SetString(PySSLErrorObject, "failed to allocate BIO");
1319 return NULL;
1320 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001321
Alex Gaynorb87c0df2017-06-06 07:53:11 -04001322 names = (GENERAL_NAMES *)X509_get_ext_d2i(
1323 certificate, NID_subject_alt_name, NULL, NULL);
1324 if (names != NULL) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001325 if (peer_alt_names == Py_None) {
1326 peer_alt_names = PyList_New(0);
1327 if (peer_alt_names == NULL)
1328 goto fail;
1329 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001330
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001331 for(j = 0; j < sk_GENERAL_NAME_num(names); j++) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001332 /* get a rendering of each name in the set of names */
Christian Heimes824f7f32013-08-17 00:54:47 +02001333 int gntype;
1334 ASN1_STRING *as = NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001335
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001336 name = sk_GENERAL_NAME_value(names, j);
Christian Heimes474afdd2013-08-17 17:18:56 +02001337 gntype = name->type;
Christian Heimes824f7f32013-08-17 00:54:47 +02001338 switch (gntype) {
1339 case GEN_DIRNAME:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001340 /* we special-case DirName as a tuple of
1341 tuples of attributes */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001342
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001343 t = PyTuple_New(2);
1344 if (t == NULL) {
1345 goto fail;
1346 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001347
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001348 v = PyUnicode_FromString("DirName");
1349 if (v == NULL) {
1350 Py_DECREF(t);
1351 goto fail;
1352 }
1353 PyTuple_SET_ITEM(t, 0, v);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001354
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001355 v = _create_tuple_for_X509_NAME (name->d.dirn);
1356 if (v == NULL) {
1357 Py_DECREF(t);
1358 goto fail;
1359 }
1360 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +02001361 break;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001362
Christian Heimes824f7f32013-08-17 00:54:47 +02001363 case GEN_EMAIL:
1364 case GEN_DNS:
1365 case GEN_URI:
1366 /* GENERAL_NAME_print() doesn't handle NULL bytes in ASN1_string
1367 correctly, CVE-2013-4238 */
1368 t = PyTuple_New(2);
1369 if (t == NULL)
1370 goto fail;
1371 switch (gntype) {
1372 case GEN_EMAIL:
1373 v = PyUnicode_FromString("email");
1374 as = name->d.rfc822Name;
1375 break;
1376 case GEN_DNS:
1377 v = PyUnicode_FromString("DNS");
1378 as = name->d.dNSName;
1379 break;
1380 case GEN_URI:
1381 v = PyUnicode_FromString("URI");
1382 as = name->d.uniformResourceIdentifier;
1383 break;
1384 }
1385 if (v == NULL) {
1386 Py_DECREF(t);
1387 goto fail;
1388 }
1389 PyTuple_SET_ITEM(t, 0, v);
Miss Islington (bot)9c0ff172020-06-01 00:17:16 -07001390 v = PyUnicode_FromStringAndSize((char *)ASN1_STRING_get0_data(as),
Christian Heimes824f7f32013-08-17 00:54:47 +02001391 ASN1_STRING_length(as));
1392 if (v == NULL) {
1393 Py_DECREF(t);
1394 goto fail;
1395 }
1396 PyTuple_SET_ITEM(t, 1, v);
1397 break;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001398
Christian Heimes1c03abd2016-09-06 23:25:35 +02001399 case GEN_RID:
1400 t = PyTuple_New(2);
1401 if (t == NULL)
1402 goto fail;
1403
1404 v = PyUnicode_FromString("Registered ID");
1405 if (v == NULL) {
1406 Py_DECREF(t);
1407 goto fail;
1408 }
1409 PyTuple_SET_ITEM(t, 0, v);
1410
1411 len = i2t_ASN1_OBJECT(buf, sizeof(buf)-1, name->d.rid);
1412 if (len < 0) {
1413 Py_DECREF(t);
1414 _setSSLError(NULL, 0, __FILE__, __LINE__);
1415 goto fail;
1416 } else if (len >= (int)sizeof(buf)) {
1417 v = PyUnicode_FromString("<INVALID>");
1418 } else {
1419 v = PyUnicode_FromStringAndSize(buf, len);
1420 }
1421 if (v == NULL) {
1422 Py_DECREF(t);
1423 goto fail;
1424 }
1425 PyTuple_SET_ITEM(t, 1, v);
1426 break;
1427
Miss Islington (bot)9d3cacd2019-12-07 09:20:27 -08001428 case GEN_IPADD:
1429 /* OpenSSL < 3.0.0 adds a trailing \n to IPv6. 3.0.0 removed
1430 * the trailing newline. Remove it in all versions
1431 */
1432 t = PyTuple_New(2);
1433 if (t == NULL)
1434 goto fail;
1435
1436 v = PyUnicode_FromString("IP Address");
1437 if (v == NULL) {
1438 Py_DECREF(t);
1439 goto fail;
1440 }
1441 PyTuple_SET_ITEM(t, 0, v);
1442
1443 if (name->d.ip->length == 4) {
1444 unsigned char *p = name->d.ip->data;
1445 v = PyUnicode_FromFormat(
1446 "%d.%d.%d.%d",
1447 p[0], p[1], p[2], p[3]
1448 );
1449 } else if (name->d.ip->length == 16) {
1450 /* PyUnicode_FromFormat() does not support %X */
1451 unsigned char *p = name->d.ip->data;
1452 len = sprintf(
1453 buf,
1454 "%X:%X:%X:%X:%X:%X:%X:%X",
1455 p[0] << 8 | p[1],
1456 p[2] << 8 | p[3],
1457 p[4] << 8 | p[5],
1458 p[6] << 8 | p[7],
1459 p[8] << 8 | p[9],
1460 p[10] << 8 | p[11],
1461 p[12] << 8 | p[13],
1462 p[14] << 8 | p[15]
1463 );
1464 v = PyUnicode_FromStringAndSize(buf, len);
1465 } else {
1466 v = PyUnicode_FromString("<invalid>");
1467 }
1468
1469 if (v == NULL) {
1470 Py_DECREF(t);
1471 goto fail;
1472 }
1473 PyTuple_SET_ITEM(t, 1, v);
1474 break;
1475
Christian Heimes824f7f32013-08-17 00:54:47 +02001476 default:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001477 /* for everything else, we use the OpenSSL print form */
Christian Heimes824f7f32013-08-17 00:54:47 +02001478 switch (gntype) {
1479 /* check for new general name type */
1480 case GEN_OTHERNAME:
1481 case GEN_X400:
1482 case GEN_EDIPARTY:
Christian Heimes824f7f32013-08-17 00:54:47 +02001483 case GEN_RID:
1484 break;
1485 default:
1486 if (PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
1487 "Unknown general name type %d",
1488 gntype) == -1) {
1489 goto fail;
1490 }
1491 break;
1492 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001493 (void) BIO_reset(biobuf);
1494 GENERAL_NAME_print(biobuf, name);
1495 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1496 if (len < 0) {
1497 _setSSLError(NULL, 0, __FILE__, __LINE__);
1498 goto fail;
1499 }
1500 vptr = strchr(buf, ':');
Christian Heimes1c03abd2016-09-06 23:25:35 +02001501 if (vptr == NULL) {
1502 PyErr_Format(PyExc_ValueError,
1503 "Invalid value %.200s",
1504 buf);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001505 goto fail;
Christian Heimes1c03abd2016-09-06 23:25:35 +02001506 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001507 t = PyTuple_New(2);
1508 if (t == NULL)
1509 goto fail;
1510 v = PyUnicode_FromStringAndSize(buf, (vptr - buf));
1511 if (v == NULL) {
1512 Py_DECREF(t);
1513 goto fail;
1514 }
1515 PyTuple_SET_ITEM(t, 0, v);
1516 v = PyUnicode_FromStringAndSize((vptr + 1),
1517 (len - (vptr - buf + 1)));
1518 if (v == NULL) {
1519 Py_DECREF(t);
1520 goto fail;
1521 }
1522 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +02001523 break;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001524 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001525
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001526 /* and add that rendering to the list */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001527
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001528 if (PyList_Append(peer_alt_names, t) < 0) {
1529 Py_DECREF(t);
1530 goto fail;
1531 }
1532 Py_DECREF(t);
1533 }
Antoine Pitrou116d6b92011-11-23 01:39:19 +01001534 sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001535 }
1536 BIO_free(biobuf);
1537 if (peer_alt_names != Py_None) {
1538 v = PyList_AsTuple(peer_alt_names);
1539 Py_DECREF(peer_alt_names);
1540 return v;
1541 } else {
1542 return peer_alt_names;
1543 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001544
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001545
1546 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001547 if (biobuf != NULL)
1548 BIO_free(biobuf);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001549
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001550 if (peer_alt_names != Py_None) {
1551 Py_XDECREF(peer_alt_names);
1552 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001553
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001554 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001555}
1556
1557static PyObject *
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001558_get_aia_uri(X509 *certificate, int nid) {
1559 PyObject *lst = NULL, *ostr = NULL;
1560 int i, result;
1561 AUTHORITY_INFO_ACCESS *info;
1562
1563 info = X509_get_ext_d2i(certificate, NID_info_access, NULL, NULL);
Benjamin Petersonf0c90382015-11-14 15:12:18 -08001564 if (info == NULL)
1565 return Py_None;
1566 if (sk_ACCESS_DESCRIPTION_num(info) == 0) {
1567 AUTHORITY_INFO_ACCESS_free(info);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001568 return Py_None;
1569 }
1570
1571 if ((lst = PyList_New(0)) == NULL) {
1572 goto fail;
1573 }
1574
1575 for (i = 0; i < sk_ACCESS_DESCRIPTION_num(info); i++) {
1576 ACCESS_DESCRIPTION *ad = sk_ACCESS_DESCRIPTION_value(info, i);
1577 ASN1_IA5STRING *uri;
1578
1579 if ((OBJ_obj2nid(ad->method) != nid) ||
1580 (ad->location->type != GEN_URI)) {
1581 continue;
1582 }
1583 uri = ad->location->d.uniformResourceIdentifier;
1584 ostr = PyUnicode_FromStringAndSize((char *)uri->data,
1585 uri->length);
1586 if (ostr == NULL) {
1587 goto fail;
1588 }
1589 result = PyList_Append(lst, ostr);
1590 Py_DECREF(ostr);
1591 if (result < 0) {
1592 goto fail;
1593 }
1594 }
1595 AUTHORITY_INFO_ACCESS_free(info);
1596
1597 /* convert to tuple or None */
1598 if (PyList_Size(lst) == 0) {
1599 Py_DECREF(lst);
1600 return Py_None;
1601 } else {
1602 PyObject *tup;
1603 tup = PyList_AsTuple(lst);
1604 Py_DECREF(lst);
1605 return tup;
1606 }
1607
1608 fail:
1609 AUTHORITY_INFO_ACCESS_free(info);
Christian Heimes18fc7be2013-11-21 23:57:49 +01001610 Py_XDECREF(lst);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001611 return NULL;
1612}
1613
1614static PyObject *
1615_get_crl_dp(X509 *certificate) {
1616 STACK_OF(DIST_POINT) *dps;
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001617 int i, j;
1618 PyObject *lst, *res = NULL;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001619
Christian Heimes598894f2016-09-05 23:19:05 +02001620 dps = X509_get_ext_d2i(certificate, NID_crl_distribution_points, NULL, NULL);
Christian Heimes949ec142013-11-21 16:26:51 +01001621
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001622 if (dps == NULL)
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001623 return Py_None;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001624
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001625 lst = PyList_New(0);
1626 if (lst == NULL)
1627 goto done;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001628
1629 for (i=0; i < sk_DIST_POINT_num(dps); i++) {
1630 DIST_POINT *dp;
1631 STACK_OF(GENERAL_NAME) *gns;
1632
1633 dp = sk_DIST_POINT_value(dps, i);
Christian Heimesa37f5242019-01-15 23:47:42 +01001634 if (dp->distpoint == NULL) {
1635 /* Ignore empty DP value, CVE-2019-5010 */
1636 continue;
1637 }
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001638 gns = dp->distpoint->name.fullname;
1639
1640 for (j=0; j < sk_GENERAL_NAME_num(gns); j++) {
1641 GENERAL_NAME *gn;
1642 ASN1_IA5STRING *uri;
1643 PyObject *ouri;
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001644 int err;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001645
1646 gn = sk_GENERAL_NAME_value(gns, j);
1647 if (gn->type != GEN_URI) {
1648 continue;
1649 }
1650 uri = gn->d.uniformResourceIdentifier;
1651 ouri = PyUnicode_FromStringAndSize((char *)uri->data,
1652 uri->length);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001653 if (ouri == NULL)
1654 goto done;
1655
1656 err = PyList_Append(lst, ouri);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001657 Py_DECREF(ouri);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001658 if (err < 0)
1659 goto done;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001660 }
1661 }
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001662
1663 /* Convert to tuple. */
1664 res = (PyList_GET_SIZE(lst) > 0) ? PyList_AsTuple(lst) : Py_None;
1665
1666 done:
1667 Py_XDECREF(lst);
Olivier Vielpeau2849cc32017-04-14 21:06:07 -04001668 CRL_DIST_POINTS_free(dps);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001669 return res;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001670}
1671
1672static PyObject *
Antoine Pitroufb046912010-11-09 20:21:19 +00001673_decode_certificate(X509 *certificate) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001674
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001675 PyObject *retval = NULL;
1676 BIO *biobuf = NULL;
1677 PyObject *peer;
1678 PyObject *peer_alt_names = NULL;
1679 PyObject *issuer;
1680 PyObject *version;
1681 PyObject *sn_obj;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001682 PyObject *obj;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001683 ASN1_INTEGER *serialNumber;
1684 char buf[2048];
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001685 int len, result;
Miss Islington (bot)9c0ff172020-06-01 00:17:16 -07001686 const ASN1_TIME *notBefore, *notAfter;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001687 PyObject *pnotBefore, *pnotAfter;
Thomas Woutersed03b412007-08-28 21:37:11 +00001688
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001689 retval = PyDict_New();
1690 if (retval == NULL)
1691 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001692
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001693 peer = _create_tuple_for_X509_NAME(
1694 X509_get_subject_name(certificate));
1695 if (peer == NULL)
1696 goto fail0;
1697 if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) {
1698 Py_DECREF(peer);
1699 goto fail0;
1700 }
1701 Py_DECREF(peer);
Thomas Woutersed03b412007-08-28 21:37:11 +00001702
Antoine Pitroufb046912010-11-09 20:21:19 +00001703 issuer = _create_tuple_for_X509_NAME(
1704 X509_get_issuer_name(certificate));
1705 if (issuer == NULL)
1706 goto fail0;
1707 if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001708 Py_DECREF(issuer);
Antoine Pitroufb046912010-11-09 20:21:19 +00001709 goto fail0;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001710 }
Antoine Pitroufb046912010-11-09 20:21:19 +00001711 Py_DECREF(issuer);
1712
1713 version = PyLong_FromLong(X509_get_version(certificate) + 1);
Christian Heimes5962bef2013-07-26 15:51:18 +02001714 if (version == NULL)
1715 goto fail0;
Antoine Pitroufb046912010-11-09 20:21:19 +00001716 if (PyDict_SetItemString(retval, "version", version) < 0) {
1717 Py_DECREF(version);
1718 goto fail0;
1719 }
1720 Py_DECREF(version);
Guido van Rossumf06628b2007-11-21 20:01:53 +00001721
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001722 /* get a memory buffer */
1723 biobuf = BIO_new(BIO_s_mem());
Zackery Spytz4c49da02018-12-07 03:11:30 -07001724 if (biobuf == NULL) {
1725 PyErr_SetString(PySSLErrorObject, "failed to allocate BIO");
1726 goto fail0;
1727 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001728
Antoine Pitroufb046912010-11-09 20:21:19 +00001729 (void) BIO_reset(biobuf);
1730 serialNumber = X509_get_serialNumber(certificate);
1731 /* should not exceed 20 octets, 160 bits, so buf is big enough */
1732 i2a_ASN1_INTEGER(biobuf, serialNumber);
1733 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1734 if (len < 0) {
1735 _setSSLError(NULL, 0, __FILE__, __LINE__);
1736 goto fail1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001737 }
Antoine Pitroufb046912010-11-09 20:21:19 +00001738 sn_obj = PyUnicode_FromStringAndSize(buf, len);
1739 if (sn_obj == NULL)
1740 goto fail1;
1741 if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) {
1742 Py_DECREF(sn_obj);
1743 goto fail1;
1744 }
1745 Py_DECREF(sn_obj);
1746
1747 (void) BIO_reset(biobuf);
Miss Islington (bot)9c0ff172020-06-01 00:17:16 -07001748 notBefore = X509_get0_notBefore(certificate);
Antoine Pitroufb046912010-11-09 20:21:19 +00001749 ASN1_TIME_print(biobuf, notBefore);
1750 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1751 if (len < 0) {
1752 _setSSLError(NULL, 0, __FILE__, __LINE__);
1753 goto fail1;
1754 }
1755 pnotBefore = PyUnicode_FromStringAndSize(buf, len);
1756 if (pnotBefore == NULL)
1757 goto fail1;
1758 if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) {
1759 Py_DECREF(pnotBefore);
1760 goto fail1;
1761 }
1762 Py_DECREF(pnotBefore);
Thomas Woutersed03b412007-08-28 21:37:11 +00001763
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001764 (void) BIO_reset(biobuf);
Miss Islington (bot)9c0ff172020-06-01 00:17:16 -07001765 notAfter = X509_get0_notAfter(certificate);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001766 ASN1_TIME_print(biobuf, notAfter);
1767 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1768 if (len < 0) {
1769 _setSSLError(NULL, 0, __FILE__, __LINE__);
1770 goto fail1;
1771 }
1772 pnotAfter = PyUnicode_FromStringAndSize(buf, len);
1773 if (pnotAfter == NULL)
1774 goto fail1;
1775 if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) {
1776 Py_DECREF(pnotAfter);
1777 goto fail1;
1778 }
1779 Py_DECREF(pnotAfter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001780
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001781 /* Now look for subjectAltName */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001782
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001783 peer_alt_names = _get_peer_alt_names(certificate);
1784 if (peer_alt_names == NULL)
1785 goto fail1;
1786 else if (peer_alt_names != Py_None) {
1787 if (PyDict_SetItemString(retval, "subjectAltName",
1788 peer_alt_names) < 0) {
1789 Py_DECREF(peer_alt_names);
1790 goto fail1;
1791 }
1792 Py_DECREF(peer_alt_names);
1793 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001794
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001795 /* Authority Information Access: OCSP URIs */
1796 obj = _get_aia_uri(certificate, NID_ad_OCSP);
1797 if (obj == NULL) {
1798 goto fail1;
1799 } else if (obj != Py_None) {
1800 result = PyDict_SetItemString(retval, "OCSP", obj);
1801 Py_DECREF(obj);
1802 if (result < 0) {
1803 goto fail1;
1804 }
1805 }
1806
1807 obj = _get_aia_uri(certificate, NID_ad_ca_issuers);
1808 if (obj == NULL) {
1809 goto fail1;
1810 } else if (obj != Py_None) {
1811 result = PyDict_SetItemString(retval, "caIssuers", obj);
1812 Py_DECREF(obj);
1813 if (result < 0) {
1814 goto fail1;
1815 }
1816 }
1817
1818 /* CDP (CRL distribution points) */
1819 obj = _get_crl_dp(certificate);
1820 if (obj == NULL) {
1821 goto fail1;
1822 } else if (obj != Py_None) {
1823 result = PyDict_SetItemString(retval, "crlDistributionPoints", obj);
1824 Py_DECREF(obj);
1825 if (result < 0) {
1826 goto fail1;
1827 }
1828 }
1829
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001830 BIO_free(biobuf);
1831 return retval;
Thomas Woutersed03b412007-08-28 21:37:11 +00001832
1833 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001834 if (biobuf != NULL)
1835 BIO_free(biobuf);
Thomas Woutersed03b412007-08-28 21:37:11 +00001836 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001837 Py_XDECREF(retval);
1838 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001839}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001840
Christian Heimes9a5395a2013-06-17 15:44:12 +02001841static PyObject *
1842_certificate_to_der(X509 *certificate)
1843{
1844 unsigned char *bytes_buf = NULL;
1845 int len;
1846 PyObject *retval;
1847
1848 bytes_buf = NULL;
1849 len = i2d_X509(certificate, &bytes_buf);
1850 if (len < 0) {
1851 _setSSLError(NULL, 0, __FILE__, __LINE__);
1852 return NULL;
1853 }
1854 /* this is actually an immutable bytes sequence */
1855 retval = PyBytes_FromStringAndSize((const char *) bytes_buf, len);
1856 OPENSSL_free(bytes_buf);
1857 return retval;
1858}
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001859
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001860/*[clinic input]
1861_ssl._test_decode_cert
1862 path: object(converter="PyUnicode_FSConverter")
1863 /
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001864
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001865[clinic start generated code]*/
1866
1867static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001868_ssl__test_decode_cert_impl(PyObject *module, PyObject *path)
1869/*[clinic end generated code: output=96becb9abb23c091 input=cdeaaf02d4346628]*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001870{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001871 PyObject *retval = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001872 X509 *x=NULL;
1873 BIO *cert;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001874
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001875 if ((cert=BIO_new(BIO_s_file())) == NULL) {
1876 PyErr_SetString(PySSLErrorObject,
1877 "Can't malloc memory to read file");
1878 goto fail0;
1879 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001880
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001881 if (BIO_read_filename(cert, PyBytes_AsString(path)) <= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001882 PyErr_SetString(PySSLErrorObject,
1883 "Can't open file");
1884 goto fail0;
1885 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001886
Miss Islington (bot)f7812832019-08-15 05:52:51 -07001887 x = PEM_read_bio_X509(cert, NULL, NULL, NULL);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001888 if (x == NULL) {
1889 PyErr_SetString(PySSLErrorObject,
1890 "Error decoding PEM-encoded file");
1891 goto fail0;
1892 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001893
Antoine Pitroufb046912010-11-09 20:21:19 +00001894 retval = _decode_certificate(x);
Mark Dickinsonee55df52010-08-03 18:31:54 +00001895 X509_free(x);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001896
1897 fail0:
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001898 Py_DECREF(path);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001899 if (cert != NULL) BIO_free(cert);
1900 return retval;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001901}
1902
1903
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001904/*[clinic input]
Christian Heimes141c5e82018-02-24 21:10:57 +01001905_ssl._SSLSocket.getpeercert
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001906 der as binary_mode: bool = False
1907 /
1908
1909Returns the certificate for the peer.
1910
1911If no certificate was provided, returns None. If a certificate was
1912provided, but not validated, returns an empty dictionary. Otherwise
1913returns a dict containing information about the peer certificate.
1914
1915If the optional argument is True, returns a DER-encoded copy of the
1916peer certificate, or None if no certificate was provided. This will
1917return the certificate even if it wasn't validated.
1918[clinic start generated code]*/
1919
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001920static PyObject *
Christian Heimes141c5e82018-02-24 21:10:57 +01001921_ssl__SSLSocket_getpeercert_impl(PySSLSocket *self, int binary_mode)
1922/*[clinic end generated code: output=1f0ab66dfb693c88 input=c0fbe802e57629b7]*/
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001923{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001924 int verification;
Christian Heimes66dc33b2017-05-23 16:02:02 -07001925 X509 *peer_cert;
1926 PyObject *result;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001927
Christian Heimes66dc33b2017-05-23 16:02:02 -07001928 if (!SSL_is_init_finished(self->ssl)) {
Antoine Pitrou20b85552013-09-29 19:50:53 +02001929 PyErr_SetString(PyExc_ValueError,
1930 "handshake not done yet");
1931 return NULL;
1932 }
Christian Heimes66dc33b2017-05-23 16:02:02 -07001933 peer_cert = SSL_get_peer_certificate(self->ssl);
1934 if (peer_cert == NULL)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001935 Py_RETURN_NONE;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001936
Antoine Pitrou721738f2012-08-15 23:20:39 +02001937 if (binary_mode) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001938 /* return cert in DER-encoded format */
Christian Heimes66dc33b2017-05-23 16:02:02 -07001939 result = _certificate_to_der(peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001940 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00001941 verification = SSL_CTX_get_verify_mode(SSL_get_SSL_CTX(self->ssl));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001942 if ((verification & SSL_VERIFY_PEER) == 0)
Christian Heimes66dc33b2017-05-23 16:02:02 -07001943 result = PyDict_New();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001944 else
Christian Heimes66dc33b2017-05-23 16:02:02 -07001945 result = _decode_certificate(peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001946 }
Christian Heimes66dc33b2017-05-23 16:02:02 -07001947 X509_free(peer_cert);
1948 return result;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001949}
1950
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001951static PyObject *
1952cipher_to_tuple(const SSL_CIPHER *cipher)
1953{
1954 const char *cipher_name, *cipher_protocol;
1955 PyObject *v, *retval = PyTuple_New(3);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001956 if (retval == NULL)
1957 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001958
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001959 cipher_name = SSL_CIPHER_get_name(cipher);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001960 if (cipher_name == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001961 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001962 PyTuple_SET_ITEM(retval, 0, Py_None);
1963 } else {
1964 v = PyUnicode_FromString(cipher_name);
1965 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001966 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001967 PyTuple_SET_ITEM(retval, 0, v);
1968 }
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001969
1970 cipher_protocol = SSL_CIPHER_get_version(cipher);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001971 if (cipher_protocol == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001972 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001973 PyTuple_SET_ITEM(retval, 1, Py_None);
1974 } else {
1975 v = PyUnicode_FromString(cipher_protocol);
1976 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001977 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001978 PyTuple_SET_ITEM(retval, 1, v);
1979 }
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001980
1981 v = PyLong_FromLong(SSL_CIPHER_get_bits(cipher, NULL));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001982 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001983 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001984 PyTuple_SET_ITEM(retval, 2, v);
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001985
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001986 return retval;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001987
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001988 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001989 Py_DECREF(retval);
1990 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001991}
1992
Christian Heimes25bfcd52016-09-06 00:04:45 +02001993#if OPENSSL_VERSION_NUMBER >= 0x10002000UL
1994static PyObject *
1995cipher_to_dict(const SSL_CIPHER *cipher)
1996{
1997 const char *cipher_name, *cipher_protocol;
1998
1999 unsigned long cipher_id;
2000 int alg_bits, strength_bits, len;
2001 char buf[512] = {0};
2002#if OPENSSL_VERSION_1_1
2003 int aead, nid;
2004 const char *skcipher = NULL, *digest = NULL, *kx = NULL, *auth = NULL;
2005#endif
Christian Heimes25bfcd52016-09-06 00:04:45 +02002006
2007 /* can be NULL */
2008 cipher_name = SSL_CIPHER_get_name(cipher);
2009 cipher_protocol = SSL_CIPHER_get_version(cipher);
2010 cipher_id = SSL_CIPHER_get_id(cipher);
2011 SSL_CIPHER_description(cipher, buf, sizeof(buf) - 1);
Segev Finer5cff6372017-07-27 01:19:17 +03002012 /* Downcast to avoid a warning. Safe since buf is always 512 bytes */
2013 len = (int)strlen(buf);
Christian Heimes25bfcd52016-09-06 00:04:45 +02002014 if (len > 1 && buf[len-1] == '\n')
2015 buf[len-1] = '\0';
2016 strength_bits = SSL_CIPHER_get_bits(cipher, &alg_bits);
2017
2018#if OPENSSL_VERSION_1_1
2019 aead = SSL_CIPHER_is_aead(cipher);
2020 nid = SSL_CIPHER_get_cipher_nid(cipher);
2021 skcipher = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
2022 nid = SSL_CIPHER_get_digest_nid(cipher);
2023 digest = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
2024 nid = SSL_CIPHER_get_kx_nid(cipher);
2025 kx = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
2026 nid = SSL_CIPHER_get_auth_nid(cipher);
2027 auth = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
2028#endif
2029
Victor Stinner410b9882016-09-12 12:00:23 +02002030 return Py_BuildValue(
Christian Heimes25bfcd52016-09-06 00:04:45 +02002031 "{sksssssssisi"
2032#if OPENSSL_VERSION_1_1
2033 "sOssssssss"
2034#endif
2035 "}",
2036 "id", cipher_id,
2037 "name", cipher_name,
2038 "protocol", cipher_protocol,
2039 "description", buf,
2040 "strength_bits", strength_bits,
2041 "alg_bits", alg_bits
2042#if OPENSSL_VERSION_1_1
2043 ,"aead", aead ? Py_True : Py_False,
2044 "symmetric", skcipher,
2045 "digest", digest,
2046 "kea", kx,
2047 "auth", auth
2048#endif
2049 );
Christian Heimes25bfcd52016-09-06 00:04:45 +02002050}
2051#endif
2052
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002053/*[clinic input]
2054_ssl._SSLSocket.shared_ciphers
2055[clinic start generated code]*/
2056
2057static PyObject *
2058_ssl__SSLSocket_shared_ciphers_impl(PySSLSocket *self)
2059/*[clinic end generated code: output=3d174ead2e42c4fd input=0bfe149da8fe6306]*/
Benjamin Peterson4cb17812015-01-07 11:14:26 -06002060{
2061 STACK_OF(SSL_CIPHER) *ciphers;
2062 int i;
2063 PyObject *res;
2064
Christian Heimes598894f2016-09-05 23:19:05 +02002065 ciphers = SSL_get_ciphers(self->ssl);
2066 if (!ciphers)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06002067 Py_RETURN_NONE;
Benjamin Peterson4cb17812015-01-07 11:14:26 -06002068 res = PyList_New(sk_SSL_CIPHER_num(ciphers));
2069 if (!res)
2070 return NULL;
2071 for (i = 0; i < sk_SSL_CIPHER_num(ciphers); i++) {
2072 PyObject *tup = cipher_to_tuple(sk_SSL_CIPHER_value(ciphers, i));
2073 if (!tup) {
2074 Py_DECREF(res);
2075 return NULL;
2076 }
2077 PyList_SET_ITEM(res, i, tup);
2078 }
2079 return res;
2080}
2081
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002082/*[clinic input]
2083_ssl._SSLSocket.cipher
2084[clinic start generated code]*/
2085
2086static PyObject *
2087_ssl__SSLSocket_cipher_impl(PySSLSocket *self)
2088/*[clinic end generated code: output=376417c16d0e5815 input=548fb0e27243796d]*/
Benjamin Peterson4cb17812015-01-07 11:14:26 -06002089{
2090 const SSL_CIPHER *current;
2091
2092 if (self->ssl == NULL)
2093 Py_RETURN_NONE;
2094 current = SSL_get_current_cipher(self->ssl);
2095 if (current == NULL)
2096 Py_RETURN_NONE;
2097 return cipher_to_tuple(current);
2098}
2099
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002100/*[clinic input]
2101_ssl._SSLSocket.version
2102[clinic start generated code]*/
2103
2104static PyObject *
2105_ssl__SSLSocket_version_impl(PySSLSocket *self)
2106/*[clinic end generated code: output=178aed33193b2cdb input=900186a503436fd6]*/
Antoine Pitrou47e40422014-09-04 21:00:10 +02002107{
2108 const char *version;
2109
2110 if (self->ssl == NULL)
2111 Py_RETURN_NONE;
Christian Heimes68771112017-09-05 21:55:40 -07002112 if (!SSL_is_init_finished(self->ssl)) {
2113 /* handshake not finished */
2114 Py_RETURN_NONE;
2115 }
Antoine Pitrou47e40422014-09-04 21:00:10 +02002116 version = SSL_get_version(self->ssl);
2117 if (!strcmp(version, "unknown"))
2118 Py_RETURN_NONE;
2119 return PyUnicode_FromString(version);
2120}
2121
Christian Heimes29eab552018-02-25 12:31:33 +01002122#if HAVE_NPN
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002123/*[clinic input]
2124_ssl._SSLSocket.selected_npn_protocol
2125[clinic start generated code]*/
2126
2127static PyObject *
2128_ssl__SSLSocket_selected_npn_protocol_impl(PySSLSocket *self)
2129/*[clinic end generated code: output=b91d494cd207ecf6 input=c28fde139204b826]*/
2130{
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002131 const unsigned char *out;
2132 unsigned int outlen;
2133
Victor Stinner4569cd52013-06-23 14:58:43 +02002134 SSL_get0_next_proto_negotiated(self->ssl,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002135 &out, &outlen);
2136
2137 if (out == NULL)
2138 Py_RETURN_NONE;
Benjamin Petersoncca27322015-01-23 16:35:37 -05002139 return PyUnicode_FromStringAndSize((char *)out, outlen);
2140}
2141#endif
2142
Christian Heimes29eab552018-02-25 12:31:33 +01002143#if HAVE_ALPN
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002144/*[clinic input]
2145_ssl._SSLSocket.selected_alpn_protocol
2146[clinic start generated code]*/
2147
2148static PyObject *
2149_ssl__SSLSocket_selected_alpn_protocol_impl(PySSLSocket *self)
2150/*[clinic end generated code: output=ec33688b303d250f input=442de30e35bc2913]*/
2151{
Benjamin Petersoncca27322015-01-23 16:35:37 -05002152 const unsigned char *out;
2153 unsigned int outlen;
2154
2155 SSL_get0_alpn_selected(self->ssl, &out, &outlen);
2156
2157 if (out == NULL)
2158 Py_RETURN_NONE;
2159 return PyUnicode_FromStringAndSize((char *)out, outlen);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002160}
2161#endif
2162
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002163/*[clinic input]
2164_ssl._SSLSocket.compression
2165[clinic start generated code]*/
2166
2167static PyObject *
2168_ssl__SSLSocket_compression_impl(PySSLSocket *self)
2169/*[clinic end generated code: output=bd16cb1bb4646ae7 input=5d059d0a2bbc32c8]*/
2170{
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01002171#ifdef OPENSSL_NO_COMP
2172 Py_RETURN_NONE;
2173#else
2174 const COMP_METHOD *comp_method;
2175 const char *short_name;
2176
2177 if (self->ssl == NULL)
2178 Py_RETURN_NONE;
2179 comp_method = SSL_get_current_compression(self->ssl);
Christian Heimes598894f2016-09-05 23:19:05 +02002180 if (comp_method == NULL || COMP_get_type(comp_method) == NID_undef)
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01002181 Py_RETURN_NONE;
Christian Heimes281e5f82016-09-06 01:10:39 +02002182 short_name = OBJ_nid2sn(COMP_get_type(comp_method));
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01002183 if (short_name == NULL)
2184 Py_RETURN_NONE;
2185 return PyUnicode_DecodeFSDefault(short_name);
2186#endif
2187}
2188
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002189static PySSLContext *PySSL_get_context(PySSLSocket *self, void *closure) {
2190 Py_INCREF(self->ctx);
2191 return self->ctx;
2192}
2193
2194static int PySSL_set_context(PySSLSocket *self, PyObject *value,
2195 void *closure) {
2196
2197 if (PyObject_TypeCheck(value, &PySSLContext_Type)) {
Antoine Pitrou912fbff2013-03-30 16:29:32 +01002198#if !HAVE_SNI
2199 PyErr_SetString(PyExc_NotImplementedError, "setting a socket's "
2200 "context is not supported by your OpenSSL library");
Antoine Pitrou41f8c4f2013-03-30 16:36:54 +01002201 return -1;
Antoine Pitrou912fbff2013-03-30 16:29:32 +01002202#else
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002203 Py_INCREF(value);
Serhiy Storchaka57a01d32016-04-10 18:05:40 +03002204 Py_SETREF(self->ctx, (PySSLContext *)value);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002205 SSL_set_SSL_CTX(self->ssl, self->ctx->ctx);
Antoine Pitrou912fbff2013-03-30 16:29:32 +01002206#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002207 } else {
Ned Deily4531ec72018-06-11 20:26:28 -04002208 PyErr_SetString(PyExc_TypeError, "The value must be a SSLContext");
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002209 return -1;
2210 }
2211
2212 return 0;
2213}
2214
2215PyDoc_STRVAR(PySSL_set_context_doc,
2216"_setter_context(ctx)\n\
2217\
2218This changes the context associated with the SSLSocket. This is typically\n\
Christian Heimes11a14932018-02-24 02:35:08 +01002219used from within a callback function set by the sni_callback\n\
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002220on the SSLContext to change the certificate information associated with the\n\
2221SSLSocket before the cryptographic exchange handshake messages\n");
2222
2223
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002224static PyObject *
2225PySSL_get_server_side(PySSLSocket *self, void *c)
2226{
2227 return PyBool_FromLong(self->socket_type == PY_SSL_SERVER);
2228}
2229
2230PyDoc_STRVAR(PySSL_get_server_side_doc,
2231"Whether this is a server-side socket.");
2232
2233static PyObject *
2234PySSL_get_server_hostname(PySSLSocket *self, void *c)
2235{
2236 if (self->server_hostname == NULL)
2237 Py_RETURN_NONE;
2238 Py_INCREF(self->server_hostname);
2239 return self->server_hostname;
2240}
2241
2242PyDoc_STRVAR(PySSL_get_server_hostname_doc,
2243"The currently set server hostname (for SNI).");
2244
2245static PyObject *
2246PySSL_get_owner(PySSLSocket *self, void *c)
2247{
2248 PyObject *owner;
2249
2250 if (self->owner == NULL)
2251 Py_RETURN_NONE;
2252
2253 owner = PyWeakref_GetObject(self->owner);
2254 Py_INCREF(owner);
2255 return owner;
2256}
2257
2258static int
2259PySSL_set_owner(PySSLSocket *self, PyObject *value, void *c)
2260{
Serhiy Storchaka48842712016-04-06 09:45:48 +03002261 Py_XSETREF(self->owner, PyWeakref_NewRef(value, NULL));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002262 if (self->owner == NULL)
2263 return -1;
2264 return 0;
2265}
2266
2267PyDoc_STRVAR(PySSL_get_owner_doc,
2268"The Python-level owner of this object.\
2269Passed as \"self\" in servername callback.");
2270
Christian Heimesc7f70692019-05-31 11:44:05 +02002271static int
2272PySSL_traverse(PySSLSocket *self, visitproc visit, void *arg)
2273{
2274 Py_VISIT(self->exc_type);
2275 Py_VISIT(self->exc_value);
2276 Py_VISIT(self->exc_tb);
2277 return 0;
2278}
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002279
Christian Heimesc7f70692019-05-31 11:44:05 +02002280static int
2281PySSL_clear(PySSLSocket *self)
2282{
2283 Py_CLEAR(self->exc_type);
2284 Py_CLEAR(self->exc_value);
2285 Py_CLEAR(self->exc_tb);
2286 return 0;
2287}
2288
2289static void
2290PySSL_dealloc(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002291{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002292 if (self->ssl)
2293 SSL_free(self->ssl);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002294 Py_XDECREF(self->Socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002295 Py_XDECREF(self->ctx);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002296 Py_XDECREF(self->server_hostname);
2297 Py_XDECREF(self->owner);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002298 PyObject_Del(self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002299}
2300
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002301/* If the socket has a timeout, do a select()/poll() on the socket.
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002302 The argument writing indicates the direction.
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00002303 Returns one of the possibilities in the timeout_state enum (above).
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002304 */
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00002305
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002306static int
Victor Stinner14690702015-04-06 22:46:13 +02002307PySSL_select(PySocketSockObject *s, int writing, _PyTime_t timeout)
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002308{
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002309 int rc;
2310#ifdef HAVE_POLL
2311 struct pollfd pollfd;
2312 _PyTime_t ms;
2313#else
2314 int nfds;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002315 fd_set fds;
2316 struct timeval tv;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002317#endif
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002318
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002319 /* Nothing to do unless we're in timeout mode (not non-blocking) */
Victor Stinner14690702015-04-06 22:46:13 +02002320 if ((s == NULL) || (timeout == 0))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002321 return SOCKET_IS_NONBLOCKING;
Victor Stinner14690702015-04-06 22:46:13 +02002322 else if (timeout < 0) {
2323 if (s->sock_timeout > 0)
2324 return SOCKET_HAS_TIMED_OUT;
2325 else
2326 return SOCKET_IS_BLOCKING;
2327 }
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002328
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002329 /* Guard against closed socket */
Victor Stinner524714e2016-07-22 17:43:59 +02002330 if (s->sock_fd == INVALID_SOCKET)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002331 return SOCKET_HAS_BEEN_CLOSED;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002332
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002333 /* Prefer poll, if available, since you can poll() any fd
2334 * which can't be done with select(). */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002335#ifdef HAVE_POLL
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002336 pollfd.fd = s->sock_fd;
2337 pollfd.events = writing ? POLLOUT : POLLIN;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002338
Victor Stinner14690702015-04-06 22:46:13 +02002339 /* timeout is in seconds, poll() uses milliseconds */
2340 ms = (int)_PyTime_AsMilliseconds(timeout, _PyTime_ROUND_CEILING);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002341 assert(ms <= INT_MAX);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002342
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002343 PySSL_BEGIN_ALLOW_THREADS
2344 rc = poll(&pollfd, 1, (int)ms);
2345 PySSL_END_ALLOW_THREADS
2346#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002347 /* Guard against socket too large for select*/
Charles-François Nataliaa26b272011-08-28 17:51:43 +02002348 if (!_PyIsSelectable_fd(s->sock_fd))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002349 return SOCKET_TOO_LARGE_FOR_SELECT;
Neal Norwitz082b2df2006-02-07 07:04:46 +00002350
Victor Stinner14690702015-04-06 22:46:13 +02002351 _PyTime_AsTimeval_noraise(timeout, &tv, _PyTime_ROUND_CEILING);
Victor Stinnere2452312015-03-28 03:00:46 +01002352
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002353 FD_ZERO(&fds);
2354 FD_SET(s->sock_fd, &fds);
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002355
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002356 /* Wait until the socket becomes ready */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002357 PySSL_BEGIN_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002358 nfds = Py_SAFE_DOWNCAST(s->sock_fd+1, SOCKET_T, int);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002359 if (writing)
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002360 rc = select(nfds, NULL, &fds, NULL, &tv);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002361 else
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002362 rc = select(nfds, &fds, NULL, NULL, &tv);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002363 PySSL_END_ALLOW_THREADS
Bill Janssen6e027db2007-11-15 22:23:56 +00002364#endif
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002365
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002366 /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
2367 (when we are able to write or when there's something to read) */
2368 return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002369}
2370
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002371/*[clinic input]
2372_ssl._SSLSocket.write
2373 b: Py_buffer
2374 /
2375
2376Writes the bytes-like object b into the SSL object.
2377
2378Returns the number of bytes written.
2379[clinic start generated code]*/
2380
2381static PyObject *
2382_ssl__SSLSocket_write_impl(PySSLSocket *self, Py_buffer *b)
2383/*[clinic end generated code: output=aa7a6be5527358d8 input=77262d994fe5100a]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002384{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002385 int len;
2386 int sockstate;
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002387 _PySSLError err;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002388 int nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002389 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002390 _PyTime_t timeout, deadline = 0;
2391 int has_timeout;
Bill Janssen54cc54c2007-12-14 22:08:56 +00002392
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002393 if (sock != NULL) {
2394 if (((PyObject*)sock) == Py_None) {
2395 _setSSLError("Underlying socket connection gone",
2396 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2397 return NULL;
2398 }
2399 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002400 }
2401
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002402 if (b->len > INT_MAX) {
Victor Stinner6efa9652013-06-25 00:42:31 +02002403 PyErr_Format(PyExc_OverflowError,
2404 "string longer than %d bytes", INT_MAX);
2405 goto error;
2406 }
2407
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002408 if (sock != NULL) {
2409 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002410 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002411 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2412 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
2413 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002414
Victor Stinner14690702015-04-06 22:46:13 +02002415 timeout = GET_SOCKET_TIMEOUT(sock);
2416 has_timeout = (timeout > 0);
2417 if (has_timeout)
2418 deadline = _PyTime_GetMonotonicClock() + timeout;
2419
2420 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002421 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002422 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002423 "The write operation timed out");
2424 goto error;
2425 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
2426 PyErr_SetString(PySSLErrorObject,
2427 "Underlying socket has been closed.");
2428 goto error;
2429 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
2430 PyErr_SetString(PySSLErrorObject,
2431 "Underlying socket too large for select().");
2432 goto error;
2433 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002434
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002435 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002436 PySSL_BEGIN_ALLOW_THREADS
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002437 len = SSL_write(self->ssl, b->buf, (int)b->len);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002438 err = _PySSL_errno(len <= 0, self->ssl, len);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002439 PySSL_END_ALLOW_THREADS
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002440 self->err = err;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002441
2442 if (PyErr_CheckSignals())
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002443 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002444
Victor Stinner14690702015-04-06 22:46:13 +02002445 if (has_timeout)
2446 timeout = deadline - _PyTime_GetMonotonicClock();
2447
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002448 if (err.ssl == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +02002449 sockstate = PySSL_select(sock, 0, timeout);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002450 } else if (err.ssl == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +02002451 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002452 } else {
2453 sockstate = SOCKET_OPERATION_OK;
2454 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002455
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002456 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002457 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002458 "The write operation timed out");
2459 goto error;
2460 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
2461 PyErr_SetString(PySSLErrorObject,
2462 "Underlying socket has been closed.");
2463 goto error;
2464 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
2465 break;
2466 }
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002467 } while (err.ssl == SSL_ERROR_WANT_READ ||
2468 err.ssl == SSL_ERROR_WANT_WRITE);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002469
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002470 Py_XDECREF(sock);
Christian Heimesc7f70692019-05-31 11:44:05 +02002471 if (len <= 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002472 return PySSL_SetError(self, len, __FILE__, __LINE__);
Christian Heimesc7f70692019-05-31 11:44:05 +02002473 if (PySSL_ChainExceptions(self) < 0)
2474 return NULL;
2475 return PyLong_FromLong(len);
Antoine Pitrou7d7aede2009-11-25 18:55:32 +00002476error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002477 Py_XDECREF(sock);
Christian Heimesc7f70692019-05-31 11:44:05 +02002478 PySSL_ChainExceptions(self);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002479 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002480}
2481
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002482/*[clinic input]
2483_ssl._SSLSocket.pending
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002484
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002485Returns the number of already decrypted bytes available for read, pending on the connection.
2486[clinic start generated code]*/
2487
2488static PyObject *
2489_ssl__SSLSocket_pending_impl(PySSLSocket *self)
2490/*[clinic end generated code: output=983d9fecdc308a83 input=2b77487d6dfd597f]*/
Bill Janssen6e027db2007-11-15 22:23:56 +00002491{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002492 int count = 0;
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002493 _PySSLError err;
Bill Janssen6e027db2007-11-15 22:23:56 +00002494
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002495 PySSL_BEGIN_ALLOW_THREADS
2496 count = SSL_pending(self->ssl);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002497 err = _PySSL_errno(count < 0, self->ssl, count);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002498 PySSL_END_ALLOW_THREADS
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002499 self->err = err;
2500
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002501 if (count < 0)
2502 return PySSL_SetError(self, count, __FILE__, __LINE__);
2503 else
2504 return PyLong_FromLong(count);
Bill Janssen6e027db2007-11-15 22:23:56 +00002505}
2506
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002507/*[clinic input]
2508_ssl._SSLSocket.read
2509 size as len: int
2510 [
Larry Hastingsdbfdc382015-05-04 06:59:46 -07002511 buffer: Py_buffer(accept={rwbuffer})
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002512 ]
2513 /
Bill Janssen6e027db2007-11-15 22:23:56 +00002514
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002515Read up to size bytes from the SSL socket.
2516[clinic start generated code]*/
2517
2518static PyObject *
2519_ssl__SSLSocket_read_impl(PySSLSocket *self, int len, int group_right_1,
2520 Py_buffer *buffer)
Larry Hastingsdbfdc382015-05-04 06:59:46 -07002521/*[clinic end generated code: output=00097776cec2a0af input=ff157eb918d0905b]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002522{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002523 PyObject *dest = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002524 char *mem;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002525 int count;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002526 int sockstate;
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002527 _PySSLError err;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002528 int nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002529 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002530 _PyTime_t timeout, deadline = 0;
2531 int has_timeout;
Bill Janssen54cc54c2007-12-14 22:08:56 +00002532
Martin Panter5503d472016-03-27 05:35:19 +00002533 if (!group_right_1 && len < 0) {
2534 PyErr_SetString(PyExc_ValueError, "size should not be negative");
2535 return NULL;
2536 }
2537
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002538 if (sock != NULL) {
2539 if (((PyObject*)sock) == Py_None) {
2540 _setSSLError("Underlying socket connection gone",
2541 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2542 return NULL;
2543 }
2544 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002545 }
2546
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002547 if (!group_right_1) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002548 dest = PyBytes_FromStringAndSize(NULL, len);
2549 if (dest == NULL)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002550 goto error;
Martin Panterbed7f1a2016-07-11 00:17:13 +00002551 if (len == 0) {
2552 Py_XDECREF(sock);
2553 return dest;
2554 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002555 mem = PyBytes_AS_STRING(dest);
2556 }
2557 else {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002558 mem = buffer->buf;
2559 if (len <= 0 || len > buffer->len) {
2560 len = (int) buffer->len;
2561 if (buffer->len != len) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002562 PyErr_SetString(PyExc_OverflowError,
2563 "maximum length can't fit in a C 'int'");
2564 goto error;
2565 }
Martin Panterbed7f1a2016-07-11 00:17:13 +00002566 if (len == 0) {
2567 count = 0;
2568 goto done;
2569 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002570 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002571 }
2572
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002573 if (sock != NULL) {
2574 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002575 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002576 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2577 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
2578 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002579
Victor Stinner14690702015-04-06 22:46:13 +02002580 timeout = GET_SOCKET_TIMEOUT(sock);
2581 has_timeout = (timeout > 0);
2582 if (has_timeout)
2583 deadline = _PyTime_GetMonotonicClock() + timeout;
2584
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002585 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002586 PySSL_BEGIN_ALLOW_THREADS
2587 count = SSL_read(self->ssl, mem, len);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002588 err = _PySSL_errno(count <= 0, self->ssl, count);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002589 PySSL_END_ALLOW_THREADS
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002590 self->err = err;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002591
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002592 if (PyErr_CheckSignals())
2593 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002594
Victor Stinner14690702015-04-06 22:46:13 +02002595 if (has_timeout)
2596 timeout = deadline - _PyTime_GetMonotonicClock();
2597
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002598 if (err.ssl == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +02002599 sockstate = PySSL_select(sock, 0, timeout);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002600 } else if (err.ssl == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +02002601 sockstate = PySSL_select(sock, 1, timeout);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002602 } else if (err.ssl == SSL_ERROR_ZERO_RETURN &&
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002603 SSL_get_shutdown(self->ssl) == SSL_RECEIVED_SHUTDOWN)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002604 {
2605 count = 0;
2606 goto done;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002607 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002608 else
2609 sockstate = SOCKET_OPERATION_OK;
2610
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002611 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002612 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002613 "The read operation timed out");
2614 goto error;
2615 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
2616 break;
2617 }
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002618 } while (err.ssl == SSL_ERROR_WANT_READ ||
2619 err.ssl == SSL_ERROR_WANT_WRITE);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002620
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002621 if (count <= 0) {
2622 PySSL_SetError(self, count, __FILE__, __LINE__);
2623 goto error;
2624 }
Christian Heimesc7f70692019-05-31 11:44:05 +02002625 if (self->exc_type != NULL)
2626 goto error;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002627
2628done:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002629 Py_XDECREF(sock);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002630 if (!group_right_1) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002631 _PyBytes_Resize(&dest, count);
2632 return dest;
2633 }
2634 else {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002635 return PyLong_FromLong(count);
2636 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002637
2638error:
Christian Heimesc7f70692019-05-31 11:44:05 +02002639 PySSL_ChainExceptions(self);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002640 Py_XDECREF(sock);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002641 if (!group_right_1)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002642 Py_XDECREF(dest);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002643 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002644}
2645
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002646/*[clinic input]
2647_ssl._SSLSocket.shutdown
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002648
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002649Does the SSL shutdown handshake with the remote end.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002650[clinic start generated code]*/
2651
2652static PyObject *
2653_ssl__SSLSocket_shutdown_impl(PySSLSocket *self)
Christian Heimes141c5e82018-02-24 21:10:57 +01002654/*[clinic end generated code: output=ca1aa7ed9d25ca42 input=11d39e69b0a2bf4a]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00002655{
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002656 _PySSLError err;
2657 int sockstate, nonblocking, ret;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002658 int zeros = 0;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002659 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002660 _PyTime_t timeout, deadline = 0;
2661 int has_timeout;
Bill Janssen40a0f662008-08-12 16:56:25 +00002662
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002663 if (sock != NULL) {
2664 /* Guard against closed socket */
Victor Stinner524714e2016-07-22 17:43:59 +02002665 if ((((PyObject*)sock) == Py_None) || (sock->sock_fd == INVALID_SOCKET)) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002666 _setSSLError("Underlying socket connection gone",
2667 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2668 return NULL;
2669 }
2670 Py_INCREF(sock);
2671
2672 /* Just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002673 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002674 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2675 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002676 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002677
Victor Stinner14690702015-04-06 22:46:13 +02002678 timeout = GET_SOCKET_TIMEOUT(sock);
2679 has_timeout = (timeout > 0);
2680 if (has_timeout)
2681 deadline = _PyTime_GetMonotonicClock() + timeout;
2682
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002683 while (1) {
2684 PySSL_BEGIN_ALLOW_THREADS
2685 /* Disable read-ahead so that unwrap can work correctly.
2686 * Otherwise OpenSSL might read in too much data,
2687 * eating clear text data that happens to be
2688 * transmitted after the SSL shutdown.
Ezio Melotti85a86292013-08-17 16:57:41 +03002689 * Should be safe to call repeatedly every time this
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002690 * function is used and the shutdown_seen_zero != 0
2691 * condition is met.
2692 */
2693 if (self->shutdown_seen_zero)
2694 SSL_set_read_ahead(self->ssl, 0);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002695 ret = SSL_shutdown(self->ssl);
2696 err = _PySSL_errno(ret < 0, self->ssl, ret);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002697 PySSL_END_ALLOW_THREADS
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002698 self->err = err;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002699
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002700 /* If err == 1, a secure shutdown with SSL_shutdown() is complete */
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002701 if (ret > 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002702 break;
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002703 if (ret == 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002704 /* Don't loop endlessly; instead preserve legacy
2705 behaviour of trying SSL_shutdown() only twice.
2706 This looks necessary for OpenSSL < 0.9.8m */
2707 if (++zeros > 1)
2708 break;
2709 /* Shutdown was sent, now try receiving */
2710 self->shutdown_seen_zero = 1;
2711 continue;
Bill Janssen40a0f662008-08-12 16:56:25 +00002712 }
2713
Victor Stinner14690702015-04-06 22:46:13 +02002714 if (has_timeout)
2715 timeout = deadline - _PyTime_GetMonotonicClock();
2716
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002717 /* Possibly retry shutdown until timeout or failure */
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002718 if (err.ssl == SSL_ERROR_WANT_READ)
Victor Stinner14690702015-04-06 22:46:13 +02002719 sockstate = PySSL_select(sock, 0, timeout);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002720 else if (err.ssl == SSL_ERROR_WANT_WRITE)
Victor Stinner14690702015-04-06 22:46:13 +02002721 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002722 else
2723 break;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002724
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002725 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002726 if (err.ssl == SSL_ERROR_WANT_READ)
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002727 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002728 "The read operation timed out");
2729 else
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002730 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002731 "The write operation timed out");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002732 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002733 }
2734 else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
2735 PyErr_SetString(PySSLErrorObject,
2736 "Underlying socket too large for select().");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002737 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002738 }
2739 else if (sockstate != SOCKET_OPERATION_OK)
2740 /* Retain the SSL error code */
2741 break;
2742 }
Nathaniel J. Smithc0da5822018-09-21 21:44:12 -07002743 if (ret < 0) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002744 Py_XDECREF(sock);
Christian Heimesc7f70692019-05-31 11:44:05 +02002745 PySSL_SetError(self, ret, __FILE__, __LINE__);
2746 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002747 }
Christian Heimesc7f70692019-05-31 11:44:05 +02002748 if (self->exc_type != NULL)
2749 goto error;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002750 if (sock)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002751 /* It's already INCREF'ed */
2752 return (PyObject *) sock;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002753 else
2754 Py_RETURN_NONE;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002755
2756error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002757 Py_XDECREF(sock);
Christian Heimesc7f70692019-05-31 11:44:05 +02002758 PySSL_ChainExceptions(self);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002759 return NULL;
Bill Janssen40a0f662008-08-12 16:56:25 +00002760}
2761
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002762/*[clinic input]
Christian Heimes141c5e82018-02-24 21:10:57 +01002763_ssl._SSLSocket.get_channel_binding
2764 cb_type: str = "tls-unique"
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002765
Christian Heimes141c5e82018-02-24 21:10:57 +01002766Get channel binding data for current connection.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002767
Christian Heimes141c5e82018-02-24 21:10:57 +01002768Raise ValueError if the requested `cb_type` is not supported. Return bytes
2769of the data or None if the data is not available (e.g. before the handshake).
2770Only 'tls-unique' channel binding data from RFC 5929 is supported.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002771[clinic start generated code]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00002772
Antoine Pitroud6494802011-07-21 01:11:30 +02002773static PyObject *
Christian Heimes141c5e82018-02-24 21:10:57 +01002774_ssl__SSLSocket_get_channel_binding_impl(PySSLSocket *self,
2775 const char *cb_type)
2776/*[clinic end generated code: output=34bac9acb6a61d31 input=08b7e43b99c17d41]*/
Antoine Pitroud6494802011-07-21 01:11:30 +02002777{
Antoine Pitroud6494802011-07-21 01:11:30 +02002778 char buf[PySSL_CB_MAXLEN];
Victor Stinner9ee02032013-06-23 15:08:23 +02002779 size_t len;
Antoine Pitroud6494802011-07-21 01:11:30 +02002780
Christian Heimes141c5e82018-02-24 21:10:57 +01002781 if (strcmp(cb_type, "tls-unique") == 0) {
2782 if (SSL_session_reused(self->ssl) ^ !self->socket_type) {
2783 /* if session is resumed XOR we are the client */
2784 len = SSL_get_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2785 }
2786 else {
2787 /* if a new session XOR we are the server */
2788 len = SSL_get_peer_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2789 }
Antoine Pitroud6494802011-07-21 01:11:30 +02002790 }
2791 else {
Christian Heimes141c5e82018-02-24 21:10:57 +01002792 PyErr_Format(
2793 PyExc_ValueError,
2794 "'%s' channel binding type not implemented",
2795 cb_type
2796 );
2797 return NULL;
Antoine Pitroud6494802011-07-21 01:11:30 +02002798 }
2799
2800 /* It cannot be negative in current OpenSSL version as of July 2011 */
Antoine Pitroud6494802011-07-21 01:11:30 +02002801 if (len == 0)
2802 Py_RETURN_NONE;
2803
Christian Heimes141c5e82018-02-24 21:10:57 +01002804 return PyBytes_FromStringAndSize(buf, len);
Antoine Pitroud6494802011-07-21 01:11:30 +02002805}
2806
Christian Heimes9fb051f2018-09-23 08:32:31 +02002807/*[clinic input]
2808_ssl._SSLSocket.verify_client_post_handshake
2809
2810Initiate TLS 1.3 post-handshake authentication
2811[clinic start generated code]*/
2812
2813static PyObject *
2814_ssl__SSLSocket_verify_client_post_handshake_impl(PySSLSocket *self)
2815/*[clinic end generated code: output=532147f3b1341425 input=6bfa874810a3d889]*/
2816{
2817#ifdef TLS1_3_VERSION
2818 int err = SSL_verify_client_post_handshake(self->ssl);
2819 if (err == 0)
2820 return _setSSLError(NULL, 0, __FILE__, __LINE__);
2821 else
2822 Py_RETURN_NONE;
2823#else
2824 PyErr_SetString(PyExc_NotImplementedError,
2825 "Post-handshake auth is not supported by your "
2826 "OpenSSL version.");
2827 return NULL;
2828#endif
2829}
2830
Christian Heimes99a65702016-09-10 23:44:53 +02002831#ifdef OPENSSL_VERSION_1_1
2832
2833static SSL_SESSION*
2834_ssl_session_dup(SSL_SESSION *session) {
2835 SSL_SESSION *newsession = NULL;
2836 int slen;
2837 unsigned char *senc = NULL, *p;
2838 const unsigned char *const_p;
2839
2840 if (session == NULL) {
2841 PyErr_SetString(PyExc_ValueError, "Invalid session");
2842 goto error;
2843 }
2844
2845 /* get length */
2846 slen = i2d_SSL_SESSION(session, NULL);
2847 if (slen == 0 || slen > 0xFF00) {
2848 PyErr_SetString(PyExc_ValueError, "i2d() failed.");
2849 goto error;
2850 }
2851 if ((senc = PyMem_Malloc(slen)) == NULL) {
2852 PyErr_NoMemory();
2853 goto error;
2854 }
2855 p = senc;
2856 if (!i2d_SSL_SESSION(session, &p)) {
2857 PyErr_SetString(PyExc_ValueError, "i2d() failed.");
2858 goto error;
2859 }
2860 const_p = senc;
2861 newsession = d2i_SSL_SESSION(NULL, &const_p, slen);
2862 if (session == NULL) {
2863 goto error;
2864 }
2865 PyMem_Free(senc);
2866 return newsession;
2867 error:
2868 if (senc != NULL) {
2869 PyMem_Free(senc);
2870 }
2871 return NULL;
2872}
2873#endif
2874
2875static PyObject *
2876PySSL_get_session(PySSLSocket *self, void *closure) {
2877 /* get_session can return sessions from a server-side connection,
2878 * it does not check for handshake done or client socket. */
2879 PySSLSession *pysess;
2880 SSL_SESSION *session;
2881
2882#ifdef OPENSSL_VERSION_1_1
2883 /* duplicate session as workaround for session bug in OpenSSL 1.1.0,
2884 * https://github.com/openssl/openssl/issues/1550 */
2885 session = SSL_get0_session(self->ssl); /* borrowed reference */
2886 if (session == NULL) {
2887 Py_RETURN_NONE;
2888 }
2889 if ((session = _ssl_session_dup(session)) == NULL) {
2890 return NULL;
2891 }
2892#else
2893 session = SSL_get1_session(self->ssl);
2894 if (session == NULL) {
2895 Py_RETURN_NONE;
2896 }
2897#endif
Christian Heimesa5d07652016-09-24 10:48:05 +02002898 pysess = PyObject_GC_New(PySSLSession, &PySSLSession_Type);
Christian Heimes99a65702016-09-10 23:44:53 +02002899 if (pysess == NULL) {
2900 SSL_SESSION_free(session);
2901 return NULL;
2902 }
2903
2904 assert(self->ctx);
2905 pysess->ctx = self->ctx;
2906 Py_INCREF(pysess->ctx);
2907 pysess->session = session;
Christian Heimesa5d07652016-09-24 10:48:05 +02002908 PyObject_GC_Track(pysess);
Christian Heimes99a65702016-09-10 23:44:53 +02002909 return (PyObject *)pysess;
2910}
2911
2912static int PySSL_set_session(PySSLSocket *self, PyObject *value,
2913 void *closure)
2914 {
2915 PySSLSession *pysess;
2916#ifdef OPENSSL_VERSION_1_1
2917 SSL_SESSION *session;
2918#endif
2919 int result;
2920
2921 if (!PySSLSession_Check(value)) {
Ned Deily4531ec72018-06-11 20:26:28 -04002922 PyErr_SetString(PyExc_TypeError, "Value is not a SSLSession.");
Christian Heimes99a65702016-09-10 23:44:53 +02002923 return -1;
2924 }
2925 pysess = (PySSLSession *)value;
2926
2927 if (self->ctx->ctx != pysess->ctx->ctx) {
2928 PyErr_SetString(PyExc_ValueError,
2929 "Session refers to a different SSLContext.");
2930 return -1;
2931 }
2932 if (self->socket_type != PY_SSL_CLIENT) {
2933 PyErr_SetString(PyExc_ValueError,
2934 "Cannot set session for server-side SSLSocket.");
2935 return -1;
2936 }
Christian Heimes66dc33b2017-05-23 16:02:02 -07002937 if (SSL_is_init_finished(self->ssl)) {
Christian Heimes99a65702016-09-10 23:44:53 +02002938 PyErr_SetString(PyExc_ValueError,
2939 "Cannot set session after handshake.");
2940 return -1;
2941 }
2942#ifdef OPENSSL_VERSION_1_1
2943 /* duplicate session */
2944 if ((session = _ssl_session_dup(pysess->session)) == NULL) {
2945 return -1;
2946 }
2947 result = SSL_set_session(self->ssl, session);
2948 /* free duplicate, SSL_set_session() bumps ref count */
2949 SSL_SESSION_free(session);
2950#else
2951 result = SSL_set_session(self->ssl, pysess->session);
2952#endif
2953 if (result == 0) {
2954 _setSSLError(NULL, 0, __FILE__, __LINE__);
2955 return -1;
2956 }
2957 return 0;
2958}
2959
2960PyDoc_STRVAR(PySSL_set_session_doc,
2961"_setter_session(session)\n\
2962\
2963Get / set SSLSession.");
2964
2965static PyObject *
2966PySSL_get_session_reused(PySSLSocket *self, void *closure) {
2967 if (SSL_session_reused(self->ssl)) {
2968 Py_RETURN_TRUE;
2969 } else {
2970 Py_RETURN_FALSE;
2971 }
2972}
2973
2974PyDoc_STRVAR(PySSL_get_session_reused_doc,
2975"Was the client session reused during handshake?");
2976
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002977static PyGetSetDef ssl_getsetlist[] = {
2978 {"context", (getter) PySSL_get_context,
2979 (setter) PySSL_set_context, PySSL_set_context_doc},
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002980 {"server_side", (getter) PySSL_get_server_side, NULL,
2981 PySSL_get_server_side_doc},
2982 {"server_hostname", (getter) PySSL_get_server_hostname, NULL,
2983 PySSL_get_server_hostname_doc},
2984 {"owner", (getter) PySSL_get_owner, (setter) PySSL_set_owner,
2985 PySSL_get_owner_doc},
Christian Heimes99a65702016-09-10 23:44:53 +02002986 {"session", (getter) PySSL_get_session,
2987 (setter) PySSL_set_session, PySSL_set_session_doc},
2988 {"session_reused", (getter) PySSL_get_session_reused, NULL,
2989 PySSL_get_session_reused_doc},
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002990 {NULL}, /* sentinel */
2991};
2992
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002993static PyMethodDef PySSLMethods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002994 _SSL__SSLSOCKET_DO_HANDSHAKE_METHODDEF
2995 _SSL__SSLSOCKET_WRITE_METHODDEF
2996 _SSL__SSLSOCKET_READ_METHODDEF
2997 _SSL__SSLSOCKET_PENDING_METHODDEF
Christian Heimes141c5e82018-02-24 21:10:57 +01002998 _SSL__SSLSOCKET_GETPEERCERT_METHODDEF
2999 _SSL__SSLSOCKET_GET_CHANNEL_BINDING_METHODDEF
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003000 _SSL__SSLSOCKET_CIPHER_METHODDEF
3001 _SSL__SSLSOCKET_SHARED_CIPHERS_METHODDEF
3002 _SSL__SSLSOCKET_VERSION_METHODDEF
3003 _SSL__SSLSOCKET_SELECTED_NPN_PROTOCOL_METHODDEF
3004 _SSL__SSLSOCKET_SELECTED_ALPN_PROTOCOL_METHODDEF
3005 _SSL__SSLSOCKET_COMPRESSION_METHODDEF
3006 _SSL__SSLSOCKET_SHUTDOWN_METHODDEF
Christian Heimes9fb051f2018-09-23 08:32:31 +02003007 _SSL__SSLSOCKET_VERIFY_CLIENT_POST_HANDSHAKE_METHODDEF
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003008 {NULL, NULL}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003009};
3010
Antoine Pitrou152efa22010-05-16 18:19:27 +00003011static PyTypeObject PySSLSocket_Type = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003012 PyVarObject_HEAD_INIT(NULL, 0)
Antoine Pitrou152efa22010-05-16 18:19:27 +00003013 "_ssl._SSLSocket", /*tp_name*/
3014 sizeof(PySSLSocket), /*tp_basicsize*/
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003015 0, /*tp_itemsize*/
3016 /* methods */
3017 (destructor)PySSL_dealloc, /*tp_dealloc*/
Jeroen Demeyer530f5062019-05-31 04:13:39 +02003018 0, /*tp_vectorcall_offset*/
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003019 0, /*tp_getattr*/
3020 0, /*tp_setattr*/
Jeroen Demeyer530f5062019-05-31 04:13:39 +02003021 0, /*tp_as_async*/
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003022 0, /*tp_repr*/
3023 0, /*tp_as_number*/
3024 0, /*tp_as_sequence*/
3025 0, /*tp_as_mapping*/
3026 0, /*tp_hash*/
3027 0, /*tp_call*/
3028 0, /*tp_str*/
3029 0, /*tp_getattro*/
3030 0, /*tp_setattro*/
3031 0, /*tp_as_buffer*/
3032 Py_TPFLAGS_DEFAULT, /*tp_flags*/
3033 0, /*tp_doc*/
Christian Heimesc7f70692019-05-31 11:44:05 +02003034 (traverseproc) PySSL_traverse, /*tp_traverse*/
3035 (inquiry) PySSL_clear, /*tp_clear*/
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003036 0, /*tp_richcompare*/
3037 0, /*tp_weaklistoffset*/
3038 0, /*tp_iter*/
3039 0, /*tp_iternext*/
3040 PySSLMethods, /*tp_methods*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003041 0, /*tp_members*/
3042 ssl_getsetlist, /*tp_getset*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003043};
3044
Antoine Pitrou152efa22010-05-16 18:19:27 +00003045
3046/*
3047 * _SSLContext objects
3048 */
3049
Christian Heimes5fe668c2016-09-12 00:01:11 +02003050static int
Christian Heimes9fb051f2018-09-23 08:32:31 +02003051_set_verify_mode(PySSLContext *self, enum py_ssl_cert_requirements n)
Christian Heimes5fe668c2016-09-12 00:01:11 +02003052{
3053 int mode;
3054 int (*verify_cb)(int, X509_STORE_CTX *) = NULL;
3055
3056 switch(n) {
3057 case PY_SSL_CERT_NONE:
3058 mode = SSL_VERIFY_NONE;
3059 break;
3060 case PY_SSL_CERT_OPTIONAL:
3061 mode = SSL_VERIFY_PEER;
3062 break;
3063 case PY_SSL_CERT_REQUIRED:
3064 mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
3065 break;
3066 default:
3067 PyErr_SetString(PyExc_ValueError,
3068 "invalid value for verify_mode");
3069 return -1;
3070 }
Christian Heimesf22c4cf2019-07-01 09:25:48 +02003071
3072 /* bpo-37428: newPySSLSocket() sets SSL_VERIFY_POST_HANDSHAKE flag for
3073 * server sockets and SSL_set_post_handshake_auth() for client. */
3074
Christian Heimes5fe668c2016-09-12 00:01:11 +02003075 /* keep current verify cb */
Christian Heimes9fb051f2018-09-23 08:32:31 +02003076 verify_cb = SSL_CTX_get_verify_callback(self->ctx);
3077 SSL_CTX_set_verify(self->ctx, mode, verify_cb);
Christian Heimes5fe668c2016-09-12 00:01:11 +02003078 return 0;
3079}
3080
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003081/*[clinic input]
3082@classmethod
3083_ssl._SSLContext.__new__
3084 protocol as proto_version: int
3085 /
3086[clinic start generated code]*/
3087
Antoine Pitrou152efa22010-05-16 18:19:27 +00003088static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003089_ssl__SSLContext_impl(PyTypeObject *type, int proto_version)
3090/*[clinic end generated code: output=2cf0d7a0741b6bd1 input=8d58a805b95fc534]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003091{
Antoine Pitrou152efa22010-05-16 18:19:27 +00003092 PySSLContext *self;
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01003093 long options;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003094 SSL_CTX *ctx = NULL;
Christian Heimes61d478c2018-01-27 15:51:38 +01003095 X509_VERIFY_PARAM *params;
Christian Heimes358cfd42016-09-10 22:43:48 +02003096 int result;
Berker Peksagdfcb0412016-04-14 16:48:48 +03003097#if defined(SSL_MODE_RELEASE_BUFFERS)
Benjamin Peterson3b1a8b32016-01-07 21:37:37 -08003098 unsigned long libver;
Berker Peksagdfcb0412016-04-14 16:48:48 +03003099#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00003100
Antoine Pitrou152efa22010-05-16 18:19:27 +00003101 PySSL_BEGIN_ALLOW_THREADS
Miss Islington (bot)a6694432020-05-16 01:33:42 -07003102 switch(proto_version) {
3103#if defined(SSL3_VERSION) && !defined(OPENSSL_NO_SSL3)
3104 case PY_SSL_VERSION_SSL3:
Antoine Pitrou152efa22010-05-16 18:19:27 +00003105 ctx = SSL_CTX_new(SSLv3_method());
Miss Islington (bot)a6694432020-05-16 01:33:42 -07003106 break;
Benjamin Petersone32467c2014-12-05 21:59:35 -05003107#endif
Miss Islington (bot)9c0ff172020-06-01 00:17:16 -07003108#if (defined(TLS1_VERSION) && \
3109 !defined(OPENSSL_NO_TLS1) && \
3110 !defined(OPENSSL_NO_TLS1_METHOD))
Miss Islington (bot)a6694432020-05-16 01:33:42 -07003111 case PY_SSL_VERSION_TLS1:
3112 ctx = SSL_CTX_new(TLSv1_method());
3113 break;
Victor Stinner3de49192011-05-09 00:42:58 +02003114#endif
Miss Islington (bot)9c0ff172020-06-01 00:17:16 -07003115#if (defined(TLS1_1_VERSION) && \
3116 !defined(OPENSSL_NO_TLS1_1) && \
3117 !defined(OPENSSL_NO_TLS1_1_METHOD))
Miss Islington (bot)a6694432020-05-16 01:33:42 -07003118 case PY_SSL_VERSION_TLS1_1:
3119 ctx = SSL_CTX_new(TLSv1_1_method());
3120 break;
3121#endif
Miss Islington (bot)9c0ff172020-06-01 00:17:16 -07003122#if (defined(TLS1_2_VERSION) && \
3123 !defined(OPENSSL_NO_TLS1_2) && \
3124 !defined(OPENSSL_NO_TLS1_2_METHOD))
Miss Islington (bot)a6694432020-05-16 01:33:42 -07003125 case PY_SSL_VERSION_TLS1_2:
3126 ctx = SSL_CTX_new(TLSv1_2_method());
3127 break;
3128#endif
3129 case PY_SSL_VERSION_TLS:
3130 /* SSLv23 */
Christian Heimes598894f2016-09-05 23:19:05 +02003131 ctx = SSL_CTX_new(TLS_method());
Miss Islington (bot)a6694432020-05-16 01:33:42 -07003132 break;
3133 case PY_SSL_VERSION_TLS_CLIENT:
Christian Heimes5fe668c2016-09-12 00:01:11 +02003134 ctx = SSL_CTX_new(TLS_client_method());
Miss Islington (bot)a6694432020-05-16 01:33:42 -07003135 break;
3136 case PY_SSL_VERSION_TLS_SERVER:
Christian Heimes5fe668c2016-09-12 00:01:11 +02003137 ctx = SSL_CTX_new(TLS_server_method());
Miss Islington (bot)a6694432020-05-16 01:33:42 -07003138 break;
3139 default:
Antoine Pitrou152efa22010-05-16 18:19:27 +00003140 proto_version = -1;
Miss Islington (bot)a6694432020-05-16 01:33:42 -07003141 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003142 PySSL_END_ALLOW_THREADS
3143
3144 if (proto_version == -1) {
3145 PyErr_SetString(PyExc_ValueError,
Miss Islington (bot)a6694432020-05-16 01:33:42 -07003146 "invalid or unsupported protocol version");
Antoine Pitrou152efa22010-05-16 18:19:27 +00003147 return NULL;
3148 }
3149 if (ctx == NULL) {
Christian Heimes17c9ac92017-09-07 14:14:00 -07003150 _setSSLError(NULL, 0, __FILE__, __LINE__);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003151 return NULL;
3152 }
3153
3154 assert(type != NULL && type->tp_alloc != NULL);
3155 self = (PySSLContext *) type->tp_alloc(type, 0);
3156 if (self == NULL) {
3157 SSL_CTX_free(ctx);
3158 return NULL;
3159 }
3160 self->ctx = ctx;
Christian Heimes61d478c2018-01-27 15:51:38 +01003161 self->hostflags = X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS;
Christian Heimes11a14932018-02-24 02:35:08 +01003162 self->protocol = proto_version;
Christian Heimesc7f70692019-05-31 11:44:05 +02003163 self->msg_cb = NULL;
3164#ifdef HAVE_OPENSSL_KEYLOG
3165 self->keylog_filename = NULL;
3166 self->keylog_bio = NULL;
3167#endif
Christian Heimes29eab552018-02-25 12:31:33 +01003168#if HAVE_NPN
Christian Heimes5cb31c92012-09-20 12:42:54 +02003169 self->npn_protocols = NULL;
3170#endif
Christian Heimes29eab552018-02-25 12:31:33 +01003171#if HAVE_ALPN
Benjamin Petersoncca27322015-01-23 16:35:37 -05003172 self->alpn_protocols = NULL;
3173#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003174#ifndef OPENSSL_NO_TLSEXT
Christian Heimes11a14932018-02-24 02:35:08 +01003175 self->set_sni_cb = NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003176#endif
Christian Heimes1aa9a752013-12-02 02:41:19 +01003177 /* Don't check host name by default */
Christian Heimes5fe668c2016-09-12 00:01:11 +02003178 if (proto_version == PY_SSL_VERSION_TLS_CLIENT) {
3179 self->check_hostname = 1;
Christian Heimes9fb051f2018-09-23 08:32:31 +02003180 if (_set_verify_mode(self, PY_SSL_CERT_REQUIRED) == -1) {
Christian Heimes5fe668c2016-09-12 00:01:11 +02003181 Py_DECREF(self);
3182 return NULL;
3183 }
3184 } else {
3185 self->check_hostname = 0;
Christian Heimes9fb051f2018-09-23 08:32:31 +02003186 if (_set_verify_mode(self, PY_SSL_CERT_NONE) == -1) {
Christian Heimes5fe668c2016-09-12 00:01:11 +02003187 Py_DECREF(self);
3188 return NULL;
3189 }
3190 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003191 /* Defaults */
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01003192 options = SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
3193 if (proto_version != PY_SSL_VERSION_SSL2)
3194 options |= SSL_OP_NO_SSLv2;
Benjamin Petersona9dcdab2015-11-11 22:38:41 -08003195 if (proto_version != PY_SSL_VERSION_SSL3)
3196 options |= SSL_OP_NO_SSLv3;
Christian Heimes358cfd42016-09-10 22:43:48 +02003197 /* Minimal security flags for server and client side context.
3198 * Client sockets ignore server-side parameters. */
3199#ifdef SSL_OP_NO_COMPRESSION
3200 options |= SSL_OP_NO_COMPRESSION;
3201#endif
3202#ifdef SSL_OP_CIPHER_SERVER_PREFERENCE
3203 options |= SSL_OP_CIPHER_SERVER_PREFERENCE;
3204#endif
3205#ifdef SSL_OP_SINGLE_DH_USE
3206 options |= SSL_OP_SINGLE_DH_USE;
3207#endif
3208#ifdef SSL_OP_SINGLE_ECDH_USE
3209 options |= SSL_OP_SINGLE_ECDH_USE;
3210#endif
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01003211 SSL_CTX_set_options(self->ctx, options);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003212
Semen Zhydenko1295e112017-10-15 21:28:31 +02003213 /* A bare minimum cipher list without completely broken cipher suites.
Christian Heimes358cfd42016-09-10 22:43:48 +02003214 * It's far from perfect but gives users a better head start. */
3215 if (proto_version != PY_SSL_VERSION_SSL2) {
Christian Heimes892d66e2018-01-29 14:10:18 +01003216#if PY_SSL_DEFAULT_CIPHERS == 2
3217 /* stick to OpenSSL's default settings */
3218 result = 1;
3219#else
3220 result = SSL_CTX_set_cipher_list(ctx, PY_SSL_DEFAULT_CIPHER_STRING);
3221#endif
Christian Heimes358cfd42016-09-10 22:43:48 +02003222 } else {
3223 /* SSLv2 needs MD5 */
3224 result = SSL_CTX_set_cipher_list(ctx, "HIGH:!aNULL:!eNULL");
3225 }
3226 if (result == 0) {
3227 Py_DECREF(self);
3228 ERR_clear_error();
3229 PyErr_SetString(PySSLErrorObject,
3230 "No cipher can be selected.");
3231 return NULL;
3232 }
3233
Benjamin Peterson3b1a8b32016-01-07 21:37:37 -08003234#if defined(SSL_MODE_RELEASE_BUFFERS)
3235 /* Set SSL_MODE_RELEASE_BUFFERS. This potentially greatly reduces memory
3236 usage for no cost at all. However, don't do this for OpenSSL versions
3237 between 1.0.1 and 1.0.1h or 1.0.0 and 1.0.0m, which are affected by CVE
3238 2014-0198. I can't find exactly which beta fixed this CVE, so be
3239 conservative and assume it wasn't fixed until release. We do this check
3240 at runtime to avoid problems from the dynamic linker.
3241 See #25672 for more on this. */
Miss Islington (bot)9c0ff172020-06-01 00:17:16 -07003242 libver = OpenSSL_version_num();
Benjamin Peterson3b1a8b32016-01-07 21:37:37 -08003243 if (!(libver >= 0x10001000UL && libver < 0x1000108fUL) &&
3244 !(libver >= 0x10000000UL && libver < 0x100000dfUL)) {
3245 SSL_CTX_set_mode(self->ctx, SSL_MODE_RELEASE_BUFFERS);
3246 }
3247#endif
3248
3249
Donald Stufft8ae264c2017-03-02 11:45:29 -05003250#if !defined(OPENSSL_NO_ECDH) && !defined(OPENSSL_VERSION_1_1)
Antoine Pitrou0bebbc32014-03-22 18:13:50 +01003251 /* Allow automatic ECDH curve selection (on OpenSSL 1.0.2+), or use
3252 prime256v1 by default. This is Apache mod_ssl's initialization
Christian Heimes598894f2016-09-05 23:19:05 +02003253 policy, so we should be safe. OpenSSL 1.1 has it enabled by default.
3254 */
Donald Stufft8ae264c2017-03-02 11:45:29 -05003255#if defined(SSL_CTX_set_ecdh_auto)
Antoine Pitrou0bebbc32014-03-22 18:13:50 +01003256 SSL_CTX_set_ecdh_auto(self->ctx, 1);
3257#else
3258 {
3259 EC_KEY *key = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
3260 SSL_CTX_set_tmp_ecdh(self->ctx, key);
3261 EC_KEY_free(key);
3262 }
3263#endif
3264#endif
3265
Antoine Pitroufc113ee2010-10-13 12:46:13 +00003266#define SID_CTX "Python"
3267 SSL_CTX_set_session_id_context(self->ctx, (const unsigned char *) SID_CTX,
3268 sizeof(SID_CTX));
3269#undef SID_CTX
3270
Christian Heimes61d478c2018-01-27 15:51:38 +01003271 params = SSL_CTX_get0_param(self->ctx);
Benjamin Petersonfdb19712015-03-04 22:11:12 -05003272#ifdef X509_V_FLAG_TRUSTED_FIRST
Christian Heimes61d478c2018-01-27 15:51:38 +01003273 /* Improve trust chain building when cross-signed intermediate
3274 certificates are present. See https://bugs.python.org/issue23476. */
3275 X509_VERIFY_PARAM_set_flags(params, X509_V_FLAG_TRUSTED_FIRST);
Benjamin Petersonfdb19712015-03-04 22:11:12 -05003276#endif
Christian Heimes61d478c2018-01-27 15:51:38 +01003277 X509_VERIFY_PARAM_set_hostflags(params, self->hostflags);
Benjamin Petersonfdb19712015-03-04 22:11:12 -05003278
Christian Heimes9fb051f2018-09-23 08:32:31 +02003279#ifdef TLS1_3_VERSION
3280 self->post_handshake_auth = 0;
3281 SSL_CTX_set_post_handshake_auth(self->ctx, self->post_handshake_auth);
3282#endif
3283
Antoine Pitrou152efa22010-05-16 18:19:27 +00003284 return (PyObject *)self;
3285}
3286
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003287static int
3288context_traverse(PySSLContext *self, visitproc visit, void *arg)
3289{
3290#ifndef OPENSSL_NO_TLSEXT
Christian Heimes11a14932018-02-24 02:35:08 +01003291 Py_VISIT(self->set_sni_cb);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003292#endif
Christian Heimesc7f70692019-05-31 11:44:05 +02003293 Py_VISIT(self->msg_cb);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003294 return 0;
3295}
3296
3297static int
3298context_clear(PySSLContext *self)
3299{
3300#ifndef OPENSSL_NO_TLSEXT
Christian Heimes11a14932018-02-24 02:35:08 +01003301 Py_CLEAR(self->set_sni_cb);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003302#endif
Christian Heimesc7f70692019-05-31 11:44:05 +02003303 Py_CLEAR(self->msg_cb);
3304#ifdef HAVE_OPENSSL_KEYLOG
3305 Py_CLEAR(self->keylog_filename);
3306 if (self->keylog_bio != NULL) {
3307 PySSL_BEGIN_ALLOW_THREADS
3308 BIO_free_all(self->keylog_bio);
3309 PySSL_END_ALLOW_THREADS
3310 self->keylog_bio = NULL;
3311 }
3312#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003313 return 0;
3314}
3315
Antoine Pitrou152efa22010-05-16 18:19:27 +00003316static void
3317context_dealloc(PySSLContext *self)
3318{
INADA Naokia6296d32017-08-24 14:55:17 +09003319 /* bpo-31095: UnTrack is needed before calling any callbacks */
3320 PyObject_GC_UnTrack(self);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003321 context_clear(self);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003322 SSL_CTX_free(self->ctx);
Christian Heimes29eab552018-02-25 12:31:33 +01003323#if HAVE_NPN
Benjamin Petersoncca27322015-01-23 16:35:37 -05003324 PyMem_FREE(self->npn_protocols);
3325#endif
Christian Heimes29eab552018-02-25 12:31:33 +01003326#if HAVE_ALPN
Benjamin Petersoncca27322015-01-23 16:35:37 -05003327 PyMem_FREE(self->alpn_protocols);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003328#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00003329 Py_TYPE(self)->tp_free(self);
3330}
3331
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003332/*[clinic input]
3333_ssl._SSLContext.set_ciphers
3334 cipherlist: str
3335 /
3336[clinic start generated code]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003337
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003338static PyObject *
3339_ssl__SSLContext_set_ciphers_impl(PySSLContext *self, const char *cipherlist)
3340/*[clinic end generated code: output=3a3162f3557c0f3f input=a7ac931b9f3ca7fc]*/
3341{
3342 int ret = SSL_CTX_set_cipher_list(self->ctx, cipherlist);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003343 if (ret == 0) {
Antoine Pitrou65ec8ae2010-05-16 19:56:32 +00003344 /* Clearing the error queue is necessary on some OpenSSL versions,
3345 otherwise the error will be reported again when another SSL call
3346 is done. */
3347 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00003348 PyErr_SetString(PySSLErrorObject,
3349 "No cipher can be selected.");
3350 return NULL;
3351 }
3352 Py_RETURN_NONE;
3353}
3354
Christian Heimes25bfcd52016-09-06 00:04:45 +02003355#if OPENSSL_VERSION_NUMBER >= 0x10002000UL
3356/*[clinic input]
3357_ssl._SSLContext.get_ciphers
3358[clinic start generated code]*/
3359
3360static PyObject *
3361_ssl__SSLContext_get_ciphers_impl(PySSLContext *self)
3362/*[clinic end generated code: output=a56e4d68a406dfc4 input=a2aadc9af89b79c5]*/
3363{
3364 SSL *ssl = NULL;
3365 STACK_OF(SSL_CIPHER) *sk = NULL;
Christian Heimes99a65702016-09-10 23:44:53 +02003366 const SSL_CIPHER *cipher;
Christian Heimes25bfcd52016-09-06 00:04:45 +02003367 int i=0;
3368 PyObject *result = NULL, *dct;
3369
3370 ssl = SSL_new(self->ctx);
3371 if (ssl == NULL) {
3372 _setSSLError(NULL, 0, __FILE__, __LINE__);
3373 goto exit;
3374 }
3375 sk = SSL_get_ciphers(ssl);
3376
3377 result = PyList_New(sk_SSL_CIPHER_num(sk));
3378 if (result == NULL) {
3379 goto exit;
3380 }
3381
3382 for (i = 0; i < sk_SSL_CIPHER_num(sk); i++) {
3383 cipher = sk_SSL_CIPHER_value(sk, i);
3384 dct = cipher_to_dict(cipher);
3385 if (dct == NULL) {
3386 Py_CLEAR(result);
3387 goto exit;
3388 }
3389 PyList_SET_ITEM(result, i, dct);
3390 }
3391
3392 exit:
3393 if (ssl != NULL)
3394 SSL_free(ssl);
3395 return result;
3396
3397}
3398#endif
3399
3400
Christian Heimes29eab552018-02-25 12:31:33 +01003401#if HAVE_NPN || HAVE_ALPN
Benjamin Petersoncca27322015-01-23 16:35:37 -05003402static int
Benjamin Peterson88615022015-01-23 17:30:26 -05003403do_protocol_selection(int alpn, unsigned char **out, unsigned char *outlen,
3404 const unsigned char *server_protocols, unsigned int server_protocols_len,
3405 const unsigned char *client_protocols, unsigned int client_protocols_len)
Benjamin Petersoncca27322015-01-23 16:35:37 -05003406{
Benjamin Peterson88615022015-01-23 17:30:26 -05003407 int ret;
3408 if (client_protocols == NULL) {
3409 client_protocols = (unsigned char *)"";
3410 client_protocols_len = 0;
3411 }
3412 if (server_protocols == NULL) {
3413 server_protocols = (unsigned char *)"";
3414 server_protocols_len = 0;
Benjamin Petersoncca27322015-01-23 16:35:37 -05003415 }
3416
Benjamin Peterson88615022015-01-23 17:30:26 -05003417 ret = SSL_select_next_proto(out, outlen,
3418 server_protocols, server_protocols_len,
3419 client_protocols, client_protocols_len);
3420 if (alpn && ret != OPENSSL_NPN_NEGOTIATED)
3421 return SSL_TLSEXT_ERR_NOACK;
Benjamin Petersoncca27322015-01-23 16:35:37 -05003422
3423 return SSL_TLSEXT_ERR_OK;
3424}
Melvyn Sopacuab2d096b2017-09-04 23:35:15 +02003425#endif
Benjamin Petersoncca27322015-01-23 16:35:37 -05003426
Christian Heimes29eab552018-02-25 12:31:33 +01003427#if HAVE_NPN
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003428/* this callback gets passed to SSL_CTX_set_next_protos_advertise_cb */
3429static int
Victor Stinner4569cd52013-06-23 14:58:43 +02003430_advertiseNPN_cb(SSL *s,
3431 const unsigned char **data, unsigned int *len,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003432 void *args)
3433{
3434 PySSLContext *ssl_ctx = (PySSLContext *) args;
3435
3436 if (ssl_ctx->npn_protocols == NULL) {
Benjamin Petersoncca27322015-01-23 16:35:37 -05003437 *data = (unsigned char *)"";
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003438 *len = 0;
3439 } else {
Benjamin Petersoncca27322015-01-23 16:35:37 -05003440 *data = ssl_ctx->npn_protocols;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003441 *len = ssl_ctx->npn_protocols_len;
3442 }
3443
3444 return SSL_TLSEXT_ERR_OK;
3445}
3446/* this callback gets passed to SSL_CTX_set_next_proto_select_cb */
3447static int
Victor Stinner4569cd52013-06-23 14:58:43 +02003448_selectNPN_cb(SSL *s,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003449 unsigned char **out, unsigned char *outlen,
3450 const unsigned char *server, unsigned int server_len,
3451 void *args)
3452{
Benjamin Petersoncca27322015-01-23 16:35:37 -05003453 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Peterson88615022015-01-23 17:30:26 -05003454 return do_protocol_selection(0, out, outlen, server, server_len,
Benjamin Petersoncca27322015-01-23 16:35:37 -05003455 ctx->npn_protocols, ctx->npn_protocols_len);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003456}
3457#endif
3458
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003459/*[clinic input]
3460_ssl._SSLContext._set_npn_protocols
3461 protos: Py_buffer
3462 /
3463[clinic start generated code]*/
3464
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003465static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003466_ssl__SSLContext__set_npn_protocols_impl(PySSLContext *self,
3467 Py_buffer *protos)
3468/*[clinic end generated code: output=72b002c3324390c6 input=319fcb66abf95bd7]*/
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003469{
Christian Heimes29eab552018-02-25 12:31:33 +01003470#if HAVE_NPN
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003471 PyMem_Free(self->npn_protocols);
3472 self->npn_protocols = PyMem_Malloc(protos->len);
3473 if (self->npn_protocols == NULL)
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003474 return PyErr_NoMemory();
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003475 memcpy(self->npn_protocols, protos->buf, protos->len);
3476 self->npn_protocols_len = (int) protos->len;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003477
3478 /* set both server and client callbacks, because the context can
3479 * be used to create both types of sockets */
3480 SSL_CTX_set_next_protos_advertised_cb(self->ctx,
3481 _advertiseNPN_cb,
3482 self);
3483 SSL_CTX_set_next_proto_select_cb(self->ctx,
3484 _selectNPN_cb,
3485 self);
3486
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003487 Py_RETURN_NONE;
3488#else
3489 PyErr_SetString(PyExc_NotImplementedError,
3490 "The NPN extension requires OpenSSL 1.0.1 or later.");
3491 return NULL;
3492#endif
3493}
3494
Christian Heimes29eab552018-02-25 12:31:33 +01003495#if HAVE_ALPN
Benjamin Petersoncca27322015-01-23 16:35:37 -05003496static int
3497_selectALPN_cb(SSL *s,
3498 const unsigned char **out, unsigned char *outlen,
3499 const unsigned char *client_protocols, unsigned int client_protocols_len,
3500 void *args)
3501{
3502 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Peterson88615022015-01-23 17:30:26 -05003503 return do_protocol_selection(1, (unsigned char **)out, outlen,
3504 ctx->alpn_protocols, ctx->alpn_protocols_len,
3505 client_protocols, client_protocols_len);
Benjamin Petersoncca27322015-01-23 16:35:37 -05003506}
3507#endif
3508
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003509/*[clinic input]
3510_ssl._SSLContext._set_alpn_protocols
3511 protos: Py_buffer
3512 /
3513[clinic start generated code]*/
3514
Benjamin Petersoncca27322015-01-23 16:35:37 -05003515static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003516_ssl__SSLContext__set_alpn_protocols_impl(PySSLContext *self,
3517 Py_buffer *protos)
3518/*[clinic end generated code: output=87599a7f76651a9b input=9bba964595d519be]*/
Benjamin Petersoncca27322015-01-23 16:35:37 -05003519{
Christian Heimes29eab552018-02-25 12:31:33 +01003520#if HAVE_ALPN
Victor Stinner5a615592017-09-14 01:10:30 -07003521 if ((size_t)protos->len > UINT_MAX) {
Segev Finer5cff6372017-07-27 01:19:17 +03003522 PyErr_Format(PyExc_OverflowError,
Serhiy Storchakad53fe5f2019-03-13 22:59:55 +02003523 "protocols longer than %u bytes", UINT_MAX);
Segev Finer5cff6372017-07-27 01:19:17 +03003524 return NULL;
3525 }
3526
Benjamin Petersoncca27322015-01-23 16:35:37 -05003527 PyMem_FREE(self->alpn_protocols);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003528 self->alpn_protocols = PyMem_Malloc(protos->len);
Benjamin Petersoncca27322015-01-23 16:35:37 -05003529 if (!self->alpn_protocols)
3530 return PyErr_NoMemory();
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003531 memcpy(self->alpn_protocols, protos->buf, protos->len);
Segev Finer5cff6372017-07-27 01:19:17 +03003532 self->alpn_protocols_len = (unsigned int)protos->len;
Benjamin Petersoncca27322015-01-23 16:35:37 -05003533
3534 if (SSL_CTX_set_alpn_protos(self->ctx, self->alpn_protocols, self->alpn_protocols_len))
3535 return PyErr_NoMemory();
3536 SSL_CTX_set_alpn_select_cb(self->ctx, _selectALPN_cb, self);
3537
Benjamin Petersoncca27322015-01-23 16:35:37 -05003538 Py_RETURN_NONE;
3539#else
3540 PyErr_SetString(PyExc_NotImplementedError,
3541 "The ALPN extension requires OpenSSL 1.0.2 or later.");
3542 return NULL;
3543#endif
3544}
3545
Antoine Pitrou152efa22010-05-16 18:19:27 +00003546static PyObject *
3547get_verify_mode(PySSLContext *self, void *c)
3548{
Christian Heimes9fb051f2018-09-23 08:32:31 +02003549 /* ignore SSL_VERIFY_CLIENT_ONCE and SSL_VERIFY_POST_HANDSHAKE */
3550 int mask = (SSL_VERIFY_NONE | SSL_VERIFY_PEER |
3551 SSL_VERIFY_FAIL_IF_NO_PEER_CERT);
3552 switch (SSL_CTX_get_verify_mode(self->ctx) & mask) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003553 case SSL_VERIFY_NONE:
3554 return PyLong_FromLong(PY_SSL_CERT_NONE);
3555 case SSL_VERIFY_PEER:
3556 return PyLong_FromLong(PY_SSL_CERT_OPTIONAL);
3557 case SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT:
3558 return PyLong_FromLong(PY_SSL_CERT_REQUIRED);
3559 }
3560 PyErr_SetString(PySSLErrorObject,
3561 "invalid return value from SSL_CTX_get_verify_mode");
3562 return NULL;
3563}
3564
3565static int
3566set_verify_mode(PySSLContext *self, PyObject *arg, void *c)
3567{
Christian Heimes5fe668c2016-09-12 00:01:11 +02003568 int n;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003569 if (!PyArg_Parse(arg, "i", &n))
3570 return -1;
Christian Heimes5fe668c2016-09-12 00:01:11 +02003571 if (n == PY_SSL_CERT_NONE && self->check_hostname) {
Christian Heimes1aa9a752013-12-02 02:41:19 +01003572 PyErr_SetString(PyExc_ValueError,
3573 "Cannot set verify_mode to CERT_NONE when "
3574 "check_hostname is enabled.");
3575 return -1;
3576 }
Christian Heimes9fb051f2018-09-23 08:32:31 +02003577 return _set_verify_mode(self, n);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003578}
3579
3580static PyObject *
Christian Heimes22587792013-11-21 23:56:13 +01003581get_verify_flags(PySSLContext *self, void *c)
3582{
Christian Heimes598894f2016-09-05 23:19:05 +02003583 X509_VERIFY_PARAM *param;
Christian Heimes22587792013-11-21 23:56:13 +01003584 unsigned long flags;
3585
Christian Heimes61d478c2018-01-27 15:51:38 +01003586 param = SSL_CTX_get0_param(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02003587 flags = X509_VERIFY_PARAM_get_flags(param);
Christian Heimes22587792013-11-21 23:56:13 +01003588 return PyLong_FromUnsignedLong(flags);
3589}
3590
3591static int
3592set_verify_flags(PySSLContext *self, PyObject *arg, void *c)
3593{
Christian Heimes598894f2016-09-05 23:19:05 +02003594 X509_VERIFY_PARAM *param;
Christian Heimes22587792013-11-21 23:56:13 +01003595 unsigned long new_flags, flags, set, clear;
3596
3597 if (!PyArg_Parse(arg, "k", &new_flags))
3598 return -1;
Christian Heimes61d478c2018-01-27 15:51:38 +01003599 param = SSL_CTX_get0_param(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02003600 flags = X509_VERIFY_PARAM_get_flags(param);
Christian Heimes22587792013-11-21 23:56:13 +01003601 clear = flags & ~new_flags;
3602 set = ~flags & new_flags;
3603 if (clear) {
Christian Heimes598894f2016-09-05 23:19:05 +02003604 if (!X509_VERIFY_PARAM_clear_flags(param, clear)) {
Christian Heimes22587792013-11-21 23:56:13 +01003605 _setSSLError(NULL, 0, __FILE__, __LINE__);
3606 return -1;
3607 }
3608 }
3609 if (set) {
Christian Heimes598894f2016-09-05 23:19:05 +02003610 if (!X509_VERIFY_PARAM_set_flags(param, set)) {
Christian Heimes22587792013-11-21 23:56:13 +01003611 _setSSLError(NULL, 0, __FILE__, __LINE__);
3612 return -1;
3613 }
3614 }
3615 return 0;
3616}
3617
Christian Heimes698dde12018-02-27 11:54:43 +01003618/* Getter and setter for protocol version */
3619#if defined(SSL_CTRL_GET_MAX_PROTO_VERSION)
3620
3621
3622static int
3623set_min_max_proto_version(PySSLContext *self, PyObject *arg, int what)
3624{
3625 long v;
3626 int result;
3627
3628 if (!PyArg_Parse(arg, "l", &v))
3629 return -1;
3630 if (v > INT_MAX) {
3631 PyErr_SetString(PyExc_OverflowError, "Option is too long");
3632 return -1;
3633 }
3634
3635 switch(self->protocol) {
3636 case PY_SSL_VERSION_TLS_CLIENT: /* fall through */
3637 case PY_SSL_VERSION_TLS_SERVER: /* fall through */
3638 case PY_SSL_VERSION_TLS:
3639 break;
3640 default:
3641 PyErr_SetString(
3642 PyExc_ValueError,
3643 "The context's protocol doesn't support modification of "
3644 "highest and lowest version."
3645 );
3646 return -1;
3647 }
3648
3649 if (what == 0) {
3650 switch(v) {
3651 case PY_PROTO_MINIMUM_SUPPORTED:
3652 v = 0;
3653 break;
3654 case PY_PROTO_MAXIMUM_SUPPORTED:
3655 /* Emulate max for set_min_proto_version */
3656 v = PY_PROTO_MAXIMUM_AVAILABLE;
3657 break;
3658 default:
3659 break;
3660 }
3661 result = SSL_CTX_set_min_proto_version(self->ctx, v);
3662 }
3663 else {
3664 switch(v) {
3665 case PY_PROTO_MAXIMUM_SUPPORTED:
3666 v = 0;
3667 break;
3668 case PY_PROTO_MINIMUM_SUPPORTED:
3669 /* Emulate max for set_min_proto_version */
3670 v = PY_PROTO_MINIMUM_AVAILABLE;
3671 break;
3672 default:
3673 break;
3674 }
3675 result = SSL_CTX_set_max_proto_version(self->ctx, v);
3676 }
3677 if (result == 0) {
3678 PyErr_Format(PyExc_ValueError,
3679 "Unsupported protocol version 0x%x", v);
3680 return -1;
3681 }
3682 return 0;
3683}
3684
3685static PyObject *
3686get_minimum_version(PySSLContext *self, void *c)
3687{
3688 int v = SSL_CTX_ctrl(self->ctx, SSL_CTRL_GET_MIN_PROTO_VERSION, 0, NULL);
3689 if (v == 0) {
3690 v = PY_PROTO_MINIMUM_SUPPORTED;
3691 }
3692 return PyLong_FromLong(v);
3693}
3694
3695static int
3696set_minimum_version(PySSLContext *self, PyObject *arg, void *c)
3697{
3698 return set_min_max_proto_version(self, arg, 0);
3699}
3700
3701static PyObject *
3702get_maximum_version(PySSLContext *self, void *c)
3703{
3704 int v = SSL_CTX_ctrl(self->ctx, SSL_CTRL_GET_MAX_PROTO_VERSION, 0, NULL);
3705 if (v == 0) {
3706 v = PY_PROTO_MAXIMUM_SUPPORTED;
3707 }
3708 return PyLong_FromLong(v);
3709}
3710
3711static int
3712set_maximum_version(PySSLContext *self, PyObject *arg, void *c)
3713{
3714 return set_min_max_proto_version(self, arg, 1);
3715}
3716#endif /* SSL_CTRL_GET_MAX_PROTO_VERSION */
3717
Christian Heimes78c7d522019-06-03 21:00:10 +02003718#if (OPENSSL_VERSION_NUMBER >= 0x10101000L) && !defined(LIBRESSL_VERSION_NUMBER)
3719static PyObject *
3720get_num_tickets(PySSLContext *self, void *c)
3721{
Miss Islington (bot)bbad6952019-07-09 05:42:49 -07003722 return PyLong_FromSize_t(SSL_CTX_get_num_tickets(self->ctx));
Christian Heimes78c7d522019-06-03 21:00:10 +02003723}
3724
3725static int
3726set_num_tickets(PySSLContext *self, PyObject *arg, void *c)
3727{
3728 long num;
3729 if (!PyArg_Parse(arg, "l", &num))
3730 return -1;
3731 if (num < 0) {
3732 PyErr_SetString(PyExc_ValueError, "value must be non-negative");
3733 return -1;
3734 }
3735 if (self->protocol != PY_SSL_VERSION_TLS_SERVER) {
3736 PyErr_SetString(PyExc_ValueError,
3737 "SSLContext is not a server context.");
3738 return -1;
3739 }
3740 if (SSL_CTX_set_num_tickets(self->ctx, num) != 1) {
3741 PyErr_SetString(PyExc_ValueError, "failed to set num tickets.");
3742 return -1;
3743 }
3744 return 0;
3745}
3746
3747PyDoc_STRVAR(PySSLContext_num_tickets_doc,
3748"Control the number of TLSv1.3 session tickets");
3749#endif /* OpenSSL 1.1.1 */
3750
Christian Heimes22587792013-11-21 23:56:13 +01003751static PyObject *
Antoine Pitroub5218772010-05-21 09:56:06 +00003752get_options(PySSLContext *self, void *c)
3753{
3754 return PyLong_FromLong(SSL_CTX_get_options(self->ctx));
3755}
3756
3757static int
3758set_options(PySSLContext *self, PyObject *arg, void *c)
3759{
3760 long new_opts, opts, set, clear;
3761 if (!PyArg_Parse(arg, "l", &new_opts))
3762 return -1;
3763 opts = SSL_CTX_get_options(self->ctx);
3764 clear = opts & ~new_opts;
3765 set = ~opts & new_opts;
3766 if (clear) {
3767#ifdef HAVE_SSL_CTX_CLEAR_OPTIONS
3768 SSL_CTX_clear_options(self->ctx, clear);
3769#else
3770 PyErr_SetString(PyExc_ValueError,
3771 "can't clear options before OpenSSL 0.9.8m");
3772 return -1;
3773#endif
3774 }
3775 if (set)
3776 SSL_CTX_set_options(self->ctx, set);
3777 return 0;
3778}
3779
Christian Heimes1aa9a752013-12-02 02:41:19 +01003780static PyObject *
Christian Heimes61d478c2018-01-27 15:51:38 +01003781get_host_flags(PySSLContext *self, void *c)
3782{
3783 return PyLong_FromUnsignedLong(self->hostflags);
3784}
3785
3786static int
3787set_host_flags(PySSLContext *self, PyObject *arg, void *c)
3788{
3789 X509_VERIFY_PARAM *param;
3790 unsigned int new_flags = 0;
3791
3792 if (!PyArg_Parse(arg, "I", &new_flags))
3793 return -1;
3794
3795 param = SSL_CTX_get0_param(self->ctx);
3796 self->hostflags = new_flags;
3797 X509_VERIFY_PARAM_set_hostflags(param, new_flags);
3798 return 0;
3799}
3800
3801static PyObject *
Christian Heimes1aa9a752013-12-02 02:41:19 +01003802get_check_hostname(PySSLContext *self, void *c)
3803{
3804 return PyBool_FromLong(self->check_hostname);
3805}
3806
3807static int
3808set_check_hostname(PySSLContext *self, PyObject *arg, void *c)
3809{
3810 int check_hostname;
3811 if (!PyArg_Parse(arg, "p", &check_hostname))
3812 return -1;
3813 if (check_hostname &&
3814 SSL_CTX_get_verify_mode(self->ctx) == SSL_VERIFY_NONE) {
Christian Heimese82c0342017-09-15 20:29:57 +02003815 /* check_hostname = True sets verify_mode = CERT_REQUIRED */
Christian Heimes9fb051f2018-09-23 08:32:31 +02003816 if (_set_verify_mode(self, PY_SSL_CERT_REQUIRED) == -1) {
Christian Heimese82c0342017-09-15 20:29:57 +02003817 return -1;
3818 }
Christian Heimes1aa9a752013-12-02 02:41:19 +01003819 }
3820 self->check_hostname = check_hostname;
3821 return 0;
3822}
3823
Christian Heimes11a14932018-02-24 02:35:08 +01003824static PyObject *
Christian Heimes9fb051f2018-09-23 08:32:31 +02003825get_post_handshake_auth(PySSLContext *self, void *c) {
3826#if TLS1_3_VERSION
3827 return PyBool_FromLong(self->post_handshake_auth);
3828#else
3829 Py_RETURN_NONE;
3830#endif
3831}
3832
3833#if TLS1_3_VERSION
3834static int
3835set_post_handshake_auth(PySSLContext *self, PyObject *arg, void *c) {
Zackery Spytz842acaa2018-12-17 07:52:45 -07003836 if (arg == NULL) {
3837 PyErr_SetString(PyExc_AttributeError, "cannot delete attribute");
3838 return -1;
3839 }
Christian Heimes9fb051f2018-09-23 08:32:31 +02003840 int pha = PyObject_IsTrue(arg);
3841
3842 if (pha == -1) {
3843 return -1;
3844 }
3845 self->post_handshake_auth = pha;
3846
Christian Heimesf22c4cf2019-07-01 09:25:48 +02003847 /* bpo-37428: newPySSLSocket() sets SSL_VERIFY_POST_HANDSHAKE flag for
3848 * server sockets and SSL_set_post_handshake_auth() for client. */
Christian Heimes9fb051f2018-09-23 08:32:31 +02003849
3850 return 0;
3851}
3852#endif
3853
3854static PyObject *
Christian Heimes11a14932018-02-24 02:35:08 +01003855get_protocol(PySSLContext *self, void *c) {
3856 return PyLong_FromLong(self->protocol);
3857}
Christian Heimes1aa9a752013-12-02 02:41:19 +01003858
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003859typedef struct {
3860 PyThreadState *thread_state;
3861 PyObject *callable;
3862 char *password;
Victor Stinner9ee02032013-06-23 15:08:23 +02003863 int size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003864 int error;
3865} _PySSLPasswordInfo;
3866
3867static int
3868_pwinfo_set(_PySSLPasswordInfo *pw_info, PyObject* password,
3869 const char *bad_type_error)
3870{
3871 /* Set the password and size fields of a _PySSLPasswordInfo struct
3872 from a unicode, bytes, or byte array object.
3873 The password field will be dynamically allocated and must be freed
3874 by the caller */
3875 PyObject *password_bytes = NULL;
3876 const char *data = NULL;
3877 Py_ssize_t size;
3878
3879 if (PyUnicode_Check(password)) {
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03003880 password_bytes = PyUnicode_AsUTF8String(password);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003881 if (!password_bytes) {
3882 goto error;
3883 }
3884 data = PyBytes_AS_STRING(password_bytes);
3885 size = PyBytes_GET_SIZE(password_bytes);
3886 } else if (PyBytes_Check(password)) {
3887 data = PyBytes_AS_STRING(password);
3888 size = PyBytes_GET_SIZE(password);
3889 } else if (PyByteArray_Check(password)) {
3890 data = PyByteArray_AS_STRING(password);
3891 size = PyByteArray_GET_SIZE(password);
3892 } else {
3893 PyErr_SetString(PyExc_TypeError, bad_type_error);
3894 goto error;
3895 }
3896
Victor Stinner9ee02032013-06-23 15:08:23 +02003897 if (size > (Py_ssize_t)INT_MAX) {
3898 PyErr_Format(PyExc_ValueError,
3899 "password cannot be longer than %d bytes", INT_MAX);
3900 goto error;
3901 }
3902
Victor Stinner11ebff22013-07-07 17:07:52 +02003903 PyMem_Free(pw_info->password);
3904 pw_info->password = PyMem_Malloc(size);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003905 if (!pw_info->password) {
3906 PyErr_SetString(PyExc_MemoryError,
3907 "unable to allocate password buffer");
3908 goto error;
3909 }
3910 memcpy(pw_info->password, data, size);
Victor Stinner9ee02032013-06-23 15:08:23 +02003911 pw_info->size = (int)size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003912
3913 Py_XDECREF(password_bytes);
3914 return 1;
3915
3916error:
3917 Py_XDECREF(password_bytes);
3918 return 0;
3919}
3920
3921static int
3922_password_callback(char *buf, int size, int rwflag, void *userdata)
3923{
3924 _PySSLPasswordInfo *pw_info = (_PySSLPasswordInfo*) userdata;
3925 PyObject *fn_ret = NULL;
3926
3927 PySSL_END_ALLOW_THREADS_S(pw_info->thread_state);
3928
3929 if (pw_info->callable) {
Victor Stinnerf17c3de2016-12-06 18:46:19 +01003930 fn_ret = _PyObject_CallNoArg(pw_info->callable);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003931 if (!fn_ret) {
3932 /* TODO: It would be nice to move _ctypes_add_traceback() into the
3933 core python API, so we could use it to add a frame here */
3934 goto error;
3935 }
3936
3937 if (!_pwinfo_set(pw_info, fn_ret,
3938 "password callback must return a string")) {
3939 goto error;
3940 }
3941 Py_CLEAR(fn_ret);
3942 }
3943
3944 if (pw_info->size > size) {
3945 PyErr_Format(PyExc_ValueError,
3946 "password cannot be longer than %d bytes", size);
3947 goto error;
3948 }
3949
3950 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
3951 memcpy(buf, pw_info->password, pw_info->size);
3952 return pw_info->size;
3953
3954error:
3955 Py_XDECREF(fn_ret);
3956 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
3957 pw_info->error = 1;
3958 return -1;
3959}
3960
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003961/*[clinic input]
3962_ssl._SSLContext.load_cert_chain
3963 certfile: object
Serhiy Storchakad322abb2019-09-14 13:31:50 +03003964 keyfile: object = None
3965 password: object = None
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003966
3967[clinic start generated code]*/
3968
Antoine Pitroub5218772010-05-21 09:56:06 +00003969static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003970_ssl__SSLContext_load_cert_chain_impl(PySSLContext *self, PyObject *certfile,
3971 PyObject *keyfile, PyObject *password)
Serhiy Storchakad322abb2019-09-14 13:31:50 +03003972/*[clinic end generated code: output=9480bc1c380e2095 input=30bc7e967ea01a58]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003973{
Antoine Pitrou152efa22010-05-16 18:19:27 +00003974 PyObject *certfile_bytes = NULL, *keyfile_bytes = NULL;
Christian Heimes598894f2016-09-05 23:19:05 +02003975 pem_password_cb *orig_passwd_cb = SSL_CTX_get_default_passwd_cb(self->ctx);
3976 void *orig_passwd_userdata = SSL_CTX_get_default_passwd_cb_userdata(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003977 _PySSLPasswordInfo pw_info = { NULL, NULL, NULL, 0, 0 };
Antoine Pitrou152efa22010-05-16 18:19:27 +00003978 int r;
3979
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003980 errno = 0;
Antoine Pitrou67e8e562010-09-01 20:55:41 +00003981 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00003982 if (keyfile == Py_None)
3983 keyfile = NULL;
3984 if (!PyUnicode_FSConverter(certfile, &certfile_bytes)) {
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03003985 if (PyErr_ExceptionMatches(PyExc_TypeError)) {
3986 PyErr_SetString(PyExc_TypeError,
3987 "certfile should be a valid filesystem path");
3988 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003989 return NULL;
3990 }
3991 if (keyfile && !PyUnicode_FSConverter(keyfile, &keyfile_bytes)) {
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03003992 if (PyErr_ExceptionMatches(PyExc_TypeError)) {
3993 PyErr_SetString(PyExc_TypeError,
3994 "keyfile should be a valid filesystem path");
3995 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003996 goto error;
3997 }
Serhiy Storchakad322abb2019-09-14 13:31:50 +03003998 if (password != Py_None) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003999 if (PyCallable_Check(password)) {
4000 pw_info.callable = password;
4001 } else if (!_pwinfo_set(&pw_info, password,
4002 "password should be a string or callable")) {
4003 goto error;
4004 }
4005 SSL_CTX_set_default_passwd_cb(self->ctx, _password_callback);
4006 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, &pw_info);
4007 }
4008 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00004009 r = SSL_CTX_use_certificate_chain_file(self->ctx,
4010 PyBytes_AS_STRING(certfile_bytes));
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02004011 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00004012 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02004013 if (pw_info.error) {
4014 ERR_clear_error();
4015 /* the password callback has already set the error information */
4016 }
4017 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00004018 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03004019 PyErr_SetFromErrno(PyExc_OSError);
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00004020 }
4021 else {
4022 _setSSLError(NULL, 0, __FILE__, __LINE__);
4023 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00004024 goto error;
4025 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02004026 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou9c254862011-04-03 18:15:34 +02004027 r = SSL_CTX_use_PrivateKey_file(self->ctx,
Antoine Pitrou152efa22010-05-16 18:19:27 +00004028 PyBytes_AS_STRING(keyfile ? keyfile_bytes : certfile_bytes),
4029 SSL_FILETYPE_PEM);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02004030 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
4031 Py_CLEAR(keyfile_bytes);
4032 Py_CLEAR(certfile_bytes);
Antoine Pitrou152efa22010-05-16 18:19:27 +00004033 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02004034 if (pw_info.error) {
4035 ERR_clear_error();
4036 /* the password callback has already set the error information */
4037 }
4038 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00004039 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03004040 PyErr_SetFromErrno(PyExc_OSError);
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00004041 }
4042 else {
4043 _setSSLError(NULL, 0, __FILE__, __LINE__);
4044 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02004045 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004046 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02004047 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00004048 r = SSL_CTX_check_private_key(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02004049 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00004050 if (r != 1) {
4051 _setSSLError(NULL, 0, __FILE__, __LINE__);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02004052 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004053 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02004054 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
4055 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02004056 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00004057 Py_RETURN_NONE;
4058
4059error:
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02004060 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
4061 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02004062 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00004063 Py_XDECREF(keyfile_bytes);
4064 Py_XDECREF(certfile_bytes);
4065 return NULL;
4066}
4067
Christian Heimesefff7062013-11-21 03:35:02 +01004068/* internal helper function, returns -1 on error
4069 */
4070static int
4071_add_ca_certs(PySSLContext *self, void *data, Py_ssize_t len,
4072 int filetype)
4073{
4074 BIO *biobuf = NULL;
4075 X509_STORE *store;
4076 int retval = 0, err, loaded = 0;
4077
4078 assert(filetype == SSL_FILETYPE_ASN1 || filetype == SSL_FILETYPE_PEM);
4079
4080 if (len <= 0) {
4081 PyErr_SetString(PyExc_ValueError,
4082 "Empty certificate data");
4083 return -1;
4084 } else if (len > INT_MAX) {
4085 PyErr_SetString(PyExc_OverflowError,
4086 "Certificate data is too long.");
4087 return -1;
4088 }
4089
Christian Heimes1dbf61f2013-11-22 00:34:18 +01004090 biobuf = BIO_new_mem_buf(data, (int)len);
Christian Heimesefff7062013-11-21 03:35:02 +01004091 if (biobuf == NULL) {
4092 _setSSLError("Can't allocate buffer", 0, __FILE__, __LINE__);
4093 return -1;
4094 }
4095
4096 store = SSL_CTX_get_cert_store(self->ctx);
4097 assert(store != NULL);
4098
4099 while (1) {
4100 X509 *cert = NULL;
4101 int r;
4102
4103 if (filetype == SSL_FILETYPE_ASN1) {
4104 cert = d2i_X509_bio(biobuf, NULL);
4105 } else {
4106 cert = PEM_read_bio_X509(biobuf, NULL,
Christian Heimes598894f2016-09-05 23:19:05 +02004107 SSL_CTX_get_default_passwd_cb(self->ctx),
4108 SSL_CTX_get_default_passwd_cb_userdata(self->ctx)
4109 );
Christian Heimesefff7062013-11-21 03:35:02 +01004110 }
4111 if (cert == NULL) {
4112 break;
4113 }
4114 r = X509_STORE_add_cert(store, cert);
4115 X509_free(cert);
4116 if (!r) {
4117 err = ERR_peek_last_error();
4118 if ((ERR_GET_LIB(err) == ERR_LIB_X509) &&
4119 (ERR_GET_REASON(err) == X509_R_CERT_ALREADY_IN_HASH_TABLE)) {
4120 /* cert already in hash table, not an error */
4121 ERR_clear_error();
4122 } else {
4123 break;
4124 }
4125 }
4126 loaded++;
4127 }
4128
4129 err = ERR_peek_last_error();
4130 if ((filetype == SSL_FILETYPE_ASN1) &&
4131 (loaded > 0) &&
4132 (ERR_GET_LIB(err) == ERR_LIB_ASN1) &&
4133 (ERR_GET_REASON(err) == ASN1_R_HEADER_TOO_LONG)) {
4134 /* EOF ASN1 file, not an error */
4135 ERR_clear_error();
4136 retval = 0;
4137 } else if ((filetype == SSL_FILETYPE_PEM) &&
4138 (loaded > 0) &&
4139 (ERR_GET_LIB(err) == ERR_LIB_PEM) &&
4140 (ERR_GET_REASON(err) == PEM_R_NO_START_LINE)) {
4141 /* EOF PEM file, not an error */
4142 ERR_clear_error();
4143 retval = 0;
4144 } else {
4145 _setSSLError(NULL, 0, __FILE__, __LINE__);
4146 retval = -1;
4147 }
4148
4149 BIO_free(biobuf);
4150 return retval;
4151}
4152
4153
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004154/*[clinic input]
4155_ssl._SSLContext.load_verify_locations
Serhiy Storchakad322abb2019-09-14 13:31:50 +03004156 cafile: object = None
4157 capath: object = None
4158 cadata: object = None
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004159
4160[clinic start generated code]*/
4161
Antoine Pitrou152efa22010-05-16 18:19:27 +00004162static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004163_ssl__SSLContext_load_verify_locations_impl(PySSLContext *self,
4164 PyObject *cafile,
4165 PyObject *capath,
4166 PyObject *cadata)
Serhiy Storchakad322abb2019-09-14 13:31:50 +03004167/*[clinic end generated code: output=454c7e41230ca551 input=42ecfe258233e194]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004168{
Antoine Pitrou152efa22010-05-16 18:19:27 +00004169 PyObject *cafile_bytes = NULL, *capath_bytes = NULL;
4170 const char *cafile_buf = NULL, *capath_buf = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01004171 int r = 0, ok = 1;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004172
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00004173 errno = 0;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004174 if (cafile == Py_None)
4175 cafile = NULL;
4176 if (capath == Py_None)
4177 capath = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01004178 if (cadata == Py_None)
4179 cadata = NULL;
4180
4181 if (cafile == NULL && capath == NULL && cadata == NULL) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00004182 PyErr_SetString(PyExc_TypeError,
Christian Heimesefff7062013-11-21 03:35:02 +01004183 "cafile, capath and cadata cannot be all omitted");
4184 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004185 }
4186 if (cafile && !PyUnicode_FSConverter(cafile, &cafile_bytes)) {
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03004187 if (PyErr_ExceptionMatches(PyExc_TypeError)) {
4188 PyErr_SetString(PyExc_TypeError,
4189 "cafile should be a valid filesystem path");
4190 }
Christian Heimesefff7062013-11-21 03:35:02 +01004191 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004192 }
4193 if (capath && !PyUnicode_FSConverter(capath, &capath_bytes)) {
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03004194 if (PyErr_ExceptionMatches(PyExc_TypeError)) {
4195 PyErr_SetString(PyExc_TypeError,
4196 "capath should be a valid filesystem path");
4197 }
Christian Heimesefff7062013-11-21 03:35:02 +01004198 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004199 }
Christian Heimesefff7062013-11-21 03:35:02 +01004200
4201 /* validata cadata type and load cadata */
4202 if (cadata) {
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03004203 if (PyUnicode_Check(cadata)) {
4204 PyObject *cadata_ascii = PyUnicode_AsASCIIString(cadata);
4205 if (cadata_ascii == NULL) {
4206 if (PyErr_ExceptionMatches(PyExc_UnicodeEncodeError)) {
4207 goto invalid_cadata;
4208 }
4209 goto error;
4210 }
4211 r = _add_ca_certs(self,
4212 PyBytes_AS_STRING(cadata_ascii),
4213 PyBytes_GET_SIZE(cadata_ascii),
4214 SSL_FILETYPE_PEM);
4215 Py_DECREF(cadata_ascii);
4216 if (r == -1) {
4217 goto error;
4218 }
4219 }
4220 else if (PyObject_CheckBuffer(cadata)) {
4221 Py_buffer buf;
4222 if (PyObject_GetBuffer(cadata, &buf, PyBUF_SIMPLE)) {
4223 goto error;
4224 }
Christian Heimesefff7062013-11-21 03:35:02 +01004225 if (!PyBuffer_IsContiguous(&buf, 'C') || buf.ndim > 1) {
4226 PyBuffer_Release(&buf);
4227 PyErr_SetString(PyExc_TypeError,
4228 "cadata should be a contiguous buffer with "
4229 "a single dimension");
4230 goto error;
4231 }
4232 r = _add_ca_certs(self, buf.buf, buf.len, SSL_FILETYPE_ASN1);
4233 PyBuffer_Release(&buf);
4234 if (r == -1) {
4235 goto error;
4236 }
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03004237 }
4238 else {
4239 invalid_cadata:
4240 PyErr_SetString(PyExc_TypeError,
4241 "cadata should be an ASCII string or a "
4242 "bytes-like object");
4243 goto error;
Christian Heimesefff7062013-11-21 03:35:02 +01004244 }
4245 }
4246
4247 /* load cafile or capath */
4248 if (cafile || capath) {
4249 if (cafile)
4250 cafile_buf = PyBytes_AS_STRING(cafile_bytes);
4251 if (capath)
4252 capath_buf = PyBytes_AS_STRING(capath_bytes);
4253 PySSL_BEGIN_ALLOW_THREADS
4254 r = SSL_CTX_load_verify_locations(self->ctx, cafile_buf, capath_buf);
4255 PySSL_END_ALLOW_THREADS
4256 if (r != 1) {
4257 ok = 0;
4258 if (errno != 0) {
4259 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03004260 PyErr_SetFromErrno(PyExc_OSError);
Christian Heimesefff7062013-11-21 03:35:02 +01004261 }
4262 else {
4263 _setSSLError(NULL, 0, __FILE__, __LINE__);
4264 }
4265 goto error;
4266 }
4267 }
4268 goto end;
4269
4270 error:
4271 ok = 0;
4272 end:
Antoine Pitrou152efa22010-05-16 18:19:27 +00004273 Py_XDECREF(cafile_bytes);
4274 Py_XDECREF(capath_bytes);
Christian Heimesefff7062013-11-21 03:35:02 +01004275 if (ok) {
4276 Py_RETURN_NONE;
4277 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00004278 return NULL;
4279 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00004280}
4281
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004282/*[clinic input]
4283_ssl._SSLContext.load_dh_params
4284 path as filepath: object
4285 /
4286
4287[clinic start generated code]*/
4288
Antoine Pitrou152efa22010-05-16 18:19:27 +00004289static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004290_ssl__SSLContext_load_dh_params(PySSLContext *self, PyObject *filepath)
4291/*[clinic end generated code: output=1c8e57a38e055af0 input=c8871f3c796ae1d6]*/
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004292{
4293 FILE *f;
4294 DH *dh;
4295
Victor Stinnerdaf45552013-08-28 00:53:59 +02004296 f = _Py_fopen_obj(filepath, "rb");
Victor Stinnere42ccd22015-03-18 01:39:23 +01004297 if (f == NULL)
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004298 return NULL;
Victor Stinnere42ccd22015-03-18 01:39:23 +01004299
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004300 errno = 0;
4301 PySSL_BEGIN_ALLOW_THREADS
4302 dh = PEM_read_DHparams(f, NULL, NULL, NULL);
Antoine Pitrou457a2292013-01-12 21:43:45 +01004303 fclose(f);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004304 PySSL_END_ALLOW_THREADS
4305 if (dh == NULL) {
4306 if (errno != 0) {
4307 ERR_clear_error();
4308 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
4309 }
4310 else {
4311 _setSSLError(NULL, 0, __FILE__, __LINE__);
4312 }
4313 return NULL;
4314 }
4315 if (SSL_CTX_set_tmp_dh(self->ctx, dh) == 0)
4316 _setSSLError(NULL, 0, __FILE__, __LINE__);
4317 DH_free(dh);
4318 Py_RETURN_NONE;
4319}
4320
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004321/*[clinic input]
4322_ssl._SSLContext._wrap_socket
4323 sock: object(subclass_of="PySocketModule.Sock_Type")
4324 server_side: int
4325 server_hostname as hostname_obj: object = None
Christian Heimes141c5e82018-02-24 21:10:57 +01004326 *
4327 owner: object = None
4328 session: object = None
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004329
4330[clinic start generated code]*/
4331
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004332static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004333_ssl__SSLContext__wrap_socket_impl(PySSLContext *self, PyObject *sock,
Christian Heimes141c5e82018-02-24 21:10:57 +01004334 int server_side, PyObject *hostname_obj,
4335 PyObject *owner, PyObject *session)
4336/*[clinic end generated code: output=f103f238633940b4 input=957d5006183d1894]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004337{
Antoine Pitroud5323212010-10-22 18:19:07 +00004338 char *hostname = NULL;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004339 PyObject *res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004340
Antoine Pitroud5323212010-10-22 18:19:07 +00004341 /* server_hostname is either None (or absent), or to be encoded
Christian Heimesd02ac252018-03-25 12:36:13 +02004342 as IDN A-label (ASCII str) without NULL bytes. */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004343 if (hostname_obj != Py_None) {
Christian Heimes11a14932018-02-24 02:35:08 +01004344 if (!PyArg_Parse(hostname_obj, "es", "ascii", &hostname))
Antoine Pitroud5323212010-10-22 18:19:07 +00004345 return NULL;
Antoine Pitroud5323212010-10-22 18:19:07 +00004346 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00004347
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004348 res = (PyObject *) newPySSLSocket(self, (PySocketSockObject *)sock,
4349 server_side, hostname,
Christian Heimes141c5e82018-02-24 21:10:57 +01004350 owner, session,
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004351 NULL, NULL);
Antoine Pitroud5323212010-10-22 18:19:07 +00004352 if (hostname != NULL)
4353 PyMem_Free(hostname);
4354 return res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004355}
4356
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004357/*[clinic input]
4358_ssl._SSLContext._wrap_bio
4359 incoming: object(subclass_of="&PySSLMemoryBIO_Type", type="PySSLMemoryBIO *")
4360 outgoing: object(subclass_of="&PySSLMemoryBIO_Type", type="PySSLMemoryBIO *")
4361 server_side: int
4362 server_hostname as hostname_obj: object = None
Christian Heimes141c5e82018-02-24 21:10:57 +01004363 *
4364 owner: object = None
4365 session: object = None
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004366
4367[clinic start generated code]*/
4368
Antoine Pitroub0182c82010-10-12 20:09:02 +00004369static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004370_ssl__SSLContext__wrap_bio_impl(PySSLContext *self, PySSLMemoryBIO *incoming,
4371 PySSLMemoryBIO *outgoing, int server_side,
Christian Heimes141c5e82018-02-24 21:10:57 +01004372 PyObject *hostname_obj, PyObject *owner,
4373 PyObject *session)
4374/*[clinic end generated code: output=5c5d6d9b41f99332 input=8cf22f4d586ac56a]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004375{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004376 char *hostname = NULL;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004377 PyObject *res;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004378
4379 /* server_hostname is either None (or absent), or to be encoded
Christian Heimesd02ac252018-03-25 12:36:13 +02004380 as IDN A-label (ASCII str) without NULL bytes. */
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004381 if (hostname_obj != Py_None) {
Christian Heimes11a14932018-02-24 02:35:08 +01004382 if (!PyArg_Parse(hostname_obj, "es", "ascii", &hostname))
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004383 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004384 }
4385
4386 res = (PyObject *) newPySSLSocket(self, NULL, server_side, hostname,
Christian Heimes141c5e82018-02-24 21:10:57 +01004387 owner, session,
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004388 incoming, outgoing);
4389
4390 PyMem_Free(hostname);
4391 return res;
4392}
4393
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004394/*[clinic input]
4395_ssl._SSLContext.session_stats
4396[clinic start generated code]*/
4397
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004398static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004399_ssl__SSLContext_session_stats_impl(PySSLContext *self)
4400/*[clinic end generated code: output=0d96411c42893bfb input=7e0a81fb11102c8b]*/
Antoine Pitroub0182c82010-10-12 20:09:02 +00004401{
4402 int r;
4403 PyObject *value, *stats = PyDict_New();
4404 if (!stats)
4405 return NULL;
4406
4407#define ADD_STATS(SSL_NAME, KEY_NAME) \
4408 value = PyLong_FromLong(SSL_CTX_sess_ ## SSL_NAME (self->ctx)); \
4409 if (value == NULL) \
4410 goto error; \
4411 r = PyDict_SetItemString(stats, KEY_NAME, value); \
4412 Py_DECREF(value); \
4413 if (r < 0) \
4414 goto error;
4415
4416 ADD_STATS(number, "number");
4417 ADD_STATS(connect, "connect");
4418 ADD_STATS(connect_good, "connect_good");
4419 ADD_STATS(connect_renegotiate, "connect_renegotiate");
4420 ADD_STATS(accept, "accept");
4421 ADD_STATS(accept_good, "accept_good");
4422 ADD_STATS(accept_renegotiate, "accept_renegotiate");
4423 ADD_STATS(accept, "accept");
4424 ADD_STATS(hits, "hits");
4425 ADD_STATS(misses, "misses");
4426 ADD_STATS(timeouts, "timeouts");
4427 ADD_STATS(cache_full, "cache_full");
4428
4429#undef ADD_STATS
4430
4431 return stats;
4432
4433error:
4434 Py_DECREF(stats);
4435 return NULL;
4436}
4437
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004438/*[clinic input]
4439_ssl._SSLContext.set_default_verify_paths
4440[clinic start generated code]*/
4441
Antoine Pitrou664c2d12010-11-17 20:29:42 +00004442static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004443_ssl__SSLContext_set_default_verify_paths_impl(PySSLContext *self)
4444/*[clinic end generated code: output=0bee74e6e09deaaa input=35f3408021463d74]*/
Antoine Pitrou664c2d12010-11-17 20:29:42 +00004445{
4446 if (!SSL_CTX_set_default_verify_paths(self->ctx)) {
4447 _setSSLError(NULL, 0, __FILE__, __LINE__);
4448 return NULL;
4449 }
4450 Py_RETURN_NONE;
4451}
4452
Antoine Pitrou501da612011-12-21 09:27:41 +01004453#ifndef OPENSSL_NO_ECDH
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004454/*[clinic input]
4455_ssl._SSLContext.set_ecdh_curve
4456 name: object
4457 /
4458
4459[clinic start generated code]*/
4460
Antoine Pitrou923df6f2011-12-19 17:16:51 +01004461static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004462_ssl__SSLContext_set_ecdh_curve(PySSLContext *self, PyObject *name)
4463/*[clinic end generated code: output=23022c196e40d7d2 input=c2bafb6f6e34726b]*/
Antoine Pitrou923df6f2011-12-19 17:16:51 +01004464{
4465 PyObject *name_bytes;
4466 int nid;
4467 EC_KEY *key;
4468
4469 if (!PyUnicode_FSConverter(name, &name_bytes))
4470 return NULL;
4471 assert(PyBytes_Check(name_bytes));
4472 nid = OBJ_sn2nid(PyBytes_AS_STRING(name_bytes));
4473 Py_DECREF(name_bytes);
4474 if (nid == 0) {
4475 PyErr_Format(PyExc_ValueError,
4476 "unknown elliptic curve name %R", name);
4477 return NULL;
4478 }
4479 key = EC_KEY_new_by_curve_name(nid);
4480 if (key == NULL) {
4481 _setSSLError(NULL, 0, __FILE__, __LINE__);
4482 return NULL;
4483 }
4484 SSL_CTX_set_tmp_ecdh(self->ctx, key);
4485 EC_KEY_free(key);
4486 Py_RETURN_NONE;
4487}
Antoine Pitrou501da612011-12-21 09:27:41 +01004488#endif
Antoine Pitrou923df6f2011-12-19 17:16:51 +01004489
Antoine Pitrou912fbff2013-03-30 16:29:32 +01004490#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004491static int
4492_servername_callback(SSL *s, int *al, void *args)
4493{
4494 int ret;
4495 PySSLContext *ssl_ctx = (PySSLContext *) args;
4496 PySSLSocket *ssl;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004497 PyObject *result;
4498 /* The high-level ssl.SSLSocket object */
4499 PyObject *ssl_socket;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004500 const char *servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
Stefan Krah20d60802013-01-17 17:07:17 +01004501 PyGILState_STATE gstate = PyGILState_Ensure();
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004502
Christian Heimes11a14932018-02-24 02:35:08 +01004503 if (ssl_ctx->set_sni_cb == NULL) {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004504 /* remove race condition in this the call back while if removing the
4505 * callback is in progress */
4506 PyGILState_Release(gstate);
Antoine Pitrou5dd12a52013-01-06 15:25:36 +01004507 return SSL_TLSEXT_ERR_OK;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004508 }
4509
4510 ssl = SSL_get_app_data(s);
4511 assert(PySSLSocket_Check(ssl));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004512
Serhiy Storchakaf51d7152015-11-02 14:40:41 +02004513 /* The servername callback expects an argument that represents the current
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004514 * SSL connection and that has a .context attribute that can be changed to
4515 * identify the requested hostname. Since the official API is the Python
4516 * level API we want to pass the callback a Python level object rather than
4517 * a _ssl.SSLSocket instance. If there's an "owner" (typically an
4518 * SSLObject) that will be passed. Otherwise if there's a socket then that
4519 * will be passed. If both do not exist only then the C-level object is
4520 * passed. */
4521 if (ssl->owner)
4522 ssl_socket = PyWeakref_GetObject(ssl->owner);
4523 else if (ssl->Socket)
4524 ssl_socket = PyWeakref_GetObject(ssl->Socket);
4525 else
4526 ssl_socket = (PyObject *) ssl;
4527
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004528 Py_INCREF(ssl_socket);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004529 if (ssl_socket == Py_None)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004530 goto error;
Victor Stinner7e001512013-06-25 00:44:31 +02004531
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004532 if (servername == NULL) {
Christian Heimes11a14932018-02-24 02:35:08 +01004533 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_sni_cb, ssl_socket,
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004534 Py_None, ssl_ctx, NULL);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004535 }
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004536 else {
Christian Heimes11a14932018-02-24 02:35:08 +01004537 PyObject *servername_bytes;
4538 PyObject *servername_str;
4539
4540 servername_bytes = PyBytes_FromString(servername);
4541 if (servername_bytes == NULL) {
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004542 PyErr_WriteUnraisable((PyObject *) ssl_ctx);
4543 goto error;
4544 }
Christian Heimes11a14932018-02-24 02:35:08 +01004545 /* server_hostname was encoded to an A-label by our caller; put it
4546 * back into a str object, but still as an A-label (bpo-28414)
4547 */
4548 servername_str = PyUnicode_FromEncodedObject(servername_bytes, "ascii", NULL);
4549 Py_DECREF(servername_bytes);
4550 if (servername_str == NULL) {
4551 PyErr_WriteUnraisable(servername_bytes);
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004552 goto error;
4553 }
Christian Heimes11a14932018-02-24 02:35:08 +01004554 result = PyObject_CallFunctionObjArgs(
4555 ssl_ctx->set_sni_cb, ssl_socket, servername_str,
4556 ssl_ctx, NULL);
4557 Py_DECREF(servername_str);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004558 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004559 Py_DECREF(ssl_socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004560
4561 if (result == NULL) {
Christian Heimes11a14932018-02-24 02:35:08 +01004562 PyErr_WriteUnraisable(ssl_ctx->set_sni_cb);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004563 *al = SSL_AD_HANDSHAKE_FAILURE;
4564 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
4565 }
4566 else {
Christian Heimes11a14932018-02-24 02:35:08 +01004567 /* Result may be None, a SSLContext or an integer
4568 * None and SSLContext are OK, integer or other values are an error.
4569 */
4570 if (result == Py_None) {
4571 ret = SSL_TLSEXT_ERR_OK;
4572 } else {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004573 *al = (int) PyLong_AsLong(result);
4574 if (PyErr_Occurred()) {
4575 PyErr_WriteUnraisable(result);
4576 *al = SSL_AD_INTERNAL_ERROR;
4577 }
4578 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
4579 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004580 Py_DECREF(result);
4581 }
4582
4583 PyGILState_Release(gstate);
4584 return ret;
4585
4586error:
4587 Py_DECREF(ssl_socket);
4588 *al = SSL_AD_INTERNAL_ERROR;
4589 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
4590 PyGILState_Release(gstate);
4591 return ret;
4592}
Antoine Pitroua5963382013-03-30 16:39:00 +01004593#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004594
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004595static PyObject *
Christian Heimes11a14932018-02-24 02:35:08 +01004596get_sni_callback(PySSLContext *self, void *c)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004597{
Christian Heimes11a14932018-02-24 02:35:08 +01004598 PyObject *cb = self->set_sni_cb;
4599 if (cb == NULL) {
4600 Py_RETURN_NONE;
4601 }
4602 Py_INCREF(cb);
4603 return cb;
4604}
4605
4606static int
4607set_sni_callback(PySSLContext *self, PyObject *arg, void *c)
4608{
4609 if (self->protocol == PY_SSL_VERSION_TLS_CLIENT) {
4610 PyErr_SetString(PyExc_ValueError,
4611 "sni_callback cannot be set on TLS_CLIENT context");
4612 return -1;
4613 }
Antoine Pitrou912fbff2013-03-30 16:29:32 +01004614#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Christian Heimes11a14932018-02-24 02:35:08 +01004615 Py_CLEAR(self->set_sni_cb);
4616 if (arg == Py_None) {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004617 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
4618 }
4619 else {
Christian Heimes11a14932018-02-24 02:35:08 +01004620 if (!PyCallable_Check(arg)) {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004621 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
4622 PyErr_SetString(PyExc_TypeError,
4623 "not a callable object");
Christian Heimes11a14932018-02-24 02:35:08 +01004624 return -1;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004625 }
Christian Heimes11a14932018-02-24 02:35:08 +01004626 Py_INCREF(arg);
4627 self->set_sni_cb = arg;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004628 SSL_CTX_set_tlsext_servername_callback(self->ctx, _servername_callback);
4629 SSL_CTX_set_tlsext_servername_arg(self->ctx, self);
4630 }
Christian Heimes11a14932018-02-24 02:35:08 +01004631 return 0;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004632#else
4633 PyErr_SetString(PyExc_NotImplementedError,
4634 "The TLS extension servername callback, "
4635 "SSL_CTX_set_tlsext_servername_callback, "
4636 "is not in the current OpenSSL library.");
Christian Heimes11a14932018-02-24 02:35:08 +01004637 return -1;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004638#endif
4639}
4640
Christian Heimes11a14932018-02-24 02:35:08 +01004641PyDoc_STRVAR(PySSLContext_sni_callback_doc,
4642"Set a callback that will be called when a server name is provided by the SSL/TLS client in the SNI extension.\n\
4643\n\
4644If the argument is None then the callback is disabled. The method is called\n\
4645with the SSLSocket, the server name as a string, and the SSLContext object.\n\
4646See RFC 6066 for details of the SNI extension.");
4647
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004648/*[clinic input]
4649_ssl._SSLContext.cert_store_stats
4650
4651Returns quantities of loaded X.509 certificates.
4652
4653X.509 certificates with a CA extension and certificate revocation lists
4654inside the context's cert store.
4655
4656NOTE: Certificates in a capath directory aren't loaded unless they have
4657been used at least once.
4658[clinic start generated code]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004659
4660static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004661_ssl__SSLContext_cert_store_stats_impl(PySSLContext *self)
4662/*[clinic end generated code: output=5f356f4d9cca874d input=eb40dd0f6d0e40cf]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004663{
4664 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02004665 STACK_OF(X509_OBJECT) *objs;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004666 X509_OBJECT *obj;
Christian Heimes598894f2016-09-05 23:19:05 +02004667 int x509 = 0, crl = 0, ca = 0, i;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004668
4669 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02004670 objs = X509_STORE_get0_objects(store);
4671 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
4672 obj = sk_X509_OBJECT_value(objs, i);
4673 switch (X509_OBJECT_get_type(obj)) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004674 case X509_LU_X509:
4675 x509++;
Christian Heimes598894f2016-09-05 23:19:05 +02004676 if (X509_check_ca(X509_OBJECT_get0_X509(obj))) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004677 ca++;
4678 }
4679 break;
4680 case X509_LU_CRL:
4681 crl++;
4682 break;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004683 default:
4684 /* Ignore X509_LU_FAIL, X509_LU_RETRY, X509_LU_PKEY.
4685 * As far as I can tell they are internal states and never
4686 * stored in a cert store */
4687 break;
4688 }
4689 }
4690 return Py_BuildValue("{sisisi}", "x509", x509, "crl", crl,
4691 "x509_ca", ca);
4692}
4693
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004694/*[clinic input]
4695_ssl._SSLContext.get_ca_certs
4696 binary_form: bool = False
4697
4698Returns a list of dicts with information of loaded CA certs.
4699
4700If the optional argument is True, returns a DER-encoded copy of the CA
4701certificate.
4702
4703NOTE: Certificates in a capath directory aren't loaded unless they have
4704been used at least once.
4705[clinic start generated code]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004706
4707static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004708_ssl__SSLContext_get_ca_certs_impl(PySSLContext *self, int binary_form)
4709/*[clinic end generated code: output=0d58f148f37e2938 input=6887b5a09b7f9076]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004710{
4711 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02004712 STACK_OF(X509_OBJECT) *objs;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004713 PyObject *ci = NULL, *rlist = NULL;
4714 int i;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004715
4716 if ((rlist = PyList_New(0)) == NULL) {
4717 return NULL;
4718 }
4719
4720 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02004721 objs = X509_STORE_get0_objects(store);
4722 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004723 X509_OBJECT *obj;
4724 X509 *cert;
4725
Christian Heimes598894f2016-09-05 23:19:05 +02004726 obj = sk_X509_OBJECT_value(objs, i);
4727 if (X509_OBJECT_get_type(obj) != X509_LU_X509) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004728 /* not a x509 cert */
4729 continue;
4730 }
4731 /* CA for any purpose */
Christian Heimes598894f2016-09-05 23:19:05 +02004732 cert = X509_OBJECT_get0_X509(obj);
Christian Heimes9a5395a2013-06-17 15:44:12 +02004733 if (!X509_check_ca(cert)) {
4734 continue;
4735 }
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004736 if (binary_form) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004737 ci = _certificate_to_der(cert);
4738 } else {
4739 ci = _decode_certificate(cert);
4740 }
4741 if (ci == NULL) {
4742 goto error;
4743 }
4744 if (PyList_Append(rlist, ci) == -1) {
4745 goto error;
4746 }
4747 Py_CLEAR(ci);
4748 }
4749 return rlist;
4750
4751 error:
4752 Py_XDECREF(ci);
4753 Py_XDECREF(rlist);
4754 return NULL;
4755}
4756
4757
Antoine Pitrou152efa22010-05-16 18:19:27 +00004758static PyGetSetDef context_getsetlist[] = {
Christian Heimes1aa9a752013-12-02 02:41:19 +01004759 {"check_hostname", (getter) get_check_hostname,
4760 (setter) set_check_hostname, NULL},
Christian Heimes61d478c2018-01-27 15:51:38 +01004761 {"_host_flags", (getter) get_host_flags,
4762 (setter) set_host_flags, NULL},
Christian Heimes698dde12018-02-27 11:54:43 +01004763#if SSL_CTRL_GET_MAX_PROTO_VERSION
4764 {"minimum_version", (getter) get_minimum_version,
4765 (setter) set_minimum_version, NULL},
4766 {"maximum_version", (getter) get_maximum_version,
4767 (setter) set_maximum_version, NULL},
4768#endif
Christian Heimesc7f70692019-05-31 11:44:05 +02004769#ifdef HAVE_OPENSSL_KEYLOG
4770 {"keylog_filename", (getter) _PySSLContext_get_keylog_filename,
4771 (setter) _PySSLContext_set_keylog_filename, NULL},
4772#endif
4773 {"_msg_callback", (getter) _PySSLContext_get_msg_callback,
4774 (setter) _PySSLContext_set_msg_callback, NULL},
Christian Heimes11a14932018-02-24 02:35:08 +01004775 {"sni_callback", (getter) get_sni_callback,
Christian Heimes698dde12018-02-27 11:54:43 +01004776 (setter) set_sni_callback, PySSLContext_sni_callback_doc},
Christian Heimes78c7d522019-06-03 21:00:10 +02004777#if (OPENSSL_VERSION_NUMBER >= 0x10101000L) && !defined(LIBRESSL_VERSION_NUMBER)
4778 {"num_tickets", (getter) get_num_tickets,
4779 (setter) set_num_tickets, PySSLContext_num_tickets_doc},
4780#endif
Antoine Pitroub5218772010-05-21 09:56:06 +00004781 {"options", (getter) get_options,
4782 (setter) set_options, NULL},
Christian Heimes9fb051f2018-09-23 08:32:31 +02004783 {"post_handshake_auth", (getter) get_post_handshake_auth,
4784#ifdef TLS1_3_VERSION
4785 (setter) set_post_handshake_auth,
4786#else
4787 NULL,
4788#endif
4789 NULL},
Christian Heimes11a14932018-02-24 02:35:08 +01004790 {"protocol", (getter) get_protocol,
4791 NULL, NULL},
Christian Heimes22587792013-11-21 23:56:13 +01004792 {"verify_flags", (getter) get_verify_flags,
4793 (setter) set_verify_flags, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00004794 {"verify_mode", (getter) get_verify_mode,
4795 (setter) set_verify_mode, NULL},
4796 {NULL}, /* sentinel */
4797};
4798
4799static struct PyMethodDef context_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004800 _SSL__SSLCONTEXT__WRAP_SOCKET_METHODDEF
4801 _SSL__SSLCONTEXT__WRAP_BIO_METHODDEF
4802 _SSL__SSLCONTEXT_SET_CIPHERS_METHODDEF
4803 _SSL__SSLCONTEXT__SET_ALPN_PROTOCOLS_METHODDEF
4804 _SSL__SSLCONTEXT__SET_NPN_PROTOCOLS_METHODDEF
4805 _SSL__SSLCONTEXT_LOAD_CERT_CHAIN_METHODDEF
4806 _SSL__SSLCONTEXT_LOAD_DH_PARAMS_METHODDEF
4807 _SSL__SSLCONTEXT_LOAD_VERIFY_LOCATIONS_METHODDEF
4808 _SSL__SSLCONTEXT_SESSION_STATS_METHODDEF
4809 _SSL__SSLCONTEXT_SET_DEFAULT_VERIFY_PATHS_METHODDEF
4810 _SSL__SSLCONTEXT_SET_ECDH_CURVE_METHODDEF
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004811 _SSL__SSLCONTEXT_CERT_STORE_STATS_METHODDEF
4812 _SSL__SSLCONTEXT_GET_CA_CERTS_METHODDEF
Christian Heimes25bfcd52016-09-06 00:04:45 +02004813 _SSL__SSLCONTEXT_GET_CIPHERS_METHODDEF
Antoine Pitrou152efa22010-05-16 18:19:27 +00004814 {NULL, NULL} /* sentinel */
4815};
4816
4817static PyTypeObject PySSLContext_Type = {
4818 PyVarObject_HEAD_INIT(NULL, 0)
4819 "_ssl._SSLContext", /*tp_name*/
4820 sizeof(PySSLContext), /*tp_basicsize*/
4821 0, /*tp_itemsize*/
4822 (destructor)context_dealloc, /*tp_dealloc*/
Jeroen Demeyer530f5062019-05-31 04:13:39 +02004823 0, /*tp_vectorcall_offset*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004824 0, /*tp_getattr*/
4825 0, /*tp_setattr*/
Jeroen Demeyer530f5062019-05-31 04:13:39 +02004826 0, /*tp_as_async*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004827 0, /*tp_repr*/
4828 0, /*tp_as_number*/
4829 0, /*tp_as_sequence*/
4830 0, /*tp_as_mapping*/
4831 0, /*tp_hash*/
4832 0, /*tp_call*/
4833 0, /*tp_str*/
4834 0, /*tp_getattro*/
4835 0, /*tp_setattro*/
4836 0, /*tp_as_buffer*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004837 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004838 0, /*tp_doc*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004839 (traverseproc) context_traverse, /*tp_traverse*/
4840 (inquiry) context_clear, /*tp_clear*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004841 0, /*tp_richcompare*/
4842 0, /*tp_weaklistoffset*/
4843 0, /*tp_iter*/
4844 0, /*tp_iternext*/
4845 context_methods, /*tp_methods*/
4846 0, /*tp_members*/
4847 context_getsetlist, /*tp_getset*/
4848 0, /*tp_base*/
4849 0, /*tp_dict*/
4850 0, /*tp_descr_get*/
4851 0, /*tp_descr_set*/
4852 0, /*tp_dictoffset*/
4853 0, /*tp_init*/
4854 0, /*tp_alloc*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004855 _ssl__SSLContext, /*tp_new*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004856};
4857
4858
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004859/*
4860 * MemoryBIO objects
4861 */
4862
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004863/*[clinic input]
4864@classmethod
4865_ssl.MemoryBIO.__new__
4866
4867[clinic start generated code]*/
4868
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004869static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004870_ssl_MemoryBIO_impl(PyTypeObject *type)
4871/*[clinic end generated code: output=8820a58db78330ac input=26d22e4909ecb1b5]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004872{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004873 BIO *bio;
4874 PySSLMemoryBIO *self;
4875
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004876 bio = BIO_new(BIO_s_mem());
4877 if (bio == NULL) {
4878 PyErr_SetString(PySSLErrorObject,
4879 "failed to allocate BIO");
4880 return NULL;
4881 }
4882 /* Since our BIO is non-blocking an empty read() does not indicate EOF,
4883 * just that no data is currently available. The SSL routines should retry
4884 * the read, which we can achieve by calling BIO_set_retry_read(). */
4885 BIO_set_retry_read(bio);
4886 BIO_set_mem_eof_return(bio, -1);
4887
4888 assert(type != NULL && type->tp_alloc != NULL);
4889 self = (PySSLMemoryBIO *) type->tp_alloc(type, 0);
4890 if (self == NULL) {
4891 BIO_free(bio);
4892 return NULL;
4893 }
4894 self->bio = bio;
4895 self->eof_written = 0;
4896
4897 return (PyObject *) self;
4898}
4899
4900static void
4901memory_bio_dealloc(PySSLMemoryBIO *self)
4902{
4903 BIO_free(self->bio);
4904 Py_TYPE(self)->tp_free(self);
4905}
4906
4907static PyObject *
4908memory_bio_get_pending(PySSLMemoryBIO *self, void *c)
4909{
Segev Finer5cff6372017-07-27 01:19:17 +03004910 return PyLong_FromSize_t(BIO_ctrl_pending(self->bio));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004911}
4912
4913PyDoc_STRVAR(PySSL_memory_bio_pending_doc,
4914"The number of bytes pending in the memory BIO.");
4915
4916static PyObject *
4917memory_bio_get_eof(PySSLMemoryBIO *self, void *c)
4918{
4919 return PyBool_FromLong((BIO_ctrl_pending(self->bio) == 0)
4920 && self->eof_written);
4921}
4922
4923PyDoc_STRVAR(PySSL_memory_bio_eof_doc,
4924"Whether the memory BIO is at EOF.");
4925
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004926/*[clinic input]
4927_ssl.MemoryBIO.read
4928 size as len: int = -1
4929 /
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004930
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004931Read up to size bytes from the memory BIO.
4932
4933If size is not specified, read the entire buffer.
4934If the return value is an empty bytes instance, this means either
4935EOF or that no data is available. Use the "eof" property to
4936distinguish between the two.
4937[clinic start generated code]*/
4938
4939static PyObject *
4940_ssl_MemoryBIO_read_impl(PySSLMemoryBIO *self, int len)
4941/*[clinic end generated code: output=a657aa1e79cd01b3 input=574d7be06a902366]*/
4942{
4943 int avail, nbytes;
4944 PyObject *result;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004945
Segev Finer5cff6372017-07-27 01:19:17 +03004946 avail = (int)Py_MIN(BIO_ctrl_pending(self->bio), INT_MAX);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004947 if ((len < 0) || (len > avail))
4948 len = avail;
4949
4950 result = PyBytes_FromStringAndSize(NULL, len);
4951 if ((result == NULL) || (len == 0))
4952 return result;
4953
4954 nbytes = BIO_read(self->bio, PyBytes_AS_STRING(result), len);
Zackery Spytz365ad2e2018-10-06 11:41:45 -06004955 if (nbytes < 0) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004956 Py_DECREF(result);
Zackery Spytz365ad2e2018-10-06 11:41:45 -06004957 _setSSLError(NULL, 0, __FILE__, __LINE__);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004958 return NULL;
4959 }
4960
Zackery Spytz365ad2e2018-10-06 11:41:45 -06004961 /* There should never be any short reads but check anyway. */
4962 if (nbytes < len) {
4963 _PyBytes_Resize(&result, nbytes);
4964 }
4965
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004966 return result;
4967}
4968
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004969/*[clinic input]
4970_ssl.MemoryBIO.write
4971 b: Py_buffer
4972 /
4973
4974Writes the bytes b into the memory BIO.
4975
4976Returns the number of bytes written.
4977[clinic start generated code]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004978
4979static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004980_ssl_MemoryBIO_write_impl(PySSLMemoryBIO *self, Py_buffer *b)
4981/*[clinic end generated code: output=156ec59110d75935 input=e45757b3e17c4808]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004982{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004983 int nbytes;
4984
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004985 if (b->len > INT_MAX) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004986 PyErr_Format(PyExc_OverflowError,
4987 "string longer than %d bytes", INT_MAX);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004988 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004989 }
4990
4991 if (self->eof_written) {
4992 PyErr_SetString(PySSLErrorObject,
4993 "cannot write() after write_eof()");
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004994 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004995 }
4996
Segev Finer5cff6372017-07-27 01:19:17 +03004997 nbytes = BIO_write(self->bio, b->buf, (int)b->len);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004998 if (nbytes < 0) {
4999 _setSSLError(NULL, 0, __FILE__, __LINE__);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005000 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005001 }
5002
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005003 return PyLong_FromLong(nbytes);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005004}
5005
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005006/*[clinic input]
5007_ssl.MemoryBIO.write_eof
5008
5009Write an EOF marker to the memory BIO.
5010
5011When all data has been read, the "eof" property will be True.
5012[clinic start generated code]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005013
5014static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005015_ssl_MemoryBIO_write_eof_impl(PySSLMemoryBIO *self)
5016/*[clinic end generated code: output=d4106276ccd1ed34 input=56a945f1d29e8bd6]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005017{
5018 self->eof_written = 1;
5019 /* After an EOF is written, a zero return from read() should be a real EOF
5020 * i.e. it should not be retried. Clear the SHOULD_RETRY flag. */
5021 BIO_clear_retry_flags(self->bio);
5022 BIO_set_mem_eof_return(self->bio, 0);
5023
5024 Py_RETURN_NONE;
5025}
5026
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005027static PyGetSetDef memory_bio_getsetlist[] = {
5028 {"pending", (getter) memory_bio_get_pending, NULL,
5029 PySSL_memory_bio_pending_doc},
5030 {"eof", (getter) memory_bio_get_eof, NULL,
5031 PySSL_memory_bio_eof_doc},
5032 {NULL}, /* sentinel */
5033};
5034
5035static struct PyMethodDef memory_bio_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005036 _SSL_MEMORYBIO_READ_METHODDEF
5037 _SSL_MEMORYBIO_WRITE_METHODDEF
5038 _SSL_MEMORYBIO_WRITE_EOF_METHODDEF
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005039 {NULL, NULL} /* sentinel */
5040};
5041
5042static PyTypeObject PySSLMemoryBIO_Type = {
5043 PyVarObject_HEAD_INIT(NULL, 0)
5044 "_ssl.MemoryBIO", /*tp_name*/
5045 sizeof(PySSLMemoryBIO), /*tp_basicsize*/
5046 0, /*tp_itemsize*/
5047 (destructor)memory_bio_dealloc, /*tp_dealloc*/
Jeroen Demeyer530f5062019-05-31 04:13:39 +02005048 0, /*tp_vectorcall_offset*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005049 0, /*tp_getattr*/
5050 0, /*tp_setattr*/
Jeroen Demeyer530f5062019-05-31 04:13:39 +02005051 0, /*tp_as_async*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005052 0, /*tp_repr*/
5053 0, /*tp_as_number*/
5054 0, /*tp_as_sequence*/
5055 0, /*tp_as_mapping*/
5056 0, /*tp_hash*/
5057 0, /*tp_call*/
5058 0, /*tp_str*/
5059 0, /*tp_getattro*/
5060 0, /*tp_setattro*/
5061 0, /*tp_as_buffer*/
5062 Py_TPFLAGS_DEFAULT, /*tp_flags*/
5063 0, /*tp_doc*/
5064 0, /*tp_traverse*/
5065 0, /*tp_clear*/
5066 0, /*tp_richcompare*/
5067 0, /*tp_weaklistoffset*/
5068 0, /*tp_iter*/
5069 0, /*tp_iternext*/
5070 memory_bio_methods, /*tp_methods*/
5071 0, /*tp_members*/
5072 memory_bio_getsetlist, /*tp_getset*/
5073 0, /*tp_base*/
5074 0, /*tp_dict*/
5075 0, /*tp_descr_get*/
5076 0, /*tp_descr_set*/
5077 0, /*tp_dictoffset*/
5078 0, /*tp_init*/
5079 0, /*tp_alloc*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005080 _ssl_MemoryBIO, /*tp_new*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005081};
5082
Antoine Pitrou152efa22010-05-16 18:19:27 +00005083
Christian Heimes99a65702016-09-10 23:44:53 +02005084/*
5085 * SSL Session object
5086 */
5087
5088static void
5089PySSLSession_dealloc(PySSLSession *self)
5090{
INADA Naokia6296d32017-08-24 14:55:17 +09005091 /* bpo-31095: UnTrack is needed before calling any callbacks */
Christian Heimesa5d07652016-09-24 10:48:05 +02005092 PyObject_GC_UnTrack(self);
Christian Heimes99a65702016-09-10 23:44:53 +02005093 Py_XDECREF(self->ctx);
5094 if (self->session != NULL) {
5095 SSL_SESSION_free(self->session);
5096 }
Christian Heimesa5d07652016-09-24 10:48:05 +02005097 PyObject_GC_Del(self);
Christian Heimes99a65702016-09-10 23:44:53 +02005098}
5099
5100static PyObject *
5101PySSLSession_richcompare(PyObject *left, PyObject *right, int op)
5102{
5103 int result;
5104
5105 if (left == NULL || right == NULL) {
5106 PyErr_BadInternalCall();
5107 return NULL;
5108 }
5109
5110 if (!PySSLSession_Check(left) || !PySSLSession_Check(right)) {
5111 Py_RETURN_NOTIMPLEMENTED;
5112 }
5113
5114 if (left == right) {
5115 result = 0;
5116 } else {
5117 const unsigned char *left_id, *right_id;
5118 unsigned int left_len, right_len;
5119 left_id = SSL_SESSION_get_id(((PySSLSession *)left)->session,
5120 &left_len);
5121 right_id = SSL_SESSION_get_id(((PySSLSession *)right)->session,
5122 &right_len);
5123 if (left_len == right_len) {
5124 result = memcmp(left_id, right_id, left_len);
5125 } else {
5126 result = 1;
5127 }
5128 }
5129
5130 switch (op) {
5131 case Py_EQ:
5132 if (result == 0) {
5133 Py_RETURN_TRUE;
5134 } else {
5135 Py_RETURN_FALSE;
5136 }
5137 break;
5138 case Py_NE:
5139 if (result != 0) {
5140 Py_RETURN_TRUE;
5141 } else {
5142 Py_RETURN_FALSE;
5143 }
5144 break;
5145 case Py_LT:
5146 case Py_LE:
5147 case Py_GT:
5148 case Py_GE:
5149 Py_RETURN_NOTIMPLEMENTED;
5150 break;
5151 default:
5152 PyErr_BadArgument();
5153 return NULL;
5154 }
5155}
5156
5157static int
5158PySSLSession_traverse(PySSLSession *self, visitproc visit, void *arg)
5159{
5160 Py_VISIT(self->ctx);
5161 return 0;
5162}
5163
5164static int
5165PySSLSession_clear(PySSLSession *self)
5166{
5167 Py_CLEAR(self->ctx);
5168 return 0;
5169}
5170
5171
5172static PyObject *
5173PySSLSession_get_time(PySSLSession *self, void *closure) {
5174 return PyLong_FromLong(SSL_SESSION_get_time(self->session));
5175}
5176
5177PyDoc_STRVAR(PySSLSession_get_time_doc,
5178"Session creation time (seconds since epoch).");
5179
5180
5181static PyObject *
5182PySSLSession_get_timeout(PySSLSession *self, void *closure) {
5183 return PyLong_FromLong(SSL_SESSION_get_timeout(self->session));
5184}
5185
5186PyDoc_STRVAR(PySSLSession_get_timeout_doc,
5187"Session timeout (delta in seconds).");
5188
5189
5190static PyObject *
5191PySSLSession_get_ticket_lifetime_hint(PySSLSession *self, void *closure) {
5192 unsigned long hint = SSL_SESSION_get_ticket_lifetime_hint(self->session);
5193 return PyLong_FromUnsignedLong(hint);
5194}
5195
5196PyDoc_STRVAR(PySSLSession_get_ticket_lifetime_hint_doc,
5197"Ticket life time hint.");
5198
5199
5200static PyObject *
5201PySSLSession_get_session_id(PySSLSession *self, void *closure) {
5202 const unsigned char *id;
5203 unsigned int len;
5204 id = SSL_SESSION_get_id(self->session, &len);
5205 return PyBytes_FromStringAndSize((const char *)id, len);
5206}
5207
5208PyDoc_STRVAR(PySSLSession_get_session_id_doc,
5209"Session id");
5210
5211
5212static PyObject *
5213PySSLSession_get_has_ticket(PySSLSession *self, void *closure) {
5214 if (SSL_SESSION_has_ticket(self->session)) {
5215 Py_RETURN_TRUE;
5216 } else {
5217 Py_RETURN_FALSE;
5218 }
5219}
5220
5221PyDoc_STRVAR(PySSLSession_get_has_ticket_doc,
5222"Does the session contain a ticket?");
5223
5224
5225static PyGetSetDef PySSLSession_getsetlist[] = {
5226 {"has_ticket", (getter) PySSLSession_get_has_ticket, NULL,
5227 PySSLSession_get_has_ticket_doc},
5228 {"id", (getter) PySSLSession_get_session_id, NULL,
5229 PySSLSession_get_session_id_doc},
5230 {"ticket_lifetime_hint", (getter) PySSLSession_get_ticket_lifetime_hint,
5231 NULL, PySSLSession_get_ticket_lifetime_hint_doc},
5232 {"time", (getter) PySSLSession_get_time, NULL,
5233 PySSLSession_get_time_doc},
5234 {"timeout", (getter) PySSLSession_get_timeout, NULL,
5235 PySSLSession_get_timeout_doc},
5236 {NULL}, /* sentinel */
5237};
5238
5239static PyTypeObject PySSLSession_Type = {
5240 PyVarObject_HEAD_INIT(NULL, 0)
5241 "_ssl.Session", /*tp_name*/
5242 sizeof(PySSLSession), /*tp_basicsize*/
5243 0, /*tp_itemsize*/
5244 (destructor)PySSLSession_dealloc, /*tp_dealloc*/
Jeroen Demeyer530f5062019-05-31 04:13:39 +02005245 0, /*tp_vectorcall_offset*/
Christian Heimes99a65702016-09-10 23:44:53 +02005246 0, /*tp_getattr*/
5247 0, /*tp_setattr*/
Jeroen Demeyer530f5062019-05-31 04:13:39 +02005248 0, /*tp_as_async*/
Christian Heimes99a65702016-09-10 23:44:53 +02005249 0, /*tp_repr*/
5250 0, /*tp_as_number*/
5251 0, /*tp_as_sequence*/
5252 0, /*tp_as_mapping*/
5253 0, /*tp_hash*/
5254 0, /*tp_call*/
5255 0, /*tp_str*/
5256 0, /*tp_getattro*/
5257 0, /*tp_setattro*/
5258 0, /*tp_as_buffer*/
Christian Heimesa5d07652016-09-24 10:48:05 +02005259 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
Christian Heimes99a65702016-09-10 23:44:53 +02005260 0, /*tp_doc*/
5261 (traverseproc)PySSLSession_traverse, /*tp_traverse*/
5262 (inquiry)PySSLSession_clear, /*tp_clear*/
5263 PySSLSession_richcompare, /*tp_richcompare*/
5264 0, /*tp_weaklistoffset*/
5265 0, /*tp_iter*/
5266 0, /*tp_iternext*/
5267 0, /*tp_methods*/
5268 0, /*tp_members*/
5269 PySSLSession_getsetlist, /*tp_getset*/
5270};
5271
5272
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005273/* helper routines for seeding the SSL PRNG */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005274/*[clinic input]
5275_ssl.RAND_add
Larry Hastingsdbfdc382015-05-04 06:59:46 -07005276 string as view: Py_buffer(accept={str, buffer})
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005277 entropy: double
5278 /
5279
5280Mix string into the OpenSSL PRNG state.
5281
5282entropy (a float) is a lower bound on the entropy contained in
Chandan Kumar63c2c8a2017-06-09 15:13:58 +05305283string. See RFC 4086.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005284[clinic start generated code]*/
5285
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005286static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005287_ssl_RAND_add_impl(PyObject *module, Py_buffer *view, double entropy)
Serhiy Storchaka5f31d5c2017-06-10 13:13:51 +03005288/*[clinic end generated code: output=e6dd48df9c9024e9 input=5c33017422828f5c]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005289{
Serhiy Storchaka8490f5a2015-03-20 09:00:36 +02005290 const char *buf;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02005291 Py_ssize_t len, written;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005292
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005293 buf = (const char *)view->buf;
5294 len = view->len;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02005295 do {
5296 written = Py_MIN(len, INT_MAX);
5297 RAND_add(buf, (int)written, entropy);
5298 buf += written;
5299 len -= written;
5300 } while (len);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02005301 Py_RETURN_NONE;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005302}
5303
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005304static PyObject *
Victor Stinner99c8b162011-05-24 12:05:19 +02005305PySSL_RAND(int len, int pseudo)
5306{
5307 int ok;
5308 PyObject *bytes;
5309 unsigned long err;
5310 const char *errstr;
5311 PyObject *v;
5312
Victor Stinner1e81a392013-12-19 16:47:04 +01005313 if (len < 0) {
5314 PyErr_SetString(PyExc_ValueError, "num must be positive");
5315 return NULL;
5316 }
5317
Victor Stinner99c8b162011-05-24 12:05:19 +02005318 bytes = PyBytes_FromStringAndSize(NULL, len);
5319 if (bytes == NULL)
5320 return NULL;
5321 if (pseudo) {
Miss Islington (bot)9c0ff172020-06-01 00:17:16 -07005322#ifdef PY_OPENSSL_1_1_API
5323 ok = RAND_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
5324#else
Victor Stinner99c8b162011-05-24 12:05:19 +02005325 ok = RAND_pseudo_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
Miss Islington (bot)9c0ff172020-06-01 00:17:16 -07005326#endif
Victor Stinner99c8b162011-05-24 12:05:19 +02005327 if (ok == 0 || ok == 1)
5328 return Py_BuildValue("NO", bytes, ok == 1 ? Py_True : Py_False);
5329 }
5330 else {
5331 ok = RAND_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
5332 if (ok == 1)
5333 return bytes;
5334 }
5335 Py_DECREF(bytes);
5336
5337 err = ERR_get_error();
5338 errstr = ERR_reason_error_string(err);
5339 v = Py_BuildValue("(ks)", err, errstr);
5340 if (v != NULL) {
5341 PyErr_SetObject(PySSLErrorObject, v);
5342 Py_DECREF(v);
5343 }
5344 return NULL;
5345}
5346
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005347/*[clinic input]
5348_ssl.RAND_bytes
5349 n: int
5350 /
5351
5352Generate n cryptographically strong pseudo-random bytes.
5353[clinic start generated code]*/
5354
Victor Stinner99c8b162011-05-24 12:05:19 +02005355static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005356_ssl_RAND_bytes_impl(PyObject *module, int n)
5357/*[clinic end generated code: output=977da635e4838bc7 input=678ddf2872dfebfc]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02005358{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005359 return PySSL_RAND(n, 0);
Victor Stinner99c8b162011-05-24 12:05:19 +02005360}
5361
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005362/*[clinic input]
5363_ssl.RAND_pseudo_bytes
5364 n: int
5365 /
5366
5367Generate n pseudo-random bytes.
5368
5369Return a pair (bytes, is_cryptographic). is_cryptographic is True
5370if the bytes generated are cryptographically strong.
5371[clinic start generated code]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02005372
5373static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005374_ssl_RAND_pseudo_bytes_impl(PyObject *module, int n)
5375/*[clinic end generated code: output=b1509e937000e52d input=58312bd53f9bbdd0]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02005376{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005377 return PySSL_RAND(n, 1);
Victor Stinner99c8b162011-05-24 12:05:19 +02005378}
5379
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005380/*[clinic input]
5381_ssl.RAND_status
5382
5383Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.
5384
5385It is necessary to seed the PRNG with RAND_add() on some platforms before
5386using the ssl() function.
5387[clinic start generated code]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02005388
5389static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005390_ssl_RAND_status_impl(PyObject *module)
5391/*[clinic end generated code: output=7e0aaa2d39fdc1ad input=8a774b02d1dc81f3]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005392{
Christian Heimes217cfd12007-12-02 14:31:20 +00005393 return PyLong_FromLong(RAND_status());
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005394}
5395
Benjamin Petersonb8a2f512016-07-06 23:55:15 -07005396#ifndef OPENSSL_NO_EGD
Christian Heimesa5d07652016-09-24 10:48:05 +02005397/* LCOV_EXCL_START */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005398/*[clinic input]
5399_ssl.RAND_egd
5400 path: object(converter="PyUnicode_FSConverter")
5401 /
5402
5403Queries the entropy gather daemon (EGD) on the socket named by 'path'.
5404
5405Returns number of bytes read. Raises SSLError if connection to EGD
5406fails or if it does not provide enough data to seed PRNG.
5407[clinic start generated code]*/
5408
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005409static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005410_ssl_RAND_egd_impl(PyObject *module, PyObject *path)
5411/*[clinic end generated code: output=02a67c7c367f52fa input=1aeb7eb948312195]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005412{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005413 int bytes = RAND_egd(PyBytes_AsString(path));
Victor Stinnerf9faaad2010-05-16 21:36:37 +00005414 Py_DECREF(path);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005415 if (bytes == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00005416 PyErr_SetString(PySSLErrorObject,
5417 "EGD connection failed or EGD did not return "
5418 "enough data to seed the PRNG");
5419 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005420 }
Christian Heimes217cfd12007-12-02 14:31:20 +00005421 return PyLong_FromLong(bytes);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005422}
Christian Heimesa5d07652016-09-24 10:48:05 +02005423/* LCOV_EXCL_STOP */
Benjamin Petersonb8a2f512016-07-06 23:55:15 -07005424#endif /* OPENSSL_NO_EGD */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005425
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005426
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005427
5428/*[clinic input]
5429_ssl.get_default_verify_paths
5430
5431Return search paths and environment vars that are used by SSLContext's set_default_verify_paths() to load default CAs.
5432
5433The values are 'cert_file_env', 'cert_file', 'cert_dir_env', 'cert_dir'.
5434[clinic start generated code]*/
Christian Heimes6d7ad132013-06-09 18:02:55 +02005435
5436static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005437_ssl_get_default_verify_paths_impl(PyObject *module)
5438/*[clinic end generated code: output=e5b62a466271928b input=5210c953d98c3eb5]*/
Christian Heimes6d7ad132013-06-09 18:02:55 +02005439{
5440 PyObject *ofile_env = NULL;
5441 PyObject *ofile = NULL;
5442 PyObject *odir_env = NULL;
5443 PyObject *odir = NULL;
5444
Benjamin Petersond113c962015-07-18 10:59:13 -07005445#define CONVERT(info, target) { \
Christian Heimes6d7ad132013-06-09 18:02:55 +02005446 const char *tmp = (info); \
5447 target = NULL; \
5448 if (!tmp) { Py_INCREF(Py_None); target = Py_None; } \
5449 else if ((target = PyUnicode_DecodeFSDefault(tmp)) == NULL) { \
5450 target = PyBytes_FromString(tmp); } \
5451 if (!target) goto error; \
Benjamin Peterson025a1fd2015-11-14 15:12:38 -08005452 }
Christian Heimes6d7ad132013-06-09 18:02:55 +02005453
Benjamin Petersond113c962015-07-18 10:59:13 -07005454 CONVERT(X509_get_default_cert_file_env(), ofile_env);
5455 CONVERT(X509_get_default_cert_file(), ofile);
5456 CONVERT(X509_get_default_cert_dir_env(), odir_env);
5457 CONVERT(X509_get_default_cert_dir(), odir);
5458#undef CONVERT
Christian Heimes6d7ad132013-06-09 18:02:55 +02005459
Christian Heimes200bb1b2013-06-14 15:14:29 +02005460 return Py_BuildValue("NNNN", ofile_env, ofile, odir_env, odir);
Christian Heimes6d7ad132013-06-09 18:02:55 +02005461
5462 error:
5463 Py_XDECREF(ofile_env);
5464 Py_XDECREF(ofile);
5465 Py_XDECREF(odir_env);
5466 Py_XDECREF(odir);
5467 return NULL;
5468}
5469
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005470static PyObject*
5471asn1obj2py(ASN1_OBJECT *obj)
5472{
5473 int nid;
5474 const char *ln, *sn;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005475
5476 nid = OBJ_obj2nid(obj);
5477 if (nid == NID_undef) {
5478 PyErr_Format(PyExc_ValueError, "Unknown object");
5479 return NULL;
5480 }
5481 sn = OBJ_nid2sn(nid);
5482 ln = OBJ_nid2ln(nid);
Serhiy Storchakae503ca52017-09-05 01:28:53 +03005483 return Py_BuildValue("issN", nid, sn, ln, _asn1obj2py(obj, 1));
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005484}
5485
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005486/*[clinic input]
5487_ssl.txt2obj
5488 txt: str
5489 name: bool = False
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005490
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005491Lookup NID, short name, long name and OID of an ASN1_OBJECT.
5492
5493By default objects are looked up by OID. With name=True short and
5494long name are also matched.
5495[clinic start generated code]*/
5496
5497static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005498_ssl_txt2obj_impl(PyObject *module, const char *txt, int name)
5499/*[clinic end generated code: output=c38e3991347079c1 input=1c1e7d0aa7c48602]*/
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005500{
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005501 PyObject *result = NULL;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005502 ASN1_OBJECT *obj;
5503
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005504 obj = OBJ_txt2obj(txt, name ? 0 : 1);
5505 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01005506 PyErr_Format(PyExc_ValueError, "unknown object '%.100s'", txt);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005507 return NULL;
5508 }
5509 result = asn1obj2py(obj);
5510 ASN1_OBJECT_free(obj);
5511 return result;
5512}
5513
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005514/*[clinic input]
5515_ssl.nid2obj
5516 nid: int
5517 /
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005518
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005519Lookup NID, short name, long name and OID of an ASN1_OBJECT by NID.
5520[clinic start generated code]*/
5521
5522static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005523_ssl_nid2obj_impl(PyObject *module, int nid)
5524/*[clinic end generated code: output=4a98ab691cd4f84a input=51787a3bee7d8f98]*/
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005525{
5526 PyObject *result = NULL;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005527 ASN1_OBJECT *obj;
5528
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005529 if (nid < NID_undef) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01005530 PyErr_SetString(PyExc_ValueError, "NID must be positive.");
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005531 return NULL;
5532 }
5533 obj = OBJ_nid2obj(nid);
5534 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01005535 PyErr_Format(PyExc_ValueError, "unknown NID %i", nid);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005536 return NULL;
5537 }
5538 result = asn1obj2py(obj);
5539 ASN1_OBJECT_free(obj);
5540 return result;
5541}
5542
Christian Heimes46bebee2013-06-09 19:03:31 +02005543#ifdef _MSC_VER
Christian Heimes44109d72013-11-22 01:51:30 +01005544
5545static PyObject*
5546certEncodingType(DWORD encodingType)
5547{
5548 static PyObject *x509_asn = NULL;
5549 static PyObject *pkcs_7_asn = NULL;
5550
5551 if (x509_asn == NULL) {
5552 x509_asn = PyUnicode_InternFromString("x509_asn");
5553 if (x509_asn == NULL)
5554 return NULL;
5555 }
5556 if (pkcs_7_asn == NULL) {
5557 pkcs_7_asn = PyUnicode_InternFromString("pkcs_7_asn");
5558 if (pkcs_7_asn == NULL)
5559 return NULL;
5560 }
5561 switch(encodingType) {
5562 case X509_ASN_ENCODING:
5563 Py_INCREF(x509_asn);
5564 return x509_asn;
5565 case PKCS_7_ASN_ENCODING:
5566 Py_INCREF(pkcs_7_asn);
5567 return pkcs_7_asn;
5568 default:
5569 return PyLong_FromLong(encodingType);
5570 }
5571}
5572
5573static PyObject*
5574parseKeyUsage(PCCERT_CONTEXT pCertCtx, DWORD flags)
5575{
5576 CERT_ENHKEY_USAGE *usage;
5577 DWORD size, error, i;
5578 PyObject *retval;
5579
5580 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, NULL, &size)) {
5581 error = GetLastError();
5582 if (error == CRYPT_E_NOT_FOUND) {
5583 Py_RETURN_TRUE;
5584 }
5585 return PyErr_SetFromWindowsErr(error);
5586 }
5587
5588 usage = (CERT_ENHKEY_USAGE*)PyMem_Malloc(size);
5589 if (usage == NULL) {
5590 return PyErr_NoMemory();
5591 }
5592
5593 /* Now get the actual enhanced usage property */
5594 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, usage, &size)) {
5595 PyMem_Free(usage);
5596 error = GetLastError();
5597 if (error == CRYPT_E_NOT_FOUND) {
5598 Py_RETURN_TRUE;
5599 }
5600 return PyErr_SetFromWindowsErr(error);
5601 }
Steve Dowerfdd17ab2019-09-10 02:02:04 -07005602 retval = PyFrozenSet_New(NULL);
Christian Heimes44109d72013-11-22 01:51:30 +01005603 if (retval == NULL) {
5604 goto error;
5605 }
5606 for (i = 0; i < usage->cUsageIdentifier; ++i) {
5607 if (usage->rgpszUsageIdentifier[i]) {
5608 PyObject *oid;
5609 int err;
5610 oid = PyUnicode_FromString(usage->rgpszUsageIdentifier[i]);
5611 if (oid == NULL) {
5612 Py_CLEAR(retval);
5613 goto error;
5614 }
5615 err = PySet_Add(retval, oid);
5616 Py_DECREF(oid);
5617 if (err == -1) {
5618 Py_CLEAR(retval);
5619 goto error;
5620 }
5621 }
5622 }
5623 error:
5624 PyMem_Free(usage);
5625 return retval;
5626}
5627
kctherookied93fbbf2019-03-29 00:59:06 +07005628static HCERTSTORE
5629ssl_collect_certificates(const char *store_name)
5630{
5631/* this function collects the system certificate stores listed in
5632 * system_stores into a collection certificate store for being
5633 * enumerated. The store must be readable to be added to the
5634 * store collection.
5635 */
5636
5637 HCERTSTORE hCollectionStore = NULL, hSystemStore = NULL;
5638 static DWORD system_stores[] = {
5639 CERT_SYSTEM_STORE_LOCAL_MACHINE,
5640 CERT_SYSTEM_STORE_LOCAL_MACHINE_ENTERPRISE,
5641 CERT_SYSTEM_STORE_LOCAL_MACHINE_GROUP_POLICY,
5642 CERT_SYSTEM_STORE_CURRENT_USER,
5643 CERT_SYSTEM_STORE_CURRENT_USER_GROUP_POLICY,
5644 CERT_SYSTEM_STORE_SERVICES,
5645 CERT_SYSTEM_STORE_USERS};
5646 size_t i, storesAdded;
5647 BOOL result;
5648
5649 hCollectionStore = CertOpenStore(CERT_STORE_PROV_COLLECTION, 0,
5650 (HCRYPTPROV)NULL, 0, NULL);
5651 if (!hCollectionStore) {
5652 return NULL;
5653 }
5654 storesAdded = 0;
5655 for (i = 0; i < sizeof(system_stores) / sizeof(DWORD); i++) {
5656 hSystemStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0,
5657 (HCRYPTPROV)NULL,
5658 CERT_STORE_READONLY_FLAG |
5659 system_stores[i], store_name);
5660 if (hSystemStore) {
5661 result = CertAddStoreToCollection(hCollectionStore, hSystemStore,
5662 CERT_PHYSICAL_STORE_ADD_ENABLE_FLAG, 0);
5663 if (result) {
5664 ++storesAdded;
5665 }
Steve Dower5d695b62019-09-09 06:48:22 -07005666 CertCloseStore(hSystemStore, 0); /* flag must be 0 */
kctherookied93fbbf2019-03-29 00:59:06 +07005667 }
5668 }
5669 if (storesAdded == 0) {
5670 CertCloseStore(hCollectionStore, CERT_CLOSE_STORE_FORCE_FLAG);
5671 return NULL;
5672 }
5673
5674 return hCollectionStore;
5675}
5676
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005677/*[clinic input]
5678_ssl.enum_certificates
5679 store_name: str
5680
5681Retrieve certificates from Windows' cert store.
5682
5683store_name may be one of 'CA', 'ROOT' or 'MY'. The system may provide
5684more cert storages, too. The function returns a list of (bytes,
5685encoding_type, trust) tuples. The encoding_type flag can be interpreted
5686with X509_ASN_ENCODING or PKCS_7_ASN_ENCODING. The trust setting is either
5687a set of OIDs or the boolean True.
5688[clinic start generated code]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00005689
Christian Heimes46bebee2013-06-09 19:03:31 +02005690static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005691_ssl_enum_certificates_impl(PyObject *module, const char *store_name)
5692/*[clinic end generated code: output=5134dc8bb3a3c893 input=915f60d70461ea4e]*/
Christian Heimes46bebee2013-06-09 19:03:31 +02005693{
kctherookied93fbbf2019-03-29 00:59:06 +07005694 HCERTSTORE hCollectionStore = NULL;
Christian Heimes44109d72013-11-22 01:51:30 +01005695 PCCERT_CONTEXT pCertCtx = NULL;
5696 PyObject *keyusage = NULL, *cert = NULL, *enc = NULL, *tup = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02005697 PyObject *result = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02005698
Steve Dowerfdd17ab2019-09-10 02:02:04 -07005699 result = PySet_New(NULL);
Christian Heimes44109d72013-11-22 01:51:30 +01005700 if (result == NULL) {
5701 return NULL;
5702 }
kctherookied93fbbf2019-03-29 00:59:06 +07005703 hCollectionStore = ssl_collect_certificates(store_name);
5704 if (hCollectionStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02005705 Py_DECREF(result);
5706 return PyErr_SetFromWindowsErr(GetLastError());
5707 }
5708
kctherookied93fbbf2019-03-29 00:59:06 +07005709 while (pCertCtx = CertEnumCertificatesInStore(hCollectionStore, pCertCtx)) {
Christian Heimes44109d72013-11-22 01:51:30 +01005710 cert = PyBytes_FromStringAndSize((const char*)pCertCtx->pbCertEncoded,
5711 pCertCtx->cbCertEncoded);
5712 if (!cert) {
5713 Py_CLEAR(result);
5714 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02005715 }
Christian Heimes44109d72013-11-22 01:51:30 +01005716 if ((enc = certEncodingType(pCertCtx->dwCertEncodingType)) == NULL) {
5717 Py_CLEAR(result);
5718 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02005719 }
Christian Heimes44109d72013-11-22 01:51:30 +01005720 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG);
5721 if (keyusage == Py_True) {
5722 Py_DECREF(keyusage);
5723 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_EXT_ONLY_ENHKEY_USAGE_FLAG);
Christian Heimes46bebee2013-06-09 19:03:31 +02005724 }
Christian Heimes44109d72013-11-22 01:51:30 +01005725 if (keyusage == NULL) {
5726 Py_CLEAR(result);
5727 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02005728 }
Christian Heimes44109d72013-11-22 01:51:30 +01005729 if ((tup = PyTuple_New(3)) == NULL) {
5730 Py_CLEAR(result);
5731 break;
5732 }
5733 PyTuple_SET_ITEM(tup, 0, cert);
5734 cert = NULL;
5735 PyTuple_SET_ITEM(tup, 1, enc);
5736 enc = NULL;
5737 PyTuple_SET_ITEM(tup, 2, keyusage);
5738 keyusage = NULL;
Steve Dowerfdd17ab2019-09-10 02:02:04 -07005739 if (PySet_Add(result, tup) == -1) {
5740 Py_CLEAR(result);
5741 Py_CLEAR(tup);
5742 break;
Christian Heimes44109d72013-11-22 01:51:30 +01005743 }
5744 Py_CLEAR(tup);
5745 }
5746 if (pCertCtx) {
5747 /* loop ended with an error, need to clean up context manually */
5748 CertFreeCertificateContext(pCertCtx);
Christian Heimes46bebee2013-06-09 19:03:31 +02005749 }
5750
5751 /* In error cases cert, enc and tup may not be NULL */
5752 Py_XDECREF(cert);
5753 Py_XDECREF(enc);
Christian Heimes44109d72013-11-22 01:51:30 +01005754 Py_XDECREF(keyusage);
Christian Heimes46bebee2013-06-09 19:03:31 +02005755 Py_XDECREF(tup);
5756
kctherookied93fbbf2019-03-29 00:59:06 +07005757 /* CERT_CLOSE_STORE_FORCE_FLAG forces freeing of memory for all contexts
5758 associated with the store, in this case our collection store and the
5759 associated system stores. */
5760 if (!CertCloseStore(hCollectionStore, CERT_CLOSE_STORE_FORCE_FLAG)) {
Christian Heimes46bebee2013-06-09 19:03:31 +02005761 /* This error case might shadow another exception.*/
Christian Heimes44109d72013-11-22 01:51:30 +01005762 Py_XDECREF(result);
5763 return PyErr_SetFromWindowsErr(GetLastError());
5764 }
kctherookied93fbbf2019-03-29 00:59:06 +07005765
Steve Dowerfdd17ab2019-09-10 02:02:04 -07005766 /* convert set to list */
5767 if (result == NULL) {
5768 return NULL;
5769 } else {
5770 PyObject *lst = PySequence_List(result);
5771 Py_DECREF(result);
5772 return lst;
5773 }
Christian Heimes44109d72013-11-22 01:51:30 +01005774}
5775
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005776/*[clinic input]
5777_ssl.enum_crls
5778 store_name: str
5779
5780Retrieve CRLs from Windows' cert store.
5781
5782store_name may be one of 'CA', 'ROOT' or 'MY'. The system may provide
5783more cert storages, too. The function returns a list of (bytes,
5784encoding_type) tuples. The encoding_type flag can be interpreted with
5785X509_ASN_ENCODING or PKCS_7_ASN_ENCODING.
5786[clinic start generated code]*/
Christian Heimes44109d72013-11-22 01:51:30 +01005787
5788static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005789_ssl_enum_crls_impl(PyObject *module, const char *store_name)
5790/*[clinic end generated code: output=bce467f60ccd03b6 input=a1f1d7629f1c5d3d]*/
Christian Heimes44109d72013-11-22 01:51:30 +01005791{
kctherookied93fbbf2019-03-29 00:59:06 +07005792 HCERTSTORE hCollectionStore = NULL;
Christian Heimes44109d72013-11-22 01:51:30 +01005793 PCCRL_CONTEXT pCrlCtx = NULL;
5794 PyObject *crl = NULL, *enc = NULL, *tup = NULL;
5795 PyObject *result = NULL;
5796
Steve Dowerfdd17ab2019-09-10 02:02:04 -07005797 result = PySet_New(NULL);
Christian Heimes44109d72013-11-22 01:51:30 +01005798 if (result == NULL) {
5799 return NULL;
5800 }
kctherookied93fbbf2019-03-29 00:59:06 +07005801 hCollectionStore = ssl_collect_certificates(store_name);
5802 if (hCollectionStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02005803 Py_DECREF(result);
5804 return PyErr_SetFromWindowsErr(GetLastError());
5805 }
Christian Heimes44109d72013-11-22 01:51:30 +01005806
kctherookied93fbbf2019-03-29 00:59:06 +07005807 while (pCrlCtx = CertEnumCRLsInStore(hCollectionStore, pCrlCtx)) {
Christian Heimes44109d72013-11-22 01:51:30 +01005808 crl = PyBytes_FromStringAndSize((const char*)pCrlCtx->pbCrlEncoded,
5809 pCrlCtx->cbCrlEncoded);
5810 if (!crl) {
5811 Py_CLEAR(result);
5812 break;
5813 }
5814 if ((enc = certEncodingType(pCrlCtx->dwCertEncodingType)) == NULL) {
5815 Py_CLEAR(result);
5816 break;
5817 }
5818 if ((tup = PyTuple_New(2)) == NULL) {
5819 Py_CLEAR(result);
5820 break;
5821 }
5822 PyTuple_SET_ITEM(tup, 0, crl);
5823 crl = NULL;
5824 PyTuple_SET_ITEM(tup, 1, enc);
5825 enc = NULL;
5826
Steve Dowerfdd17ab2019-09-10 02:02:04 -07005827 if (PySet_Add(result, tup) == -1) {
5828 Py_CLEAR(result);
5829 Py_CLEAR(tup);
5830 break;
Christian Heimes44109d72013-11-22 01:51:30 +01005831 }
5832 Py_CLEAR(tup);
Christian Heimes46bebee2013-06-09 19:03:31 +02005833 }
Christian Heimes44109d72013-11-22 01:51:30 +01005834 if (pCrlCtx) {
5835 /* loop ended with an error, need to clean up context manually */
5836 CertFreeCRLContext(pCrlCtx);
5837 }
5838
5839 /* In error cases cert, enc and tup may not be NULL */
5840 Py_XDECREF(crl);
5841 Py_XDECREF(enc);
5842 Py_XDECREF(tup);
5843
kctherookied93fbbf2019-03-29 00:59:06 +07005844 /* CERT_CLOSE_STORE_FORCE_FLAG forces freeing of memory for all contexts
5845 associated with the store, in this case our collection store and the
5846 associated system stores. */
5847 if (!CertCloseStore(hCollectionStore, CERT_CLOSE_STORE_FORCE_FLAG)) {
Christian Heimes44109d72013-11-22 01:51:30 +01005848 /* This error case might shadow another exception.*/
5849 Py_XDECREF(result);
5850 return PyErr_SetFromWindowsErr(GetLastError());
5851 }
Steve Dowerfdd17ab2019-09-10 02:02:04 -07005852 /* convert set to list */
5853 if (result == NULL) {
5854 return NULL;
5855 } else {
5856 PyObject *lst = PySequence_List(result);
5857 Py_DECREF(result);
5858 return lst;
5859 }
Christian Heimes46bebee2013-06-09 19:03:31 +02005860}
Christian Heimes44109d72013-11-22 01:51:30 +01005861
5862#endif /* _MSC_VER */
Bill Janssen40a0f662008-08-12 16:56:25 +00005863
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005864/* List of functions exported by this module. */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005865static PyMethodDef PySSL_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005866 _SSL__TEST_DECODE_CERT_METHODDEF
5867 _SSL_RAND_ADD_METHODDEF
5868 _SSL_RAND_BYTES_METHODDEF
5869 _SSL_RAND_PSEUDO_BYTES_METHODDEF
5870 _SSL_RAND_EGD_METHODDEF
5871 _SSL_RAND_STATUS_METHODDEF
5872 _SSL_GET_DEFAULT_VERIFY_PATHS_METHODDEF
5873 _SSL_ENUM_CERTIFICATES_METHODDEF
5874 _SSL_ENUM_CRLS_METHODDEF
5875 _SSL_TXT2OBJ_METHODDEF
5876 _SSL_NID2OBJ_METHODDEF
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005877 {NULL, NULL} /* Sentinel */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005878};
5879
5880
Christian Heimes598894f2016-09-05 23:19:05 +02005881#ifdef HAVE_OPENSSL_CRYPTO_LOCK
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005882
5883/* an implementation of OpenSSL threading operations in terms
Christian Heimes598894f2016-09-05 23:19:05 +02005884 * of the Python C thread library
5885 * Only used up to 1.0.2. OpenSSL 1.1.0+ has its own locking code.
5886 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005887
5888static PyThread_type_lock *_ssl_locks = NULL;
5889
Christian Heimes4d98ca92013-08-19 17:36:29 +02005890#if OPENSSL_VERSION_NUMBER >= 0x10000000
5891/* use new CRYPTO_THREADID API. */
5892static void
5893_ssl_threadid_callback(CRYPTO_THREADID *id)
5894{
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +02005895 CRYPTO_THREADID_set_numeric(id, PyThread_get_thread_ident());
Christian Heimes4d98ca92013-08-19 17:36:29 +02005896}
5897#else
5898/* deprecated CRYPTO_set_id_callback() API. */
5899static unsigned long
5900_ssl_thread_id_function (void) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005901 return PyThread_get_thread_ident();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005902}
Christian Heimes4d98ca92013-08-19 17:36:29 +02005903#endif
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005904
Bill Janssen6e027db2007-11-15 22:23:56 +00005905static void _ssl_thread_locking_function
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005906 (int mode, int n, const char *file, int line) {
5907 /* this function is needed to perform locking on shared data
5908 structures. (Note that OpenSSL uses a number of global data
5909 structures that will be implicitly shared whenever multiple
5910 threads use OpenSSL.) Multi-threaded applications will
5911 crash at random if it is not set.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005912
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005913 locking_function() must be able to handle up to
5914 CRYPTO_num_locks() different mutex locks. It sets the n-th
5915 lock if mode & CRYPTO_LOCK, and releases it otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005916
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005917 file and line are the file number of the function setting the
5918 lock. They can be useful for debugging.
5919 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005920
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005921 if ((_ssl_locks == NULL) ||
5922 (n < 0) || ((unsigned)n >= _ssl_locks_count))
5923 return;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005924
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005925 if (mode & CRYPTO_LOCK) {
5926 PyThread_acquire_lock(_ssl_locks[n], 1);
5927 } else {
5928 PyThread_release_lock(_ssl_locks[n]);
5929 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005930}
5931
5932static int _setup_ssl_threads(void) {
5933
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005934 unsigned int i;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005935
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005936 if (_ssl_locks == NULL) {
5937 _ssl_locks_count = CRYPTO_num_locks();
Christian Heimesf6365e32016-09-13 20:48:13 +02005938 _ssl_locks = PyMem_Calloc(_ssl_locks_count,
5939 sizeof(PyThread_type_lock));
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02005940 if (_ssl_locks == NULL) {
5941 PyErr_NoMemory();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005942 return 0;
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02005943 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005944 for (i = 0; i < _ssl_locks_count; i++) {
5945 _ssl_locks[i] = PyThread_allocate_lock();
5946 if (_ssl_locks[i] == NULL) {
5947 unsigned int j;
5948 for (j = 0; j < i; j++) {
5949 PyThread_free_lock(_ssl_locks[j]);
5950 }
Victor Stinnerb6404912013-07-07 16:21:41 +02005951 PyMem_Free(_ssl_locks);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005952 return 0;
5953 }
5954 }
5955 CRYPTO_set_locking_callback(_ssl_thread_locking_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02005956#if OPENSSL_VERSION_NUMBER >= 0x10000000
5957 CRYPTO_THREADID_set_callback(_ssl_threadid_callback);
5958#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005959 CRYPTO_set_id_callback(_ssl_thread_id_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02005960#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005961 }
5962 return 1;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005963}
5964
Antoine Pitroua6a4dc82017-09-07 18:56:24 +02005965#endif /* HAVE_OPENSSL_CRYPTO_LOCK for OpenSSL < 1.1.0 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005966
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005967PyDoc_STRVAR(module_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005968"Implementation module for SSL socket operations. See the socket module\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005969for documentation.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005970
Martin v. Löwis1a214512008-06-11 05:26:20 +00005971
5972static struct PyModuleDef _sslmodule = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005973 PyModuleDef_HEAD_INIT,
5974 "_ssl",
5975 module_doc,
5976 -1,
5977 PySSL_methods,
5978 NULL,
5979 NULL,
5980 NULL,
5981 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00005982};
5983
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02005984
5985static void
5986parse_openssl_version(unsigned long libver,
5987 unsigned int *major, unsigned int *minor,
5988 unsigned int *fix, unsigned int *patch,
5989 unsigned int *status)
5990{
5991 *status = libver & 0xF;
5992 libver >>= 4;
5993 *patch = libver & 0xFF;
5994 libver >>= 8;
5995 *fix = libver & 0xFF;
5996 libver >>= 8;
5997 *minor = libver & 0xFF;
5998 libver >>= 8;
5999 *major = libver & 0xFF;
6000}
6001
Mark Hammondfe51c6d2002-08-02 02:27:13 +00006002PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00006003PyInit__ssl(void)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00006004{
Christian Heimesb3ad0e52017-09-08 12:00:19 -07006005 PyObject *m, *d, *r, *bases;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006006 unsigned long libver;
6007 unsigned int major, minor, fix, patch, status;
6008 PySocketModule_APIObject *socket_api;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02006009 struct py_ssl_error_code *errcode;
6010 struct py_ssl_library_code *libcode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00006011
Antoine Pitrou152efa22010-05-16 18:19:27 +00006012 if (PyType_Ready(&PySSLContext_Type) < 0)
6013 return NULL;
6014 if (PyType_Ready(&PySSLSocket_Type) < 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006015 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02006016 if (PyType_Ready(&PySSLMemoryBIO_Type) < 0)
6017 return NULL;
Christian Heimes99a65702016-09-10 23:44:53 +02006018 if (PyType_Ready(&PySSLSession_Type) < 0)
6019 return NULL;
6020
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00006021
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006022 m = PyModule_Create(&_sslmodule);
6023 if (m == NULL)
6024 return NULL;
6025 d = PyModule_GetDict(m);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00006026
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006027 /* Load _socket module and its C API */
6028 socket_api = PySocketModule_ImportModuleAndAPI();
6029 if (!socket_api)
6030 return NULL;
6031 PySocketModule = *socket_api;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00006032
Christian Heimesc941e622017-09-05 15:47:11 +02006033#ifndef OPENSSL_VERSION_1_1
6034 /* Load all algorithms and initialize cpuid */
6035 OPENSSL_add_all_algorithms_noconf();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006036 /* Init OpenSSL */
6037 SSL_load_error_strings();
6038 SSL_library_init();
Christian Heimesc941e622017-09-05 15:47:11 +02006039#endif
6040
Christian Heimes598894f2016-09-05 23:19:05 +02006041#ifdef HAVE_OPENSSL_CRYPTO_LOCK
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006042 /* note that this will start threading if not already started */
6043 if (!_setup_ssl_threads()) {
6044 return NULL;
6045 }
Christian Heimes387c7442020-05-15 22:36:51 +02006046#elif OPENSSL_VERSION_1_1
Christian Heimes598894f2016-09-05 23:19:05 +02006047 /* OpenSSL 1.1.0 builtin thread support is enabled */
6048 _ssl_locks_count++;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00006049#endif
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00006050
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006051 /* Add symbols to module dict */
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02006052 sslerror_type_slots[0].pfunc = PyExc_OSError;
6053 PySSLErrorObject = PyType_FromSpec(&sslerror_type_spec);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006054 if (PySSLErrorObject == NULL)
6055 return NULL;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02006056
Christian Heimesb3ad0e52017-09-08 12:00:19 -07006057 /* ssl.CertificateError used to be a subclass of ValueError */
6058 bases = Py_BuildValue("OO", PySSLErrorObject, PyExc_ValueError);
6059 if (bases == NULL)
6060 return NULL;
6061 PySSLCertVerificationErrorObject = PyErr_NewExceptionWithDoc(
6062 "ssl.SSLCertVerificationError", SSLCertVerificationError_doc,
6063 bases, NULL);
6064 Py_DECREF(bases);
Antoine Pitrou41032a62011-10-27 23:56:55 +02006065 PySSLZeroReturnErrorObject = PyErr_NewExceptionWithDoc(
6066 "ssl.SSLZeroReturnError", SSLZeroReturnError_doc,
6067 PySSLErrorObject, NULL);
6068 PySSLWantReadErrorObject = PyErr_NewExceptionWithDoc(
6069 "ssl.SSLWantReadError", SSLWantReadError_doc,
6070 PySSLErrorObject, NULL);
6071 PySSLWantWriteErrorObject = PyErr_NewExceptionWithDoc(
6072 "ssl.SSLWantWriteError", SSLWantWriteError_doc,
6073 PySSLErrorObject, NULL);
6074 PySSLSyscallErrorObject = PyErr_NewExceptionWithDoc(
6075 "ssl.SSLSyscallError", SSLSyscallError_doc,
6076 PySSLErrorObject, NULL);
6077 PySSLEOFErrorObject = PyErr_NewExceptionWithDoc(
6078 "ssl.SSLEOFError", SSLEOFError_doc,
6079 PySSLErrorObject, NULL);
Christian Heimesb3ad0e52017-09-08 12:00:19 -07006080 if (PySSLCertVerificationErrorObject == NULL
6081 || PySSLZeroReturnErrorObject == NULL
Antoine Pitrou41032a62011-10-27 23:56:55 +02006082 || PySSLWantReadErrorObject == NULL
6083 || PySSLWantWriteErrorObject == NULL
6084 || PySSLSyscallErrorObject == NULL
6085 || PySSLEOFErrorObject == NULL)
6086 return NULL;
6087 if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0
Christian Heimesb3ad0e52017-09-08 12:00:19 -07006088 || PyDict_SetItemString(d, "SSLCertVerificationError",
6089 PySSLCertVerificationErrorObject) != 0
Antoine Pitrou41032a62011-10-27 23:56:55 +02006090 || PyDict_SetItemString(d, "SSLZeroReturnError", PySSLZeroReturnErrorObject) != 0
6091 || PyDict_SetItemString(d, "SSLWantReadError", PySSLWantReadErrorObject) != 0
6092 || PyDict_SetItemString(d, "SSLWantWriteError", PySSLWantWriteErrorObject) != 0
6093 || PyDict_SetItemString(d, "SSLSyscallError", PySSLSyscallErrorObject) != 0
6094 || PyDict_SetItemString(d, "SSLEOFError", PySSLEOFErrorObject) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006095 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00006096 if (PyDict_SetItemString(d, "_SSLContext",
6097 (PyObject *)&PySSLContext_Type) != 0)
6098 return NULL;
6099 if (PyDict_SetItemString(d, "_SSLSocket",
6100 (PyObject *)&PySSLSocket_Type) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006101 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02006102 if (PyDict_SetItemString(d, "MemoryBIO",
6103 (PyObject *)&PySSLMemoryBIO_Type) != 0)
6104 return NULL;
Christian Heimes99a65702016-09-10 23:44:53 +02006105 if (PyDict_SetItemString(d, "SSLSession",
6106 (PyObject *)&PySSLSession_Type) != 0)
6107 return NULL;
6108
Christian Heimes892d66e2018-01-29 14:10:18 +01006109 PyModule_AddStringConstant(m, "_DEFAULT_CIPHERS",
6110 PY_SSL_DEFAULT_CIPHER_STRING);
6111
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006112 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
6113 PY_SSL_ERROR_ZERO_RETURN);
6114 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
6115 PY_SSL_ERROR_WANT_READ);
6116 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
6117 PY_SSL_ERROR_WANT_WRITE);
6118 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
6119 PY_SSL_ERROR_WANT_X509_LOOKUP);
6120 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
6121 PY_SSL_ERROR_SYSCALL);
6122 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
6123 PY_SSL_ERROR_SSL);
6124 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
6125 PY_SSL_ERROR_WANT_CONNECT);
6126 /* non ssl.h errorcodes */
6127 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
6128 PY_SSL_ERROR_EOF);
6129 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
6130 PY_SSL_ERROR_INVALID_ERROR_CODE);
6131 /* cert requirements */
6132 PyModule_AddIntConstant(m, "CERT_NONE",
6133 PY_SSL_CERT_NONE);
6134 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
6135 PY_SSL_CERT_OPTIONAL);
6136 PyModule_AddIntConstant(m, "CERT_REQUIRED",
6137 PY_SSL_CERT_REQUIRED);
Christian Heimes22587792013-11-21 23:56:13 +01006138 /* CRL verification for verification_flags */
6139 PyModule_AddIntConstant(m, "VERIFY_DEFAULT",
6140 0);
6141 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_LEAF",
6142 X509_V_FLAG_CRL_CHECK);
6143 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_CHAIN",
6144 X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
6145 PyModule_AddIntConstant(m, "VERIFY_X509_STRICT",
6146 X509_V_FLAG_X509_STRICT);
Benjamin Peterson990fcaa2015-03-04 22:49:41 -05006147#ifdef X509_V_FLAG_TRUSTED_FIRST
6148 PyModule_AddIntConstant(m, "VERIFY_X509_TRUSTED_FIRST",
6149 X509_V_FLAG_TRUSTED_FIRST);
6150#endif
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00006151
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01006152 /* Alert Descriptions from ssl.h */
6153 /* note RESERVED constants no longer intended for use have been removed */
6154 /* http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-6 */
6155
6156#define ADD_AD_CONSTANT(s) \
6157 PyModule_AddIntConstant(m, "ALERT_DESCRIPTION_"#s, \
6158 SSL_AD_##s)
6159
6160 ADD_AD_CONSTANT(CLOSE_NOTIFY);
6161 ADD_AD_CONSTANT(UNEXPECTED_MESSAGE);
6162 ADD_AD_CONSTANT(BAD_RECORD_MAC);
6163 ADD_AD_CONSTANT(RECORD_OVERFLOW);
6164 ADD_AD_CONSTANT(DECOMPRESSION_FAILURE);
6165 ADD_AD_CONSTANT(HANDSHAKE_FAILURE);
6166 ADD_AD_CONSTANT(BAD_CERTIFICATE);
6167 ADD_AD_CONSTANT(UNSUPPORTED_CERTIFICATE);
6168 ADD_AD_CONSTANT(CERTIFICATE_REVOKED);
6169 ADD_AD_CONSTANT(CERTIFICATE_EXPIRED);
6170 ADD_AD_CONSTANT(CERTIFICATE_UNKNOWN);
6171 ADD_AD_CONSTANT(ILLEGAL_PARAMETER);
6172 ADD_AD_CONSTANT(UNKNOWN_CA);
6173 ADD_AD_CONSTANT(ACCESS_DENIED);
6174 ADD_AD_CONSTANT(DECODE_ERROR);
6175 ADD_AD_CONSTANT(DECRYPT_ERROR);
6176 ADD_AD_CONSTANT(PROTOCOL_VERSION);
6177 ADD_AD_CONSTANT(INSUFFICIENT_SECURITY);
6178 ADD_AD_CONSTANT(INTERNAL_ERROR);
6179 ADD_AD_CONSTANT(USER_CANCELLED);
6180 ADD_AD_CONSTANT(NO_RENEGOTIATION);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01006181 /* Not all constants are in old OpenSSL versions */
Antoine Pitrou912fbff2013-03-30 16:29:32 +01006182#ifdef SSL_AD_UNSUPPORTED_EXTENSION
6183 ADD_AD_CONSTANT(UNSUPPORTED_EXTENSION);
6184#endif
6185#ifdef SSL_AD_CERTIFICATE_UNOBTAINABLE
6186 ADD_AD_CONSTANT(CERTIFICATE_UNOBTAINABLE);
6187#endif
6188#ifdef SSL_AD_UNRECOGNIZED_NAME
6189 ADD_AD_CONSTANT(UNRECOGNIZED_NAME);
6190#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01006191#ifdef SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE
6192 ADD_AD_CONSTANT(BAD_CERTIFICATE_STATUS_RESPONSE);
6193#endif
6194#ifdef SSL_AD_BAD_CERTIFICATE_HASH_VALUE
6195 ADD_AD_CONSTANT(BAD_CERTIFICATE_HASH_VALUE);
6196#endif
6197#ifdef SSL_AD_UNKNOWN_PSK_IDENTITY
6198 ADD_AD_CONSTANT(UNKNOWN_PSK_IDENTITY);
6199#endif
6200
6201#undef ADD_AD_CONSTANT
6202
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006203 /* protocol versions */
Victor Stinner3de49192011-05-09 00:42:58 +02006204#ifndef OPENSSL_NO_SSL2
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006205 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
6206 PY_SSL_VERSION_SSL2);
Victor Stinner3de49192011-05-09 00:42:58 +02006207#endif
Benjamin Petersone32467c2014-12-05 21:59:35 -05006208#ifndef OPENSSL_NO_SSL3
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006209 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
6210 PY_SSL_VERSION_SSL3);
Benjamin Petersone32467c2014-12-05 21:59:35 -05006211#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006212 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
Christian Heimes598894f2016-09-05 23:19:05 +02006213 PY_SSL_VERSION_TLS);
6214 PyModule_AddIntConstant(m, "PROTOCOL_TLS",
6215 PY_SSL_VERSION_TLS);
Christian Heimes5fe668c2016-09-12 00:01:11 +02006216 PyModule_AddIntConstant(m, "PROTOCOL_TLS_CLIENT",
6217 PY_SSL_VERSION_TLS_CLIENT);
6218 PyModule_AddIntConstant(m, "PROTOCOL_TLS_SERVER",
6219 PY_SSL_VERSION_TLS_SERVER);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006220 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
6221 PY_SSL_VERSION_TLS1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01006222 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_1",
6223 PY_SSL_VERSION_TLS1_1);
6224 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_2",
6225 PY_SSL_VERSION_TLS1_2);
Antoine Pitrou04f6a322010-04-05 21:40:07 +00006226
Antoine Pitroub5218772010-05-21 09:56:06 +00006227 /* protocol options */
Antoine Pitrou3f366312012-01-27 09:50:45 +01006228 PyModule_AddIntConstant(m, "OP_ALL",
6229 SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
Antoine Pitroub5218772010-05-21 09:56:06 +00006230 PyModule_AddIntConstant(m, "OP_NO_SSLv2", SSL_OP_NO_SSLv2);
6231 PyModule_AddIntConstant(m, "OP_NO_SSLv3", SSL_OP_NO_SSLv3);
6232 PyModule_AddIntConstant(m, "OP_NO_TLSv1", SSL_OP_NO_TLSv1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01006233 PyModule_AddIntConstant(m, "OP_NO_TLSv1_1", SSL_OP_NO_TLSv1_1);
6234 PyModule_AddIntConstant(m, "OP_NO_TLSv1_2", SSL_OP_NO_TLSv1_2);
Christian Heimescb5b68a2017-09-07 18:07:00 -07006235#ifdef SSL_OP_NO_TLSv1_3
6236 PyModule_AddIntConstant(m, "OP_NO_TLSv1_3", SSL_OP_NO_TLSv1_3);
6237#else
6238 PyModule_AddIntConstant(m, "OP_NO_TLSv1_3", 0);
6239#endif
Antoine Pitrou6db49442011-12-19 13:27:11 +01006240 PyModule_AddIntConstant(m, "OP_CIPHER_SERVER_PREFERENCE",
6241 SSL_OP_CIPHER_SERVER_PREFERENCE);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01006242 PyModule_AddIntConstant(m, "OP_SINGLE_DH_USE", SSL_OP_SINGLE_DH_USE);
Christian Heimes99a65702016-09-10 23:44:53 +02006243 PyModule_AddIntConstant(m, "OP_NO_TICKET", SSL_OP_NO_TICKET);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01006244#ifdef SSL_OP_SINGLE_ECDH_USE
Antoine Pitrou923df6f2011-12-19 17:16:51 +01006245 PyModule_AddIntConstant(m, "OP_SINGLE_ECDH_USE", SSL_OP_SINGLE_ECDH_USE);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01006246#endif
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01006247#ifdef SSL_OP_NO_COMPRESSION
6248 PyModule_AddIntConstant(m, "OP_NO_COMPRESSION",
6249 SSL_OP_NO_COMPRESSION);
6250#endif
Christian Heimes05d9fe32018-02-27 08:55:39 +01006251#ifdef SSL_OP_ENABLE_MIDDLEBOX_COMPAT
6252 PyModule_AddIntConstant(m, "OP_ENABLE_MIDDLEBOX_COMPAT",
6253 SSL_OP_ENABLE_MIDDLEBOX_COMPAT);
6254#endif
Christian Heimes67c48012018-05-15 16:25:40 -04006255#ifdef SSL_OP_NO_RENEGOTIATION
6256 PyModule_AddIntConstant(m, "OP_NO_RENEGOTIATION",
6257 SSL_OP_NO_RENEGOTIATION);
6258#endif
Antoine Pitroub5218772010-05-21 09:56:06 +00006259
Christian Heimes61d478c2018-01-27 15:51:38 +01006260#ifdef X509_CHECK_FLAG_ALWAYS_CHECK_SUBJECT
6261 PyModule_AddIntConstant(m, "HOSTFLAG_ALWAYS_CHECK_SUBJECT",
6262 X509_CHECK_FLAG_ALWAYS_CHECK_SUBJECT);
6263#endif
6264#ifdef X509_CHECK_FLAG_NEVER_CHECK_SUBJECT
6265 PyModule_AddIntConstant(m, "HOSTFLAG_NEVER_CHECK_SUBJECT",
6266 X509_CHECK_FLAG_NEVER_CHECK_SUBJECT);
6267#endif
6268#ifdef X509_CHECK_FLAG_NO_WILDCARDS
6269 PyModule_AddIntConstant(m, "HOSTFLAG_NO_WILDCARDS",
6270 X509_CHECK_FLAG_NO_WILDCARDS);
6271#endif
6272#ifdef X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS
6273 PyModule_AddIntConstant(m, "HOSTFLAG_NO_PARTIAL_WILDCARDS",
6274 X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS);
6275#endif
6276#ifdef X509_CHECK_FLAG_MULTI_LABEL_WILDCARDS
6277 PyModule_AddIntConstant(m, "HOSTFLAG_MULTI_LABEL_WILDCARDS",
6278 X509_CHECK_FLAG_MULTI_LABEL_WILDCARDS);
6279#endif
6280#ifdef X509_CHECK_FLAG_SINGLE_LABEL_SUBDOMAINS
6281 PyModule_AddIntConstant(m, "HOSTFLAG_SINGLE_LABEL_SUBDOMAINS",
6282 X509_CHECK_FLAG_SINGLE_LABEL_SUBDOMAINS);
6283#endif
6284
Christian Heimes698dde12018-02-27 11:54:43 +01006285 /* protocol versions */
6286 PyModule_AddIntConstant(m, "PROTO_MINIMUM_SUPPORTED",
6287 PY_PROTO_MINIMUM_SUPPORTED);
6288 PyModule_AddIntConstant(m, "PROTO_MAXIMUM_SUPPORTED",
6289 PY_PROTO_MAXIMUM_SUPPORTED);
6290 PyModule_AddIntConstant(m, "PROTO_SSLv3", PY_PROTO_SSLv3);
6291 PyModule_AddIntConstant(m, "PROTO_TLSv1", PY_PROTO_TLSv1);
6292 PyModule_AddIntConstant(m, "PROTO_TLSv1_1", PY_PROTO_TLSv1_1);
6293 PyModule_AddIntConstant(m, "PROTO_TLSv1_2", PY_PROTO_TLSv1_2);
6294 PyModule_AddIntConstant(m, "PROTO_TLSv1_3", PY_PROTO_TLSv1_3);
Antoine Pitroud5323212010-10-22 18:19:07 +00006295
Victor Stinnerb37672d2018-11-22 03:37:50 +01006296#define addbool(m, key, value) \
6297 do { \
6298 PyObject *bool_obj = (value) ? Py_True : Py_False; \
6299 Py_INCREF(bool_obj); \
6300 PyModule_AddObject((m), (key), bool_obj); \
6301 } while (0)
Christian Heimes698dde12018-02-27 11:54:43 +01006302
6303#if HAVE_SNI
6304 addbool(m, "HAS_SNI", 1);
Antoine Pitrou501da612011-12-21 09:27:41 +01006305#else
Christian Heimes698dde12018-02-27 11:54:43 +01006306 addbool(m, "HAS_SNI", 0);
Antoine Pitrou501da612011-12-21 09:27:41 +01006307#endif
Christian Heimes698dde12018-02-27 11:54:43 +01006308
6309 addbool(m, "HAS_TLS_UNIQUE", 1);
6310
6311#ifndef OPENSSL_NO_ECDH
6312 addbool(m, "HAS_ECDH", 1);
6313#else
6314 addbool(m, "HAS_ECDH", 0);
6315#endif
Antoine Pitrou501da612011-12-21 09:27:41 +01006316
Christian Heimes29eab552018-02-25 12:31:33 +01006317#if HAVE_NPN
Christian Heimes698dde12018-02-27 11:54:43 +01006318 addbool(m, "HAS_NPN", 1);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01006319#else
Christian Heimes698dde12018-02-27 11:54:43 +01006320 addbool(m, "HAS_NPN", 0);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01006321#endif
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01006322
Christian Heimes29eab552018-02-25 12:31:33 +01006323#if HAVE_ALPN
Christian Heimes698dde12018-02-27 11:54:43 +01006324 addbool(m, "HAS_ALPN", 1);
Benjamin Petersoncca27322015-01-23 16:35:37 -05006325#else
Christian Heimes698dde12018-02-27 11:54:43 +01006326 addbool(m, "HAS_ALPN", 0);
Benjamin Petersoncca27322015-01-23 16:35:37 -05006327#endif
Christian Heimes698dde12018-02-27 11:54:43 +01006328
6329#if defined(SSL2_VERSION) && !defined(OPENSSL_NO_SSL2)
6330 addbool(m, "HAS_SSLv2", 1);
6331#else
6332 addbool(m, "HAS_SSLv2", 0);
6333#endif
6334
6335#if defined(SSL3_VERSION) && !defined(OPENSSL_NO_SSL3)
6336 addbool(m, "HAS_SSLv3", 1);
6337#else
6338 addbool(m, "HAS_SSLv3", 0);
6339#endif
6340
6341#if defined(TLS1_VERSION) && !defined(OPENSSL_NO_TLS1)
6342 addbool(m, "HAS_TLSv1", 1);
6343#else
6344 addbool(m, "HAS_TLSv1", 0);
6345#endif
6346
6347#if defined(TLS1_1_VERSION) && !defined(OPENSSL_NO_TLS1_1)
6348 addbool(m, "HAS_TLSv1_1", 1);
6349#else
6350 addbool(m, "HAS_TLSv1_1", 0);
6351#endif
6352
6353#if defined(TLS1_2_VERSION) && !defined(OPENSSL_NO_TLS1_2)
6354 addbool(m, "HAS_TLSv1_2", 1);
6355#else
6356 addbool(m, "HAS_TLSv1_2", 0);
6357#endif
Benjamin Petersoncca27322015-01-23 16:35:37 -05006358
Christian Heimescb5b68a2017-09-07 18:07:00 -07006359#if defined(TLS1_3_VERSION) && !defined(OPENSSL_NO_TLS1_3)
Christian Heimes698dde12018-02-27 11:54:43 +01006360 addbool(m, "HAS_TLSv1_3", 1);
Christian Heimescb5b68a2017-09-07 18:07:00 -07006361#else
Christian Heimes698dde12018-02-27 11:54:43 +01006362 addbool(m, "HAS_TLSv1_3", 0);
Christian Heimescb5b68a2017-09-07 18:07:00 -07006363#endif
Christian Heimescb5b68a2017-09-07 18:07:00 -07006364
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02006365 /* Mappings for error codes */
6366 err_codes_to_names = PyDict_New();
6367 err_names_to_codes = PyDict_New();
6368 if (err_codes_to_names == NULL || err_names_to_codes == NULL)
6369 return NULL;
6370 errcode = error_codes;
6371 while (errcode->mnemonic != NULL) {
6372 PyObject *mnemo, *key;
6373 mnemo = PyUnicode_FromString(errcode->mnemonic);
6374 key = Py_BuildValue("ii", errcode->library, errcode->reason);
6375 if (mnemo == NULL || key == NULL)
6376 return NULL;
6377 if (PyDict_SetItem(err_codes_to_names, key, mnemo))
6378 return NULL;
6379 if (PyDict_SetItem(err_names_to_codes, mnemo, key))
6380 return NULL;
6381 Py_DECREF(key);
6382 Py_DECREF(mnemo);
6383 errcode++;
6384 }
6385 if (PyModule_AddObject(m, "err_codes_to_names", err_codes_to_names))
6386 return NULL;
6387 if (PyModule_AddObject(m, "err_names_to_codes", err_names_to_codes))
6388 return NULL;
6389
6390 lib_codes_to_names = PyDict_New();
6391 if (lib_codes_to_names == NULL)
6392 return NULL;
6393 libcode = library_codes;
6394 while (libcode->library != NULL) {
6395 PyObject *mnemo, *key;
6396 key = PyLong_FromLong(libcode->code);
6397 mnemo = PyUnicode_FromString(libcode->library);
6398 if (key == NULL || mnemo == NULL)
6399 return NULL;
6400 if (PyDict_SetItem(lib_codes_to_names, key, mnemo))
6401 return NULL;
6402 Py_DECREF(key);
6403 Py_DECREF(mnemo);
6404 libcode++;
6405 }
6406 if (PyModule_AddObject(m, "lib_codes_to_names", lib_codes_to_names))
6407 return NULL;
Victor Stinner4569cd52013-06-23 14:58:43 +02006408
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006409 /* OpenSSL version */
6410 /* SSLeay() gives us the version of the library linked against,
6411 which could be different from the headers version.
6412 */
Miss Islington (bot)9c0ff172020-06-01 00:17:16 -07006413 libver = OpenSSL_version_num();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006414 r = PyLong_FromUnsignedLong(libver);
6415 if (r == NULL)
6416 return NULL;
6417 if (PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r))
6418 return NULL;
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02006419 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006420 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
6421 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r))
6422 return NULL;
Miss Islington (bot)9c0ff172020-06-01 00:17:16 -07006423 r = PyUnicode_FromString(OpenSSL_version(OPENSSL_VERSION));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006424 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r))
6425 return NULL;
Antoine Pitrou04f6a322010-04-05 21:40:07 +00006426
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02006427 libver = OPENSSL_VERSION_NUMBER;
6428 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
6429 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
6430 if (r == NULL || PyModule_AddObject(m, "_OPENSSL_API_VERSION", r))
6431 return NULL;
6432
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006433 return m;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00006434}