blob: 55a95ddf774e6d470a2d73e21edb3d9c2aafbdb7 [file] [log] [blame]
Thomas Woutersed03b412007-08-28 21:37:11 +00001/* SSL socket module
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002
3 SSL support based on patches by Brian E Gallew and Laszlo Kovacs.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004 Re-worked a bit by Bill Janssen to add server-side support and
Bill Janssen6e027db2007-11-15 22:23:56 +00005 certificate decoding. Chris Stawarz contributed some non-blocking
6 patches.
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00007
Thomas Wouters1b7f8912007-09-19 03:06:30 +00008 This module is imported by ssl.py. It should *not* be used
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00009 directly.
10
Thomas Wouters1b7f8912007-09-19 03:06:30 +000011 XXX should partial writes be enabled, SSL_MODE_ENABLE_PARTIAL_WRITE?
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +000012
13 XXX integrate several "shutdown modes" as suggested in
14 http://bugs.python.org/issue8108#msg102867 ?
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000015*/
16
Victor Stinner2e57b4e2014-07-01 16:37:17 +020017#define PY_SSIZE_T_CLEAN
18
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000019#include "Python.h"
Thomas Woutersed03b412007-08-28 21:37:11 +000020
Steve Dower68d663c2017-07-17 11:15:48 +020021/* Redefined below for Windows debug builds after important #includes */
22#define _PySSL_FIX_ERRNO
Christian Heimesf77b4b22013-08-21 13:26:05 +020023
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +020024#define PySSL_BEGIN_ALLOW_THREADS_S(save) \
25 do { if (_ssl_locks_count>0) { (save) = PyEval_SaveThread(); } } while (0)
26#define PySSL_END_ALLOW_THREADS_S(save) \
Steve Dower68d663c2017-07-17 11:15:48 +020027 do { if (_ssl_locks_count>0) { PyEval_RestoreThread(save); } _PySSL_FIX_ERRNO; } while (0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +000028#define PySSL_BEGIN_ALLOW_THREADS { \
Antoine Pitroucbb82eb2010-05-05 15:57:33 +000029 PyThreadState *_save = NULL; \
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +020030 PySSL_BEGIN_ALLOW_THREADS_S(_save);
31#define PySSL_BLOCK_THREADS PySSL_END_ALLOW_THREADS_S(_save);
32#define PySSL_UNBLOCK_THREADS PySSL_BEGIN_ALLOW_THREADS_S(_save);
33#define PySSL_END_ALLOW_THREADS PySSL_END_ALLOW_THREADS_S(_save); }
Thomas Wouters1b7f8912007-09-19 03:06:30 +000034
Antoine Pitrou2463e5f2013-03-28 22:24:43 +010035/* Include symbols from _socket module */
36#include "socketmodule.h"
37
38static PySocketModule_APIObject PySocketModule;
39
40#if defined(HAVE_POLL_H)
41#include <poll.h>
42#elif defined(HAVE_SYS_POLL_H)
43#include <sys/poll.h>
44#endif
45
Christian Heimes598894f2016-09-05 23:19:05 +020046/* Don't warn about deprecated functions */
47#ifdef __GNUC__
48#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
49#endif
50#ifdef __clang__
51#pragma clang diagnostic ignored "-Wdeprecated-declarations"
52#endif
53
Antoine Pitrou2463e5f2013-03-28 22:24:43 +010054/* Include OpenSSL header files */
55#include "openssl/rsa.h"
56#include "openssl/crypto.h"
57#include "openssl/x509.h"
58#include "openssl/x509v3.h"
59#include "openssl/pem.h"
60#include "openssl/ssl.h"
61#include "openssl/err.h"
62#include "openssl/rand.h"
Antoine Pitroub1fdf472014-10-05 20:41:53 +020063#include "openssl/bio.h"
Alexandru Ardeleanb3a271f2018-09-17 14:53:31 +030064#include "openssl/dh.h"
Antoine Pitrou2463e5f2013-03-28 22:24:43 +010065
Christian Heimesff5be6e2018-01-20 13:19:21 +010066#ifndef HAVE_X509_VERIFY_PARAM_SET1_HOST
Christian Heimes61d478c2018-01-27 15:51:38 +010067# ifdef LIBRESSL_VERSION_NUMBER
68# error "LibreSSL is missing X509_VERIFY_PARAM_set1_host(), see https://github.com/libressl-portable/portable/issues/381"
69# elif OPENSSL_VERSION_NUMBER > 0x1000200fL
Christian Heimesff5be6e2018-01-20 13:19:21 +010070# define HAVE_X509_VERIFY_PARAM_SET1_HOST
Christian Heimes61d478c2018-01-27 15:51:38 +010071# else
72# error "libssl is too old and does not support X509_VERIFY_PARAM_set1_host()"
Christian Heimesff5be6e2018-01-20 13:19:21 +010073# endif
74#endif
75
Christian Heimesc087a262020-05-15 20:55:25 +020076#ifndef OPENSSL_THREADS
77# error "OPENSSL_THREADS is not defined, Python requires thread-safe OpenSSL"
78#endif
79
Antoine Pitrou2463e5f2013-03-28 22:24:43 +010080/* SSL error object */
81static PyObject *PySSLErrorObject;
Christian Heimesb3ad0e52017-09-08 12:00:19 -070082static PyObject *PySSLCertVerificationErrorObject;
Antoine Pitrou2463e5f2013-03-28 22:24:43 +010083static PyObject *PySSLZeroReturnErrorObject;
84static PyObject *PySSLWantReadErrorObject;
85static PyObject *PySSLWantWriteErrorObject;
86static PyObject *PySSLSyscallErrorObject;
87static PyObject *PySSLEOFErrorObject;
88
89/* Error mappings */
90static PyObject *err_codes_to_names;
91static PyObject *err_names_to_codes;
92static PyObject *lib_codes_to_names;
93
94struct py_ssl_error_code {
95 const char *mnemonic;
96 int library, reason;
97};
98struct py_ssl_library_code {
99 const char *library;
100 int code;
101};
102
Steve Dower68d663c2017-07-17 11:15:48 +0200103#if defined(MS_WINDOWS) && defined(Py_DEBUG)
104/* Debug builds on Windows rely on getting errno directly from OpenSSL.
105 * However, because it uses a different CRT, we need to transfer the
106 * value of errno from OpenSSL into our debug CRT.
107 *
108 * Don't be fooled - this is horribly ugly code. The only reasonable
109 * alternative is to do both debug and release builds of OpenSSL, which
110 * requires much uglier code to transform their automatically generated
111 * makefile. This is the lesser of all the evils.
112 */
113
114static void _PySSLFixErrno(void) {
115 HMODULE ucrtbase = GetModuleHandleW(L"ucrtbase.dll");
116 if (!ucrtbase) {
117 /* If ucrtbase.dll is not loaded but the SSL DLLs are, we likely
118 * have a catastrophic failure, but this function is not the
119 * place to raise it. */
120 return;
121 }
122
123 typedef int *(__stdcall *errno_func)(void);
124 errno_func ssl_errno = (errno_func)GetProcAddress(ucrtbase, "_errno");
125 if (ssl_errno) {
126 errno = *ssl_errno();
127 *ssl_errno() = 0;
128 } else {
129 errno = ENOTRECOVERABLE;
130 }
131}
132
133#undef _PySSL_FIX_ERRNO
134#define _PySSL_FIX_ERRNO _PySSLFixErrno()
135#endif
136
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100137/* Include generated data (error codes) */
138#include "_ssl_data.h"
139
Christian Heimes598894f2016-09-05 23:19:05 +0200140#if (OPENSSL_VERSION_NUMBER >= 0x10100000L) && !defined(LIBRESSL_VERSION_NUMBER)
141# define OPENSSL_VERSION_1_1 1
Christian Heimes4ca07392018-03-24 15:41:37 +0100142# define PY_OPENSSL_1_1_API 1
143#endif
144
Christian Heimesa871f692020-06-01 08:58:14 +0200145/* OpenSSL API compat */
146#ifdef OPENSSL_API_COMPAT
147#if OPENSSL_API_COMPAT >= 0x10100000L
148
149/* OpenSSL API 1.1.0+ does not include version methods */
150#ifndef OPENSSL_NO_TLS1_METHOD
151#define OPENSSL_NO_TLS1_METHOD 1
152#endif
153#ifndef OPENSSL_NO_TLS1_1_METHOD
154#define OPENSSL_NO_TLS1_1_METHOD 1
155#endif
156#ifndef OPENSSL_NO_TLS1_2_METHOD
157#define OPENSSL_NO_TLS1_2_METHOD 1
158#endif
159
160#endif /* >= 1.1.0 compcat */
161#endif /* OPENSSL_API_COMPAT */
162
Christian Heimes4ca07392018-03-24 15:41:37 +0100163/* LibreSSL 2.7.0 provides necessary OpenSSL 1.1.0 APIs */
164#if defined(LIBRESSL_VERSION_NUMBER) && LIBRESSL_VERSION_NUMBER >= 0x2070000fL
165# define PY_OPENSSL_1_1_API 1
Christian Heimes598894f2016-09-05 23:19:05 +0200166#endif
167
Christian Heimes470fba12013-11-28 15:12:15 +0100168/* SNI support (client- and server-side) appeared in OpenSSL 1.0.0 and 0.9.8f
Antoine Pitrou912fbff2013-03-30 16:29:32 +0100169 * This includes the SSL_set_SSL_CTX() function.
170 */
171#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
172# define HAVE_SNI 1
173#else
174# define HAVE_SNI 0
175#endif
176
Benjamin Petersond3308222015-09-27 00:09:02 -0700177#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
Christian Heimes29eab552018-02-25 12:31:33 +0100178# define HAVE_ALPN 1
179#else
180# define HAVE_ALPN 0
Benjamin Petersoncca27322015-01-23 16:35:37 -0500181#endif
182
Christian Heimes6cdb7952018-02-24 22:12:40 +0100183/* We cannot rely on OPENSSL_NO_NEXTPROTONEG because LibreSSL 2.6.1 dropped
184 * NPN support but did not set OPENSSL_NO_NEXTPROTONEG for compatibility
185 * reasons. The check for TLSEXT_TYPE_next_proto_neg works with
186 * OpenSSL 1.0.1+ and LibreSSL.
Christian Heimes29eab552018-02-25 12:31:33 +0100187 * OpenSSL 1.1.1-pre1 dropped NPN but still has TLSEXT_TYPE_next_proto_neg.
Christian Heimes6cdb7952018-02-24 22:12:40 +0100188 */
189#ifdef OPENSSL_NO_NEXTPROTONEG
Christian Heimes29eab552018-02-25 12:31:33 +0100190# define HAVE_NPN 0
191#elif (OPENSSL_VERSION_NUMBER >= 0x10101000L) && !defined(LIBRESSL_VERSION_NUMBER)
192# define HAVE_NPN 0
Christian Heimes6cdb7952018-02-24 22:12:40 +0100193#elif defined(TLSEXT_TYPE_next_proto_neg)
Christian Heimes29eab552018-02-25 12:31:33 +0100194# define HAVE_NPN 1
Christian Heimes6cdb7952018-02-24 22:12:40 +0100195#else
Christian Heimes29eab552018-02-25 12:31:33 +0100196# define HAVE_NPN 0
197#endif
Christian Heimes6cdb7952018-02-24 22:12:40 +0100198
Christian Heimesc7f70692019-05-31 11:44:05 +0200199#if (OPENSSL_VERSION_NUMBER >= 0x10101000L) && !defined(LIBRESSL_VERSION_NUMBER)
200#define HAVE_OPENSSL_KEYLOG 1
201#endif
202
Victor Stinner524714e2016-07-22 17:43:59 +0200203#ifndef INVALID_SOCKET /* MS defines this */
204#define INVALID_SOCKET (-1)
205#endif
206
Christian Heimes4ca07392018-03-24 15:41:37 +0100207/* OpenSSL 1.0.2 and LibreSSL needs extra code for locking */
208#ifndef OPENSSL_VERSION_1_1
209#define HAVE_OPENSSL_CRYPTO_LOCK
210#endif
211
212#if defined(OPENSSL_VERSION_1_1) && !defined(OPENSSL_NO_SSL2)
Christian Heimes598894f2016-09-05 23:19:05 +0200213#define OPENSSL_NO_SSL2
214#endif
Christian Heimes4ca07392018-03-24 15:41:37 +0100215
216#ifndef PY_OPENSSL_1_1_API
217/* OpenSSL 1.1 API shims for OpenSSL < 1.1.0 and LibreSSL < 2.7.0 */
Christian Heimes598894f2016-09-05 23:19:05 +0200218
219#define TLS_method SSLv23_method
Christian Heimes5fe668c2016-09-12 00:01:11 +0200220#define TLS_client_method SSLv23_client_method
221#define TLS_server_method SSLv23_server_method
Christian Heimesa871f692020-06-01 08:58:14 +0200222#define ASN1_STRING_get0_data ASN1_STRING_data
223#define X509_get0_notBefore X509_get_notBefore
224#define X509_get0_notAfter X509_get_notAfter
225#define OpenSSL_version_num SSLeay
226#define OpenSSL_version SSLeay_version
227#define OPENSSL_VERSION SSLEAY_VERSION
Christian Heimes598894f2016-09-05 23:19:05 +0200228
229static int X509_NAME_ENTRY_set(const X509_NAME_ENTRY *ne)
230{
231 return ne->set;
232}
233
234#ifndef OPENSSL_NO_COMP
Christian Heimesa5d07652016-09-24 10:48:05 +0200235/* LCOV_EXCL_START */
Christian Heimes598894f2016-09-05 23:19:05 +0200236static int COMP_get_type(const COMP_METHOD *meth)
237{
238 return meth->type;
239}
Christian Heimes1a63b9f2016-09-24 12:07:21 +0200240/* LCOV_EXCL_STOP */
Christian Heimes598894f2016-09-05 23:19:05 +0200241#endif
242
243static pem_password_cb *SSL_CTX_get_default_passwd_cb(SSL_CTX *ctx)
244{
245 return ctx->default_passwd_callback;
246}
247
248static void *SSL_CTX_get_default_passwd_cb_userdata(SSL_CTX *ctx)
249{
250 return ctx->default_passwd_callback_userdata;
251}
252
253static int X509_OBJECT_get_type(X509_OBJECT *x)
254{
255 return x->type;
256}
257
258static X509 *X509_OBJECT_get0_X509(X509_OBJECT *x)
259{
260 return x->data.x509;
261}
262
263static int BIO_up_ref(BIO *b)
264{
265 CRYPTO_add(&b->references, 1, CRYPTO_LOCK_BIO);
266 return 1;
267}
268
269static STACK_OF(X509_OBJECT) *X509_STORE_get0_objects(X509_STORE *store) {
270 return store->objs;
271}
272
Christian Heimes99a65702016-09-10 23:44:53 +0200273static int
274SSL_SESSION_has_ticket(const SSL_SESSION *s)
275{
276 return (s->tlsext_ticklen > 0) ? 1 : 0;
277}
278
279static unsigned long
280SSL_SESSION_get_ticket_lifetime_hint(const SSL_SESSION *s)
281{
282 return s->tlsext_tick_lifetime_hint;
283}
284
Christian Heimes4ca07392018-03-24 15:41:37 +0100285#endif /* OpenSSL < 1.1.0 or LibreSSL < 2.7.0 */
Christian Heimes598894f2016-09-05 23:19:05 +0200286
Christian Heimes892d66e2018-01-29 14:10:18 +0100287/* Default cipher suites */
288#ifndef PY_SSL_DEFAULT_CIPHERS
289#define PY_SSL_DEFAULT_CIPHERS 1
290#endif
291
292#if PY_SSL_DEFAULT_CIPHERS == 0
293 #ifndef PY_SSL_DEFAULT_CIPHER_STRING
294 #error "Py_SSL_DEFAULT_CIPHERS 0 needs Py_SSL_DEFAULT_CIPHER_STRING"
295 #endif
296#elif PY_SSL_DEFAULT_CIPHERS == 1
Stéphane Wirtel07fbbfd2018-10-05 16:17:18 +0200297/* Python custom selection of sensible cipher suites
Christian Heimes892d66e2018-01-29 14:10:18 +0100298 * DEFAULT: OpenSSL's default cipher list. Since 1.0.2 the list is in sensible order.
299 * !aNULL:!eNULL: really no NULL ciphers
300 * !MD5:!3DES:!DES:!RC4:!IDEA:!SEED: no weak or broken algorithms on old OpenSSL versions.
301 * !aDSS: no authentication with discrete logarithm DSA algorithm
302 * !SRP:!PSK: no secure remote password or pre-shared key authentication
303 */
304 #define PY_SSL_DEFAULT_CIPHER_STRING "DEFAULT:!aNULL:!eNULL:!MD5:!3DES:!DES:!RC4:!IDEA:!SEED:!aDSS:!SRP:!PSK"
305#elif PY_SSL_DEFAULT_CIPHERS == 2
306/* Ignored in SSLContext constructor, only used to as _ssl.DEFAULT_CIPHER_STRING */
307 #define PY_SSL_DEFAULT_CIPHER_STRING SSL_DEFAULT_CIPHER_LIST
308#else
309 #error "Unsupported PY_SSL_DEFAULT_CIPHERS"
310#endif
311
Christian Heimes598894f2016-09-05 23:19:05 +0200312
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000313enum py_ssl_error {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000314 /* these mirror ssl.h */
315 PY_SSL_ERROR_NONE,
316 PY_SSL_ERROR_SSL,
317 PY_SSL_ERROR_WANT_READ,
318 PY_SSL_ERROR_WANT_WRITE,
319 PY_SSL_ERROR_WANT_X509_LOOKUP,
320 PY_SSL_ERROR_SYSCALL, /* look at error stack/return value/errno */
321 PY_SSL_ERROR_ZERO_RETURN,
322 PY_SSL_ERROR_WANT_CONNECT,
323 /* start of non ssl.h errorcodes */
324 PY_SSL_ERROR_EOF, /* special case of SSL_ERROR_SYSCALL */
325 PY_SSL_ERROR_NO_SOCKET, /* socket has been GC'd */
326 PY_SSL_ERROR_INVALID_ERROR_CODE
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000327};
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000328
Thomas Woutersed03b412007-08-28 21:37:11 +0000329enum py_ssl_server_or_client {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000330 PY_SSL_CLIENT,
331 PY_SSL_SERVER
Thomas Woutersed03b412007-08-28 21:37:11 +0000332};
333
334enum py_ssl_cert_requirements {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000335 PY_SSL_CERT_NONE,
336 PY_SSL_CERT_OPTIONAL,
337 PY_SSL_CERT_REQUIRED
Thomas Woutersed03b412007-08-28 21:37:11 +0000338};
339
340enum py_ssl_version {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000341 PY_SSL_VERSION_SSL2,
Victor Stinner3de49192011-05-09 00:42:58 +0200342 PY_SSL_VERSION_SSL3=1,
Christian Heimes5fe668c2016-09-12 00:01:11 +0200343 PY_SSL_VERSION_TLS, /* SSLv23 */
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100344 PY_SSL_VERSION_TLS1,
345 PY_SSL_VERSION_TLS1_1,
Christian Heimes5fe668c2016-09-12 00:01:11 +0200346 PY_SSL_VERSION_TLS1_2,
Christian Heimes5fe668c2016-09-12 00:01:11 +0200347 PY_SSL_VERSION_TLS_CLIENT=0x10,
348 PY_SSL_VERSION_TLS_SERVER,
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100349};
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200350
Christian Heimes698dde12018-02-27 11:54:43 +0100351enum py_proto_version {
352 PY_PROTO_MINIMUM_SUPPORTED = -2,
353 PY_PROTO_SSLv3 = SSL3_VERSION,
354 PY_PROTO_TLSv1 = TLS1_VERSION,
355 PY_PROTO_TLSv1_1 = TLS1_1_VERSION,
356 PY_PROTO_TLSv1_2 = TLS1_2_VERSION,
357#ifdef TLS1_3_VERSION
358 PY_PROTO_TLSv1_3 = TLS1_3_VERSION,
359#else
360 PY_PROTO_TLSv1_3 = 0x304,
361#endif
362 PY_PROTO_MAXIMUM_SUPPORTED = -1,
363
364/* OpenSSL has no dedicated API to set the minimum version to the maximum
365 * available version, and the other way around. We have to figure out the
366 * minimum and maximum available version on our own and hope for the best.
367 */
368#if defined(SSL3_VERSION) && !defined(OPENSSL_NO_SSL3)
369 PY_PROTO_MINIMUM_AVAILABLE = PY_PROTO_SSLv3,
370#elif defined(TLS1_VERSION) && !defined(OPENSSL_NO_TLS1)
371 PY_PROTO_MINIMUM_AVAILABLE = PY_PROTO_TLSv1,
372#elif defined(TLS1_1_VERSION) && !defined(OPENSSL_NO_TLS1_1)
373 PY_PROTO_MINIMUM_AVAILABLE = PY_PROTO_TLSv1_1,
374#elif defined(TLS1_2_VERSION) && !defined(OPENSSL_NO_TLS1_2)
375 PY_PROTO_MINIMUM_AVAILABLE = PY_PROTO_TLSv1_2,
376#elif defined(TLS1_3_VERSION) && !defined(OPENSSL_NO_TLS1_3)
377 PY_PROTO_MINIMUM_AVAILABLE = PY_PROTO_TLSv1_3,
378#else
379 #error "PY_PROTO_MINIMUM_AVAILABLE not found"
380#endif
381
382#if defined(TLS1_3_VERSION) && !defined(OPENSSL_NO_TLS1_3)
383 PY_PROTO_MAXIMUM_AVAILABLE = PY_PROTO_TLSv1_3,
384#elif defined(TLS1_2_VERSION) && !defined(OPENSSL_NO_TLS1_2)
385 PY_PROTO_MAXIMUM_AVAILABLE = PY_PROTO_TLSv1_2,
386#elif defined(TLS1_1_VERSION) && !defined(OPENSSL_NO_TLS1_1)
387 PY_PROTO_MAXIMUM_AVAILABLE = PY_PROTO_TLSv1_1,
388#elif defined(TLS1_VERSION) && !defined(OPENSSL_NO_TLS1)
389 PY_PROTO_MAXIMUM_AVAILABLE = PY_PROTO_TLSv1,
390#elif defined(SSL3_VERSION) && !defined(OPENSSL_NO_SSL3)
391 PY_PROTO_MAXIMUM_AVAILABLE = PY_PROTO_SSLv3,
392#else
393 #error "PY_PROTO_MAXIMUM_AVAILABLE not found"
394#endif
395};
396
397
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000398/* serves as a flag to see whether we've initialized the SSL thread support. */
399/* 0 means no, greater than 0 means yes */
400
401static unsigned int _ssl_locks_count = 0;
402
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000403/* SSL socket object */
404
405#define X509_NAME_MAXLEN 256
406
Gregory P. Smithbd4dacb2010-10-13 03:53:21 +0000407/* SSL_CTX_clear_options() and SSL_clear_options() were first added in
408 * OpenSSL 0.9.8m but do not appear in some 0.9.9-dev versions such the
409 * 0.9.9 from "May 2008" that NetBSD 5.0 uses. */
410#if OPENSSL_VERSION_NUMBER >= 0x009080dfL && OPENSSL_VERSION_NUMBER != 0x00909000L
Antoine Pitroub5218772010-05-21 09:56:06 +0000411# define HAVE_SSL_CTX_CLEAR_OPTIONS
412#else
413# undef HAVE_SSL_CTX_CLEAR_OPTIONS
414#endif
415
Antoine Pitroud6494802011-07-21 01:11:30 +0200416/* In case of 'tls-unique' it will be 12 bytes for TLS, 36 bytes for
417 * older SSL, but let's be safe */
418#define PySSL_CB_MAXLEN 128
419
Antoine Pitroua9bf2ac2012-02-17 18:47:54 +0100420
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000421typedef struct {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000422 PyObject_HEAD
Antoine Pitrou152efa22010-05-16 18:19:27 +0000423 SSL_CTX *ctx;
Christian Heimes29eab552018-02-25 12:31:33 +0100424#if HAVE_NPN
Benjamin Petersoncca27322015-01-23 16:35:37 -0500425 unsigned char *npn_protocols;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100426 int npn_protocols_len;
427#endif
Christian Heimes29eab552018-02-25 12:31:33 +0100428#if HAVE_ALPN
Benjamin Petersoncca27322015-01-23 16:35:37 -0500429 unsigned char *alpn_protocols;
Segev Finer5cff6372017-07-27 01:19:17 +0300430 unsigned int alpn_protocols_len;
Benjamin Petersoncca27322015-01-23 16:35:37 -0500431#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100432#ifndef OPENSSL_NO_TLSEXT
Christian Heimes11a14932018-02-24 02:35:08 +0100433 PyObject *set_sni_cb;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100434#endif
Christian Heimes1aa9a752013-12-02 02:41:19 +0100435 int check_hostname;
Christian Heimes61d478c2018-01-27 15:51:38 +0100436 /* OpenSSL has no API to get hostflags from X509_VERIFY_PARAM* struct.
437 * We have to maintain our own copy. OpenSSL's hostflags default to 0.
438 */
439 unsigned int hostflags;
Christian Heimes11a14932018-02-24 02:35:08 +0100440 int protocol;
Christian Heimes9fb051f2018-09-23 08:32:31 +0200441#ifdef TLS1_3_VERSION
442 int post_handshake_auth;
443#endif
Christian Heimesc7f70692019-05-31 11:44:05 +0200444 PyObject *msg_cb;
445#ifdef HAVE_OPENSSL_KEYLOG
446 PyObject *keylog_filename;
447 BIO *keylog_bio;
448#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +0000449} PySSLContext;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000450
Antoine Pitrou152efa22010-05-16 18:19:27 +0000451typedef struct {
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700452 int ssl; /* last seen error from SSL */
453 int c; /* last seen error from libc */
454#ifdef MS_WINDOWS
455 int ws; /* last seen error from winsock */
456#endif
457} _PySSLError;
458
459typedef struct {
Antoine Pitrou152efa22010-05-16 18:19:27 +0000460 PyObject_HEAD
461 PyObject *Socket; /* weakref to socket on which we're layered */
462 SSL *ssl;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100463 PySSLContext *ctx; /* weakref to SSL context */
Antoine Pitrou20b85552013-09-29 19:50:53 +0200464 char shutdown_seen_zero;
Antoine Pitroud6494802011-07-21 01:11:30 +0200465 enum py_ssl_server_or_client socket_type;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200466 PyObject *owner; /* Python level "owner" passed to servername callback */
467 PyObject *server_hostname;
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700468 _PySSLError err; /* last seen error from various sources */
Christian Heimesc7f70692019-05-31 11:44:05 +0200469 /* Some SSL callbacks don't have error reporting. Callback wrappers
470 * store exception information on the socket. The handshake, read, write,
471 * and shutdown methods check for chained exceptions.
472 */
473 PyObject *exc_type;
474 PyObject *exc_value;
475 PyObject *exc_tb;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000476} PySSLSocket;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000477
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200478typedef struct {
479 PyObject_HEAD
480 BIO *bio;
481 int eof_written;
482} PySSLMemoryBIO;
483
Christian Heimes99a65702016-09-10 23:44:53 +0200484typedef struct {
485 PyObject_HEAD
486 SSL_SESSION *session;
487 PySSLContext *ctx;
488} PySSLSession;
489
Antoine Pitrou152efa22010-05-16 18:19:27 +0000490static PyTypeObject PySSLContext_Type;
491static PyTypeObject PySSLSocket_Type;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200492static PyTypeObject PySSLMemoryBIO_Type;
Christian Heimes99a65702016-09-10 23:44:53 +0200493static PyTypeObject PySSLSession_Type;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000494
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700495static inline _PySSLError _PySSL_errno(int failed, const SSL *ssl, int retcode)
496{
497 _PySSLError err = { 0 };
498 if (failed) {
Steve Dowere6eb48c2017-09-08 15:16:15 -0700499#ifdef MS_WINDOWS
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700500 err.ws = WSAGetLastError();
501 _PySSL_FIX_ERRNO;
Steve Dowere6eb48c2017-09-08 15:16:15 -0700502#endif
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700503 err.c = errno;
504 err.ssl = SSL_get_error(ssl, retcode);
505 }
506 return err;
507}
Steve Dowere6eb48c2017-09-08 15:16:15 -0700508
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +0300509/*[clinic input]
510module _ssl
511class _ssl._SSLContext "PySSLContext *" "&PySSLContext_Type"
512class _ssl._SSLSocket "PySSLSocket *" "&PySSLSocket_Type"
513class _ssl.MemoryBIO "PySSLMemoryBIO *" "&PySSLMemoryBIO_Type"
Christian Heimes99a65702016-09-10 23:44:53 +0200514class _ssl.SSLSession "PySSLSession *" "&PySSLSession_Type"
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +0300515[clinic start generated code]*/
Christian Heimes99a65702016-09-10 23:44:53 +0200516/*[clinic end generated code: output=da39a3ee5e6b4b0d input=bdc67fafeeaa8109]*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +0300517
518#include "clinic/_ssl.c.h"
519
Victor Stinner14690702015-04-06 22:46:13 +0200520static int PySSL_select(PySocketSockObject *s, int writing, _PyTime_t timeout);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000521
Christian Heimes141c5e82018-02-24 21:10:57 +0100522static int PySSL_set_owner(PySSLSocket *, PyObject *, void *);
523static int PySSL_set_session(PySSLSocket *, PyObject *, void *);
Dong-hee Na1b55b652020-02-17 19:09:15 +0900524#define PySSLSocket_Check(v) Py_IS_TYPE(v, &PySSLSocket_Type)
525#define PySSLMemoryBIO_Check(v) Py_IS_TYPE(v, &PySSLMemoryBIO_Type)
526#define PySSLSession_Check(v) Py_IS_TYPE(v, &PySSLSession_Type)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000527
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000528typedef enum {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000529 SOCKET_IS_NONBLOCKING,
530 SOCKET_IS_BLOCKING,
531 SOCKET_HAS_TIMED_OUT,
532 SOCKET_HAS_BEEN_CLOSED,
533 SOCKET_TOO_LARGE_FOR_SELECT,
534 SOCKET_OPERATION_OK
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000535} timeout_state;
536
Thomas Woutersed03b412007-08-28 21:37:11 +0000537/* Wrap error strings with filename and line # */
Thomas Woutersed03b412007-08-28 21:37:11 +0000538#define ERRSTR1(x,y,z) (x ":" y ": " z)
Victor Stinner45e8e2f2014-05-14 17:24:35 +0200539#define ERRSTR(x) ERRSTR1("_ssl.c", Py_STRINGIFY(__LINE__), x)
Thomas Woutersed03b412007-08-28 21:37:11 +0000540
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200541/* Get the socket from a PySSLSocket, if it has one */
542#define GET_SOCKET(obj) ((obj)->Socket ? \
543 (PySocketSockObject *) PyWeakref_GetObject((obj)->Socket) : NULL)
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200544
Victor Stinner14690702015-04-06 22:46:13 +0200545/* If sock is NULL, use a timeout of 0 second */
546#define GET_SOCKET_TIMEOUT(sock) \
547 ((sock != NULL) ? (sock)->sock_timeout : 0)
548
Christian Heimesc7f70692019-05-31 11:44:05 +0200549#include "_ssl/debughelpers.c"
550
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200551/*
552 * SSL errors.
553 */
554
555PyDoc_STRVAR(SSLError_doc,
556"An error occurred in the SSL implementation.");
557
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700558PyDoc_STRVAR(SSLCertVerificationError_doc,
559"A certificate could not be verified.");
560
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200561PyDoc_STRVAR(SSLZeroReturnError_doc,
562"SSL/TLS session closed cleanly.");
563
564PyDoc_STRVAR(SSLWantReadError_doc,
565"Non-blocking SSL socket needs to read more data\n"
566"before the requested operation can be completed.");
567
568PyDoc_STRVAR(SSLWantWriteError_doc,
569"Non-blocking SSL socket needs to write more data\n"
570"before the requested operation can be completed.");
571
572PyDoc_STRVAR(SSLSyscallError_doc,
573"System error when attempting SSL operation.");
574
575PyDoc_STRVAR(SSLEOFError_doc,
576"SSL/TLS connection terminated abruptly.");
577
578static PyObject *
579SSLError_str(PyOSErrorObject *self)
580{
581 if (self->strerror != NULL && PyUnicode_Check(self->strerror)) {
582 Py_INCREF(self->strerror);
583 return self->strerror;
584 }
585 else
586 return PyObject_Str(self->args);
587}
588
589static PyType_Slot sslerror_type_slots[] = {
590 {Py_tp_base, NULL}, /* Filled out in module init as it's not a constant */
Inada Naoki926b0cb2019-04-17 08:39:46 +0900591 {Py_tp_doc, (void*)SSLError_doc},
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200592 {Py_tp_str, SSLError_str},
593 {0, 0},
594};
595
596static PyType_Spec sslerror_type_spec = {
597 "ssl.SSLError",
598 sizeof(PyOSErrorObject),
599 0,
600 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
601 sslerror_type_slots
602};
603
604static void
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700605fill_and_set_sslerror(PySSLSocket *sslsock, PyObject *type, int ssl_errno,
606 const char *errstr, int lineno, unsigned long errcode)
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200607{
608 PyObject *err_value = NULL, *reason_obj = NULL, *lib_obj = NULL;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700609 PyObject *verify_obj = NULL, *verify_code_obj = NULL;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200610 PyObject *init_value, *msg, *key;
611 _Py_IDENTIFIER(reason);
612 _Py_IDENTIFIER(library);
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700613 _Py_IDENTIFIER(verify_message);
614 _Py_IDENTIFIER(verify_code);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200615
616 if (errcode != 0) {
617 int lib, reason;
618
619 lib = ERR_GET_LIB(errcode);
620 reason = ERR_GET_REASON(errcode);
621 key = Py_BuildValue("ii", lib, reason);
622 if (key == NULL)
623 goto fail;
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +0300624 reason_obj = PyDict_GetItemWithError(err_codes_to_names, key);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200625 Py_DECREF(key);
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +0300626 if (reason_obj == NULL && PyErr_Occurred()) {
627 goto fail;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200628 }
629 key = PyLong_FromLong(lib);
630 if (key == NULL)
631 goto fail;
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +0300632 lib_obj = PyDict_GetItemWithError(lib_codes_to_names, key);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200633 Py_DECREF(key);
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +0300634 if (lib_obj == NULL && PyErr_Occurred()) {
635 goto fail;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200636 }
637 if (errstr == NULL)
638 errstr = ERR_reason_error_string(errcode);
639 }
640 if (errstr == NULL)
641 errstr = "unknown error";
642
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700643 /* verify code for cert validation error */
644 if ((sslsock != NULL) && (type == PySSLCertVerificationErrorObject)) {
645 const char *verify_str = NULL;
646 long verify_code;
647
648 verify_code = SSL_get_verify_result(sslsock->ssl);
649 verify_code_obj = PyLong_FromLong(verify_code);
650 if (verify_code_obj == NULL) {
651 goto fail;
652 }
653
654 switch (verify_code) {
Christian Heimes09153602017-09-08 14:47:58 -0700655#ifdef X509_V_ERR_HOSTNAME_MISMATCH
656 /* OpenSSL >= 1.0.2, LibreSSL >= 2.5.3 */
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700657 case X509_V_ERR_HOSTNAME_MISMATCH:
658 verify_obj = PyUnicode_FromFormat(
659 "Hostname mismatch, certificate is not valid for '%S'.",
660 sslsock->server_hostname
661 );
662 break;
Christian Heimes09153602017-09-08 14:47:58 -0700663#endif
664#ifdef X509_V_ERR_IP_ADDRESS_MISMATCH
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700665 case X509_V_ERR_IP_ADDRESS_MISMATCH:
666 verify_obj = PyUnicode_FromFormat(
667 "IP address mismatch, certificate is not valid for '%S'.",
668 sslsock->server_hostname
669 );
670 break;
Christian Heimes09153602017-09-08 14:47:58 -0700671#endif
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700672 default:
673 verify_str = X509_verify_cert_error_string(verify_code);
674 if (verify_str != NULL) {
675 verify_obj = PyUnicode_FromString(verify_str);
676 } else {
677 verify_obj = Py_None;
678 Py_INCREF(verify_obj);
679 }
680 break;
681 }
682 if (verify_obj == NULL) {
683 goto fail;
684 }
685 }
686
687 if (verify_obj && reason_obj && lib_obj)
688 msg = PyUnicode_FromFormat("[%S: %S] %s: %S (_ssl.c:%d)",
689 lib_obj, reason_obj, errstr, verify_obj,
690 lineno);
691 else if (reason_obj && lib_obj)
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200692 msg = PyUnicode_FromFormat("[%S: %S] %s (_ssl.c:%d)",
693 lib_obj, reason_obj, errstr, lineno);
694 else if (lib_obj)
695 msg = PyUnicode_FromFormat("[%S] %s (_ssl.c:%d)",
696 lib_obj, errstr, lineno);
697 else
698 msg = PyUnicode_FromFormat("%s (_ssl.c:%d)", errstr, lineno);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200699 if (msg == NULL)
700 goto fail;
Victor Stinnerba9be472013-10-31 15:00:24 +0100701
Paul Monsonfb7e7502019-05-15 15:38:55 -0700702 init_value = Py_BuildValue("iN", ERR_GET_REASON(ssl_errno), msg);
Victor Stinnerba9be472013-10-31 15:00:24 +0100703 if (init_value == NULL)
704 goto fail;
705
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200706 err_value = PyObject_CallObject(type, init_value);
707 Py_DECREF(init_value);
708 if (err_value == NULL)
709 goto fail;
Victor Stinnerba9be472013-10-31 15:00:24 +0100710
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200711 if (reason_obj == NULL)
712 reason_obj = Py_None;
713 if (_PyObject_SetAttrId(err_value, &PyId_reason, reason_obj))
714 goto fail;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700715
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200716 if (lib_obj == NULL)
717 lib_obj = Py_None;
718 if (_PyObject_SetAttrId(err_value, &PyId_library, lib_obj))
719 goto fail;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700720
721 if ((sslsock != NULL) && (type == PySSLCertVerificationErrorObject)) {
722 /* Only set verify code / message for SSLCertVerificationError */
723 if (_PyObject_SetAttrId(err_value, &PyId_verify_code,
724 verify_code_obj))
725 goto fail;
726 if (_PyObject_SetAttrId(err_value, &PyId_verify_message, verify_obj))
727 goto fail;
728 }
729
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200730 PyErr_SetObject(type, err_value);
731fail:
732 Py_XDECREF(err_value);
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700733 Py_XDECREF(verify_code_obj);
734 Py_XDECREF(verify_obj);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200735}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000736
Christian Heimesc7f70692019-05-31 11:44:05 +0200737static int
738PySSL_ChainExceptions(PySSLSocket *sslsock) {
739 if (sslsock->exc_type == NULL)
740 return 0;
741
742 _PyErr_ChainExceptions(sslsock->exc_type, sslsock->exc_value, sslsock->exc_tb);
743 sslsock->exc_type = NULL;
744 sslsock->exc_value = NULL;
745 sslsock->exc_tb = NULL;
746 return -1;
747}
748
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000749static PyObject *
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700750PySSL_SetError(PySSLSocket *sslsock, int ret, const char *filename, int lineno)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000751{
Antoine Pitrou41032a62011-10-27 23:56:55 +0200752 PyObject *type = PySSLErrorObject;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200753 char *errstr = NULL;
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700754 _PySSLError err;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000755 enum py_ssl_error p = PY_SSL_ERROR_NONE;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200756 unsigned long e = 0;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000757
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000758 assert(ret <= 0);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200759 e = ERR_peek_last_error();
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000760
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700761 if (sslsock->ssl != NULL) {
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700762 err = sslsock->err;
Thomas Woutersed03b412007-08-28 21:37:11 +0000763
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700764 switch (err.ssl) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000765 case SSL_ERROR_ZERO_RETURN:
Antoine Pitrou41032a62011-10-27 23:56:55 +0200766 errstr = "TLS/SSL connection has been closed (EOF)";
767 type = PySSLZeroReturnErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000768 p = PY_SSL_ERROR_ZERO_RETURN;
769 break;
770 case SSL_ERROR_WANT_READ:
771 errstr = "The operation did not complete (read)";
Antoine Pitrou41032a62011-10-27 23:56:55 +0200772 type = PySSLWantReadErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000773 p = PY_SSL_ERROR_WANT_READ;
774 break;
775 case SSL_ERROR_WANT_WRITE:
776 p = PY_SSL_ERROR_WANT_WRITE;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200777 type = PySSLWantWriteErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000778 errstr = "The operation did not complete (write)";
779 break;
780 case SSL_ERROR_WANT_X509_LOOKUP:
781 p = PY_SSL_ERROR_WANT_X509_LOOKUP;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000782 errstr = "The operation did not complete (X509 lookup)";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000783 break;
784 case SSL_ERROR_WANT_CONNECT:
785 p = PY_SSL_ERROR_WANT_CONNECT;
786 errstr = "The operation did not complete (connect)";
787 break;
788 case SSL_ERROR_SYSCALL:
789 {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000790 if (e == 0) {
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700791 PySocketSockObject *s = GET_SOCKET(sslsock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000792 if (ret == 0 || (((PyObject *)s) == Py_None)) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000793 p = PY_SSL_ERROR_EOF;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200794 type = PySSLEOFErrorObject;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000795 errstr = "EOF occurred in violation of protocol";
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200796 } else if (s && ret == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000797 /* underlying BIO reported an I/O error */
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000798 ERR_clear_error();
Steve Dowere6eb48c2017-09-08 15:16:15 -0700799#ifdef MS_WINDOWS
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700800 if (err.ws) {
801 return PyErr_SetFromWindowsErr(err.ws);
802 }
Steve Dowere6eb48c2017-09-08 15:16:15 -0700803#endif
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700804 if (err.c) {
805 errno = err.c;
Steve Dowere6eb48c2017-09-08 15:16:15 -0700806 return PyErr_SetFromErrno(PyExc_OSError);
807 }
808 Py_INCREF(s);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200809 s->errorhandler();
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000810 Py_DECREF(s);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200811 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000812 } else { /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000813 p = PY_SSL_ERROR_SYSCALL;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200814 type = PySSLSyscallErrorObject;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000815 errstr = "Some I/O error occurred";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000816 }
817 } else {
818 p = PY_SSL_ERROR_SYSCALL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000819 }
820 break;
821 }
822 case SSL_ERROR_SSL:
823 {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000824 p = PY_SSL_ERROR_SSL;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700825 if (e == 0) {
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200826 /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000827 errstr = "A failure in the SSL library occurred";
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700828 }
829 if (ERR_GET_LIB(e) == ERR_LIB_SSL &&
830 ERR_GET_REASON(e) == SSL_R_CERTIFICATE_VERIFY_FAILED) {
831 type = PySSLCertVerificationErrorObject;
832 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000833 break;
834 }
835 default:
836 p = PY_SSL_ERROR_INVALID_ERROR_CODE;
837 errstr = "Invalid error code";
838 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000839 }
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700840 fill_and_set_sslerror(sslsock, type, p, errstr, lineno, e);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000841 ERR_clear_error();
Christian Heimesc7f70692019-05-31 11:44:05 +0200842 PySSL_ChainExceptions(sslsock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000843 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000844}
845
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000846static PyObject *
Serhiy Storchakaef1585e2015-12-25 20:01:53 +0200847_setSSLError (const char *errstr, int errcode, const char *filename, int lineno) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000848
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200849 if (errstr == NULL)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000850 errcode = ERR_peek_last_error();
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200851 else
852 errcode = 0;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700853 fill_and_set_sslerror(NULL, PySSLErrorObject, errcode, errstr, lineno, errcode);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000854 ERR_clear_error();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000855 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000856}
857
Christian Heimes61d478c2018-01-27 15:51:38 +0100858/*
859 * SSL objects
860 */
861
862static int
863_ssl_configure_hostname(PySSLSocket *self, const char* server_hostname)
864{
865 int retval = -1;
866 ASN1_OCTET_STRING *ip;
867 PyObject *hostname;
868 size_t len;
869
870 assert(server_hostname);
871
872 /* Disable OpenSSL's special mode with leading dot in hostname:
873 * When name starts with a dot (e.g ".example.com"), it will be
874 * matched by a certificate valid for any sub-domain of name.
875 */
876 len = strlen(server_hostname);
877 if (len == 0 || *server_hostname == '.') {
878 PyErr_SetString(
879 PyExc_ValueError,
880 "server_hostname cannot be an empty string or start with a "
881 "leading dot.");
882 return retval;
883 }
884
885 /* inet_pton is not available on all platforms. */
886 ip = a2i_IPADDRESS(server_hostname);
887 if (ip == NULL) {
888 ERR_clear_error();
889 }
890
Christian Heimes11a14932018-02-24 02:35:08 +0100891 hostname = PyUnicode_Decode(server_hostname, len, "ascii", "strict");
Christian Heimes61d478c2018-01-27 15:51:38 +0100892 if (hostname == NULL) {
893 goto error;
894 }
895 self->server_hostname = hostname;
896
897 /* Only send SNI extension for non-IP hostnames */
898 if (ip == NULL) {
899 if (!SSL_set_tlsext_host_name(self->ssl, server_hostname)) {
900 _setSSLError(NULL, 0, __FILE__, __LINE__);
901 }
902 }
903 if (self->ctx->check_hostname) {
904 X509_VERIFY_PARAM *param = SSL_get0_param(self->ssl);
905 if (ip == NULL) {
Christian Heimesd02ac252018-03-25 12:36:13 +0200906 if (!X509_VERIFY_PARAM_set1_host(param, server_hostname,
907 strlen(server_hostname))) {
Christian Heimes61d478c2018-01-27 15:51:38 +0100908 _setSSLError(NULL, 0, __FILE__, __LINE__);
909 goto error;
910 }
911 } else {
Christian Heimesa871f692020-06-01 08:58:14 +0200912 if (!X509_VERIFY_PARAM_set1_ip(param, ASN1_STRING_get0_data(ip),
Christian Heimes61d478c2018-01-27 15:51:38 +0100913 ASN1_STRING_length(ip))) {
914 _setSSLError(NULL, 0, __FILE__, __LINE__);
915 goto error;
916 }
917 }
918 }
919 retval = 0;
920 error:
921 if (ip != NULL) {
922 ASN1_OCTET_STRING_free(ip);
923 }
924 return retval;
925}
926
Antoine Pitrou152efa22010-05-16 18:19:27 +0000927static PySSLSocket *
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100928newPySSLSocket(PySSLContext *sslctx, PySocketSockObject *sock,
Antoine Pitroud5323212010-10-22 18:19:07 +0000929 enum py_ssl_server_or_client socket_type,
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200930 char *server_hostname,
Christian Heimes141c5e82018-02-24 21:10:57 +0100931 PyObject *owner, PyObject *session,
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200932 PySSLMemoryBIO *inbio, PySSLMemoryBIO *outbio)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000933{
Antoine Pitrou152efa22010-05-16 18:19:27 +0000934 PySSLSocket *self;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100935 SSL_CTX *ctx = sslctx->ctx;
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700936 _PySSLError err = { 0 };
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000937
Antoine Pitrou152efa22010-05-16 18:19:27 +0000938 self = PyObject_New(PySSLSocket, &PySSLSocket_Type);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000939 if (self == NULL)
940 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000941
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000942 self->ssl = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000943 self->Socket = NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100944 self->ctx = sslctx;
Nathaniel J. Smith65ece7c2017-06-07 23:30:43 -0700945 Py_INCREF(sslctx);
Antoine Pitrou860aee72013-09-29 19:52:45 +0200946 self->shutdown_seen_zero = 0;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200947 self->owner = NULL;
Benjamin Peterson81b9ecd2016-08-15 21:55:37 -0700948 self->server_hostname = NULL;
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700949 self->err = err;
Christian Heimesc7f70692019-05-31 11:44:05 +0200950 self->exc_type = NULL;
951 self->exc_value = NULL;
952 self->exc_tb = NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200953
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000954 /* Make sure the SSL error state is initialized */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000955 ERR_clear_error();
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000956
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000957 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitrou152efa22010-05-16 18:19:27 +0000958 self->ssl = SSL_new(ctx);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000959 PySSL_END_ALLOW_THREADS
Zackery Spytz4c49da02018-12-07 03:11:30 -0700960 if (self->ssl == NULL) {
961 Py_DECREF(self);
962 _setSSLError(NULL, 0, __FILE__, __LINE__);
963 return NULL;
964 }
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200965 SSL_set_app_data(self->ssl, self);
966 if (sock) {
967 SSL_set_fd(self->ssl, Py_SAFE_DOWNCAST(sock->sock_fd, SOCKET_T, int));
968 } else {
969 /* BIOs are reference counted and SSL_set_bio borrows our reference.
970 * To prevent a double free in memory_bio_dealloc() we need to take an
971 * extra reference here. */
Christian Heimes598894f2016-09-05 23:19:05 +0200972 BIO_up_ref(inbio->bio);
973 BIO_up_ref(outbio->bio);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200974 SSL_set_bio(self->ssl, inbio->bio, outbio->bio);
975 }
Alex Gaynorf0422422018-05-14 11:51:45 -0400976 SSL_set_mode(self->ssl,
977 SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER | SSL_MODE_AUTO_RETRY);
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000978
Christian Heimesf0f59302019-07-01 08:29:17 +0200979#ifdef TLS1_3_VERSION
980 if (sslctx->post_handshake_auth == 1) {
981 if (socket_type == PY_SSL_SERVER) {
982 /* bpo-37428: OpenSSL does not ignore SSL_VERIFY_POST_HANDSHAKE.
983 * Set SSL_VERIFY_POST_HANDSHAKE flag only for server sockets and
984 * only in combination with SSL_VERIFY_PEER flag. */
985 int mode = SSL_get_verify_mode(self->ssl);
986 if (mode & SSL_VERIFY_PEER) {
987 int (*verify_cb)(int, X509_STORE_CTX *) = NULL;
988 verify_cb = SSL_get_verify_callback(self->ssl);
989 mode |= SSL_VERIFY_POST_HANDSHAKE;
990 SSL_set_verify(self->ssl, mode, verify_cb);
991 }
992 } else {
993 /* client socket */
994 SSL_set_post_handshake_auth(self->ssl, 1);
995 }
996 }
997#endif
998
Christian Heimes61d478c2018-01-27 15:51:38 +0100999 if (server_hostname != NULL) {
1000 if (_ssl_configure_hostname(self, server_hostname) < 0) {
1001 Py_DECREF(self);
1002 return NULL;
1003 }
1004 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001005 /* If the socket is in non-blocking mode or timeout mode, set the BIO
1006 * to non-blocking mode (blocking is the default)
1007 */
Victor Stinnere2452312015-03-28 03:00:46 +01001008 if (sock && sock->sock_timeout >= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001009 BIO_set_nbio(SSL_get_rbio(self->ssl), 1);
1010 BIO_set_nbio(SSL_get_wbio(self->ssl), 1);
1011 }
Guido van Rossum4f707ac2003-01-31 18:13:18 +00001012
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001013 PySSL_BEGIN_ALLOW_THREADS
1014 if (socket_type == PY_SSL_CLIENT)
1015 SSL_set_connect_state(self->ssl);
1016 else
1017 SSL_set_accept_state(self->ssl);
1018 PySSL_END_ALLOW_THREADS
Martin v. Löwis09c35f72002-07-28 09:57:45 +00001019
Antoine Pitroud6494802011-07-21 01:11:30 +02001020 self->socket_type = socket_type;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001021 if (sock != NULL) {
1022 self->Socket = PyWeakref_NewRef((PyObject *) sock, NULL);
1023 if (self->Socket == NULL) {
1024 Py_DECREF(self);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001025 return NULL;
1026 }
Victor Stinnera9eb38f2013-10-31 16:35:38 +01001027 }
Christian Heimes141c5e82018-02-24 21:10:57 +01001028 if (owner && owner != Py_None) {
1029 if (PySSL_set_owner(self, owner, NULL) == -1) {
1030 Py_DECREF(self);
1031 return NULL;
1032 }
1033 }
1034 if (session && session != Py_None) {
1035 if (PySSL_set_session(self, session, NULL) == -1) {
1036 Py_DECREF(self);
1037 return NULL;
1038 }
1039 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001040 return self;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001041}
1042
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001043/* SSL object methods */
1044
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001045/*[clinic input]
1046_ssl._SSLSocket.do_handshake
1047[clinic start generated code]*/
1048
1049static PyObject *
1050_ssl__SSLSocket_do_handshake_impl(PySSLSocket *self)
1051/*[clinic end generated code: output=6c0898a8936548f6 input=d2d737de3df018c8]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001052{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001053 int ret;
Steve Dowerc6fd1c12018-09-17 11:34:47 -07001054 _PySSLError err;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001055 int sockstate, nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001056 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02001057 _PyTime_t timeout, deadline = 0;
1058 int has_timeout;
Antoine Pitroud3f8ab82010-04-24 21:26:44 +00001059
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001060 if (sock) {
1061 if (((PyObject*)sock) == Py_None) {
1062 _setSSLError("Underlying socket connection gone",
1063 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1064 return NULL;
1065 }
1066 Py_INCREF(sock);
1067
1068 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01001069 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001070 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1071 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001072 }
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001073
Victor Stinner14690702015-04-06 22:46:13 +02001074 timeout = GET_SOCKET_TIMEOUT(sock);
1075 has_timeout = (timeout > 0);
1076 if (has_timeout)
1077 deadline = _PyTime_GetMonotonicClock() + timeout;
1078
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001079 /* Actually negotiate SSL connection */
1080 /* XXX If SSL_do_handshake() returns 0, it's also a failure. */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001081 do {
Bill Janssen6e027db2007-11-15 22:23:56 +00001082 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001083 ret = SSL_do_handshake(self->ssl);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07001084 err = _PySSL_errno(ret < 1, self->ssl, ret);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001085 PySSL_END_ALLOW_THREADS
Steve Dowerc6fd1c12018-09-17 11:34:47 -07001086 self->err = err;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001087
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001088 if (PyErr_CheckSignals())
1089 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001090
Victor Stinner14690702015-04-06 22:46:13 +02001091 if (has_timeout)
1092 timeout = deadline - _PyTime_GetMonotonicClock();
1093
Steve Dowerc6fd1c12018-09-17 11:34:47 -07001094 if (err.ssl == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +02001095 sockstate = PySSL_select(sock, 0, timeout);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07001096 } else if (err.ssl == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +02001097 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001098 } else {
1099 sockstate = SOCKET_OPERATION_OK;
1100 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001101
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001102 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001103 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitrou525807b2010-05-12 14:05:24 +00001104 ERRSTR("The handshake operation timed out"));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001105 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001106 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1107 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +00001108 ERRSTR("Underlying socket has been closed."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001109 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001110 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1111 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +00001112 ERRSTR("Underlying socket too large for select()."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001113 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001114 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1115 break;
1116 }
Steve Dowerc6fd1c12018-09-17 11:34:47 -07001117 } while (err.ssl == SSL_ERROR_WANT_READ ||
1118 err.ssl == SSL_ERROR_WANT_WRITE);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001119 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001120 if (ret < 1)
1121 return PySSL_SetError(self, ret, __FILE__, __LINE__);
Christian Heimesc7f70692019-05-31 11:44:05 +02001122 if (PySSL_ChainExceptions(self) < 0)
1123 return NULL;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001124 Py_RETURN_NONE;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001125error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001126 Py_XDECREF(sock);
Christian Heimesc7f70692019-05-31 11:44:05 +02001127 PySSL_ChainExceptions(self);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001128 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001129}
1130
Thomas Woutersed03b412007-08-28 21:37:11 +00001131static PyObject *
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001132_asn1obj2py(const ASN1_OBJECT *name, int no_name)
1133{
1134 char buf[X509_NAME_MAXLEN];
1135 char *namebuf = buf;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001136 int buflen;
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001137 PyObject *name_obj = NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001138
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001139 buflen = OBJ_obj2txt(namebuf, X509_NAME_MAXLEN, name, no_name);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001140 if (buflen < 0) {
1141 _setSSLError(NULL, 0, __FILE__, __LINE__);
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001142 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001143 }
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001144 /* initial buffer is too small for oid + terminating null byte */
1145 if (buflen > X509_NAME_MAXLEN - 1) {
1146 /* make OBJ_obj2txt() calculate the required buflen */
1147 buflen = OBJ_obj2txt(NULL, 0, name, no_name);
1148 /* allocate len + 1 for terminating NULL byte */
1149 namebuf = PyMem_Malloc(buflen + 1);
1150 if (namebuf == NULL) {
1151 PyErr_NoMemory();
1152 return NULL;
1153 }
1154 buflen = OBJ_obj2txt(namebuf, buflen + 1, name, no_name);
1155 if (buflen < 0) {
1156 _setSSLError(NULL, 0, __FILE__, __LINE__);
1157 goto done;
1158 }
1159 }
1160 if (!buflen && no_name) {
1161 Py_INCREF(Py_None);
1162 name_obj = Py_None;
1163 }
1164 else {
1165 name_obj = PyUnicode_FromStringAndSize(namebuf, buflen);
1166 }
1167
1168 done:
1169 if (buf != namebuf) {
1170 PyMem_Free(namebuf);
1171 }
1172 return name_obj;
1173}
1174
1175static PyObject *
1176_create_tuple_for_attribute(ASN1_OBJECT *name, ASN1_STRING *value)
1177{
1178 Py_ssize_t buflen;
1179 unsigned char *valuebuf = NULL;
1180 PyObject *attr;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001181
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001182 buflen = ASN1_STRING_to_UTF8(&valuebuf, value);
1183 if (buflen < 0) {
1184 _setSSLError(NULL, 0, __FILE__, __LINE__);
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001185 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001186 }
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001187 attr = Py_BuildValue("Ns#", _asn1obj2py(name, 0), valuebuf, buflen);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001188 OPENSSL_free(valuebuf);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001189 return attr;
Thomas Woutersed03b412007-08-28 21:37:11 +00001190}
1191
1192static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001193_create_tuple_for_X509_NAME (X509_NAME *xname)
Thomas Woutersed03b412007-08-28 21:37:11 +00001194{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001195 PyObject *dn = NULL; /* tuple which represents the "distinguished name" */
1196 PyObject *rdn = NULL; /* tuple to hold a "relative distinguished name" */
1197 PyObject *rdnt;
1198 PyObject *attr = NULL; /* tuple to hold an attribute */
1199 int entry_count = X509_NAME_entry_count(xname);
1200 X509_NAME_ENTRY *entry;
1201 ASN1_OBJECT *name;
1202 ASN1_STRING *value;
1203 int index_counter;
1204 int rdn_level = -1;
1205 int retcode;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001206
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001207 dn = PyList_New(0);
1208 if (dn == NULL)
1209 return NULL;
1210 /* now create another tuple to hold the top-level RDN */
1211 rdn = PyList_New(0);
1212 if (rdn == NULL)
1213 goto fail0;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001214
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001215 for (index_counter = 0;
1216 index_counter < entry_count;
1217 index_counter++)
1218 {
1219 entry = X509_NAME_get_entry(xname, index_counter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001220
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001221 /* check to see if we've gotten to a new RDN */
1222 if (rdn_level >= 0) {
Christian Heimes598894f2016-09-05 23:19:05 +02001223 if (rdn_level != X509_NAME_ENTRY_set(entry)) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001224 /* yes, new RDN */
1225 /* add old RDN to DN */
1226 rdnt = PyList_AsTuple(rdn);
1227 Py_DECREF(rdn);
1228 if (rdnt == NULL)
1229 goto fail0;
1230 retcode = PyList_Append(dn, rdnt);
1231 Py_DECREF(rdnt);
1232 if (retcode < 0)
1233 goto fail0;
1234 /* create new RDN */
1235 rdn = PyList_New(0);
1236 if (rdn == NULL)
1237 goto fail0;
1238 }
1239 }
Christian Heimes598894f2016-09-05 23:19:05 +02001240 rdn_level = X509_NAME_ENTRY_set(entry);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001241
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001242 /* now add this attribute to the current RDN */
1243 name = X509_NAME_ENTRY_get_object(entry);
1244 value = X509_NAME_ENTRY_get_data(entry);
1245 attr = _create_tuple_for_attribute(name, value);
1246 /*
1247 fprintf(stderr, "RDN level %d, attribute %s: %s\n",
1248 entry->set,
1249 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 0)),
1250 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 1)));
1251 */
1252 if (attr == NULL)
1253 goto fail1;
1254 retcode = PyList_Append(rdn, attr);
1255 Py_DECREF(attr);
1256 if (retcode < 0)
1257 goto fail1;
1258 }
1259 /* now, there's typically a dangling RDN */
Antoine Pitrou2f5a1632012-02-15 22:25:27 +01001260 if (rdn != NULL) {
1261 if (PyList_GET_SIZE(rdn) > 0) {
1262 rdnt = PyList_AsTuple(rdn);
1263 Py_DECREF(rdn);
1264 if (rdnt == NULL)
1265 goto fail0;
1266 retcode = PyList_Append(dn, rdnt);
1267 Py_DECREF(rdnt);
1268 if (retcode < 0)
1269 goto fail0;
1270 }
1271 else {
1272 Py_DECREF(rdn);
1273 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001274 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001275
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001276 /* convert list to tuple */
1277 rdnt = PyList_AsTuple(dn);
1278 Py_DECREF(dn);
1279 if (rdnt == NULL)
1280 return NULL;
1281 return rdnt;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001282
1283 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001284 Py_XDECREF(rdn);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001285
1286 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001287 Py_XDECREF(dn);
1288 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001289}
1290
1291static PyObject *
1292_get_peer_alt_names (X509 *certificate) {
Guido van Rossumf06628b2007-11-21 20:01:53 +00001293
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001294 /* this code follows the procedure outlined in
1295 OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print()
1296 function to extract the STACK_OF(GENERAL_NAME),
1297 then iterates through the stack to add the
1298 names. */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001299
Alex Gaynorb87c0df2017-06-06 07:53:11 -04001300 int j;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001301 PyObject *peer_alt_names = Py_None;
Christian Heimes60bf2fc2013-09-05 16:04:35 +02001302 PyObject *v = NULL, *t;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001303 GENERAL_NAMES *names = NULL;
1304 GENERAL_NAME *name;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001305 BIO *biobuf = NULL;
1306 char buf[2048];
1307 char *vptr;
1308 int len;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001309
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001310 if (certificate == NULL)
1311 return peer_alt_names;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001312
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001313 /* get a memory buffer */
1314 biobuf = BIO_new(BIO_s_mem());
Zackery Spytz4c49da02018-12-07 03:11:30 -07001315 if (biobuf == NULL) {
1316 PyErr_SetString(PySSLErrorObject, "failed to allocate BIO");
1317 return NULL;
1318 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001319
Alex Gaynorb87c0df2017-06-06 07:53:11 -04001320 names = (GENERAL_NAMES *)X509_get_ext_d2i(
1321 certificate, NID_subject_alt_name, NULL, NULL);
1322 if (names != NULL) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001323 if (peer_alt_names == Py_None) {
1324 peer_alt_names = PyList_New(0);
1325 if (peer_alt_names == NULL)
1326 goto fail;
1327 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001328
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001329 for(j = 0; j < sk_GENERAL_NAME_num(names); j++) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001330 /* get a rendering of each name in the set of names */
Christian Heimes824f7f32013-08-17 00:54:47 +02001331 int gntype;
1332 ASN1_STRING *as = NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001333
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001334 name = sk_GENERAL_NAME_value(names, j);
Christian Heimes474afdd2013-08-17 17:18:56 +02001335 gntype = name->type;
Christian Heimes824f7f32013-08-17 00:54:47 +02001336 switch (gntype) {
1337 case GEN_DIRNAME:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001338 /* we special-case DirName as a tuple of
1339 tuples of attributes */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001340
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001341 t = PyTuple_New(2);
1342 if (t == NULL) {
1343 goto fail;
1344 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001345
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001346 v = PyUnicode_FromString("DirName");
1347 if (v == NULL) {
1348 Py_DECREF(t);
1349 goto fail;
1350 }
1351 PyTuple_SET_ITEM(t, 0, v);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001352
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001353 v = _create_tuple_for_X509_NAME (name->d.dirn);
1354 if (v == NULL) {
1355 Py_DECREF(t);
1356 goto fail;
1357 }
1358 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +02001359 break;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001360
Christian Heimes824f7f32013-08-17 00:54:47 +02001361 case GEN_EMAIL:
1362 case GEN_DNS:
1363 case GEN_URI:
1364 /* GENERAL_NAME_print() doesn't handle NULL bytes in ASN1_string
1365 correctly, CVE-2013-4238 */
1366 t = PyTuple_New(2);
1367 if (t == NULL)
1368 goto fail;
1369 switch (gntype) {
1370 case GEN_EMAIL:
1371 v = PyUnicode_FromString("email");
1372 as = name->d.rfc822Name;
1373 break;
1374 case GEN_DNS:
1375 v = PyUnicode_FromString("DNS");
1376 as = name->d.dNSName;
1377 break;
1378 case GEN_URI:
1379 v = PyUnicode_FromString("URI");
1380 as = name->d.uniformResourceIdentifier;
1381 break;
1382 }
1383 if (v == NULL) {
1384 Py_DECREF(t);
1385 goto fail;
1386 }
1387 PyTuple_SET_ITEM(t, 0, v);
Christian Heimesa871f692020-06-01 08:58:14 +02001388 v = PyUnicode_FromStringAndSize((char *)ASN1_STRING_get0_data(as),
Christian Heimes824f7f32013-08-17 00:54:47 +02001389 ASN1_STRING_length(as));
1390 if (v == NULL) {
1391 Py_DECREF(t);
1392 goto fail;
1393 }
1394 PyTuple_SET_ITEM(t, 1, v);
1395 break;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001396
Christian Heimes1c03abd2016-09-06 23:25:35 +02001397 case GEN_RID:
1398 t = PyTuple_New(2);
1399 if (t == NULL)
1400 goto fail;
1401
1402 v = PyUnicode_FromString("Registered ID");
1403 if (v == NULL) {
1404 Py_DECREF(t);
1405 goto fail;
1406 }
1407 PyTuple_SET_ITEM(t, 0, v);
1408
1409 len = i2t_ASN1_OBJECT(buf, sizeof(buf)-1, name->d.rid);
1410 if (len < 0) {
1411 Py_DECREF(t);
1412 _setSSLError(NULL, 0, __FILE__, __LINE__);
1413 goto fail;
1414 } else if (len >= (int)sizeof(buf)) {
1415 v = PyUnicode_FromString("<INVALID>");
1416 } else {
1417 v = PyUnicode_FromStringAndSize(buf, len);
1418 }
1419 if (v == NULL) {
1420 Py_DECREF(t);
1421 goto fail;
1422 }
1423 PyTuple_SET_ITEM(t, 1, v);
1424 break;
1425
Christian Heimes2b7de662019-12-07 17:59:36 +01001426 case GEN_IPADD:
1427 /* OpenSSL < 3.0.0 adds a trailing \n to IPv6. 3.0.0 removed
1428 * the trailing newline. Remove it in all versions
1429 */
1430 t = PyTuple_New(2);
1431 if (t == NULL)
1432 goto fail;
1433
1434 v = PyUnicode_FromString("IP Address");
1435 if (v == NULL) {
1436 Py_DECREF(t);
1437 goto fail;
1438 }
1439 PyTuple_SET_ITEM(t, 0, v);
1440
1441 if (name->d.ip->length == 4) {
1442 unsigned char *p = name->d.ip->data;
1443 v = PyUnicode_FromFormat(
1444 "%d.%d.%d.%d",
1445 p[0], p[1], p[2], p[3]
1446 );
1447 } else if (name->d.ip->length == 16) {
1448 /* PyUnicode_FromFormat() does not support %X */
1449 unsigned char *p = name->d.ip->data;
1450 len = sprintf(
1451 buf,
1452 "%X:%X:%X:%X:%X:%X:%X:%X",
1453 p[0] << 8 | p[1],
1454 p[2] << 8 | p[3],
1455 p[4] << 8 | p[5],
1456 p[6] << 8 | p[7],
1457 p[8] << 8 | p[9],
1458 p[10] << 8 | p[11],
1459 p[12] << 8 | p[13],
1460 p[14] << 8 | p[15]
1461 );
1462 v = PyUnicode_FromStringAndSize(buf, len);
1463 } else {
1464 v = PyUnicode_FromString("<invalid>");
1465 }
1466
1467 if (v == NULL) {
1468 Py_DECREF(t);
1469 goto fail;
1470 }
1471 PyTuple_SET_ITEM(t, 1, v);
1472 break;
1473
Christian Heimes824f7f32013-08-17 00:54:47 +02001474 default:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001475 /* for everything else, we use the OpenSSL print form */
Christian Heimes824f7f32013-08-17 00:54:47 +02001476 switch (gntype) {
1477 /* check for new general name type */
1478 case GEN_OTHERNAME:
1479 case GEN_X400:
1480 case GEN_EDIPARTY:
Christian Heimes824f7f32013-08-17 00:54:47 +02001481 case GEN_RID:
1482 break;
1483 default:
1484 if (PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
1485 "Unknown general name type %d",
1486 gntype) == -1) {
1487 goto fail;
1488 }
1489 break;
1490 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001491 (void) BIO_reset(biobuf);
1492 GENERAL_NAME_print(biobuf, name);
1493 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1494 if (len < 0) {
1495 _setSSLError(NULL, 0, __FILE__, __LINE__);
1496 goto fail;
1497 }
1498 vptr = strchr(buf, ':');
Christian Heimes1c03abd2016-09-06 23:25:35 +02001499 if (vptr == NULL) {
1500 PyErr_Format(PyExc_ValueError,
1501 "Invalid value %.200s",
1502 buf);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001503 goto fail;
Christian Heimes1c03abd2016-09-06 23:25:35 +02001504 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001505 t = PyTuple_New(2);
1506 if (t == NULL)
1507 goto fail;
1508 v = PyUnicode_FromStringAndSize(buf, (vptr - buf));
1509 if (v == NULL) {
1510 Py_DECREF(t);
1511 goto fail;
1512 }
1513 PyTuple_SET_ITEM(t, 0, v);
1514 v = PyUnicode_FromStringAndSize((vptr + 1),
1515 (len - (vptr - buf + 1)));
1516 if (v == NULL) {
1517 Py_DECREF(t);
1518 goto fail;
1519 }
1520 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +02001521 break;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001522 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001523
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001524 /* and add that rendering to the list */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001525
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001526 if (PyList_Append(peer_alt_names, t) < 0) {
1527 Py_DECREF(t);
1528 goto fail;
1529 }
1530 Py_DECREF(t);
1531 }
Antoine Pitrou116d6b92011-11-23 01:39:19 +01001532 sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001533 }
1534 BIO_free(biobuf);
1535 if (peer_alt_names != Py_None) {
1536 v = PyList_AsTuple(peer_alt_names);
1537 Py_DECREF(peer_alt_names);
1538 return v;
1539 } else {
1540 return peer_alt_names;
1541 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001542
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001543
1544 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001545 if (biobuf != NULL)
1546 BIO_free(biobuf);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001547
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001548 if (peer_alt_names != Py_None) {
1549 Py_XDECREF(peer_alt_names);
1550 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001551
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001552 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001553}
1554
1555static PyObject *
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001556_get_aia_uri(X509 *certificate, int nid) {
1557 PyObject *lst = NULL, *ostr = NULL;
1558 int i, result;
1559 AUTHORITY_INFO_ACCESS *info;
1560
1561 info = X509_get_ext_d2i(certificate, NID_info_access, NULL, NULL);
Benjamin Petersonf0c90382015-11-14 15:12:18 -08001562 if (info == NULL)
1563 return Py_None;
1564 if (sk_ACCESS_DESCRIPTION_num(info) == 0) {
1565 AUTHORITY_INFO_ACCESS_free(info);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001566 return Py_None;
1567 }
1568
1569 if ((lst = PyList_New(0)) == NULL) {
1570 goto fail;
1571 }
1572
1573 for (i = 0; i < sk_ACCESS_DESCRIPTION_num(info); i++) {
1574 ACCESS_DESCRIPTION *ad = sk_ACCESS_DESCRIPTION_value(info, i);
1575 ASN1_IA5STRING *uri;
1576
1577 if ((OBJ_obj2nid(ad->method) != nid) ||
1578 (ad->location->type != GEN_URI)) {
1579 continue;
1580 }
1581 uri = ad->location->d.uniformResourceIdentifier;
1582 ostr = PyUnicode_FromStringAndSize((char *)uri->data,
1583 uri->length);
1584 if (ostr == NULL) {
1585 goto fail;
1586 }
1587 result = PyList_Append(lst, ostr);
1588 Py_DECREF(ostr);
1589 if (result < 0) {
1590 goto fail;
1591 }
1592 }
1593 AUTHORITY_INFO_ACCESS_free(info);
1594
1595 /* convert to tuple or None */
1596 if (PyList_Size(lst) == 0) {
1597 Py_DECREF(lst);
1598 return Py_None;
1599 } else {
1600 PyObject *tup;
1601 tup = PyList_AsTuple(lst);
1602 Py_DECREF(lst);
1603 return tup;
1604 }
1605
1606 fail:
1607 AUTHORITY_INFO_ACCESS_free(info);
Christian Heimes18fc7be2013-11-21 23:57:49 +01001608 Py_XDECREF(lst);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001609 return NULL;
1610}
1611
1612static PyObject *
1613_get_crl_dp(X509 *certificate) {
1614 STACK_OF(DIST_POINT) *dps;
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001615 int i, j;
1616 PyObject *lst, *res = NULL;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001617
Christian Heimes598894f2016-09-05 23:19:05 +02001618 dps = X509_get_ext_d2i(certificate, NID_crl_distribution_points, NULL, NULL);
Christian Heimes949ec142013-11-21 16:26:51 +01001619
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001620 if (dps == NULL)
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001621 return Py_None;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001622
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001623 lst = PyList_New(0);
1624 if (lst == NULL)
1625 goto done;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001626
1627 for (i=0; i < sk_DIST_POINT_num(dps); i++) {
1628 DIST_POINT *dp;
1629 STACK_OF(GENERAL_NAME) *gns;
1630
1631 dp = sk_DIST_POINT_value(dps, i);
Christian Heimesa37f5242019-01-15 23:47:42 +01001632 if (dp->distpoint == NULL) {
1633 /* Ignore empty DP value, CVE-2019-5010 */
1634 continue;
1635 }
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001636 gns = dp->distpoint->name.fullname;
1637
1638 for (j=0; j < sk_GENERAL_NAME_num(gns); j++) {
1639 GENERAL_NAME *gn;
1640 ASN1_IA5STRING *uri;
1641 PyObject *ouri;
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001642 int err;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001643
1644 gn = sk_GENERAL_NAME_value(gns, j);
1645 if (gn->type != GEN_URI) {
1646 continue;
1647 }
1648 uri = gn->d.uniformResourceIdentifier;
1649 ouri = PyUnicode_FromStringAndSize((char *)uri->data,
1650 uri->length);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001651 if (ouri == NULL)
1652 goto done;
1653
1654 err = PyList_Append(lst, ouri);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001655 Py_DECREF(ouri);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001656 if (err < 0)
1657 goto done;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001658 }
1659 }
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001660
1661 /* Convert to tuple. */
1662 res = (PyList_GET_SIZE(lst) > 0) ? PyList_AsTuple(lst) : Py_None;
1663
1664 done:
1665 Py_XDECREF(lst);
Olivier Vielpeau2849cc32017-04-14 21:06:07 -04001666 CRL_DIST_POINTS_free(dps);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001667 return res;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001668}
1669
1670static PyObject *
Antoine Pitroufb046912010-11-09 20:21:19 +00001671_decode_certificate(X509 *certificate) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001672
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001673 PyObject *retval = NULL;
1674 BIO *biobuf = NULL;
1675 PyObject *peer;
1676 PyObject *peer_alt_names = NULL;
1677 PyObject *issuer;
1678 PyObject *version;
1679 PyObject *sn_obj;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001680 PyObject *obj;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001681 ASN1_INTEGER *serialNumber;
1682 char buf[2048];
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001683 int len, result;
Christian Heimesa871f692020-06-01 08:58:14 +02001684 const ASN1_TIME *notBefore, *notAfter;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001685 PyObject *pnotBefore, *pnotAfter;
Thomas Woutersed03b412007-08-28 21:37:11 +00001686
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001687 retval = PyDict_New();
1688 if (retval == NULL)
1689 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001690
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001691 peer = _create_tuple_for_X509_NAME(
1692 X509_get_subject_name(certificate));
1693 if (peer == NULL)
1694 goto fail0;
1695 if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) {
1696 Py_DECREF(peer);
1697 goto fail0;
1698 }
1699 Py_DECREF(peer);
Thomas Woutersed03b412007-08-28 21:37:11 +00001700
Antoine Pitroufb046912010-11-09 20:21:19 +00001701 issuer = _create_tuple_for_X509_NAME(
1702 X509_get_issuer_name(certificate));
1703 if (issuer == NULL)
1704 goto fail0;
1705 if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001706 Py_DECREF(issuer);
Antoine Pitroufb046912010-11-09 20:21:19 +00001707 goto fail0;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001708 }
Antoine Pitroufb046912010-11-09 20:21:19 +00001709 Py_DECREF(issuer);
1710
1711 version = PyLong_FromLong(X509_get_version(certificate) + 1);
Christian Heimes5962bef2013-07-26 15:51:18 +02001712 if (version == NULL)
1713 goto fail0;
Antoine Pitroufb046912010-11-09 20:21:19 +00001714 if (PyDict_SetItemString(retval, "version", version) < 0) {
1715 Py_DECREF(version);
1716 goto fail0;
1717 }
1718 Py_DECREF(version);
Guido van Rossumf06628b2007-11-21 20:01:53 +00001719
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001720 /* get a memory buffer */
1721 biobuf = BIO_new(BIO_s_mem());
Zackery Spytz4c49da02018-12-07 03:11:30 -07001722 if (biobuf == NULL) {
1723 PyErr_SetString(PySSLErrorObject, "failed to allocate BIO");
1724 goto fail0;
1725 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001726
Antoine Pitroufb046912010-11-09 20:21:19 +00001727 (void) BIO_reset(biobuf);
1728 serialNumber = X509_get_serialNumber(certificate);
1729 /* should not exceed 20 octets, 160 bits, so buf is big enough */
1730 i2a_ASN1_INTEGER(biobuf, serialNumber);
1731 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1732 if (len < 0) {
1733 _setSSLError(NULL, 0, __FILE__, __LINE__);
1734 goto fail1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001735 }
Antoine Pitroufb046912010-11-09 20:21:19 +00001736 sn_obj = PyUnicode_FromStringAndSize(buf, len);
1737 if (sn_obj == NULL)
1738 goto fail1;
1739 if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) {
1740 Py_DECREF(sn_obj);
1741 goto fail1;
1742 }
1743 Py_DECREF(sn_obj);
1744
1745 (void) BIO_reset(biobuf);
Christian Heimesa871f692020-06-01 08:58:14 +02001746 notBefore = X509_get0_notBefore(certificate);
Antoine Pitroufb046912010-11-09 20:21:19 +00001747 ASN1_TIME_print(biobuf, notBefore);
1748 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1749 if (len < 0) {
1750 _setSSLError(NULL, 0, __FILE__, __LINE__);
1751 goto fail1;
1752 }
1753 pnotBefore = PyUnicode_FromStringAndSize(buf, len);
1754 if (pnotBefore == NULL)
1755 goto fail1;
1756 if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) {
1757 Py_DECREF(pnotBefore);
1758 goto fail1;
1759 }
1760 Py_DECREF(pnotBefore);
Thomas Woutersed03b412007-08-28 21:37:11 +00001761
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001762 (void) BIO_reset(biobuf);
Christian Heimesa871f692020-06-01 08:58:14 +02001763 notAfter = X509_get0_notAfter(certificate);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001764 ASN1_TIME_print(biobuf, notAfter);
1765 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1766 if (len < 0) {
1767 _setSSLError(NULL, 0, __FILE__, __LINE__);
1768 goto fail1;
1769 }
1770 pnotAfter = PyUnicode_FromStringAndSize(buf, len);
1771 if (pnotAfter == NULL)
1772 goto fail1;
1773 if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) {
1774 Py_DECREF(pnotAfter);
1775 goto fail1;
1776 }
1777 Py_DECREF(pnotAfter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001778
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001779 /* Now look for subjectAltName */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001780
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001781 peer_alt_names = _get_peer_alt_names(certificate);
1782 if (peer_alt_names == NULL)
1783 goto fail1;
1784 else if (peer_alt_names != Py_None) {
1785 if (PyDict_SetItemString(retval, "subjectAltName",
1786 peer_alt_names) < 0) {
1787 Py_DECREF(peer_alt_names);
1788 goto fail1;
1789 }
1790 Py_DECREF(peer_alt_names);
1791 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001792
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001793 /* Authority Information Access: OCSP URIs */
1794 obj = _get_aia_uri(certificate, NID_ad_OCSP);
1795 if (obj == NULL) {
1796 goto fail1;
1797 } else if (obj != Py_None) {
1798 result = PyDict_SetItemString(retval, "OCSP", obj);
1799 Py_DECREF(obj);
1800 if (result < 0) {
1801 goto fail1;
1802 }
1803 }
1804
1805 obj = _get_aia_uri(certificate, NID_ad_ca_issuers);
1806 if (obj == NULL) {
1807 goto fail1;
1808 } else if (obj != Py_None) {
1809 result = PyDict_SetItemString(retval, "caIssuers", obj);
1810 Py_DECREF(obj);
1811 if (result < 0) {
1812 goto fail1;
1813 }
1814 }
1815
1816 /* CDP (CRL distribution points) */
1817 obj = _get_crl_dp(certificate);
1818 if (obj == NULL) {
1819 goto fail1;
1820 } else if (obj != Py_None) {
1821 result = PyDict_SetItemString(retval, "crlDistributionPoints", obj);
1822 Py_DECREF(obj);
1823 if (result < 0) {
1824 goto fail1;
1825 }
1826 }
1827
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001828 BIO_free(biobuf);
1829 return retval;
Thomas Woutersed03b412007-08-28 21:37:11 +00001830
1831 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001832 if (biobuf != NULL)
1833 BIO_free(biobuf);
Thomas Woutersed03b412007-08-28 21:37:11 +00001834 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001835 Py_XDECREF(retval);
1836 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001837}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001838
Christian Heimes9a5395a2013-06-17 15:44:12 +02001839static PyObject *
1840_certificate_to_der(X509 *certificate)
1841{
1842 unsigned char *bytes_buf = NULL;
1843 int len;
1844 PyObject *retval;
1845
1846 bytes_buf = NULL;
1847 len = i2d_X509(certificate, &bytes_buf);
1848 if (len < 0) {
1849 _setSSLError(NULL, 0, __FILE__, __LINE__);
1850 return NULL;
1851 }
1852 /* this is actually an immutable bytes sequence */
1853 retval = PyBytes_FromStringAndSize((const char *) bytes_buf, len);
1854 OPENSSL_free(bytes_buf);
1855 return retval;
1856}
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001857
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001858/*[clinic input]
1859_ssl._test_decode_cert
1860 path: object(converter="PyUnicode_FSConverter")
1861 /
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001862
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001863[clinic start generated code]*/
1864
1865static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001866_ssl__test_decode_cert_impl(PyObject *module, PyObject *path)
1867/*[clinic end generated code: output=96becb9abb23c091 input=cdeaaf02d4346628]*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001868{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001869 PyObject *retval = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001870 X509 *x=NULL;
1871 BIO *cert;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001872
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001873 if ((cert=BIO_new(BIO_s_file())) == NULL) {
1874 PyErr_SetString(PySSLErrorObject,
1875 "Can't malloc memory to read file");
1876 goto fail0;
1877 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001878
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001879 if (BIO_read_filename(cert, PyBytes_AsString(path)) <= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001880 PyErr_SetString(PySSLErrorObject,
1881 "Can't open file");
1882 goto fail0;
1883 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001884
Alex Gaynor40dad952019-08-15 08:31:28 -04001885 x = PEM_read_bio_X509(cert, NULL, NULL, NULL);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001886 if (x == NULL) {
1887 PyErr_SetString(PySSLErrorObject,
1888 "Error decoding PEM-encoded file");
1889 goto fail0;
1890 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001891
Antoine Pitroufb046912010-11-09 20:21:19 +00001892 retval = _decode_certificate(x);
Mark Dickinsonee55df52010-08-03 18:31:54 +00001893 X509_free(x);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001894
1895 fail0:
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001896 Py_DECREF(path);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001897 if (cert != NULL) BIO_free(cert);
1898 return retval;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001899}
1900
1901
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001902/*[clinic input]
Christian Heimes141c5e82018-02-24 21:10:57 +01001903_ssl._SSLSocket.getpeercert
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001904 der as binary_mode: bool = False
1905 /
1906
1907Returns the certificate for the peer.
1908
1909If no certificate was provided, returns None. If a certificate was
1910provided, but not validated, returns an empty dictionary. Otherwise
1911returns a dict containing information about the peer certificate.
1912
1913If the optional argument is True, returns a DER-encoded copy of the
1914peer certificate, or None if no certificate was provided. This will
1915return the certificate even if it wasn't validated.
1916[clinic start generated code]*/
1917
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001918static PyObject *
Christian Heimes141c5e82018-02-24 21:10:57 +01001919_ssl__SSLSocket_getpeercert_impl(PySSLSocket *self, int binary_mode)
1920/*[clinic end generated code: output=1f0ab66dfb693c88 input=c0fbe802e57629b7]*/
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001921{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001922 int verification;
Christian Heimes66dc33b2017-05-23 16:02:02 -07001923 X509 *peer_cert;
1924 PyObject *result;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001925
Christian Heimes66dc33b2017-05-23 16:02:02 -07001926 if (!SSL_is_init_finished(self->ssl)) {
Antoine Pitrou20b85552013-09-29 19:50:53 +02001927 PyErr_SetString(PyExc_ValueError,
1928 "handshake not done yet");
1929 return NULL;
1930 }
Christian Heimes66dc33b2017-05-23 16:02:02 -07001931 peer_cert = SSL_get_peer_certificate(self->ssl);
1932 if (peer_cert == NULL)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001933 Py_RETURN_NONE;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001934
Antoine Pitrou721738f2012-08-15 23:20:39 +02001935 if (binary_mode) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001936 /* return cert in DER-encoded format */
Christian Heimes66dc33b2017-05-23 16:02:02 -07001937 result = _certificate_to_der(peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001938 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00001939 verification = SSL_CTX_get_verify_mode(SSL_get_SSL_CTX(self->ssl));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001940 if ((verification & SSL_VERIFY_PEER) == 0)
Christian Heimes66dc33b2017-05-23 16:02:02 -07001941 result = PyDict_New();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001942 else
Christian Heimes66dc33b2017-05-23 16:02:02 -07001943 result = _decode_certificate(peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001944 }
Christian Heimes66dc33b2017-05-23 16:02:02 -07001945 X509_free(peer_cert);
1946 return result;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001947}
1948
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001949static PyObject *
1950cipher_to_tuple(const SSL_CIPHER *cipher)
1951{
1952 const char *cipher_name, *cipher_protocol;
1953 PyObject *v, *retval = PyTuple_New(3);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001954 if (retval == NULL)
1955 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001956
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001957 cipher_name = SSL_CIPHER_get_name(cipher);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001958 if (cipher_name == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001959 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001960 PyTuple_SET_ITEM(retval, 0, Py_None);
1961 } else {
1962 v = PyUnicode_FromString(cipher_name);
1963 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001964 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001965 PyTuple_SET_ITEM(retval, 0, v);
1966 }
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001967
1968 cipher_protocol = SSL_CIPHER_get_version(cipher);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001969 if (cipher_protocol == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001970 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001971 PyTuple_SET_ITEM(retval, 1, Py_None);
1972 } else {
1973 v = PyUnicode_FromString(cipher_protocol);
1974 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001975 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001976 PyTuple_SET_ITEM(retval, 1, v);
1977 }
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001978
1979 v = PyLong_FromLong(SSL_CIPHER_get_bits(cipher, NULL));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001980 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001981 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001982 PyTuple_SET_ITEM(retval, 2, v);
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001983
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001984 return retval;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001985
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001986 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001987 Py_DECREF(retval);
1988 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001989}
1990
Christian Heimes25bfcd52016-09-06 00:04:45 +02001991#if OPENSSL_VERSION_NUMBER >= 0x10002000UL
1992static PyObject *
1993cipher_to_dict(const SSL_CIPHER *cipher)
1994{
1995 const char *cipher_name, *cipher_protocol;
1996
1997 unsigned long cipher_id;
1998 int alg_bits, strength_bits, len;
1999 char buf[512] = {0};
2000#if OPENSSL_VERSION_1_1
2001 int aead, nid;
2002 const char *skcipher = NULL, *digest = NULL, *kx = NULL, *auth = NULL;
2003#endif
Christian Heimes25bfcd52016-09-06 00:04:45 +02002004
2005 /* can be NULL */
2006 cipher_name = SSL_CIPHER_get_name(cipher);
2007 cipher_protocol = SSL_CIPHER_get_version(cipher);
2008 cipher_id = SSL_CIPHER_get_id(cipher);
2009 SSL_CIPHER_description(cipher, buf, sizeof(buf) - 1);
Segev Finer5cff6372017-07-27 01:19:17 +03002010 /* Downcast to avoid a warning. Safe since buf is always 512 bytes */
2011 len = (int)strlen(buf);
Christian Heimes25bfcd52016-09-06 00:04:45 +02002012 if (len > 1 && buf[len-1] == '\n')
2013 buf[len-1] = '\0';
2014 strength_bits = SSL_CIPHER_get_bits(cipher, &alg_bits);
2015
2016#if OPENSSL_VERSION_1_1
2017 aead = SSL_CIPHER_is_aead(cipher);
2018 nid = SSL_CIPHER_get_cipher_nid(cipher);
2019 skcipher = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
2020 nid = SSL_CIPHER_get_digest_nid(cipher);
2021 digest = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
2022 nid = SSL_CIPHER_get_kx_nid(cipher);
2023 kx = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
2024 nid = SSL_CIPHER_get_auth_nid(cipher);
2025 auth = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
2026#endif
2027
Victor Stinner410b9882016-09-12 12:00:23 +02002028 return Py_BuildValue(
Christian Heimes25bfcd52016-09-06 00:04:45 +02002029 "{sksssssssisi"
2030#if OPENSSL_VERSION_1_1
2031 "sOssssssss"
2032#endif
2033 "}",
2034 "id", cipher_id,
2035 "name", cipher_name,
2036 "protocol", cipher_protocol,
2037 "description", buf,
2038 "strength_bits", strength_bits,
2039 "alg_bits", alg_bits
2040#if OPENSSL_VERSION_1_1
2041 ,"aead", aead ? Py_True : Py_False,
2042 "symmetric", skcipher,
2043 "digest", digest,
2044 "kea", kx,
2045 "auth", auth
2046#endif
2047 );
Christian Heimes25bfcd52016-09-06 00:04:45 +02002048}
2049#endif
2050
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002051/*[clinic input]
2052_ssl._SSLSocket.shared_ciphers
2053[clinic start generated code]*/
2054
2055static PyObject *
2056_ssl__SSLSocket_shared_ciphers_impl(PySSLSocket *self)
2057/*[clinic end generated code: output=3d174ead2e42c4fd input=0bfe149da8fe6306]*/
Benjamin Peterson4cb17812015-01-07 11:14:26 -06002058{
2059 STACK_OF(SSL_CIPHER) *ciphers;
2060 int i;
2061 PyObject *res;
2062
Christian Heimes598894f2016-09-05 23:19:05 +02002063 ciphers = SSL_get_ciphers(self->ssl);
2064 if (!ciphers)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06002065 Py_RETURN_NONE;
Benjamin Peterson4cb17812015-01-07 11:14:26 -06002066 res = PyList_New(sk_SSL_CIPHER_num(ciphers));
2067 if (!res)
2068 return NULL;
2069 for (i = 0; i < sk_SSL_CIPHER_num(ciphers); i++) {
2070 PyObject *tup = cipher_to_tuple(sk_SSL_CIPHER_value(ciphers, i));
2071 if (!tup) {
2072 Py_DECREF(res);
2073 return NULL;
2074 }
2075 PyList_SET_ITEM(res, i, tup);
2076 }
2077 return res;
2078}
2079
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002080/*[clinic input]
2081_ssl._SSLSocket.cipher
2082[clinic start generated code]*/
2083
2084static PyObject *
2085_ssl__SSLSocket_cipher_impl(PySSLSocket *self)
2086/*[clinic end generated code: output=376417c16d0e5815 input=548fb0e27243796d]*/
Benjamin Peterson4cb17812015-01-07 11:14:26 -06002087{
2088 const SSL_CIPHER *current;
2089
2090 if (self->ssl == NULL)
2091 Py_RETURN_NONE;
2092 current = SSL_get_current_cipher(self->ssl);
2093 if (current == NULL)
2094 Py_RETURN_NONE;
2095 return cipher_to_tuple(current);
2096}
2097
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002098/*[clinic input]
2099_ssl._SSLSocket.version
2100[clinic start generated code]*/
2101
2102static PyObject *
2103_ssl__SSLSocket_version_impl(PySSLSocket *self)
2104/*[clinic end generated code: output=178aed33193b2cdb input=900186a503436fd6]*/
Antoine Pitrou47e40422014-09-04 21:00:10 +02002105{
2106 const char *version;
2107
2108 if (self->ssl == NULL)
2109 Py_RETURN_NONE;
Christian Heimes68771112017-09-05 21:55:40 -07002110 if (!SSL_is_init_finished(self->ssl)) {
2111 /* handshake not finished */
2112 Py_RETURN_NONE;
2113 }
Antoine Pitrou47e40422014-09-04 21:00:10 +02002114 version = SSL_get_version(self->ssl);
2115 if (!strcmp(version, "unknown"))
2116 Py_RETURN_NONE;
2117 return PyUnicode_FromString(version);
2118}
2119
Christian Heimes29eab552018-02-25 12:31:33 +01002120#if HAVE_NPN
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002121/*[clinic input]
2122_ssl._SSLSocket.selected_npn_protocol
2123[clinic start generated code]*/
2124
2125static PyObject *
2126_ssl__SSLSocket_selected_npn_protocol_impl(PySSLSocket *self)
2127/*[clinic end generated code: output=b91d494cd207ecf6 input=c28fde139204b826]*/
2128{
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002129 const unsigned char *out;
2130 unsigned int outlen;
2131
Victor Stinner4569cd52013-06-23 14:58:43 +02002132 SSL_get0_next_proto_negotiated(self->ssl,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002133 &out, &outlen);
2134
2135 if (out == NULL)
2136 Py_RETURN_NONE;
Benjamin Petersoncca27322015-01-23 16:35:37 -05002137 return PyUnicode_FromStringAndSize((char *)out, outlen);
2138}
2139#endif
2140
Christian Heimes29eab552018-02-25 12:31:33 +01002141#if HAVE_ALPN
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002142/*[clinic input]
2143_ssl._SSLSocket.selected_alpn_protocol
2144[clinic start generated code]*/
2145
2146static PyObject *
2147_ssl__SSLSocket_selected_alpn_protocol_impl(PySSLSocket *self)
2148/*[clinic end generated code: output=ec33688b303d250f input=442de30e35bc2913]*/
2149{
Benjamin Petersoncca27322015-01-23 16:35:37 -05002150 const unsigned char *out;
2151 unsigned int outlen;
2152
2153 SSL_get0_alpn_selected(self->ssl, &out, &outlen);
2154
2155 if (out == NULL)
2156 Py_RETURN_NONE;
2157 return PyUnicode_FromStringAndSize((char *)out, outlen);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002158}
2159#endif
2160
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002161/*[clinic input]
2162_ssl._SSLSocket.compression
2163[clinic start generated code]*/
2164
2165static PyObject *
2166_ssl__SSLSocket_compression_impl(PySSLSocket *self)
2167/*[clinic end generated code: output=bd16cb1bb4646ae7 input=5d059d0a2bbc32c8]*/
2168{
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01002169#ifdef OPENSSL_NO_COMP
2170 Py_RETURN_NONE;
2171#else
2172 const COMP_METHOD *comp_method;
2173 const char *short_name;
2174
2175 if (self->ssl == NULL)
2176 Py_RETURN_NONE;
2177 comp_method = SSL_get_current_compression(self->ssl);
Christian Heimes598894f2016-09-05 23:19:05 +02002178 if (comp_method == NULL || COMP_get_type(comp_method) == NID_undef)
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01002179 Py_RETURN_NONE;
Christian Heimes281e5f82016-09-06 01:10:39 +02002180 short_name = OBJ_nid2sn(COMP_get_type(comp_method));
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01002181 if (short_name == NULL)
2182 Py_RETURN_NONE;
2183 return PyUnicode_DecodeFSDefault(short_name);
2184#endif
2185}
2186
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002187static PySSLContext *PySSL_get_context(PySSLSocket *self, void *closure) {
2188 Py_INCREF(self->ctx);
2189 return self->ctx;
2190}
2191
2192static int PySSL_set_context(PySSLSocket *self, PyObject *value,
2193 void *closure) {
2194
2195 if (PyObject_TypeCheck(value, &PySSLContext_Type)) {
Antoine Pitrou912fbff2013-03-30 16:29:32 +01002196#if !HAVE_SNI
2197 PyErr_SetString(PyExc_NotImplementedError, "setting a socket's "
2198 "context is not supported by your OpenSSL library");
Antoine Pitrou41f8c4f2013-03-30 16:36:54 +01002199 return -1;
Antoine Pitrou912fbff2013-03-30 16:29:32 +01002200#else
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002201 Py_INCREF(value);
Serhiy Storchaka57a01d32016-04-10 18:05:40 +03002202 Py_SETREF(self->ctx, (PySSLContext *)value);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002203 SSL_set_SSL_CTX(self->ssl, self->ctx->ctx);
Antoine Pitrou912fbff2013-03-30 16:29:32 +01002204#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002205 } else {
Ned Deily4531ec72018-06-11 20:26:28 -04002206 PyErr_SetString(PyExc_TypeError, "The value must be a SSLContext");
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002207 return -1;
2208 }
2209
2210 return 0;
2211}
2212
2213PyDoc_STRVAR(PySSL_set_context_doc,
2214"_setter_context(ctx)\n\
2215\
2216This changes the context associated with the SSLSocket. This is typically\n\
Christian Heimes11a14932018-02-24 02:35:08 +01002217used from within a callback function set by the sni_callback\n\
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002218on the SSLContext to change the certificate information associated with the\n\
2219SSLSocket before the cryptographic exchange handshake messages\n");
2220
2221
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002222static PyObject *
2223PySSL_get_server_side(PySSLSocket *self, void *c)
2224{
2225 return PyBool_FromLong(self->socket_type == PY_SSL_SERVER);
2226}
2227
2228PyDoc_STRVAR(PySSL_get_server_side_doc,
2229"Whether this is a server-side socket.");
2230
2231static PyObject *
2232PySSL_get_server_hostname(PySSLSocket *self, void *c)
2233{
2234 if (self->server_hostname == NULL)
2235 Py_RETURN_NONE;
2236 Py_INCREF(self->server_hostname);
2237 return self->server_hostname;
2238}
2239
2240PyDoc_STRVAR(PySSL_get_server_hostname_doc,
2241"The currently set server hostname (for SNI).");
2242
2243static PyObject *
2244PySSL_get_owner(PySSLSocket *self, void *c)
2245{
2246 PyObject *owner;
2247
2248 if (self->owner == NULL)
2249 Py_RETURN_NONE;
2250
2251 owner = PyWeakref_GetObject(self->owner);
2252 Py_INCREF(owner);
2253 return owner;
2254}
2255
2256static int
2257PySSL_set_owner(PySSLSocket *self, PyObject *value, void *c)
2258{
Serhiy Storchaka48842712016-04-06 09:45:48 +03002259 Py_XSETREF(self->owner, PyWeakref_NewRef(value, NULL));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002260 if (self->owner == NULL)
2261 return -1;
2262 return 0;
2263}
2264
2265PyDoc_STRVAR(PySSL_get_owner_doc,
2266"The Python-level owner of this object.\
2267Passed as \"self\" in servername callback.");
2268
Christian Heimesc7f70692019-05-31 11:44:05 +02002269static int
2270PySSL_traverse(PySSLSocket *self, visitproc visit, void *arg)
2271{
2272 Py_VISIT(self->exc_type);
2273 Py_VISIT(self->exc_value);
2274 Py_VISIT(self->exc_tb);
2275 return 0;
2276}
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002277
Christian Heimesc7f70692019-05-31 11:44:05 +02002278static int
2279PySSL_clear(PySSLSocket *self)
2280{
2281 Py_CLEAR(self->exc_type);
2282 Py_CLEAR(self->exc_value);
2283 Py_CLEAR(self->exc_tb);
2284 return 0;
2285}
2286
2287static void
2288PySSL_dealloc(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002289{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002290 if (self->ssl)
2291 SSL_free(self->ssl);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002292 Py_XDECREF(self->Socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002293 Py_XDECREF(self->ctx);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002294 Py_XDECREF(self->server_hostname);
2295 Py_XDECREF(self->owner);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002296 PyObject_Del(self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002297}
2298
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002299/* If the socket has a timeout, do a select()/poll() on the socket.
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002300 The argument writing indicates the direction.
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00002301 Returns one of the possibilities in the timeout_state enum (above).
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002302 */
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00002303
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002304static int
Victor Stinner14690702015-04-06 22:46:13 +02002305PySSL_select(PySocketSockObject *s, int writing, _PyTime_t timeout)
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002306{
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002307 int rc;
2308#ifdef HAVE_POLL
2309 struct pollfd pollfd;
2310 _PyTime_t ms;
2311#else
2312 int nfds;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002313 fd_set fds;
2314 struct timeval tv;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002315#endif
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002316
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002317 /* Nothing to do unless we're in timeout mode (not non-blocking) */
Victor Stinner14690702015-04-06 22:46:13 +02002318 if ((s == NULL) || (timeout == 0))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002319 return SOCKET_IS_NONBLOCKING;
Victor Stinner14690702015-04-06 22:46:13 +02002320 else if (timeout < 0) {
2321 if (s->sock_timeout > 0)
2322 return SOCKET_HAS_TIMED_OUT;
2323 else
2324 return SOCKET_IS_BLOCKING;
2325 }
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002326
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002327 /* Guard against closed socket */
Victor Stinner524714e2016-07-22 17:43:59 +02002328 if (s->sock_fd == INVALID_SOCKET)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002329 return SOCKET_HAS_BEEN_CLOSED;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002330
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002331 /* Prefer poll, if available, since you can poll() any fd
2332 * which can't be done with select(). */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002333#ifdef HAVE_POLL
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002334 pollfd.fd = s->sock_fd;
2335 pollfd.events = writing ? POLLOUT : POLLIN;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002336
Victor Stinner14690702015-04-06 22:46:13 +02002337 /* timeout is in seconds, poll() uses milliseconds */
2338 ms = (int)_PyTime_AsMilliseconds(timeout, _PyTime_ROUND_CEILING);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002339 assert(ms <= INT_MAX);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002340
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002341 PySSL_BEGIN_ALLOW_THREADS
2342 rc = poll(&pollfd, 1, (int)ms);
2343 PySSL_END_ALLOW_THREADS
2344#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002345 /* Guard against socket too large for select*/
Charles-François Nataliaa26b272011-08-28 17:51:43 +02002346 if (!_PyIsSelectable_fd(s->sock_fd))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002347 return SOCKET_TOO_LARGE_FOR_SELECT;
Neal Norwitz082b2df2006-02-07 07:04:46 +00002348
Victor Stinner14690702015-04-06 22:46:13 +02002349 _PyTime_AsTimeval_noraise(timeout, &tv, _PyTime_ROUND_CEILING);
Victor Stinnere2452312015-03-28 03:00:46 +01002350
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002351 FD_ZERO(&fds);
2352 FD_SET(s->sock_fd, &fds);
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002353
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002354 /* Wait until the socket becomes ready */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002355 PySSL_BEGIN_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002356 nfds = Py_SAFE_DOWNCAST(s->sock_fd+1, SOCKET_T, int);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002357 if (writing)
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002358 rc = select(nfds, NULL, &fds, NULL, &tv);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002359 else
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002360 rc = select(nfds, &fds, NULL, NULL, &tv);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002361 PySSL_END_ALLOW_THREADS
Bill Janssen6e027db2007-11-15 22:23:56 +00002362#endif
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002363
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002364 /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
2365 (when we are able to write or when there's something to read) */
2366 return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002367}
2368
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002369/*[clinic input]
2370_ssl._SSLSocket.write
2371 b: Py_buffer
2372 /
2373
2374Writes the bytes-like object b into the SSL object.
2375
2376Returns the number of bytes written.
2377[clinic start generated code]*/
2378
2379static PyObject *
2380_ssl__SSLSocket_write_impl(PySSLSocket *self, Py_buffer *b)
2381/*[clinic end generated code: output=aa7a6be5527358d8 input=77262d994fe5100a]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002382{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002383 int len;
2384 int sockstate;
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002385 _PySSLError err;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002386 int nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002387 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002388 _PyTime_t timeout, deadline = 0;
2389 int has_timeout;
Bill Janssen54cc54c2007-12-14 22:08:56 +00002390
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002391 if (sock != NULL) {
2392 if (((PyObject*)sock) == Py_None) {
2393 _setSSLError("Underlying socket connection gone",
2394 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2395 return NULL;
2396 }
2397 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002398 }
2399
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002400 if (b->len > INT_MAX) {
Victor Stinner6efa9652013-06-25 00:42:31 +02002401 PyErr_Format(PyExc_OverflowError,
2402 "string longer than %d bytes", INT_MAX);
2403 goto error;
2404 }
2405
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002406 if (sock != NULL) {
2407 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002408 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002409 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2410 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
2411 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002412
Victor Stinner14690702015-04-06 22:46:13 +02002413 timeout = GET_SOCKET_TIMEOUT(sock);
2414 has_timeout = (timeout > 0);
2415 if (has_timeout)
2416 deadline = _PyTime_GetMonotonicClock() + timeout;
2417
2418 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002419 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002420 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002421 "The write operation timed out");
2422 goto error;
2423 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
2424 PyErr_SetString(PySSLErrorObject,
2425 "Underlying socket has been closed.");
2426 goto error;
2427 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
2428 PyErr_SetString(PySSLErrorObject,
2429 "Underlying socket too large for select().");
2430 goto error;
2431 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002432
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002433 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002434 PySSL_BEGIN_ALLOW_THREADS
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002435 len = SSL_write(self->ssl, b->buf, (int)b->len);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002436 err = _PySSL_errno(len <= 0, self->ssl, len);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002437 PySSL_END_ALLOW_THREADS
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002438 self->err = err;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002439
2440 if (PyErr_CheckSignals())
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002441 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002442
Victor Stinner14690702015-04-06 22:46:13 +02002443 if (has_timeout)
2444 timeout = deadline - _PyTime_GetMonotonicClock();
2445
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002446 if (err.ssl == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +02002447 sockstate = PySSL_select(sock, 0, timeout);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002448 } else if (err.ssl == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +02002449 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002450 } else {
2451 sockstate = SOCKET_OPERATION_OK;
2452 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002453
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002454 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002455 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002456 "The write operation timed out");
2457 goto error;
2458 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
2459 PyErr_SetString(PySSLErrorObject,
2460 "Underlying socket has been closed.");
2461 goto error;
2462 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
2463 break;
2464 }
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002465 } while (err.ssl == SSL_ERROR_WANT_READ ||
2466 err.ssl == SSL_ERROR_WANT_WRITE);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002467
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002468 Py_XDECREF(sock);
Christian Heimesc7f70692019-05-31 11:44:05 +02002469 if (len <= 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002470 return PySSL_SetError(self, len, __FILE__, __LINE__);
Christian Heimesc7f70692019-05-31 11:44:05 +02002471 if (PySSL_ChainExceptions(self) < 0)
2472 return NULL;
2473 return PyLong_FromLong(len);
Antoine Pitrou7d7aede2009-11-25 18:55:32 +00002474error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002475 Py_XDECREF(sock);
Christian Heimesc7f70692019-05-31 11:44:05 +02002476 PySSL_ChainExceptions(self);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002477 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002478}
2479
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002480/*[clinic input]
2481_ssl._SSLSocket.pending
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002482
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002483Returns the number of already decrypted bytes available for read, pending on the connection.
2484[clinic start generated code]*/
2485
2486static PyObject *
2487_ssl__SSLSocket_pending_impl(PySSLSocket *self)
2488/*[clinic end generated code: output=983d9fecdc308a83 input=2b77487d6dfd597f]*/
Bill Janssen6e027db2007-11-15 22:23:56 +00002489{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002490 int count = 0;
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002491 _PySSLError err;
Bill Janssen6e027db2007-11-15 22:23:56 +00002492
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002493 PySSL_BEGIN_ALLOW_THREADS
2494 count = SSL_pending(self->ssl);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002495 err = _PySSL_errno(count < 0, self->ssl, count);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002496 PySSL_END_ALLOW_THREADS
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002497 self->err = err;
2498
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002499 if (count < 0)
2500 return PySSL_SetError(self, count, __FILE__, __LINE__);
2501 else
2502 return PyLong_FromLong(count);
Bill Janssen6e027db2007-11-15 22:23:56 +00002503}
2504
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002505/*[clinic input]
2506_ssl._SSLSocket.read
2507 size as len: int
2508 [
Larry Hastingsdbfdc382015-05-04 06:59:46 -07002509 buffer: Py_buffer(accept={rwbuffer})
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002510 ]
2511 /
Bill Janssen6e027db2007-11-15 22:23:56 +00002512
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002513Read up to size bytes from the SSL socket.
2514[clinic start generated code]*/
2515
2516static PyObject *
2517_ssl__SSLSocket_read_impl(PySSLSocket *self, int len, int group_right_1,
2518 Py_buffer *buffer)
Larry Hastingsdbfdc382015-05-04 06:59:46 -07002519/*[clinic end generated code: output=00097776cec2a0af input=ff157eb918d0905b]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002520{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002521 PyObject *dest = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002522 char *mem;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002523 int count;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002524 int sockstate;
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002525 _PySSLError err;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002526 int nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002527 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002528 _PyTime_t timeout, deadline = 0;
2529 int has_timeout;
Bill Janssen54cc54c2007-12-14 22:08:56 +00002530
Martin Panter5503d472016-03-27 05:35:19 +00002531 if (!group_right_1 && len < 0) {
2532 PyErr_SetString(PyExc_ValueError, "size should not be negative");
2533 return NULL;
2534 }
2535
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002536 if (sock != NULL) {
2537 if (((PyObject*)sock) == Py_None) {
2538 _setSSLError("Underlying socket connection gone",
2539 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2540 return NULL;
2541 }
2542 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002543 }
2544
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002545 if (!group_right_1) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002546 dest = PyBytes_FromStringAndSize(NULL, len);
2547 if (dest == NULL)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002548 goto error;
Martin Panterbed7f1a2016-07-11 00:17:13 +00002549 if (len == 0) {
2550 Py_XDECREF(sock);
2551 return dest;
2552 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002553 mem = PyBytes_AS_STRING(dest);
2554 }
2555 else {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002556 mem = buffer->buf;
2557 if (len <= 0 || len > buffer->len) {
2558 len = (int) buffer->len;
2559 if (buffer->len != len) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002560 PyErr_SetString(PyExc_OverflowError,
2561 "maximum length can't fit in a C 'int'");
2562 goto error;
2563 }
Martin Panterbed7f1a2016-07-11 00:17:13 +00002564 if (len == 0) {
2565 count = 0;
2566 goto done;
2567 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002568 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002569 }
2570
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002571 if (sock != NULL) {
2572 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002573 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002574 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2575 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
2576 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002577
Victor Stinner14690702015-04-06 22:46:13 +02002578 timeout = GET_SOCKET_TIMEOUT(sock);
2579 has_timeout = (timeout > 0);
2580 if (has_timeout)
2581 deadline = _PyTime_GetMonotonicClock() + timeout;
2582
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002583 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002584 PySSL_BEGIN_ALLOW_THREADS
2585 count = SSL_read(self->ssl, mem, len);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002586 err = _PySSL_errno(count <= 0, self->ssl, count);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002587 PySSL_END_ALLOW_THREADS
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002588 self->err = err;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002589
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002590 if (PyErr_CheckSignals())
2591 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002592
Victor Stinner14690702015-04-06 22:46:13 +02002593 if (has_timeout)
2594 timeout = deadline - _PyTime_GetMonotonicClock();
2595
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002596 if (err.ssl == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +02002597 sockstate = PySSL_select(sock, 0, timeout);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002598 } else if (err.ssl == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +02002599 sockstate = PySSL_select(sock, 1, timeout);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002600 } else if (err.ssl == SSL_ERROR_ZERO_RETURN &&
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002601 SSL_get_shutdown(self->ssl) == SSL_RECEIVED_SHUTDOWN)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002602 {
2603 count = 0;
2604 goto done;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002605 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002606 else
2607 sockstate = SOCKET_OPERATION_OK;
2608
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002609 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002610 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002611 "The read operation timed out");
2612 goto error;
2613 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
2614 break;
2615 }
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002616 } while (err.ssl == SSL_ERROR_WANT_READ ||
2617 err.ssl == SSL_ERROR_WANT_WRITE);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002618
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002619 if (count <= 0) {
2620 PySSL_SetError(self, count, __FILE__, __LINE__);
2621 goto error;
2622 }
Christian Heimesc7f70692019-05-31 11:44:05 +02002623 if (self->exc_type != NULL)
2624 goto error;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002625
2626done:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002627 Py_XDECREF(sock);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002628 if (!group_right_1) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002629 _PyBytes_Resize(&dest, count);
2630 return dest;
2631 }
2632 else {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002633 return PyLong_FromLong(count);
2634 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002635
2636error:
Christian Heimesc7f70692019-05-31 11:44:05 +02002637 PySSL_ChainExceptions(self);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002638 Py_XDECREF(sock);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002639 if (!group_right_1)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002640 Py_XDECREF(dest);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002641 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002642}
2643
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002644/*[clinic input]
2645_ssl._SSLSocket.shutdown
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002646
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002647Does the SSL shutdown handshake with the remote end.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002648[clinic start generated code]*/
2649
2650static PyObject *
2651_ssl__SSLSocket_shutdown_impl(PySSLSocket *self)
Christian Heimes141c5e82018-02-24 21:10:57 +01002652/*[clinic end generated code: output=ca1aa7ed9d25ca42 input=11d39e69b0a2bf4a]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00002653{
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002654 _PySSLError err;
2655 int sockstate, nonblocking, ret;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002656 int zeros = 0;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002657 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002658 _PyTime_t timeout, deadline = 0;
2659 int has_timeout;
Bill Janssen40a0f662008-08-12 16:56:25 +00002660
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002661 if (sock != NULL) {
2662 /* Guard against closed socket */
Victor Stinner524714e2016-07-22 17:43:59 +02002663 if ((((PyObject*)sock) == Py_None) || (sock->sock_fd == INVALID_SOCKET)) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002664 _setSSLError("Underlying socket connection gone",
2665 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2666 return NULL;
2667 }
2668 Py_INCREF(sock);
2669
2670 /* Just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002671 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002672 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2673 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002674 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002675
Victor Stinner14690702015-04-06 22:46:13 +02002676 timeout = GET_SOCKET_TIMEOUT(sock);
2677 has_timeout = (timeout > 0);
2678 if (has_timeout)
2679 deadline = _PyTime_GetMonotonicClock() + timeout;
2680
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002681 while (1) {
2682 PySSL_BEGIN_ALLOW_THREADS
2683 /* Disable read-ahead so that unwrap can work correctly.
2684 * Otherwise OpenSSL might read in too much data,
2685 * eating clear text data that happens to be
2686 * transmitted after the SSL shutdown.
Ezio Melotti85a86292013-08-17 16:57:41 +03002687 * Should be safe to call repeatedly every time this
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002688 * function is used and the shutdown_seen_zero != 0
2689 * condition is met.
2690 */
2691 if (self->shutdown_seen_zero)
2692 SSL_set_read_ahead(self->ssl, 0);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002693 ret = SSL_shutdown(self->ssl);
2694 err = _PySSL_errno(ret < 0, self->ssl, ret);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002695 PySSL_END_ALLOW_THREADS
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002696 self->err = err;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002697
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002698 /* If err == 1, a secure shutdown with SSL_shutdown() is complete */
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002699 if (ret > 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002700 break;
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002701 if (ret == 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002702 /* Don't loop endlessly; instead preserve legacy
2703 behaviour of trying SSL_shutdown() only twice.
2704 This looks necessary for OpenSSL < 0.9.8m */
2705 if (++zeros > 1)
2706 break;
2707 /* Shutdown was sent, now try receiving */
2708 self->shutdown_seen_zero = 1;
2709 continue;
Bill Janssen40a0f662008-08-12 16:56:25 +00002710 }
2711
Victor Stinner14690702015-04-06 22:46:13 +02002712 if (has_timeout)
2713 timeout = deadline - _PyTime_GetMonotonicClock();
2714
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002715 /* Possibly retry shutdown until timeout or failure */
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002716 if (err.ssl == SSL_ERROR_WANT_READ)
Victor Stinner14690702015-04-06 22:46:13 +02002717 sockstate = PySSL_select(sock, 0, timeout);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002718 else if (err.ssl == SSL_ERROR_WANT_WRITE)
Victor Stinner14690702015-04-06 22:46:13 +02002719 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002720 else
2721 break;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002722
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002723 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002724 if (err.ssl == SSL_ERROR_WANT_READ)
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002725 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002726 "The read operation timed out");
2727 else
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002728 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002729 "The write operation timed out");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002730 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002731 }
2732 else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
2733 PyErr_SetString(PySSLErrorObject,
2734 "Underlying socket too large for select().");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002735 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002736 }
2737 else if (sockstate != SOCKET_OPERATION_OK)
2738 /* Retain the SSL error code */
2739 break;
2740 }
Nathaniel J. Smithc0da5822018-09-21 21:44:12 -07002741 if (ret < 0) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002742 Py_XDECREF(sock);
Christian Heimesc7f70692019-05-31 11:44:05 +02002743 PySSL_SetError(self, ret, __FILE__, __LINE__);
2744 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002745 }
Christian Heimesc7f70692019-05-31 11:44:05 +02002746 if (self->exc_type != NULL)
2747 goto error;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002748 if (sock)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002749 /* It's already INCREF'ed */
2750 return (PyObject *) sock;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002751 else
2752 Py_RETURN_NONE;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002753
2754error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002755 Py_XDECREF(sock);
Christian Heimesc7f70692019-05-31 11:44:05 +02002756 PySSL_ChainExceptions(self);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002757 return NULL;
Bill Janssen40a0f662008-08-12 16:56:25 +00002758}
2759
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002760/*[clinic input]
Christian Heimes141c5e82018-02-24 21:10:57 +01002761_ssl._SSLSocket.get_channel_binding
2762 cb_type: str = "tls-unique"
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002763
Christian Heimes141c5e82018-02-24 21:10:57 +01002764Get channel binding data for current connection.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002765
Christian Heimes141c5e82018-02-24 21:10:57 +01002766Raise ValueError if the requested `cb_type` is not supported. Return bytes
2767of the data or None if the data is not available (e.g. before the handshake).
2768Only 'tls-unique' channel binding data from RFC 5929 is supported.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002769[clinic start generated code]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00002770
Antoine Pitroud6494802011-07-21 01:11:30 +02002771static PyObject *
Christian Heimes141c5e82018-02-24 21:10:57 +01002772_ssl__SSLSocket_get_channel_binding_impl(PySSLSocket *self,
2773 const char *cb_type)
2774/*[clinic end generated code: output=34bac9acb6a61d31 input=08b7e43b99c17d41]*/
Antoine Pitroud6494802011-07-21 01:11:30 +02002775{
Antoine Pitroud6494802011-07-21 01:11:30 +02002776 char buf[PySSL_CB_MAXLEN];
Victor Stinner9ee02032013-06-23 15:08:23 +02002777 size_t len;
Antoine Pitroud6494802011-07-21 01:11:30 +02002778
Christian Heimes141c5e82018-02-24 21:10:57 +01002779 if (strcmp(cb_type, "tls-unique") == 0) {
2780 if (SSL_session_reused(self->ssl) ^ !self->socket_type) {
2781 /* if session is resumed XOR we are the client */
2782 len = SSL_get_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2783 }
2784 else {
2785 /* if a new session XOR we are the server */
2786 len = SSL_get_peer_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2787 }
Antoine Pitroud6494802011-07-21 01:11:30 +02002788 }
2789 else {
Christian Heimes141c5e82018-02-24 21:10:57 +01002790 PyErr_Format(
2791 PyExc_ValueError,
2792 "'%s' channel binding type not implemented",
2793 cb_type
2794 );
2795 return NULL;
Antoine Pitroud6494802011-07-21 01:11:30 +02002796 }
2797
2798 /* It cannot be negative in current OpenSSL version as of July 2011 */
Antoine Pitroud6494802011-07-21 01:11:30 +02002799 if (len == 0)
2800 Py_RETURN_NONE;
2801
Christian Heimes141c5e82018-02-24 21:10:57 +01002802 return PyBytes_FromStringAndSize(buf, len);
Antoine Pitroud6494802011-07-21 01:11:30 +02002803}
2804
Christian Heimes9fb051f2018-09-23 08:32:31 +02002805/*[clinic input]
2806_ssl._SSLSocket.verify_client_post_handshake
2807
2808Initiate TLS 1.3 post-handshake authentication
2809[clinic start generated code]*/
2810
2811static PyObject *
2812_ssl__SSLSocket_verify_client_post_handshake_impl(PySSLSocket *self)
2813/*[clinic end generated code: output=532147f3b1341425 input=6bfa874810a3d889]*/
2814{
2815#ifdef TLS1_3_VERSION
2816 int err = SSL_verify_client_post_handshake(self->ssl);
2817 if (err == 0)
2818 return _setSSLError(NULL, 0, __FILE__, __LINE__);
2819 else
2820 Py_RETURN_NONE;
2821#else
2822 PyErr_SetString(PyExc_NotImplementedError,
2823 "Post-handshake auth is not supported by your "
2824 "OpenSSL version.");
2825 return NULL;
2826#endif
2827}
2828
Christian Heimes99a65702016-09-10 23:44:53 +02002829#ifdef OPENSSL_VERSION_1_1
2830
2831static SSL_SESSION*
2832_ssl_session_dup(SSL_SESSION *session) {
2833 SSL_SESSION *newsession = NULL;
2834 int slen;
2835 unsigned char *senc = NULL, *p;
2836 const unsigned char *const_p;
2837
2838 if (session == NULL) {
2839 PyErr_SetString(PyExc_ValueError, "Invalid session");
2840 goto error;
2841 }
2842
2843 /* get length */
2844 slen = i2d_SSL_SESSION(session, NULL);
2845 if (slen == 0 || slen > 0xFF00) {
2846 PyErr_SetString(PyExc_ValueError, "i2d() failed.");
2847 goto error;
2848 }
2849 if ((senc = PyMem_Malloc(slen)) == NULL) {
2850 PyErr_NoMemory();
2851 goto error;
2852 }
2853 p = senc;
2854 if (!i2d_SSL_SESSION(session, &p)) {
2855 PyErr_SetString(PyExc_ValueError, "i2d() failed.");
2856 goto error;
2857 }
2858 const_p = senc;
2859 newsession = d2i_SSL_SESSION(NULL, &const_p, slen);
2860 if (session == NULL) {
2861 goto error;
2862 }
2863 PyMem_Free(senc);
2864 return newsession;
2865 error:
2866 if (senc != NULL) {
2867 PyMem_Free(senc);
2868 }
2869 return NULL;
2870}
2871#endif
2872
2873static PyObject *
2874PySSL_get_session(PySSLSocket *self, void *closure) {
2875 /* get_session can return sessions from a server-side connection,
2876 * it does not check for handshake done or client socket. */
2877 PySSLSession *pysess;
2878 SSL_SESSION *session;
2879
2880#ifdef OPENSSL_VERSION_1_1
2881 /* duplicate session as workaround for session bug in OpenSSL 1.1.0,
2882 * https://github.com/openssl/openssl/issues/1550 */
2883 session = SSL_get0_session(self->ssl); /* borrowed reference */
2884 if (session == NULL) {
2885 Py_RETURN_NONE;
2886 }
2887 if ((session = _ssl_session_dup(session)) == NULL) {
2888 return NULL;
2889 }
2890#else
2891 session = SSL_get1_session(self->ssl);
2892 if (session == NULL) {
2893 Py_RETURN_NONE;
2894 }
2895#endif
Christian Heimesa5d07652016-09-24 10:48:05 +02002896 pysess = PyObject_GC_New(PySSLSession, &PySSLSession_Type);
Christian Heimes99a65702016-09-10 23:44:53 +02002897 if (pysess == NULL) {
2898 SSL_SESSION_free(session);
2899 return NULL;
2900 }
2901
2902 assert(self->ctx);
2903 pysess->ctx = self->ctx;
2904 Py_INCREF(pysess->ctx);
2905 pysess->session = session;
Christian Heimesa5d07652016-09-24 10:48:05 +02002906 PyObject_GC_Track(pysess);
Christian Heimes99a65702016-09-10 23:44:53 +02002907 return (PyObject *)pysess;
2908}
2909
2910static int PySSL_set_session(PySSLSocket *self, PyObject *value,
2911 void *closure)
2912 {
2913 PySSLSession *pysess;
2914#ifdef OPENSSL_VERSION_1_1
2915 SSL_SESSION *session;
2916#endif
2917 int result;
2918
2919 if (!PySSLSession_Check(value)) {
Ned Deily4531ec72018-06-11 20:26:28 -04002920 PyErr_SetString(PyExc_TypeError, "Value is not a SSLSession.");
Christian Heimes99a65702016-09-10 23:44:53 +02002921 return -1;
2922 }
2923 pysess = (PySSLSession *)value;
2924
2925 if (self->ctx->ctx != pysess->ctx->ctx) {
2926 PyErr_SetString(PyExc_ValueError,
2927 "Session refers to a different SSLContext.");
2928 return -1;
2929 }
2930 if (self->socket_type != PY_SSL_CLIENT) {
2931 PyErr_SetString(PyExc_ValueError,
2932 "Cannot set session for server-side SSLSocket.");
2933 return -1;
2934 }
Christian Heimes66dc33b2017-05-23 16:02:02 -07002935 if (SSL_is_init_finished(self->ssl)) {
Christian Heimes99a65702016-09-10 23:44:53 +02002936 PyErr_SetString(PyExc_ValueError,
2937 "Cannot set session after handshake.");
2938 return -1;
2939 }
2940#ifdef OPENSSL_VERSION_1_1
2941 /* duplicate session */
2942 if ((session = _ssl_session_dup(pysess->session)) == NULL) {
2943 return -1;
2944 }
2945 result = SSL_set_session(self->ssl, session);
2946 /* free duplicate, SSL_set_session() bumps ref count */
2947 SSL_SESSION_free(session);
2948#else
2949 result = SSL_set_session(self->ssl, pysess->session);
2950#endif
2951 if (result == 0) {
2952 _setSSLError(NULL, 0, __FILE__, __LINE__);
2953 return -1;
2954 }
2955 return 0;
2956}
2957
2958PyDoc_STRVAR(PySSL_set_session_doc,
2959"_setter_session(session)\n\
2960\
2961Get / set SSLSession.");
2962
2963static PyObject *
2964PySSL_get_session_reused(PySSLSocket *self, void *closure) {
2965 if (SSL_session_reused(self->ssl)) {
2966 Py_RETURN_TRUE;
2967 } else {
2968 Py_RETURN_FALSE;
2969 }
2970}
2971
2972PyDoc_STRVAR(PySSL_get_session_reused_doc,
2973"Was the client session reused during handshake?");
2974
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002975static PyGetSetDef ssl_getsetlist[] = {
2976 {"context", (getter) PySSL_get_context,
2977 (setter) PySSL_set_context, PySSL_set_context_doc},
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002978 {"server_side", (getter) PySSL_get_server_side, NULL,
2979 PySSL_get_server_side_doc},
2980 {"server_hostname", (getter) PySSL_get_server_hostname, NULL,
2981 PySSL_get_server_hostname_doc},
2982 {"owner", (getter) PySSL_get_owner, (setter) PySSL_set_owner,
2983 PySSL_get_owner_doc},
Christian Heimes99a65702016-09-10 23:44:53 +02002984 {"session", (getter) PySSL_get_session,
2985 (setter) PySSL_set_session, PySSL_set_session_doc},
2986 {"session_reused", (getter) PySSL_get_session_reused, NULL,
2987 PySSL_get_session_reused_doc},
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002988 {NULL}, /* sentinel */
2989};
2990
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002991static PyMethodDef PySSLMethods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002992 _SSL__SSLSOCKET_DO_HANDSHAKE_METHODDEF
2993 _SSL__SSLSOCKET_WRITE_METHODDEF
2994 _SSL__SSLSOCKET_READ_METHODDEF
2995 _SSL__SSLSOCKET_PENDING_METHODDEF
Christian Heimes141c5e82018-02-24 21:10:57 +01002996 _SSL__SSLSOCKET_GETPEERCERT_METHODDEF
2997 _SSL__SSLSOCKET_GET_CHANNEL_BINDING_METHODDEF
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002998 _SSL__SSLSOCKET_CIPHER_METHODDEF
2999 _SSL__SSLSOCKET_SHARED_CIPHERS_METHODDEF
3000 _SSL__SSLSOCKET_VERSION_METHODDEF
3001 _SSL__SSLSOCKET_SELECTED_NPN_PROTOCOL_METHODDEF
3002 _SSL__SSLSOCKET_SELECTED_ALPN_PROTOCOL_METHODDEF
3003 _SSL__SSLSOCKET_COMPRESSION_METHODDEF
3004 _SSL__SSLSOCKET_SHUTDOWN_METHODDEF
Christian Heimes9fb051f2018-09-23 08:32:31 +02003005 _SSL__SSLSOCKET_VERIFY_CLIENT_POST_HANDSHAKE_METHODDEF
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003006 {NULL, NULL}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003007};
3008
Antoine Pitrou152efa22010-05-16 18:19:27 +00003009static PyTypeObject PySSLSocket_Type = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003010 PyVarObject_HEAD_INIT(NULL, 0)
Antoine Pitrou152efa22010-05-16 18:19:27 +00003011 "_ssl._SSLSocket", /*tp_name*/
3012 sizeof(PySSLSocket), /*tp_basicsize*/
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003013 0, /*tp_itemsize*/
3014 /* methods */
3015 (destructor)PySSL_dealloc, /*tp_dealloc*/
Jeroen Demeyer530f5062019-05-31 04:13:39 +02003016 0, /*tp_vectorcall_offset*/
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003017 0, /*tp_getattr*/
3018 0, /*tp_setattr*/
Jeroen Demeyer530f5062019-05-31 04:13:39 +02003019 0, /*tp_as_async*/
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003020 0, /*tp_repr*/
3021 0, /*tp_as_number*/
3022 0, /*tp_as_sequence*/
3023 0, /*tp_as_mapping*/
3024 0, /*tp_hash*/
3025 0, /*tp_call*/
3026 0, /*tp_str*/
3027 0, /*tp_getattro*/
3028 0, /*tp_setattro*/
3029 0, /*tp_as_buffer*/
3030 Py_TPFLAGS_DEFAULT, /*tp_flags*/
3031 0, /*tp_doc*/
Christian Heimesc7f70692019-05-31 11:44:05 +02003032 (traverseproc) PySSL_traverse, /*tp_traverse*/
3033 (inquiry) PySSL_clear, /*tp_clear*/
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003034 0, /*tp_richcompare*/
3035 0, /*tp_weaklistoffset*/
3036 0, /*tp_iter*/
3037 0, /*tp_iternext*/
3038 PySSLMethods, /*tp_methods*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003039 0, /*tp_members*/
3040 ssl_getsetlist, /*tp_getset*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003041};
3042
Antoine Pitrou152efa22010-05-16 18:19:27 +00003043
3044/*
3045 * _SSLContext objects
3046 */
3047
Christian Heimes5fe668c2016-09-12 00:01:11 +02003048static int
Christian Heimes9fb051f2018-09-23 08:32:31 +02003049_set_verify_mode(PySSLContext *self, enum py_ssl_cert_requirements n)
Christian Heimes5fe668c2016-09-12 00:01:11 +02003050{
3051 int mode;
3052 int (*verify_cb)(int, X509_STORE_CTX *) = NULL;
3053
3054 switch(n) {
3055 case PY_SSL_CERT_NONE:
3056 mode = SSL_VERIFY_NONE;
3057 break;
3058 case PY_SSL_CERT_OPTIONAL:
3059 mode = SSL_VERIFY_PEER;
3060 break;
3061 case PY_SSL_CERT_REQUIRED:
3062 mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
3063 break;
3064 default:
3065 PyErr_SetString(PyExc_ValueError,
3066 "invalid value for verify_mode");
3067 return -1;
3068 }
Christian Heimesf0f59302019-07-01 08:29:17 +02003069
3070 /* bpo-37428: newPySSLSocket() sets SSL_VERIFY_POST_HANDSHAKE flag for
3071 * server sockets and SSL_set_post_handshake_auth() for client. */
3072
Christian Heimes5fe668c2016-09-12 00:01:11 +02003073 /* keep current verify cb */
Christian Heimes9fb051f2018-09-23 08:32:31 +02003074 verify_cb = SSL_CTX_get_verify_callback(self->ctx);
3075 SSL_CTX_set_verify(self->ctx, mode, verify_cb);
Christian Heimes5fe668c2016-09-12 00:01:11 +02003076 return 0;
3077}
3078
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003079/*[clinic input]
3080@classmethod
3081_ssl._SSLContext.__new__
3082 protocol as proto_version: int
3083 /
3084[clinic start generated code]*/
3085
Antoine Pitrou152efa22010-05-16 18:19:27 +00003086static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003087_ssl__SSLContext_impl(PyTypeObject *type, int proto_version)
3088/*[clinic end generated code: output=2cf0d7a0741b6bd1 input=8d58a805b95fc534]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003089{
Antoine Pitrou152efa22010-05-16 18:19:27 +00003090 PySSLContext *self;
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01003091 long options;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003092 SSL_CTX *ctx = NULL;
Christian Heimes61d478c2018-01-27 15:51:38 +01003093 X509_VERIFY_PARAM *params;
Christian Heimes358cfd42016-09-10 22:43:48 +02003094 int result;
Berker Peksagdfcb0412016-04-14 16:48:48 +03003095#if defined(SSL_MODE_RELEASE_BUFFERS)
Benjamin Peterson3b1a8b32016-01-07 21:37:37 -08003096 unsigned long libver;
Berker Peksagdfcb0412016-04-14 16:48:48 +03003097#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00003098
Antoine Pitrou152efa22010-05-16 18:19:27 +00003099 PySSL_BEGIN_ALLOW_THREADS
Christian Heimes6e8cda92020-05-16 03:33:05 +02003100 switch(proto_version) {
3101#if defined(SSL3_VERSION) && !defined(OPENSSL_NO_SSL3)
3102 case PY_SSL_VERSION_SSL3:
Antoine Pitrou152efa22010-05-16 18:19:27 +00003103 ctx = SSL_CTX_new(SSLv3_method());
Christian Heimes6e8cda92020-05-16 03:33:05 +02003104 break;
Benjamin Petersone32467c2014-12-05 21:59:35 -05003105#endif
Christian Heimesa871f692020-06-01 08:58:14 +02003106#if (defined(TLS1_VERSION) && \
3107 !defined(OPENSSL_NO_TLS1) && \
3108 !defined(OPENSSL_NO_TLS1_METHOD))
Christian Heimes6e8cda92020-05-16 03:33:05 +02003109 case PY_SSL_VERSION_TLS1:
3110 ctx = SSL_CTX_new(TLSv1_method());
3111 break;
Victor Stinner3de49192011-05-09 00:42:58 +02003112#endif
Christian Heimesa871f692020-06-01 08:58:14 +02003113#if (defined(TLS1_1_VERSION) && \
3114 !defined(OPENSSL_NO_TLS1_1) && \
3115 !defined(OPENSSL_NO_TLS1_1_METHOD))
Christian Heimes6e8cda92020-05-16 03:33:05 +02003116 case PY_SSL_VERSION_TLS1_1:
3117 ctx = SSL_CTX_new(TLSv1_1_method());
3118 break;
3119#endif
Christian Heimesa871f692020-06-01 08:58:14 +02003120#if (defined(TLS1_2_VERSION) && \
3121 !defined(OPENSSL_NO_TLS1_2) && \
3122 !defined(OPENSSL_NO_TLS1_2_METHOD))
Christian Heimes6e8cda92020-05-16 03:33:05 +02003123 case PY_SSL_VERSION_TLS1_2:
3124 ctx = SSL_CTX_new(TLSv1_2_method());
3125 break;
3126#endif
3127 case PY_SSL_VERSION_TLS:
3128 /* SSLv23 */
Christian Heimes598894f2016-09-05 23:19:05 +02003129 ctx = SSL_CTX_new(TLS_method());
Christian Heimes6e8cda92020-05-16 03:33:05 +02003130 break;
3131 case PY_SSL_VERSION_TLS_CLIENT:
Christian Heimes5fe668c2016-09-12 00:01:11 +02003132 ctx = SSL_CTX_new(TLS_client_method());
Christian Heimes6e8cda92020-05-16 03:33:05 +02003133 break;
3134 case PY_SSL_VERSION_TLS_SERVER:
Christian Heimes5fe668c2016-09-12 00:01:11 +02003135 ctx = SSL_CTX_new(TLS_server_method());
Christian Heimes6e8cda92020-05-16 03:33:05 +02003136 break;
3137 default:
Antoine Pitrou152efa22010-05-16 18:19:27 +00003138 proto_version = -1;
Christian Heimes6e8cda92020-05-16 03:33:05 +02003139 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003140 PySSL_END_ALLOW_THREADS
3141
3142 if (proto_version == -1) {
3143 PyErr_SetString(PyExc_ValueError,
Christian Heimes6e8cda92020-05-16 03:33:05 +02003144 "invalid or unsupported protocol version");
Antoine Pitrou152efa22010-05-16 18:19:27 +00003145 return NULL;
3146 }
3147 if (ctx == NULL) {
Christian Heimes17c9ac92017-09-07 14:14:00 -07003148 _setSSLError(NULL, 0, __FILE__, __LINE__);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003149 return NULL;
3150 }
3151
3152 assert(type != NULL && type->tp_alloc != NULL);
3153 self = (PySSLContext *) type->tp_alloc(type, 0);
3154 if (self == NULL) {
3155 SSL_CTX_free(ctx);
3156 return NULL;
3157 }
3158 self->ctx = ctx;
Christian Heimes61d478c2018-01-27 15:51:38 +01003159 self->hostflags = X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS;
Christian Heimes11a14932018-02-24 02:35:08 +01003160 self->protocol = proto_version;
Christian Heimesc7f70692019-05-31 11:44:05 +02003161 self->msg_cb = NULL;
3162#ifdef HAVE_OPENSSL_KEYLOG
3163 self->keylog_filename = NULL;
3164 self->keylog_bio = NULL;
3165#endif
Christian Heimes29eab552018-02-25 12:31:33 +01003166#if HAVE_NPN
Christian Heimes5cb31c92012-09-20 12:42:54 +02003167 self->npn_protocols = NULL;
3168#endif
Christian Heimes29eab552018-02-25 12:31:33 +01003169#if HAVE_ALPN
Benjamin Petersoncca27322015-01-23 16:35:37 -05003170 self->alpn_protocols = NULL;
3171#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003172#ifndef OPENSSL_NO_TLSEXT
Christian Heimes11a14932018-02-24 02:35:08 +01003173 self->set_sni_cb = NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003174#endif
Christian Heimes1aa9a752013-12-02 02:41:19 +01003175 /* Don't check host name by default */
Christian Heimes5fe668c2016-09-12 00:01:11 +02003176 if (proto_version == PY_SSL_VERSION_TLS_CLIENT) {
3177 self->check_hostname = 1;
Christian Heimes9fb051f2018-09-23 08:32:31 +02003178 if (_set_verify_mode(self, PY_SSL_CERT_REQUIRED) == -1) {
Christian Heimes5fe668c2016-09-12 00:01:11 +02003179 Py_DECREF(self);
3180 return NULL;
3181 }
3182 } else {
3183 self->check_hostname = 0;
Christian Heimes9fb051f2018-09-23 08:32:31 +02003184 if (_set_verify_mode(self, PY_SSL_CERT_NONE) == -1) {
Christian Heimes5fe668c2016-09-12 00:01:11 +02003185 Py_DECREF(self);
3186 return NULL;
3187 }
3188 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003189 /* Defaults */
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01003190 options = SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
3191 if (proto_version != PY_SSL_VERSION_SSL2)
3192 options |= SSL_OP_NO_SSLv2;
Benjamin Petersona9dcdab2015-11-11 22:38:41 -08003193 if (proto_version != PY_SSL_VERSION_SSL3)
3194 options |= SSL_OP_NO_SSLv3;
Christian Heimes358cfd42016-09-10 22:43:48 +02003195 /* Minimal security flags for server and client side context.
3196 * Client sockets ignore server-side parameters. */
3197#ifdef SSL_OP_NO_COMPRESSION
3198 options |= SSL_OP_NO_COMPRESSION;
3199#endif
3200#ifdef SSL_OP_CIPHER_SERVER_PREFERENCE
3201 options |= SSL_OP_CIPHER_SERVER_PREFERENCE;
3202#endif
3203#ifdef SSL_OP_SINGLE_DH_USE
3204 options |= SSL_OP_SINGLE_DH_USE;
3205#endif
3206#ifdef SSL_OP_SINGLE_ECDH_USE
3207 options |= SSL_OP_SINGLE_ECDH_USE;
3208#endif
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01003209 SSL_CTX_set_options(self->ctx, options);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003210
Semen Zhydenko1295e112017-10-15 21:28:31 +02003211 /* A bare minimum cipher list without completely broken cipher suites.
Christian Heimes358cfd42016-09-10 22:43:48 +02003212 * It's far from perfect but gives users a better head start. */
3213 if (proto_version != PY_SSL_VERSION_SSL2) {
Christian Heimes892d66e2018-01-29 14:10:18 +01003214#if PY_SSL_DEFAULT_CIPHERS == 2
3215 /* stick to OpenSSL's default settings */
3216 result = 1;
3217#else
3218 result = SSL_CTX_set_cipher_list(ctx, PY_SSL_DEFAULT_CIPHER_STRING);
3219#endif
Christian Heimes358cfd42016-09-10 22:43:48 +02003220 } else {
3221 /* SSLv2 needs MD5 */
3222 result = SSL_CTX_set_cipher_list(ctx, "HIGH:!aNULL:!eNULL");
3223 }
3224 if (result == 0) {
3225 Py_DECREF(self);
3226 ERR_clear_error();
3227 PyErr_SetString(PySSLErrorObject,
3228 "No cipher can be selected.");
3229 return NULL;
3230 }
3231
Benjamin Peterson3b1a8b32016-01-07 21:37:37 -08003232#if defined(SSL_MODE_RELEASE_BUFFERS)
3233 /* Set SSL_MODE_RELEASE_BUFFERS. This potentially greatly reduces memory
3234 usage for no cost at all. However, don't do this for OpenSSL versions
3235 between 1.0.1 and 1.0.1h or 1.0.0 and 1.0.0m, which are affected by CVE
3236 2014-0198. I can't find exactly which beta fixed this CVE, so be
3237 conservative and assume it wasn't fixed until release. We do this check
3238 at runtime to avoid problems from the dynamic linker.
3239 See #25672 for more on this. */
Christian Heimesa871f692020-06-01 08:58:14 +02003240 libver = OpenSSL_version_num();
Benjamin Peterson3b1a8b32016-01-07 21:37:37 -08003241 if (!(libver >= 0x10001000UL && libver < 0x1000108fUL) &&
3242 !(libver >= 0x10000000UL && libver < 0x100000dfUL)) {
3243 SSL_CTX_set_mode(self->ctx, SSL_MODE_RELEASE_BUFFERS);
3244 }
3245#endif
3246
3247
Donald Stufft8ae264c2017-03-02 11:45:29 -05003248#if !defined(OPENSSL_NO_ECDH) && !defined(OPENSSL_VERSION_1_1)
Antoine Pitrou0bebbc32014-03-22 18:13:50 +01003249 /* Allow automatic ECDH curve selection (on OpenSSL 1.0.2+), or use
3250 prime256v1 by default. This is Apache mod_ssl's initialization
Christian Heimes598894f2016-09-05 23:19:05 +02003251 policy, so we should be safe. OpenSSL 1.1 has it enabled by default.
3252 */
Donald Stufft8ae264c2017-03-02 11:45:29 -05003253#if defined(SSL_CTX_set_ecdh_auto)
Antoine Pitrou0bebbc32014-03-22 18:13:50 +01003254 SSL_CTX_set_ecdh_auto(self->ctx, 1);
3255#else
3256 {
3257 EC_KEY *key = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
3258 SSL_CTX_set_tmp_ecdh(self->ctx, key);
3259 EC_KEY_free(key);
3260 }
3261#endif
3262#endif
3263
Antoine Pitroufc113ee2010-10-13 12:46:13 +00003264#define SID_CTX "Python"
3265 SSL_CTX_set_session_id_context(self->ctx, (const unsigned char *) SID_CTX,
3266 sizeof(SID_CTX));
3267#undef SID_CTX
3268
Christian Heimes61d478c2018-01-27 15:51:38 +01003269 params = SSL_CTX_get0_param(self->ctx);
Benjamin Petersonfdb19712015-03-04 22:11:12 -05003270#ifdef X509_V_FLAG_TRUSTED_FIRST
Christian Heimes61d478c2018-01-27 15:51:38 +01003271 /* Improve trust chain building when cross-signed intermediate
3272 certificates are present. See https://bugs.python.org/issue23476. */
3273 X509_VERIFY_PARAM_set_flags(params, X509_V_FLAG_TRUSTED_FIRST);
Benjamin Petersonfdb19712015-03-04 22:11:12 -05003274#endif
Christian Heimes61d478c2018-01-27 15:51:38 +01003275 X509_VERIFY_PARAM_set_hostflags(params, self->hostflags);
Benjamin Petersonfdb19712015-03-04 22:11:12 -05003276
Christian Heimes9fb051f2018-09-23 08:32:31 +02003277#ifdef TLS1_3_VERSION
3278 self->post_handshake_auth = 0;
3279 SSL_CTX_set_post_handshake_auth(self->ctx, self->post_handshake_auth);
3280#endif
3281
Antoine Pitrou152efa22010-05-16 18:19:27 +00003282 return (PyObject *)self;
3283}
3284
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003285static int
3286context_traverse(PySSLContext *self, visitproc visit, void *arg)
3287{
3288#ifndef OPENSSL_NO_TLSEXT
Christian Heimes11a14932018-02-24 02:35:08 +01003289 Py_VISIT(self->set_sni_cb);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003290#endif
Christian Heimesc7f70692019-05-31 11:44:05 +02003291 Py_VISIT(self->msg_cb);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003292 return 0;
3293}
3294
3295static int
3296context_clear(PySSLContext *self)
3297{
3298#ifndef OPENSSL_NO_TLSEXT
Christian Heimes11a14932018-02-24 02:35:08 +01003299 Py_CLEAR(self->set_sni_cb);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003300#endif
Christian Heimesc7f70692019-05-31 11:44:05 +02003301 Py_CLEAR(self->msg_cb);
3302#ifdef HAVE_OPENSSL_KEYLOG
3303 Py_CLEAR(self->keylog_filename);
3304 if (self->keylog_bio != NULL) {
3305 PySSL_BEGIN_ALLOW_THREADS
3306 BIO_free_all(self->keylog_bio);
3307 PySSL_END_ALLOW_THREADS
3308 self->keylog_bio = NULL;
3309 }
3310#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003311 return 0;
3312}
3313
Antoine Pitrou152efa22010-05-16 18:19:27 +00003314static void
3315context_dealloc(PySSLContext *self)
3316{
INADA Naokia6296d32017-08-24 14:55:17 +09003317 /* bpo-31095: UnTrack is needed before calling any callbacks */
3318 PyObject_GC_UnTrack(self);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003319 context_clear(self);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003320 SSL_CTX_free(self->ctx);
Christian Heimes29eab552018-02-25 12:31:33 +01003321#if HAVE_NPN
Benjamin Petersoncca27322015-01-23 16:35:37 -05003322 PyMem_FREE(self->npn_protocols);
3323#endif
Christian Heimes29eab552018-02-25 12:31:33 +01003324#if HAVE_ALPN
Benjamin Petersoncca27322015-01-23 16:35:37 -05003325 PyMem_FREE(self->alpn_protocols);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003326#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00003327 Py_TYPE(self)->tp_free(self);
3328}
3329
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003330/*[clinic input]
3331_ssl._SSLContext.set_ciphers
3332 cipherlist: str
3333 /
3334[clinic start generated code]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003335
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003336static PyObject *
3337_ssl__SSLContext_set_ciphers_impl(PySSLContext *self, const char *cipherlist)
3338/*[clinic end generated code: output=3a3162f3557c0f3f input=a7ac931b9f3ca7fc]*/
3339{
3340 int ret = SSL_CTX_set_cipher_list(self->ctx, cipherlist);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003341 if (ret == 0) {
Antoine Pitrou65ec8ae2010-05-16 19:56:32 +00003342 /* Clearing the error queue is necessary on some OpenSSL versions,
3343 otherwise the error will be reported again when another SSL call
3344 is done. */
3345 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00003346 PyErr_SetString(PySSLErrorObject,
3347 "No cipher can be selected.");
3348 return NULL;
3349 }
3350 Py_RETURN_NONE;
3351}
3352
Christian Heimes25bfcd52016-09-06 00:04:45 +02003353#if OPENSSL_VERSION_NUMBER >= 0x10002000UL
3354/*[clinic input]
3355_ssl._SSLContext.get_ciphers
3356[clinic start generated code]*/
3357
3358static PyObject *
3359_ssl__SSLContext_get_ciphers_impl(PySSLContext *self)
3360/*[clinic end generated code: output=a56e4d68a406dfc4 input=a2aadc9af89b79c5]*/
3361{
3362 SSL *ssl = NULL;
3363 STACK_OF(SSL_CIPHER) *sk = NULL;
Christian Heimes99a65702016-09-10 23:44:53 +02003364 const SSL_CIPHER *cipher;
Christian Heimes25bfcd52016-09-06 00:04:45 +02003365 int i=0;
3366 PyObject *result = NULL, *dct;
3367
3368 ssl = SSL_new(self->ctx);
3369 if (ssl == NULL) {
3370 _setSSLError(NULL, 0, __FILE__, __LINE__);
3371 goto exit;
3372 }
3373 sk = SSL_get_ciphers(ssl);
3374
3375 result = PyList_New(sk_SSL_CIPHER_num(sk));
3376 if (result == NULL) {
3377 goto exit;
3378 }
3379
3380 for (i = 0; i < sk_SSL_CIPHER_num(sk); i++) {
3381 cipher = sk_SSL_CIPHER_value(sk, i);
3382 dct = cipher_to_dict(cipher);
3383 if (dct == NULL) {
3384 Py_CLEAR(result);
3385 goto exit;
3386 }
3387 PyList_SET_ITEM(result, i, dct);
3388 }
3389
3390 exit:
3391 if (ssl != NULL)
3392 SSL_free(ssl);
3393 return result;
3394
3395}
3396#endif
3397
3398
Christian Heimes29eab552018-02-25 12:31:33 +01003399#if HAVE_NPN || HAVE_ALPN
Benjamin Petersoncca27322015-01-23 16:35:37 -05003400static int
Benjamin Peterson88615022015-01-23 17:30:26 -05003401do_protocol_selection(int alpn, unsigned char **out, unsigned char *outlen,
3402 const unsigned char *server_protocols, unsigned int server_protocols_len,
3403 const unsigned char *client_protocols, unsigned int client_protocols_len)
Benjamin Petersoncca27322015-01-23 16:35:37 -05003404{
Benjamin Peterson88615022015-01-23 17:30:26 -05003405 int ret;
3406 if (client_protocols == NULL) {
3407 client_protocols = (unsigned char *)"";
3408 client_protocols_len = 0;
3409 }
3410 if (server_protocols == NULL) {
3411 server_protocols = (unsigned char *)"";
3412 server_protocols_len = 0;
Benjamin Petersoncca27322015-01-23 16:35:37 -05003413 }
3414
Benjamin Peterson88615022015-01-23 17:30:26 -05003415 ret = SSL_select_next_proto(out, outlen,
3416 server_protocols, server_protocols_len,
3417 client_protocols, client_protocols_len);
3418 if (alpn && ret != OPENSSL_NPN_NEGOTIATED)
3419 return SSL_TLSEXT_ERR_NOACK;
Benjamin Petersoncca27322015-01-23 16:35:37 -05003420
3421 return SSL_TLSEXT_ERR_OK;
3422}
Melvyn Sopacuab2d096b2017-09-04 23:35:15 +02003423#endif
Benjamin Petersoncca27322015-01-23 16:35:37 -05003424
Christian Heimes29eab552018-02-25 12:31:33 +01003425#if HAVE_NPN
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003426/* this callback gets passed to SSL_CTX_set_next_protos_advertise_cb */
3427static int
Victor Stinner4569cd52013-06-23 14:58:43 +02003428_advertiseNPN_cb(SSL *s,
3429 const unsigned char **data, unsigned int *len,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003430 void *args)
3431{
3432 PySSLContext *ssl_ctx = (PySSLContext *) args;
3433
3434 if (ssl_ctx->npn_protocols == NULL) {
Benjamin Petersoncca27322015-01-23 16:35:37 -05003435 *data = (unsigned char *)"";
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003436 *len = 0;
3437 } else {
Benjamin Petersoncca27322015-01-23 16:35:37 -05003438 *data = ssl_ctx->npn_protocols;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003439 *len = ssl_ctx->npn_protocols_len;
3440 }
3441
3442 return SSL_TLSEXT_ERR_OK;
3443}
3444/* this callback gets passed to SSL_CTX_set_next_proto_select_cb */
3445static int
Victor Stinner4569cd52013-06-23 14:58:43 +02003446_selectNPN_cb(SSL *s,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003447 unsigned char **out, unsigned char *outlen,
3448 const unsigned char *server, unsigned int server_len,
3449 void *args)
3450{
Benjamin Petersoncca27322015-01-23 16:35:37 -05003451 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Peterson88615022015-01-23 17:30:26 -05003452 return do_protocol_selection(0, out, outlen, server, server_len,
Benjamin Petersoncca27322015-01-23 16:35:37 -05003453 ctx->npn_protocols, ctx->npn_protocols_len);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003454}
3455#endif
3456
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003457/*[clinic input]
3458_ssl._SSLContext._set_npn_protocols
3459 protos: Py_buffer
3460 /
3461[clinic start generated code]*/
3462
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003463static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003464_ssl__SSLContext__set_npn_protocols_impl(PySSLContext *self,
3465 Py_buffer *protos)
3466/*[clinic end generated code: output=72b002c3324390c6 input=319fcb66abf95bd7]*/
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003467{
Christian Heimes29eab552018-02-25 12:31:33 +01003468#if HAVE_NPN
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003469 PyMem_Free(self->npn_protocols);
3470 self->npn_protocols = PyMem_Malloc(protos->len);
3471 if (self->npn_protocols == NULL)
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003472 return PyErr_NoMemory();
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003473 memcpy(self->npn_protocols, protos->buf, protos->len);
3474 self->npn_protocols_len = (int) protos->len;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003475
3476 /* set both server and client callbacks, because the context can
3477 * be used to create both types of sockets */
3478 SSL_CTX_set_next_protos_advertised_cb(self->ctx,
3479 _advertiseNPN_cb,
3480 self);
3481 SSL_CTX_set_next_proto_select_cb(self->ctx,
3482 _selectNPN_cb,
3483 self);
3484
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003485 Py_RETURN_NONE;
3486#else
3487 PyErr_SetString(PyExc_NotImplementedError,
3488 "The NPN extension requires OpenSSL 1.0.1 or later.");
3489 return NULL;
3490#endif
3491}
3492
Christian Heimes29eab552018-02-25 12:31:33 +01003493#if HAVE_ALPN
Benjamin Petersoncca27322015-01-23 16:35:37 -05003494static int
3495_selectALPN_cb(SSL *s,
3496 const unsigned char **out, unsigned char *outlen,
3497 const unsigned char *client_protocols, unsigned int client_protocols_len,
3498 void *args)
3499{
3500 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Peterson88615022015-01-23 17:30:26 -05003501 return do_protocol_selection(1, (unsigned char **)out, outlen,
3502 ctx->alpn_protocols, ctx->alpn_protocols_len,
3503 client_protocols, client_protocols_len);
Benjamin Petersoncca27322015-01-23 16:35:37 -05003504}
3505#endif
3506
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003507/*[clinic input]
3508_ssl._SSLContext._set_alpn_protocols
3509 protos: Py_buffer
3510 /
3511[clinic start generated code]*/
3512
Benjamin Petersoncca27322015-01-23 16:35:37 -05003513static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003514_ssl__SSLContext__set_alpn_protocols_impl(PySSLContext *self,
3515 Py_buffer *protos)
3516/*[clinic end generated code: output=87599a7f76651a9b input=9bba964595d519be]*/
Benjamin Petersoncca27322015-01-23 16:35:37 -05003517{
Christian Heimes29eab552018-02-25 12:31:33 +01003518#if HAVE_ALPN
Victor Stinner5a615592017-09-14 01:10:30 -07003519 if ((size_t)protos->len > UINT_MAX) {
Segev Finer5cff6372017-07-27 01:19:17 +03003520 PyErr_Format(PyExc_OverflowError,
Serhiy Storchakad53fe5f2019-03-13 22:59:55 +02003521 "protocols longer than %u bytes", UINT_MAX);
Segev Finer5cff6372017-07-27 01:19:17 +03003522 return NULL;
3523 }
3524
Benjamin Petersoncca27322015-01-23 16:35:37 -05003525 PyMem_FREE(self->alpn_protocols);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003526 self->alpn_protocols = PyMem_Malloc(protos->len);
Benjamin Petersoncca27322015-01-23 16:35:37 -05003527 if (!self->alpn_protocols)
3528 return PyErr_NoMemory();
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003529 memcpy(self->alpn_protocols, protos->buf, protos->len);
Segev Finer5cff6372017-07-27 01:19:17 +03003530 self->alpn_protocols_len = (unsigned int)protos->len;
Benjamin Petersoncca27322015-01-23 16:35:37 -05003531
3532 if (SSL_CTX_set_alpn_protos(self->ctx, self->alpn_protocols, self->alpn_protocols_len))
3533 return PyErr_NoMemory();
3534 SSL_CTX_set_alpn_select_cb(self->ctx, _selectALPN_cb, self);
3535
Benjamin Petersoncca27322015-01-23 16:35:37 -05003536 Py_RETURN_NONE;
3537#else
3538 PyErr_SetString(PyExc_NotImplementedError,
3539 "The ALPN extension requires OpenSSL 1.0.2 or later.");
3540 return NULL;
3541#endif
3542}
3543
Antoine Pitrou152efa22010-05-16 18:19:27 +00003544static PyObject *
3545get_verify_mode(PySSLContext *self, void *c)
3546{
Christian Heimes9fb051f2018-09-23 08:32:31 +02003547 /* ignore SSL_VERIFY_CLIENT_ONCE and SSL_VERIFY_POST_HANDSHAKE */
3548 int mask = (SSL_VERIFY_NONE | SSL_VERIFY_PEER |
3549 SSL_VERIFY_FAIL_IF_NO_PEER_CERT);
3550 switch (SSL_CTX_get_verify_mode(self->ctx) & mask) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003551 case SSL_VERIFY_NONE:
3552 return PyLong_FromLong(PY_SSL_CERT_NONE);
3553 case SSL_VERIFY_PEER:
3554 return PyLong_FromLong(PY_SSL_CERT_OPTIONAL);
3555 case SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT:
3556 return PyLong_FromLong(PY_SSL_CERT_REQUIRED);
3557 }
3558 PyErr_SetString(PySSLErrorObject,
3559 "invalid return value from SSL_CTX_get_verify_mode");
3560 return NULL;
3561}
3562
3563static int
3564set_verify_mode(PySSLContext *self, PyObject *arg, void *c)
3565{
Christian Heimes5fe668c2016-09-12 00:01:11 +02003566 int n;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003567 if (!PyArg_Parse(arg, "i", &n))
3568 return -1;
Christian Heimes5fe668c2016-09-12 00:01:11 +02003569 if (n == PY_SSL_CERT_NONE && self->check_hostname) {
Christian Heimes1aa9a752013-12-02 02:41:19 +01003570 PyErr_SetString(PyExc_ValueError,
3571 "Cannot set verify_mode to CERT_NONE when "
3572 "check_hostname is enabled.");
3573 return -1;
3574 }
Christian Heimes9fb051f2018-09-23 08:32:31 +02003575 return _set_verify_mode(self, n);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003576}
3577
3578static PyObject *
Christian Heimes22587792013-11-21 23:56:13 +01003579get_verify_flags(PySSLContext *self, void *c)
3580{
Christian Heimes598894f2016-09-05 23:19:05 +02003581 X509_VERIFY_PARAM *param;
Christian Heimes22587792013-11-21 23:56:13 +01003582 unsigned long flags;
3583
Christian Heimes61d478c2018-01-27 15:51:38 +01003584 param = SSL_CTX_get0_param(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02003585 flags = X509_VERIFY_PARAM_get_flags(param);
Christian Heimes22587792013-11-21 23:56:13 +01003586 return PyLong_FromUnsignedLong(flags);
3587}
3588
3589static int
3590set_verify_flags(PySSLContext *self, PyObject *arg, void *c)
3591{
Christian Heimes598894f2016-09-05 23:19:05 +02003592 X509_VERIFY_PARAM *param;
Christian Heimes22587792013-11-21 23:56:13 +01003593 unsigned long new_flags, flags, set, clear;
3594
3595 if (!PyArg_Parse(arg, "k", &new_flags))
3596 return -1;
Christian Heimes61d478c2018-01-27 15:51:38 +01003597 param = SSL_CTX_get0_param(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02003598 flags = X509_VERIFY_PARAM_get_flags(param);
Christian Heimes22587792013-11-21 23:56:13 +01003599 clear = flags & ~new_flags;
3600 set = ~flags & new_flags;
3601 if (clear) {
Christian Heimes598894f2016-09-05 23:19:05 +02003602 if (!X509_VERIFY_PARAM_clear_flags(param, clear)) {
Christian Heimes22587792013-11-21 23:56:13 +01003603 _setSSLError(NULL, 0, __FILE__, __LINE__);
3604 return -1;
3605 }
3606 }
3607 if (set) {
Christian Heimes598894f2016-09-05 23:19:05 +02003608 if (!X509_VERIFY_PARAM_set_flags(param, set)) {
Christian Heimes22587792013-11-21 23:56:13 +01003609 _setSSLError(NULL, 0, __FILE__, __LINE__);
3610 return -1;
3611 }
3612 }
3613 return 0;
3614}
3615
Christian Heimes698dde12018-02-27 11:54:43 +01003616/* Getter and setter for protocol version */
3617#if defined(SSL_CTRL_GET_MAX_PROTO_VERSION)
3618
3619
3620static int
3621set_min_max_proto_version(PySSLContext *self, PyObject *arg, int what)
3622{
3623 long v;
3624 int result;
3625
3626 if (!PyArg_Parse(arg, "l", &v))
3627 return -1;
3628 if (v > INT_MAX) {
3629 PyErr_SetString(PyExc_OverflowError, "Option is too long");
3630 return -1;
3631 }
3632
3633 switch(self->protocol) {
3634 case PY_SSL_VERSION_TLS_CLIENT: /* fall through */
3635 case PY_SSL_VERSION_TLS_SERVER: /* fall through */
3636 case PY_SSL_VERSION_TLS:
3637 break;
3638 default:
3639 PyErr_SetString(
3640 PyExc_ValueError,
3641 "The context's protocol doesn't support modification of "
3642 "highest and lowest version."
3643 );
3644 return -1;
3645 }
3646
3647 if (what == 0) {
3648 switch(v) {
3649 case PY_PROTO_MINIMUM_SUPPORTED:
3650 v = 0;
3651 break;
3652 case PY_PROTO_MAXIMUM_SUPPORTED:
3653 /* Emulate max for set_min_proto_version */
3654 v = PY_PROTO_MAXIMUM_AVAILABLE;
3655 break;
3656 default:
3657 break;
3658 }
3659 result = SSL_CTX_set_min_proto_version(self->ctx, v);
3660 }
3661 else {
3662 switch(v) {
3663 case PY_PROTO_MAXIMUM_SUPPORTED:
3664 v = 0;
3665 break;
3666 case PY_PROTO_MINIMUM_SUPPORTED:
3667 /* Emulate max for set_min_proto_version */
3668 v = PY_PROTO_MINIMUM_AVAILABLE;
3669 break;
3670 default:
3671 break;
3672 }
3673 result = SSL_CTX_set_max_proto_version(self->ctx, v);
3674 }
3675 if (result == 0) {
3676 PyErr_Format(PyExc_ValueError,
3677 "Unsupported protocol version 0x%x", v);
3678 return -1;
3679 }
3680 return 0;
3681}
3682
3683static PyObject *
3684get_minimum_version(PySSLContext *self, void *c)
3685{
3686 int v = SSL_CTX_ctrl(self->ctx, SSL_CTRL_GET_MIN_PROTO_VERSION, 0, NULL);
3687 if (v == 0) {
3688 v = PY_PROTO_MINIMUM_SUPPORTED;
3689 }
3690 return PyLong_FromLong(v);
3691}
3692
3693static int
3694set_minimum_version(PySSLContext *self, PyObject *arg, void *c)
3695{
3696 return set_min_max_proto_version(self, arg, 0);
3697}
3698
3699static PyObject *
3700get_maximum_version(PySSLContext *self, void *c)
3701{
3702 int v = SSL_CTX_ctrl(self->ctx, SSL_CTRL_GET_MAX_PROTO_VERSION, 0, NULL);
3703 if (v == 0) {
3704 v = PY_PROTO_MAXIMUM_SUPPORTED;
3705 }
3706 return PyLong_FromLong(v);
3707}
3708
3709static int
3710set_maximum_version(PySSLContext *self, PyObject *arg, void *c)
3711{
3712 return set_min_max_proto_version(self, arg, 1);
3713}
3714#endif /* SSL_CTRL_GET_MAX_PROTO_VERSION */
3715
Christian Heimes78c7d522019-06-03 21:00:10 +02003716#if (OPENSSL_VERSION_NUMBER >= 0x10101000L) && !defined(LIBRESSL_VERSION_NUMBER)
3717static PyObject *
3718get_num_tickets(PySSLContext *self, void *c)
3719{
Victor Stinner76611c72019-07-09 13:30:52 +02003720 return PyLong_FromSize_t(SSL_CTX_get_num_tickets(self->ctx));
Christian Heimes78c7d522019-06-03 21:00:10 +02003721}
3722
3723static int
3724set_num_tickets(PySSLContext *self, PyObject *arg, void *c)
3725{
3726 long num;
3727 if (!PyArg_Parse(arg, "l", &num))
3728 return -1;
3729 if (num < 0) {
3730 PyErr_SetString(PyExc_ValueError, "value must be non-negative");
3731 return -1;
3732 }
3733 if (self->protocol != PY_SSL_VERSION_TLS_SERVER) {
3734 PyErr_SetString(PyExc_ValueError,
3735 "SSLContext is not a server context.");
3736 return -1;
3737 }
3738 if (SSL_CTX_set_num_tickets(self->ctx, num) != 1) {
3739 PyErr_SetString(PyExc_ValueError, "failed to set num tickets.");
3740 return -1;
3741 }
3742 return 0;
3743}
3744
3745PyDoc_STRVAR(PySSLContext_num_tickets_doc,
3746"Control the number of TLSv1.3 session tickets");
3747#endif /* OpenSSL 1.1.1 */
3748
matthewhughes9348e836bb2020-07-17 09:59:15 +01003749#if (OPENSSL_VERSION_NUMBER >= 0x10100000L) && !defined(LIBRESSL_VERSION_NUMBER)
3750static PyObject *
3751get_security_level(PySSLContext *self, void *c)
3752{
3753 return PyLong_FromLong(SSL_CTX_get_security_level(self->ctx));
3754}
3755PyDoc_STRVAR(PySSLContext_security_level_doc, "The current security level");
3756#endif /* OpenSSL 1.1.0 */
3757
Christian Heimes22587792013-11-21 23:56:13 +01003758static PyObject *
Antoine Pitroub5218772010-05-21 09:56:06 +00003759get_options(PySSLContext *self, void *c)
3760{
3761 return PyLong_FromLong(SSL_CTX_get_options(self->ctx));
3762}
3763
3764static int
3765set_options(PySSLContext *self, PyObject *arg, void *c)
3766{
3767 long new_opts, opts, set, clear;
3768 if (!PyArg_Parse(arg, "l", &new_opts))
3769 return -1;
3770 opts = SSL_CTX_get_options(self->ctx);
3771 clear = opts & ~new_opts;
3772 set = ~opts & new_opts;
3773 if (clear) {
3774#ifdef HAVE_SSL_CTX_CLEAR_OPTIONS
3775 SSL_CTX_clear_options(self->ctx, clear);
3776#else
3777 PyErr_SetString(PyExc_ValueError,
3778 "can't clear options before OpenSSL 0.9.8m");
3779 return -1;
3780#endif
3781 }
3782 if (set)
3783 SSL_CTX_set_options(self->ctx, set);
3784 return 0;
3785}
3786
Christian Heimes1aa9a752013-12-02 02:41:19 +01003787static PyObject *
Christian Heimes61d478c2018-01-27 15:51:38 +01003788get_host_flags(PySSLContext *self, void *c)
3789{
3790 return PyLong_FromUnsignedLong(self->hostflags);
3791}
3792
3793static int
3794set_host_flags(PySSLContext *self, PyObject *arg, void *c)
3795{
3796 X509_VERIFY_PARAM *param;
3797 unsigned int new_flags = 0;
3798
3799 if (!PyArg_Parse(arg, "I", &new_flags))
3800 return -1;
3801
3802 param = SSL_CTX_get0_param(self->ctx);
3803 self->hostflags = new_flags;
3804 X509_VERIFY_PARAM_set_hostflags(param, new_flags);
3805 return 0;
3806}
3807
3808static PyObject *
Christian Heimes1aa9a752013-12-02 02:41:19 +01003809get_check_hostname(PySSLContext *self, void *c)
3810{
3811 return PyBool_FromLong(self->check_hostname);
3812}
3813
3814static int
3815set_check_hostname(PySSLContext *self, PyObject *arg, void *c)
3816{
3817 int check_hostname;
3818 if (!PyArg_Parse(arg, "p", &check_hostname))
3819 return -1;
3820 if (check_hostname &&
3821 SSL_CTX_get_verify_mode(self->ctx) == SSL_VERIFY_NONE) {
Christian Heimese82c0342017-09-15 20:29:57 +02003822 /* check_hostname = True sets verify_mode = CERT_REQUIRED */
Christian Heimes9fb051f2018-09-23 08:32:31 +02003823 if (_set_verify_mode(self, PY_SSL_CERT_REQUIRED) == -1) {
Christian Heimese82c0342017-09-15 20:29:57 +02003824 return -1;
3825 }
Christian Heimes1aa9a752013-12-02 02:41:19 +01003826 }
3827 self->check_hostname = check_hostname;
3828 return 0;
3829}
3830
Christian Heimes11a14932018-02-24 02:35:08 +01003831static PyObject *
Christian Heimes9fb051f2018-09-23 08:32:31 +02003832get_post_handshake_auth(PySSLContext *self, void *c) {
3833#if TLS1_3_VERSION
3834 return PyBool_FromLong(self->post_handshake_auth);
3835#else
3836 Py_RETURN_NONE;
3837#endif
3838}
3839
3840#if TLS1_3_VERSION
3841static int
3842set_post_handshake_auth(PySSLContext *self, PyObject *arg, void *c) {
Zackery Spytz842acaa2018-12-17 07:52:45 -07003843 if (arg == NULL) {
3844 PyErr_SetString(PyExc_AttributeError, "cannot delete attribute");
3845 return -1;
3846 }
Christian Heimes9fb051f2018-09-23 08:32:31 +02003847 int pha = PyObject_IsTrue(arg);
3848
3849 if (pha == -1) {
3850 return -1;
3851 }
3852 self->post_handshake_auth = pha;
3853
Christian Heimesf0f59302019-07-01 08:29:17 +02003854 /* bpo-37428: newPySSLSocket() sets SSL_VERIFY_POST_HANDSHAKE flag for
3855 * server sockets and SSL_set_post_handshake_auth() for client. */
Christian Heimes9fb051f2018-09-23 08:32:31 +02003856
3857 return 0;
3858}
3859#endif
3860
3861static PyObject *
Christian Heimes11a14932018-02-24 02:35:08 +01003862get_protocol(PySSLContext *self, void *c) {
3863 return PyLong_FromLong(self->protocol);
3864}
Christian Heimes1aa9a752013-12-02 02:41:19 +01003865
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003866typedef struct {
3867 PyThreadState *thread_state;
3868 PyObject *callable;
3869 char *password;
Victor Stinner9ee02032013-06-23 15:08:23 +02003870 int size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003871 int error;
3872} _PySSLPasswordInfo;
3873
3874static int
3875_pwinfo_set(_PySSLPasswordInfo *pw_info, PyObject* password,
3876 const char *bad_type_error)
3877{
3878 /* Set the password and size fields of a _PySSLPasswordInfo struct
3879 from a unicode, bytes, or byte array object.
3880 The password field will be dynamically allocated and must be freed
3881 by the caller */
3882 PyObject *password_bytes = NULL;
3883 const char *data = NULL;
3884 Py_ssize_t size;
3885
3886 if (PyUnicode_Check(password)) {
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03003887 password_bytes = PyUnicode_AsUTF8String(password);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003888 if (!password_bytes) {
3889 goto error;
3890 }
3891 data = PyBytes_AS_STRING(password_bytes);
3892 size = PyBytes_GET_SIZE(password_bytes);
3893 } else if (PyBytes_Check(password)) {
3894 data = PyBytes_AS_STRING(password);
3895 size = PyBytes_GET_SIZE(password);
3896 } else if (PyByteArray_Check(password)) {
3897 data = PyByteArray_AS_STRING(password);
3898 size = PyByteArray_GET_SIZE(password);
3899 } else {
3900 PyErr_SetString(PyExc_TypeError, bad_type_error);
3901 goto error;
3902 }
3903
Victor Stinner9ee02032013-06-23 15:08:23 +02003904 if (size > (Py_ssize_t)INT_MAX) {
3905 PyErr_Format(PyExc_ValueError,
3906 "password cannot be longer than %d bytes", INT_MAX);
3907 goto error;
3908 }
3909
Victor Stinner11ebff22013-07-07 17:07:52 +02003910 PyMem_Free(pw_info->password);
3911 pw_info->password = PyMem_Malloc(size);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003912 if (!pw_info->password) {
3913 PyErr_SetString(PyExc_MemoryError,
3914 "unable to allocate password buffer");
3915 goto error;
3916 }
3917 memcpy(pw_info->password, data, size);
Victor Stinner9ee02032013-06-23 15:08:23 +02003918 pw_info->size = (int)size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003919
3920 Py_XDECREF(password_bytes);
3921 return 1;
3922
3923error:
3924 Py_XDECREF(password_bytes);
3925 return 0;
3926}
3927
3928static int
3929_password_callback(char *buf, int size, int rwflag, void *userdata)
3930{
3931 _PySSLPasswordInfo *pw_info = (_PySSLPasswordInfo*) userdata;
3932 PyObject *fn_ret = NULL;
3933
3934 PySSL_END_ALLOW_THREADS_S(pw_info->thread_state);
3935
3936 if (pw_info->callable) {
Victor Stinnerf17c3de2016-12-06 18:46:19 +01003937 fn_ret = _PyObject_CallNoArg(pw_info->callable);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003938 if (!fn_ret) {
3939 /* TODO: It would be nice to move _ctypes_add_traceback() into the
3940 core python API, so we could use it to add a frame here */
3941 goto error;
3942 }
3943
3944 if (!_pwinfo_set(pw_info, fn_ret,
3945 "password callback must return a string")) {
3946 goto error;
3947 }
3948 Py_CLEAR(fn_ret);
3949 }
3950
3951 if (pw_info->size > size) {
3952 PyErr_Format(PyExc_ValueError,
3953 "password cannot be longer than %d bytes", size);
3954 goto error;
3955 }
3956
3957 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
3958 memcpy(buf, pw_info->password, pw_info->size);
3959 return pw_info->size;
3960
3961error:
3962 Py_XDECREF(fn_ret);
3963 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
3964 pw_info->error = 1;
3965 return -1;
3966}
3967
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003968/*[clinic input]
3969_ssl._SSLContext.load_cert_chain
3970 certfile: object
Serhiy Storchaka279f4462019-09-14 12:24:05 +03003971 keyfile: object = None
3972 password: object = None
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003973
3974[clinic start generated code]*/
3975
Antoine Pitroub5218772010-05-21 09:56:06 +00003976static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003977_ssl__SSLContext_load_cert_chain_impl(PySSLContext *self, PyObject *certfile,
3978 PyObject *keyfile, PyObject *password)
Serhiy Storchaka279f4462019-09-14 12:24:05 +03003979/*[clinic end generated code: output=9480bc1c380e2095 input=30bc7e967ea01a58]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003980{
Antoine Pitrou152efa22010-05-16 18:19:27 +00003981 PyObject *certfile_bytes = NULL, *keyfile_bytes = NULL;
Christian Heimes598894f2016-09-05 23:19:05 +02003982 pem_password_cb *orig_passwd_cb = SSL_CTX_get_default_passwd_cb(self->ctx);
3983 void *orig_passwd_userdata = SSL_CTX_get_default_passwd_cb_userdata(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003984 _PySSLPasswordInfo pw_info = { NULL, NULL, NULL, 0, 0 };
Antoine Pitrou152efa22010-05-16 18:19:27 +00003985 int r;
3986
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003987 errno = 0;
Antoine Pitrou67e8e562010-09-01 20:55:41 +00003988 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00003989 if (keyfile == Py_None)
3990 keyfile = NULL;
3991 if (!PyUnicode_FSConverter(certfile, &certfile_bytes)) {
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03003992 if (PyErr_ExceptionMatches(PyExc_TypeError)) {
3993 PyErr_SetString(PyExc_TypeError,
3994 "certfile should be a valid filesystem path");
3995 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003996 return NULL;
3997 }
3998 if (keyfile && !PyUnicode_FSConverter(keyfile, &keyfile_bytes)) {
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03003999 if (PyErr_ExceptionMatches(PyExc_TypeError)) {
4000 PyErr_SetString(PyExc_TypeError,
4001 "keyfile should be a valid filesystem path");
4002 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00004003 goto error;
4004 }
Serhiy Storchaka279f4462019-09-14 12:24:05 +03004005 if (password != Py_None) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02004006 if (PyCallable_Check(password)) {
4007 pw_info.callable = password;
4008 } else if (!_pwinfo_set(&pw_info, password,
4009 "password should be a string or callable")) {
4010 goto error;
4011 }
4012 SSL_CTX_set_default_passwd_cb(self->ctx, _password_callback);
4013 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, &pw_info);
4014 }
4015 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00004016 r = SSL_CTX_use_certificate_chain_file(self->ctx,
4017 PyBytes_AS_STRING(certfile_bytes));
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02004018 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00004019 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02004020 if (pw_info.error) {
4021 ERR_clear_error();
4022 /* the password callback has already set the error information */
4023 }
4024 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00004025 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03004026 PyErr_SetFromErrno(PyExc_OSError);
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00004027 }
4028 else {
4029 _setSSLError(NULL, 0, __FILE__, __LINE__);
4030 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00004031 goto error;
4032 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02004033 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou9c254862011-04-03 18:15:34 +02004034 r = SSL_CTX_use_PrivateKey_file(self->ctx,
Antoine Pitrou152efa22010-05-16 18:19:27 +00004035 PyBytes_AS_STRING(keyfile ? keyfile_bytes : certfile_bytes),
4036 SSL_FILETYPE_PEM);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02004037 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
4038 Py_CLEAR(keyfile_bytes);
4039 Py_CLEAR(certfile_bytes);
Antoine Pitrou152efa22010-05-16 18:19:27 +00004040 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02004041 if (pw_info.error) {
4042 ERR_clear_error();
4043 /* the password callback has already set the error information */
4044 }
4045 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00004046 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03004047 PyErr_SetFromErrno(PyExc_OSError);
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00004048 }
4049 else {
4050 _setSSLError(NULL, 0, __FILE__, __LINE__);
4051 }
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 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00004055 r = SSL_CTX_check_private_key(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02004056 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00004057 if (r != 1) {
4058 _setSSLError(NULL, 0, __FILE__, __LINE__);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02004059 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004060 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02004061 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
4062 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02004063 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00004064 Py_RETURN_NONE;
4065
4066error:
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02004067 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
4068 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02004069 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00004070 Py_XDECREF(keyfile_bytes);
4071 Py_XDECREF(certfile_bytes);
4072 return NULL;
4073}
4074
Christian Heimesefff7062013-11-21 03:35:02 +01004075/* internal helper function, returns -1 on error
4076 */
4077static int
Serhiy Storchaka8f87eef2020-04-12 14:58:27 +03004078_add_ca_certs(PySSLContext *self, const void *data, Py_ssize_t len,
Christian Heimesefff7062013-11-21 03:35:02 +01004079 int filetype)
4080{
4081 BIO *biobuf = NULL;
4082 X509_STORE *store;
4083 int retval = 0, err, loaded = 0;
4084
4085 assert(filetype == SSL_FILETYPE_ASN1 || filetype == SSL_FILETYPE_PEM);
4086
4087 if (len <= 0) {
4088 PyErr_SetString(PyExc_ValueError,
4089 "Empty certificate data");
4090 return -1;
4091 } else if (len > INT_MAX) {
4092 PyErr_SetString(PyExc_OverflowError,
4093 "Certificate data is too long.");
4094 return -1;
4095 }
4096
Christian Heimes1dbf61f2013-11-22 00:34:18 +01004097 biobuf = BIO_new_mem_buf(data, (int)len);
Christian Heimesefff7062013-11-21 03:35:02 +01004098 if (biobuf == NULL) {
4099 _setSSLError("Can't allocate buffer", 0, __FILE__, __LINE__);
4100 return -1;
4101 }
4102
4103 store = SSL_CTX_get_cert_store(self->ctx);
4104 assert(store != NULL);
4105
4106 while (1) {
4107 X509 *cert = NULL;
4108 int r;
4109
4110 if (filetype == SSL_FILETYPE_ASN1) {
4111 cert = d2i_X509_bio(biobuf, NULL);
4112 } else {
4113 cert = PEM_read_bio_X509(biobuf, NULL,
Christian Heimes598894f2016-09-05 23:19:05 +02004114 SSL_CTX_get_default_passwd_cb(self->ctx),
4115 SSL_CTX_get_default_passwd_cb_userdata(self->ctx)
4116 );
Christian Heimesefff7062013-11-21 03:35:02 +01004117 }
4118 if (cert == NULL) {
4119 break;
4120 }
4121 r = X509_STORE_add_cert(store, cert);
4122 X509_free(cert);
4123 if (!r) {
4124 err = ERR_peek_last_error();
4125 if ((ERR_GET_LIB(err) == ERR_LIB_X509) &&
4126 (ERR_GET_REASON(err) == X509_R_CERT_ALREADY_IN_HASH_TABLE)) {
4127 /* cert already in hash table, not an error */
4128 ERR_clear_error();
4129 } else {
4130 break;
4131 }
4132 }
4133 loaded++;
4134 }
4135
4136 err = ERR_peek_last_error();
4137 if ((filetype == SSL_FILETYPE_ASN1) &&
4138 (loaded > 0) &&
4139 (ERR_GET_LIB(err) == ERR_LIB_ASN1) &&
4140 (ERR_GET_REASON(err) == ASN1_R_HEADER_TOO_LONG)) {
4141 /* EOF ASN1 file, not an error */
4142 ERR_clear_error();
4143 retval = 0;
4144 } else if ((filetype == SSL_FILETYPE_PEM) &&
4145 (loaded > 0) &&
4146 (ERR_GET_LIB(err) == ERR_LIB_PEM) &&
4147 (ERR_GET_REASON(err) == PEM_R_NO_START_LINE)) {
4148 /* EOF PEM file, not an error */
4149 ERR_clear_error();
4150 retval = 0;
4151 } else {
4152 _setSSLError(NULL, 0, __FILE__, __LINE__);
4153 retval = -1;
4154 }
4155
4156 BIO_free(biobuf);
4157 return retval;
4158}
4159
4160
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004161/*[clinic input]
4162_ssl._SSLContext.load_verify_locations
Serhiy Storchaka279f4462019-09-14 12:24:05 +03004163 cafile: object = None
4164 capath: object = None
4165 cadata: object = None
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004166
4167[clinic start generated code]*/
4168
Antoine Pitrou152efa22010-05-16 18:19:27 +00004169static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004170_ssl__SSLContext_load_verify_locations_impl(PySSLContext *self,
4171 PyObject *cafile,
4172 PyObject *capath,
4173 PyObject *cadata)
Serhiy Storchaka279f4462019-09-14 12:24:05 +03004174/*[clinic end generated code: output=454c7e41230ca551 input=42ecfe258233e194]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004175{
Antoine Pitrou152efa22010-05-16 18:19:27 +00004176 PyObject *cafile_bytes = NULL, *capath_bytes = NULL;
4177 const char *cafile_buf = NULL, *capath_buf = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01004178 int r = 0, ok = 1;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004179
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00004180 errno = 0;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004181 if (cafile == Py_None)
4182 cafile = NULL;
4183 if (capath == Py_None)
4184 capath = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01004185 if (cadata == Py_None)
4186 cadata = NULL;
4187
4188 if (cafile == NULL && capath == NULL && cadata == NULL) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00004189 PyErr_SetString(PyExc_TypeError,
Christian Heimesefff7062013-11-21 03:35:02 +01004190 "cafile, capath and cadata cannot be all omitted");
4191 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004192 }
4193 if (cafile && !PyUnicode_FSConverter(cafile, &cafile_bytes)) {
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03004194 if (PyErr_ExceptionMatches(PyExc_TypeError)) {
4195 PyErr_SetString(PyExc_TypeError,
4196 "cafile 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 }
4200 if (capath && !PyUnicode_FSConverter(capath, &capath_bytes)) {
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03004201 if (PyErr_ExceptionMatches(PyExc_TypeError)) {
4202 PyErr_SetString(PyExc_TypeError,
4203 "capath should be a valid filesystem path");
4204 }
Christian Heimesefff7062013-11-21 03:35:02 +01004205 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004206 }
Christian Heimesefff7062013-11-21 03:35:02 +01004207
4208 /* validata cadata type and load cadata */
4209 if (cadata) {
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03004210 if (PyUnicode_Check(cadata)) {
4211 PyObject *cadata_ascii = PyUnicode_AsASCIIString(cadata);
4212 if (cadata_ascii == NULL) {
4213 if (PyErr_ExceptionMatches(PyExc_UnicodeEncodeError)) {
4214 goto invalid_cadata;
4215 }
4216 goto error;
4217 }
4218 r = _add_ca_certs(self,
4219 PyBytes_AS_STRING(cadata_ascii),
4220 PyBytes_GET_SIZE(cadata_ascii),
4221 SSL_FILETYPE_PEM);
4222 Py_DECREF(cadata_ascii);
4223 if (r == -1) {
4224 goto error;
4225 }
4226 }
4227 else if (PyObject_CheckBuffer(cadata)) {
4228 Py_buffer buf;
4229 if (PyObject_GetBuffer(cadata, &buf, PyBUF_SIMPLE)) {
4230 goto error;
4231 }
Christian Heimesefff7062013-11-21 03:35:02 +01004232 if (!PyBuffer_IsContiguous(&buf, 'C') || buf.ndim > 1) {
4233 PyBuffer_Release(&buf);
4234 PyErr_SetString(PyExc_TypeError,
4235 "cadata should be a contiguous buffer with "
4236 "a single dimension");
4237 goto error;
4238 }
4239 r = _add_ca_certs(self, buf.buf, buf.len, SSL_FILETYPE_ASN1);
4240 PyBuffer_Release(&buf);
4241 if (r == -1) {
4242 goto error;
4243 }
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03004244 }
4245 else {
4246 invalid_cadata:
4247 PyErr_SetString(PyExc_TypeError,
4248 "cadata should be an ASCII string or a "
4249 "bytes-like object");
4250 goto error;
Christian Heimesefff7062013-11-21 03:35:02 +01004251 }
4252 }
4253
4254 /* load cafile or capath */
4255 if (cafile || capath) {
4256 if (cafile)
4257 cafile_buf = PyBytes_AS_STRING(cafile_bytes);
4258 if (capath)
4259 capath_buf = PyBytes_AS_STRING(capath_bytes);
4260 PySSL_BEGIN_ALLOW_THREADS
4261 r = SSL_CTX_load_verify_locations(self->ctx, cafile_buf, capath_buf);
4262 PySSL_END_ALLOW_THREADS
4263 if (r != 1) {
Christian Heimesefff7062013-11-21 03:35:02 +01004264 if (errno != 0) {
4265 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03004266 PyErr_SetFromErrno(PyExc_OSError);
Christian Heimesefff7062013-11-21 03:35:02 +01004267 }
4268 else {
4269 _setSSLError(NULL, 0, __FILE__, __LINE__);
4270 }
4271 goto error;
4272 }
4273 }
4274 goto end;
4275
4276 error:
4277 ok = 0;
4278 end:
Antoine Pitrou152efa22010-05-16 18:19:27 +00004279 Py_XDECREF(cafile_bytes);
4280 Py_XDECREF(capath_bytes);
Christian Heimesefff7062013-11-21 03:35:02 +01004281 if (ok) {
4282 Py_RETURN_NONE;
4283 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00004284 return NULL;
4285 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00004286}
4287
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004288/*[clinic input]
4289_ssl._SSLContext.load_dh_params
4290 path as filepath: object
4291 /
4292
4293[clinic start generated code]*/
4294
Antoine Pitrou152efa22010-05-16 18:19:27 +00004295static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004296_ssl__SSLContext_load_dh_params(PySSLContext *self, PyObject *filepath)
4297/*[clinic end generated code: output=1c8e57a38e055af0 input=c8871f3c796ae1d6]*/
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004298{
4299 FILE *f;
4300 DH *dh;
4301
Victor Stinnerdaf45552013-08-28 00:53:59 +02004302 f = _Py_fopen_obj(filepath, "rb");
Victor Stinnere42ccd22015-03-18 01:39:23 +01004303 if (f == NULL)
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004304 return NULL;
Victor Stinnere42ccd22015-03-18 01:39:23 +01004305
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004306 errno = 0;
4307 PySSL_BEGIN_ALLOW_THREADS
4308 dh = PEM_read_DHparams(f, NULL, NULL, NULL);
Antoine Pitrou457a2292013-01-12 21:43:45 +01004309 fclose(f);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004310 PySSL_END_ALLOW_THREADS
4311 if (dh == NULL) {
4312 if (errno != 0) {
4313 ERR_clear_error();
4314 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
4315 }
4316 else {
4317 _setSSLError(NULL, 0, __FILE__, __LINE__);
4318 }
4319 return NULL;
4320 }
Zackery Spytzaebc0492020-07-07 22:21:58 -06004321 if (!SSL_CTX_set_tmp_dh(self->ctx, dh)) {
4322 DH_free(dh);
4323 return _setSSLError(NULL, 0, __FILE__, __LINE__);
4324 }
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004325 DH_free(dh);
4326 Py_RETURN_NONE;
4327}
4328
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004329/*[clinic input]
4330_ssl._SSLContext._wrap_socket
4331 sock: object(subclass_of="PySocketModule.Sock_Type")
4332 server_side: int
4333 server_hostname as hostname_obj: object = None
Christian Heimes141c5e82018-02-24 21:10:57 +01004334 *
4335 owner: object = None
4336 session: object = None
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004337
4338[clinic start generated code]*/
4339
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004340static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004341_ssl__SSLContext__wrap_socket_impl(PySSLContext *self, PyObject *sock,
Christian Heimes141c5e82018-02-24 21:10:57 +01004342 int server_side, PyObject *hostname_obj,
4343 PyObject *owner, PyObject *session)
4344/*[clinic end generated code: output=f103f238633940b4 input=957d5006183d1894]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004345{
Antoine Pitroud5323212010-10-22 18:19:07 +00004346 char *hostname = NULL;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004347 PyObject *res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004348
Antoine Pitroud5323212010-10-22 18:19:07 +00004349 /* server_hostname is either None (or absent), or to be encoded
Christian Heimesd02ac252018-03-25 12:36:13 +02004350 as IDN A-label (ASCII str) without NULL bytes. */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004351 if (hostname_obj != Py_None) {
Christian Heimes11a14932018-02-24 02:35:08 +01004352 if (!PyArg_Parse(hostname_obj, "es", "ascii", &hostname))
Antoine Pitroud5323212010-10-22 18:19:07 +00004353 return NULL;
Antoine Pitroud5323212010-10-22 18:19:07 +00004354 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00004355
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004356 res = (PyObject *) newPySSLSocket(self, (PySocketSockObject *)sock,
4357 server_side, hostname,
Christian Heimes141c5e82018-02-24 21:10:57 +01004358 owner, session,
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004359 NULL, NULL);
Antoine Pitroud5323212010-10-22 18:19:07 +00004360 if (hostname != NULL)
4361 PyMem_Free(hostname);
4362 return res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004363}
4364
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004365/*[clinic input]
4366_ssl._SSLContext._wrap_bio
4367 incoming: object(subclass_of="&PySSLMemoryBIO_Type", type="PySSLMemoryBIO *")
4368 outgoing: object(subclass_of="&PySSLMemoryBIO_Type", type="PySSLMemoryBIO *")
4369 server_side: int
4370 server_hostname as hostname_obj: object = None
Christian Heimes141c5e82018-02-24 21:10:57 +01004371 *
4372 owner: object = None
4373 session: object = None
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004374
4375[clinic start generated code]*/
4376
Antoine Pitroub0182c82010-10-12 20:09:02 +00004377static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004378_ssl__SSLContext__wrap_bio_impl(PySSLContext *self, PySSLMemoryBIO *incoming,
4379 PySSLMemoryBIO *outgoing, int server_side,
Christian Heimes141c5e82018-02-24 21:10:57 +01004380 PyObject *hostname_obj, PyObject *owner,
4381 PyObject *session)
4382/*[clinic end generated code: output=5c5d6d9b41f99332 input=8cf22f4d586ac56a]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004383{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004384 char *hostname = NULL;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004385 PyObject *res;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004386
4387 /* server_hostname is either None (or absent), or to be encoded
Christian Heimesd02ac252018-03-25 12:36:13 +02004388 as IDN A-label (ASCII str) without NULL bytes. */
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004389 if (hostname_obj != Py_None) {
Christian Heimes11a14932018-02-24 02:35:08 +01004390 if (!PyArg_Parse(hostname_obj, "es", "ascii", &hostname))
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004391 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004392 }
4393
4394 res = (PyObject *) newPySSLSocket(self, NULL, server_side, hostname,
Christian Heimes141c5e82018-02-24 21:10:57 +01004395 owner, session,
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004396 incoming, outgoing);
4397
4398 PyMem_Free(hostname);
4399 return res;
4400}
4401
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004402/*[clinic input]
4403_ssl._SSLContext.session_stats
4404[clinic start generated code]*/
4405
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004406static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004407_ssl__SSLContext_session_stats_impl(PySSLContext *self)
4408/*[clinic end generated code: output=0d96411c42893bfb input=7e0a81fb11102c8b]*/
Antoine Pitroub0182c82010-10-12 20:09:02 +00004409{
4410 int r;
4411 PyObject *value, *stats = PyDict_New();
4412 if (!stats)
4413 return NULL;
4414
4415#define ADD_STATS(SSL_NAME, KEY_NAME) \
4416 value = PyLong_FromLong(SSL_CTX_sess_ ## SSL_NAME (self->ctx)); \
4417 if (value == NULL) \
4418 goto error; \
4419 r = PyDict_SetItemString(stats, KEY_NAME, value); \
4420 Py_DECREF(value); \
4421 if (r < 0) \
4422 goto error;
4423
4424 ADD_STATS(number, "number");
4425 ADD_STATS(connect, "connect");
4426 ADD_STATS(connect_good, "connect_good");
4427 ADD_STATS(connect_renegotiate, "connect_renegotiate");
4428 ADD_STATS(accept, "accept");
4429 ADD_STATS(accept_good, "accept_good");
4430 ADD_STATS(accept_renegotiate, "accept_renegotiate");
4431 ADD_STATS(accept, "accept");
4432 ADD_STATS(hits, "hits");
4433 ADD_STATS(misses, "misses");
4434 ADD_STATS(timeouts, "timeouts");
4435 ADD_STATS(cache_full, "cache_full");
4436
4437#undef ADD_STATS
4438
4439 return stats;
4440
4441error:
4442 Py_DECREF(stats);
4443 return NULL;
4444}
4445
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004446/*[clinic input]
4447_ssl._SSLContext.set_default_verify_paths
4448[clinic start generated code]*/
4449
Antoine Pitrou664c2d12010-11-17 20:29:42 +00004450static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004451_ssl__SSLContext_set_default_verify_paths_impl(PySSLContext *self)
4452/*[clinic end generated code: output=0bee74e6e09deaaa input=35f3408021463d74]*/
Antoine Pitrou664c2d12010-11-17 20:29:42 +00004453{
4454 if (!SSL_CTX_set_default_verify_paths(self->ctx)) {
4455 _setSSLError(NULL, 0, __FILE__, __LINE__);
4456 return NULL;
4457 }
4458 Py_RETURN_NONE;
4459}
4460
Antoine Pitrou501da612011-12-21 09:27:41 +01004461#ifndef OPENSSL_NO_ECDH
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004462/*[clinic input]
4463_ssl._SSLContext.set_ecdh_curve
4464 name: object
4465 /
4466
4467[clinic start generated code]*/
4468
Antoine Pitrou923df6f2011-12-19 17:16:51 +01004469static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004470_ssl__SSLContext_set_ecdh_curve(PySSLContext *self, PyObject *name)
4471/*[clinic end generated code: output=23022c196e40d7d2 input=c2bafb6f6e34726b]*/
Antoine Pitrou923df6f2011-12-19 17:16:51 +01004472{
4473 PyObject *name_bytes;
4474 int nid;
4475 EC_KEY *key;
4476
4477 if (!PyUnicode_FSConverter(name, &name_bytes))
4478 return NULL;
4479 assert(PyBytes_Check(name_bytes));
4480 nid = OBJ_sn2nid(PyBytes_AS_STRING(name_bytes));
4481 Py_DECREF(name_bytes);
4482 if (nid == 0) {
4483 PyErr_Format(PyExc_ValueError,
4484 "unknown elliptic curve name %R", name);
4485 return NULL;
4486 }
4487 key = EC_KEY_new_by_curve_name(nid);
4488 if (key == NULL) {
4489 _setSSLError(NULL, 0, __FILE__, __LINE__);
4490 return NULL;
4491 }
4492 SSL_CTX_set_tmp_ecdh(self->ctx, key);
4493 EC_KEY_free(key);
4494 Py_RETURN_NONE;
4495}
Antoine Pitrou501da612011-12-21 09:27:41 +01004496#endif
Antoine Pitrou923df6f2011-12-19 17:16:51 +01004497
Antoine Pitrou912fbff2013-03-30 16:29:32 +01004498#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004499static int
4500_servername_callback(SSL *s, int *al, void *args)
4501{
4502 int ret;
4503 PySSLContext *ssl_ctx = (PySSLContext *) args;
4504 PySSLSocket *ssl;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004505 PyObject *result;
4506 /* The high-level ssl.SSLSocket object */
4507 PyObject *ssl_socket;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004508 const char *servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
Stefan Krah20d60802013-01-17 17:07:17 +01004509 PyGILState_STATE gstate = PyGILState_Ensure();
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004510
Christian Heimes11a14932018-02-24 02:35:08 +01004511 if (ssl_ctx->set_sni_cb == NULL) {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004512 /* remove race condition in this the call back while if removing the
4513 * callback is in progress */
4514 PyGILState_Release(gstate);
Antoine Pitrou5dd12a52013-01-06 15:25:36 +01004515 return SSL_TLSEXT_ERR_OK;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004516 }
4517
4518 ssl = SSL_get_app_data(s);
4519 assert(PySSLSocket_Check(ssl));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004520
Serhiy Storchakaf51d7152015-11-02 14:40:41 +02004521 /* The servername callback expects an argument that represents the current
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004522 * SSL connection and that has a .context attribute that can be changed to
4523 * identify the requested hostname. Since the official API is the Python
4524 * level API we want to pass the callback a Python level object rather than
4525 * a _ssl.SSLSocket instance. If there's an "owner" (typically an
4526 * SSLObject) that will be passed. Otherwise if there's a socket then that
4527 * will be passed. If both do not exist only then the C-level object is
4528 * passed. */
4529 if (ssl->owner)
4530 ssl_socket = PyWeakref_GetObject(ssl->owner);
4531 else if (ssl->Socket)
4532 ssl_socket = PyWeakref_GetObject(ssl->Socket);
4533 else
4534 ssl_socket = (PyObject *) ssl;
4535
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004536 Py_INCREF(ssl_socket);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004537 if (ssl_socket == Py_None)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004538 goto error;
Victor Stinner7e001512013-06-25 00:44:31 +02004539
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004540 if (servername == NULL) {
Christian Heimes11a14932018-02-24 02:35:08 +01004541 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_sni_cb, ssl_socket,
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004542 Py_None, ssl_ctx, NULL);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004543 }
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004544 else {
Christian Heimes11a14932018-02-24 02:35:08 +01004545 PyObject *servername_bytes;
4546 PyObject *servername_str;
4547
4548 servername_bytes = PyBytes_FromString(servername);
4549 if (servername_bytes == NULL) {
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004550 PyErr_WriteUnraisable((PyObject *) ssl_ctx);
4551 goto error;
4552 }
Christian Heimes11a14932018-02-24 02:35:08 +01004553 /* server_hostname was encoded to an A-label by our caller; put it
4554 * back into a str object, but still as an A-label (bpo-28414)
4555 */
4556 servername_str = PyUnicode_FromEncodedObject(servername_bytes, "ascii", NULL);
Christian Heimes11a14932018-02-24 02:35:08 +01004557 if (servername_str == NULL) {
4558 PyErr_WriteUnraisable(servername_bytes);
Zackery Spytzee96f322020-07-09 04:00:21 -06004559 Py_DECREF(servername_bytes);
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004560 goto error;
4561 }
Zackery Spytzee96f322020-07-09 04:00:21 -06004562 Py_DECREF(servername_bytes);
Christian Heimes11a14932018-02-24 02:35:08 +01004563 result = PyObject_CallFunctionObjArgs(
4564 ssl_ctx->set_sni_cb, ssl_socket, servername_str,
4565 ssl_ctx, NULL);
4566 Py_DECREF(servername_str);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004567 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004568 Py_DECREF(ssl_socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004569
4570 if (result == NULL) {
Christian Heimes11a14932018-02-24 02:35:08 +01004571 PyErr_WriteUnraisable(ssl_ctx->set_sni_cb);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004572 *al = SSL_AD_HANDSHAKE_FAILURE;
4573 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
4574 }
4575 else {
Christian Heimes11a14932018-02-24 02:35:08 +01004576 /* Result may be None, a SSLContext or an integer
4577 * None and SSLContext are OK, integer or other values are an error.
4578 */
4579 if (result == Py_None) {
4580 ret = SSL_TLSEXT_ERR_OK;
4581 } else {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004582 *al = (int) PyLong_AsLong(result);
4583 if (PyErr_Occurred()) {
4584 PyErr_WriteUnraisable(result);
4585 *al = SSL_AD_INTERNAL_ERROR;
4586 }
4587 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
4588 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004589 Py_DECREF(result);
4590 }
4591
4592 PyGILState_Release(gstate);
4593 return ret;
4594
4595error:
4596 Py_DECREF(ssl_socket);
4597 *al = SSL_AD_INTERNAL_ERROR;
4598 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
4599 PyGILState_Release(gstate);
4600 return ret;
4601}
Antoine Pitroua5963382013-03-30 16:39:00 +01004602#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004603
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004604static PyObject *
Christian Heimes11a14932018-02-24 02:35:08 +01004605get_sni_callback(PySSLContext *self, void *c)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004606{
Christian Heimes11a14932018-02-24 02:35:08 +01004607 PyObject *cb = self->set_sni_cb;
4608 if (cb == NULL) {
4609 Py_RETURN_NONE;
4610 }
4611 Py_INCREF(cb);
4612 return cb;
4613}
4614
4615static int
4616set_sni_callback(PySSLContext *self, PyObject *arg, void *c)
4617{
4618 if (self->protocol == PY_SSL_VERSION_TLS_CLIENT) {
4619 PyErr_SetString(PyExc_ValueError,
4620 "sni_callback cannot be set on TLS_CLIENT context");
4621 return -1;
4622 }
Antoine Pitrou912fbff2013-03-30 16:29:32 +01004623#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Christian Heimes11a14932018-02-24 02:35:08 +01004624 Py_CLEAR(self->set_sni_cb);
4625 if (arg == Py_None) {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004626 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
4627 }
4628 else {
Christian Heimes11a14932018-02-24 02:35:08 +01004629 if (!PyCallable_Check(arg)) {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004630 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
4631 PyErr_SetString(PyExc_TypeError,
4632 "not a callable object");
Christian Heimes11a14932018-02-24 02:35:08 +01004633 return -1;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004634 }
Christian Heimes11a14932018-02-24 02:35:08 +01004635 Py_INCREF(arg);
4636 self->set_sni_cb = arg;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004637 SSL_CTX_set_tlsext_servername_callback(self->ctx, _servername_callback);
4638 SSL_CTX_set_tlsext_servername_arg(self->ctx, self);
4639 }
Christian Heimes11a14932018-02-24 02:35:08 +01004640 return 0;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004641#else
4642 PyErr_SetString(PyExc_NotImplementedError,
4643 "The TLS extension servername callback, "
4644 "SSL_CTX_set_tlsext_servername_callback, "
4645 "is not in the current OpenSSL library.");
Christian Heimes11a14932018-02-24 02:35:08 +01004646 return -1;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004647#endif
4648}
4649
Christian Heimes11a14932018-02-24 02:35:08 +01004650PyDoc_STRVAR(PySSLContext_sni_callback_doc,
4651"Set a callback that will be called when a server name is provided by the SSL/TLS client in the SNI extension.\n\
4652\n\
4653If the argument is None then the callback is disabled. The method is called\n\
4654with the SSLSocket, the server name as a string, and the SSLContext object.\n\
4655See RFC 6066 for details of the SNI extension.");
4656
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004657/*[clinic input]
4658_ssl._SSLContext.cert_store_stats
4659
4660Returns quantities of loaded X.509 certificates.
4661
4662X.509 certificates with a CA extension and certificate revocation lists
4663inside the context's cert store.
4664
4665NOTE: Certificates in a capath directory aren't loaded unless they have
4666been used at least once.
4667[clinic start generated code]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004668
4669static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004670_ssl__SSLContext_cert_store_stats_impl(PySSLContext *self)
4671/*[clinic end generated code: output=5f356f4d9cca874d input=eb40dd0f6d0e40cf]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004672{
4673 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02004674 STACK_OF(X509_OBJECT) *objs;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004675 X509_OBJECT *obj;
Christian Heimes598894f2016-09-05 23:19:05 +02004676 int x509 = 0, crl = 0, ca = 0, i;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004677
4678 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02004679 objs = X509_STORE_get0_objects(store);
4680 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
4681 obj = sk_X509_OBJECT_value(objs, i);
4682 switch (X509_OBJECT_get_type(obj)) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004683 case X509_LU_X509:
4684 x509++;
Christian Heimes598894f2016-09-05 23:19:05 +02004685 if (X509_check_ca(X509_OBJECT_get0_X509(obj))) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004686 ca++;
4687 }
4688 break;
4689 case X509_LU_CRL:
4690 crl++;
4691 break;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004692 default:
4693 /* Ignore X509_LU_FAIL, X509_LU_RETRY, X509_LU_PKEY.
4694 * As far as I can tell they are internal states and never
4695 * stored in a cert store */
4696 break;
4697 }
4698 }
4699 return Py_BuildValue("{sisisi}", "x509", x509, "crl", crl,
4700 "x509_ca", ca);
4701}
4702
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004703/*[clinic input]
4704_ssl._SSLContext.get_ca_certs
4705 binary_form: bool = False
4706
4707Returns a list of dicts with information of loaded CA certs.
4708
4709If the optional argument is True, returns a DER-encoded copy of the CA
4710certificate.
4711
4712NOTE: Certificates in a capath directory aren't loaded unless they have
4713been used at least once.
4714[clinic start generated code]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004715
4716static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004717_ssl__SSLContext_get_ca_certs_impl(PySSLContext *self, int binary_form)
4718/*[clinic end generated code: output=0d58f148f37e2938 input=6887b5a09b7f9076]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004719{
4720 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02004721 STACK_OF(X509_OBJECT) *objs;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004722 PyObject *ci = NULL, *rlist = NULL;
4723 int i;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004724
4725 if ((rlist = PyList_New(0)) == NULL) {
4726 return NULL;
4727 }
4728
4729 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02004730 objs = X509_STORE_get0_objects(store);
4731 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004732 X509_OBJECT *obj;
4733 X509 *cert;
4734
Christian Heimes598894f2016-09-05 23:19:05 +02004735 obj = sk_X509_OBJECT_value(objs, i);
4736 if (X509_OBJECT_get_type(obj) != X509_LU_X509) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004737 /* not a x509 cert */
4738 continue;
4739 }
4740 /* CA for any purpose */
Christian Heimes598894f2016-09-05 23:19:05 +02004741 cert = X509_OBJECT_get0_X509(obj);
Christian Heimes9a5395a2013-06-17 15:44:12 +02004742 if (!X509_check_ca(cert)) {
4743 continue;
4744 }
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004745 if (binary_form) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004746 ci = _certificate_to_der(cert);
4747 } else {
4748 ci = _decode_certificate(cert);
4749 }
4750 if (ci == NULL) {
4751 goto error;
4752 }
4753 if (PyList_Append(rlist, ci) == -1) {
4754 goto error;
4755 }
4756 Py_CLEAR(ci);
4757 }
4758 return rlist;
4759
4760 error:
4761 Py_XDECREF(ci);
4762 Py_XDECREF(rlist);
4763 return NULL;
4764}
4765
4766
Antoine Pitrou152efa22010-05-16 18:19:27 +00004767static PyGetSetDef context_getsetlist[] = {
Christian Heimes1aa9a752013-12-02 02:41:19 +01004768 {"check_hostname", (getter) get_check_hostname,
4769 (setter) set_check_hostname, NULL},
Christian Heimes61d478c2018-01-27 15:51:38 +01004770 {"_host_flags", (getter) get_host_flags,
4771 (setter) set_host_flags, NULL},
Christian Heimes698dde12018-02-27 11:54:43 +01004772#if SSL_CTRL_GET_MAX_PROTO_VERSION
4773 {"minimum_version", (getter) get_minimum_version,
4774 (setter) set_minimum_version, NULL},
4775 {"maximum_version", (getter) get_maximum_version,
4776 (setter) set_maximum_version, NULL},
4777#endif
Christian Heimesc7f70692019-05-31 11:44:05 +02004778#ifdef HAVE_OPENSSL_KEYLOG
4779 {"keylog_filename", (getter) _PySSLContext_get_keylog_filename,
4780 (setter) _PySSLContext_set_keylog_filename, NULL},
4781#endif
4782 {"_msg_callback", (getter) _PySSLContext_get_msg_callback,
4783 (setter) _PySSLContext_set_msg_callback, NULL},
Christian Heimes11a14932018-02-24 02:35:08 +01004784 {"sni_callback", (getter) get_sni_callback,
Christian Heimes698dde12018-02-27 11:54:43 +01004785 (setter) set_sni_callback, PySSLContext_sni_callback_doc},
Christian Heimes78c7d522019-06-03 21:00:10 +02004786#if (OPENSSL_VERSION_NUMBER >= 0x10101000L) && !defined(LIBRESSL_VERSION_NUMBER)
4787 {"num_tickets", (getter) get_num_tickets,
4788 (setter) set_num_tickets, PySSLContext_num_tickets_doc},
4789#endif
Antoine Pitroub5218772010-05-21 09:56:06 +00004790 {"options", (getter) get_options,
4791 (setter) set_options, NULL},
Christian Heimes9fb051f2018-09-23 08:32:31 +02004792 {"post_handshake_auth", (getter) get_post_handshake_auth,
4793#ifdef TLS1_3_VERSION
4794 (setter) set_post_handshake_auth,
4795#else
4796 NULL,
4797#endif
4798 NULL},
Christian Heimes11a14932018-02-24 02:35:08 +01004799 {"protocol", (getter) get_protocol,
4800 NULL, NULL},
Christian Heimes22587792013-11-21 23:56:13 +01004801 {"verify_flags", (getter) get_verify_flags,
4802 (setter) set_verify_flags, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00004803 {"verify_mode", (getter) get_verify_mode,
4804 (setter) set_verify_mode, NULL},
matthewhughes9348e836bb2020-07-17 09:59:15 +01004805#if (OPENSSL_VERSION_NUMBER >= 0x10100000L) && !defined(LIBRESSL_VERSION_NUMBER)
4806 {"security_level", (getter) get_security_level,
4807 NULL, PySSLContext_security_level_doc},
4808#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00004809 {NULL}, /* sentinel */
4810};
4811
4812static struct PyMethodDef context_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004813 _SSL__SSLCONTEXT__WRAP_SOCKET_METHODDEF
4814 _SSL__SSLCONTEXT__WRAP_BIO_METHODDEF
4815 _SSL__SSLCONTEXT_SET_CIPHERS_METHODDEF
4816 _SSL__SSLCONTEXT__SET_ALPN_PROTOCOLS_METHODDEF
4817 _SSL__SSLCONTEXT__SET_NPN_PROTOCOLS_METHODDEF
4818 _SSL__SSLCONTEXT_LOAD_CERT_CHAIN_METHODDEF
4819 _SSL__SSLCONTEXT_LOAD_DH_PARAMS_METHODDEF
4820 _SSL__SSLCONTEXT_LOAD_VERIFY_LOCATIONS_METHODDEF
4821 _SSL__SSLCONTEXT_SESSION_STATS_METHODDEF
4822 _SSL__SSLCONTEXT_SET_DEFAULT_VERIFY_PATHS_METHODDEF
4823 _SSL__SSLCONTEXT_SET_ECDH_CURVE_METHODDEF
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004824 _SSL__SSLCONTEXT_CERT_STORE_STATS_METHODDEF
4825 _SSL__SSLCONTEXT_GET_CA_CERTS_METHODDEF
Christian Heimes25bfcd52016-09-06 00:04:45 +02004826 _SSL__SSLCONTEXT_GET_CIPHERS_METHODDEF
Antoine Pitrou152efa22010-05-16 18:19:27 +00004827 {NULL, NULL} /* sentinel */
4828};
4829
4830static PyTypeObject PySSLContext_Type = {
4831 PyVarObject_HEAD_INIT(NULL, 0)
4832 "_ssl._SSLContext", /*tp_name*/
4833 sizeof(PySSLContext), /*tp_basicsize*/
4834 0, /*tp_itemsize*/
4835 (destructor)context_dealloc, /*tp_dealloc*/
Jeroen Demeyer530f5062019-05-31 04:13:39 +02004836 0, /*tp_vectorcall_offset*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004837 0, /*tp_getattr*/
4838 0, /*tp_setattr*/
Jeroen Demeyer530f5062019-05-31 04:13:39 +02004839 0, /*tp_as_async*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004840 0, /*tp_repr*/
4841 0, /*tp_as_number*/
4842 0, /*tp_as_sequence*/
4843 0, /*tp_as_mapping*/
4844 0, /*tp_hash*/
4845 0, /*tp_call*/
4846 0, /*tp_str*/
4847 0, /*tp_getattro*/
4848 0, /*tp_setattro*/
4849 0, /*tp_as_buffer*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004850 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004851 0, /*tp_doc*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004852 (traverseproc) context_traverse, /*tp_traverse*/
4853 (inquiry) context_clear, /*tp_clear*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004854 0, /*tp_richcompare*/
4855 0, /*tp_weaklistoffset*/
4856 0, /*tp_iter*/
4857 0, /*tp_iternext*/
4858 context_methods, /*tp_methods*/
4859 0, /*tp_members*/
4860 context_getsetlist, /*tp_getset*/
4861 0, /*tp_base*/
4862 0, /*tp_dict*/
4863 0, /*tp_descr_get*/
4864 0, /*tp_descr_set*/
4865 0, /*tp_dictoffset*/
4866 0, /*tp_init*/
4867 0, /*tp_alloc*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004868 _ssl__SSLContext, /*tp_new*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004869};
4870
4871
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004872/*
4873 * MemoryBIO objects
4874 */
4875
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004876/*[clinic input]
4877@classmethod
4878_ssl.MemoryBIO.__new__
4879
4880[clinic start generated code]*/
4881
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004882static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004883_ssl_MemoryBIO_impl(PyTypeObject *type)
4884/*[clinic end generated code: output=8820a58db78330ac input=26d22e4909ecb1b5]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004885{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004886 BIO *bio;
4887 PySSLMemoryBIO *self;
4888
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004889 bio = BIO_new(BIO_s_mem());
4890 if (bio == NULL) {
4891 PyErr_SetString(PySSLErrorObject,
4892 "failed to allocate BIO");
4893 return NULL;
4894 }
4895 /* Since our BIO is non-blocking an empty read() does not indicate EOF,
4896 * just that no data is currently available. The SSL routines should retry
4897 * the read, which we can achieve by calling BIO_set_retry_read(). */
4898 BIO_set_retry_read(bio);
4899 BIO_set_mem_eof_return(bio, -1);
4900
4901 assert(type != NULL && type->tp_alloc != NULL);
4902 self = (PySSLMemoryBIO *) type->tp_alloc(type, 0);
4903 if (self == NULL) {
4904 BIO_free(bio);
4905 return NULL;
4906 }
4907 self->bio = bio;
4908 self->eof_written = 0;
4909
4910 return (PyObject *) self;
4911}
4912
4913static void
4914memory_bio_dealloc(PySSLMemoryBIO *self)
4915{
4916 BIO_free(self->bio);
4917 Py_TYPE(self)->tp_free(self);
4918}
4919
4920static PyObject *
4921memory_bio_get_pending(PySSLMemoryBIO *self, void *c)
4922{
Segev Finer5cff6372017-07-27 01:19:17 +03004923 return PyLong_FromSize_t(BIO_ctrl_pending(self->bio));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004924}
4925
4926PyDoc_STRVAR(PySSL_memory_bio_pending_doc,
4927"The number of bytes pending in the memory BIO.");
4928
4929static PyObject *
4930memory_bio_get_eof(PySSLMemoryBIO *self, void *c)
4931{
4932 return PyBool_FromLong((BIO_ctrl_pending(self->bio) == 0)
4933 && self->eof_written);
4934}
4935
4936PyDoc_STRVAR(PySSL_memory_bio_eof_doc,
4937"Whether the memory BIO is at EOF.");
4938
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004939/*[clinic input]
4940_ssl.MemoryBIO.read
4941 size as len: int = -1
4942 /
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004943
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004944Read up to size bytes from the memory BIO.
4945
4946If size is not specified, read the entire buffer.
4947If the return value is an empty bytes instance, this means either
4948EOF or that no data is available. Use the "eof" property to
4949distinguish between the two.
4950[clinic start generated code]*/
4951
4952static PyObject *
4953_ssl_MemoryBIO_read_impl(PySSLMemoryBIO *self, int len)
4954/*[clinic end generated code: output=a657aa1e79cd01b3 input=574d7be06a902366]*/
4955{
4956 int avail, nbytes;
4957 PyObject *result;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004958
Segev Finer5cff6372017-07-27 01:19:17 +03004959 avail = (int)Py_MIN(BIO_ctrl_pending(self->bio), INT_MAX);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004960 if ((len < 0) || (len > avail))
4961 len = avail;
4962
4963 result = PyBytes_FromStringAndSize(NULL, len);
4964 if ((result == NULL) || (len == 0))
4965 return result;
4966
4967 nbytes = BIO_read(self->bio, PyBytes_AS_STRING(result), len);
Zackery Spytz365ad2e2018-10-06 11:41:45 -06004968 if (nbytes < 0) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004969 Py_DECREF(result);
Zackery Spytz365ad2e2018-10-06 11:41:45 -06004970 _setSSLError(NULL, 0, __FILE__, __LINE__);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004971 return NULL;
4972 }
4973
Zackery Spytz365ad2e2018-10-06 11:41:45 -06004974 /* There should never be any short reads but check anyway. */
4975 if (nbytes < len) {
4976 _PyBytes_Resize(&result, nbytes);
4977 }
4978
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004979 return result;
4980}
4981
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004982/*[clinic input]
4983_ssl.MemoryBIO.write
4984 b: Py_buffer
4985 /
4986
4987Writes the bytes b into the memory BIO.
4988
4989Returns the number of bytes written.
4990[clinic start generated code]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004991
4992static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004993_ssl_MemoryBIO_write_impl(PySSLMemoryBIO *self, Py_buffer *b)
4994/*[clinic end generated code: output=156ec59110d75935 input=e45757b3e17c4808]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004995{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004996 int nbytes;
4997
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004998 if (b->len > INT_MAX) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004999 PyErr_Format(PyExc_OverflowError,
5000 "string longer than %d bytes", INT_MAX);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005001 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005002 }
5003
5004 if (self->eof_written) {
5005 PyErr_SetString(PySSLErrorObject,
5006 "cannot write() after write_eof()");
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005007 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005008 }
5009
Segev Finer5cff6372017-07-27 01:19:17 +03005010 nbytes = BIO_write(self->bio, b->buf, (int)b->len);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005011 if (nbytes < 0) {
5012 _setSSLError(NULL, 0, __FILE__, __LINE__);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005013 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005014 }
5015
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005016 return PyLong_FromLong(nbytes);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005017}
5018
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005019/*[clinic input]
5020_ssl.MemoryBIO.write_eof
5021
5022Write an EOF marker to the memory BIO.
5023
5024When all data has been read, the "eof" property will be True.
5025[clinic start generated code]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005026
5027static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005028_ssl_MemoryBIO_write_eof_impl(PySSLMemoryBIO *self)
5029/*[clinic end generated code: output=d4106276ccd1ed34 input=56a945f1d29e8bd6]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005030{
5031 self->eof_written = 1;
5032 /* After an EOF is written, a zero return from read() should be a real EOF
5033 * i.e. it should not be retried. Clear the SHOULD_RETRY flag. */
5034 BIO_clear_retry_flags(self->bio);
5035 BIO_set_mem_eof_return(self->bio, 0);
5036
5037 Py_RETURN_NONE;
5038}
5039
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005040static PyGetSetDef memory_bio_getsetlist[] = {
5041 {"pending", (getter) memory_bio_get_pending, NULL,
5042 PySSL_memory_bio_pending_doc},
5043 {"eof", (getter) memory_bio_get_eof, NULL,
5044 PySSL_memory_bio_eof_doc},
5045 {NULL}, /* sentinel */
5046};
5047
5048static struct PyMethodDef memory_bio_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005049 _SSL_MEMORYBIO_READ_METHODDEF
5050 _SSL_MEMORYBIO_WRITE_METHODDEF
5051 _SSL_MEMORYBIO_WRITE_EOF_METHODDEF
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005052 {NULL, NULL} /* sentinel */
5053};
5054
5055static PyTypeObject PySSLMemoryBIO_Type = {
5056 PyVarObject_HEAD_INIT(NULL, 0)
5057 "_ssl.MemoryBIO", /*tp_name*/
5058 sizeof(PySSLMemoryBIO), /*tp_basicsize*/
5059 0, /*tp_itemsize*/
5060 (destructor)memory_bio_dealloc, /*tp_dealloc*/
Jeroen Demeyer530f5062019-05-31 04:13:39 +02005061 0, /*tp_vectorcall_offset*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005062 0, /*tp_getattr*/
5063 0, /*tp_setattr*/
Jeroen Demeyer530f5062019-05-31 04:13:39 +02005064 0, /*tp_as_async*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005065 0, /*tp_repr*/
5066 0, /*tp_as_number*/
5067 0, /*tp_as_sequence*/
5068 0, /*tp_as_mapping*/
5069 0, /*tp_hash*/
5070 0, /*tp_call*/
5071 0, /*tp_str*/
5072 0, /*tp_getattro*/
5073 0, /*tp_setattro*/
5074 0, /*tp_as_buffer*/
5075 Py_TPFLAGS_DEFAULT, /*tp_flags*/
5076 0, /*tp_doc*/
5077 0, /*tp_traverse*/
5078 0, /*tp_clear*/
5079 0, /*tp_richcompare*/
5080 0, /*tp_weaklistoffset*/
5081 0, /*tp_iter*/
5082 0, /*tp_iternext*/
5083 memory_bio_methods, /*tp_methods*/
5084 0, /*tp_members*/
5085 memory_bio_getsetlist, /*tp_getset*/
5086 0, /*tp_base*/
5087 0, /*tp_dict*/
5088 0, /*tp_descr_get*/
5089 0, /*tp_descr_set*/
5090 0, /*tp_dictoffset*/
5091 0, /*tp_init*/
5092 0, /*tp_alloc*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005093 _ssl_MemoryBIO, /*tp_new*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005094};
5095
Antoine Pitrou152efa22010-05-16 18:19:27 +00005096
Christian Heimes99a65702016-09-10 23:44:53 +02005097/*
5098 * SSL Session object
5099 */
5100
5101static void
5102PySSLSession_dealloc(PySSLSession *self)
5103{
INADA Naokia6296d32017-08-24 14:55:17 +09005104 /* bpo-31095: UnTrack is needed before calling any callbacks */
Christian Heimesa5d07652016-09-24 10:48:05 +02005105 PyObject_GC_UnTrack(self);
Christian Heimes99a65702016-09-10 23:44:53 +02005106 Py_XDECREF(self->ctx);
5107 if (self->session != NULL) {
5108 SSL_SESSION_free(self->session);
5109 }
Christian Heimesa5d07652016-09-24 10:48:05 +02005110 PyObject_GC_Del(self);
Christian Heimes99a65702016-09-10 23:44:53 +02005111}
5112
5113static PyObject *
5114PySSLSession_richcompare(PyObject *left, PyObject *right, int op)
5115{
5116 int result;
5117
5118 if (left == NULL || right == NULL) {
5119 PyErr_BadInternalCall();
5120 return NULL;
5121 }
5122
5123 if (!PySSLSession_Check(left) || !PySSLSession_Check(right)) {
5124 Py_RETURN_NOTIMPLEMENTED;
5125 }
5126
5127 if (left == right) {
5128 result = 0;
5129 } else {
5130 const unsigned char *left_id, *right_id;
5131 unsigned int left_len, right_len;
5132 left_id = SSL_SESSION_get_id(((PySSLSession *)left)->session,
5133 &left_len);
5134 right_id = SSL_SESSION_get_id(((PySSLSession *)right)->session,
5135 &right_len);
5136 if (left_len == right_len) {
5137 result = memcmp(left_id, right_id, left_len);
5138 } else {
5139 result = 1;
5140 }
5141 }
5142
5143 switch (op) {
5144 case Py_EQ:
5145 if (result == 0) {
5146 Py_RETURN_TRUE;
5147 } else {
5148 Py_RETURN_FALSE;
5149 }
5150 break;
5151 case Py_NE:
5152 if (result != 0) {
5153 Py_RETURN_TRUE;
5154 } else {
5155 Py_RETURN_FALSE;
5156 }
5157 break;
5158 case Py_LT:
5159 case Py_LE:
5160 case Py_GT:
5161 case Py_GE:
5162 Py_RETURN_NOTIMPLEMENTED;
5163 break;
5164 default:
5165 PyErr_BadArgument();
5166 return NULL;
5167 }
5168}
5169
5170static int
5171PySSLSession_traverse(PySSLSession *self, visitproc visit, void *arg)
5172{
5173 Py_VISIT(self->ctx);
5174 return 0;
5175}
5176
5177static int
5178PySSLSession_clear(PySSLSession *self)
5179{
5180 Py_CLEAR(self->ctx);
5181 return 0;
5182}
5183
5184
5185static PyObject *
5186PySSLSession_get_time(PySSLSession *self, void *closure) {
5187 return PyLong_FromLong(SSL_SESSION_get_time(self->session));
5188}
5189
5190PyDoc_STRVAR(PySSLSession_get_time_doc,
5191"Session creation time (seconds since epoch).");
5192
5193
5194static PyObject *
5195PySSLSession_get_timeout(PySSLSession *self, void *closure) {
5196 return PyLong_FromLong(SSL_SESSION_get_timeout(self->session));
5197}
5198
5199PyDoc_STRVAR(PySSLSession_get_timeout_doc,
5200"Session timeout (delta in seconds).");
5201
5202
5203static PyObject *
5204PySSLSession_get_ticket_lifetime_hint(PySSLSession *self, void *closure) {
5205 unsigned long hint = SSL_SESSION_get_ticket_lifetime_hint(self->session);
5206 return PyLong_FromUnsignedLong(hint);
5207}
5208
5209PyDoc_STRVAR(PySSLSession_get_ticket_lifetime_hint_doc,
5210"Ticket life time hint.");
5211
5212
5213static PyObject *
5214PySSLSession_get_session_id(PySSLSession *self, void *closure) {
5215 const unsigned char *id;
5216 unsigned int len;
5217 id = SSL_SESSION_get_id(self->session, &len);
5218 return PyBytes_FromStringAndSize((const char *)id, len);
5219}
5220
5221PyDoc_STRVAR(PySSLSession_get_session_id_doc,
5222"Session id");
5223
5224
5225static PyObject *
5226PySSLSession_get_has_ticket(PySSLSession *self, void *closure) {
5227 if (SSL_SESSION_has_ticket(self->session)) {
5228 Py_RETURN_TRUE;
5229 } else {
5230 Py_RETURN_FALSE;
5231 }
5232}
5233
5234PyDoc_STRVAR(PySSLSession_get_has_ticket_doc,
5235"Does the session contain a ticket?");
5236
5237
5238static PyGetSetDef PySSLSession_getsetlist[] = {
5239 {"has_ticket", (getter) PySSLSession_get_has_ticket, NULL,
5240 PySSLSession_get_has_ticket_doc},
5241 {"id", (getter) PySSLSession_get_session_id, NULL,
5242 PySSLSession_get_session_id_doc},
5243 {"ticket_lifetime_hint", (getter) PySSLSession_get_ticket_lifetime_hint,
5244 NULL, PySSLSession_get_ticket_lifetime_hint_doc},
5245 {"time", (getter) PySSLSession_get_time, NULL,
5246 PySSLSession_get_time_doc},
5247 {"timeout", (getter) PySSLSession_get_timeout, NULL,
5248 PySSLSession_get_timeout_doc},
5249 {NULL}, /* sentinel */
5250};
5251
5252static PyTypeObject PySSLSession_Type = {
5253 PyVarObject_HEAD_INIT(NULL, 0)
5254 "_ssl.Session", /*tp_name*/
5255 sizeof(PySSLSession), /*tp_basicsize*/
5256 0, /*tp_itemsize*/
5257 (destructor)PySSLSession_dealloc, /*tp_dealloc*/
Jeroen Demeyer530f5062019-05-31 04:13:39 +02005258 0, /*tp_vectorcall_offset*/
Christian Heimes99a65702016-09-10 23:44:53 +02005259 0, /*tp_getattr*/
5260 0, /*tp_setattr*/
Jeroen Demeyer530f5062019-05-31 04:13:39 +02005261 0, /*tp_as_async*/
Christian Heimes99a65702016-09-10 23:44:53 +02005262 0, /*tp_repr*/
5263 0, /*tp_as_number*/
5264 0, /*tp_as_sequence*/
5265 0, /*tp_as_mapping*/
5266 0, /*tp_hash*/
5267 0, /*tp_call*/
5268 0, /*tp_str*/
5269 0, /*tp_getattro*/
5270 0, /*tp_setattro*/
5271 0, /*tp_as_buffer*/
Christian Heimesa5d07652016-09-24 10:48:05 +02005272 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
Christian Heimes99a65702016-09-10 23:44:53 +02005273 0, /*tp_doc*/
5274 (traverseproc)PySSLSession_traverse, /*tp_traverse*/
5275 (inquiry)PySSLSession_clear, /*tp_clear*/
5276 PySSLSession_richcompare, /*tp_richcompare*/
5277 0, /*tp_weaklistoffset*/
5278 0, /*tp_iter*/
5279 0, /*tp_iternext*/
5280 0, /*tp_methods*/
5281 0, /*tp_members*/
5282 PySSLSession_getsetlist, /*tp_getset*/
5283};
5284
5285
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005286/* helper routines for seeding the SSL PRNG */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005287/*[clinic input]
5288_ssl.RAND_add
Larry Hastingsdbfdc382015-05-04 06:59:46 -07005289 string as view: Py_buffer(accept={str, buffer})
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005290 entropy: double
5291 /
5292
5293Mix string into the OpenSSL PRNG state.
5294
5295entropy (a float) is a lower bound on the entropy contained in
Chandan Kumar63c2c8a2017-06-09 15:13:58 +05305296string. See RFC 4086.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005297[clinic start generated code]*/
5298
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005299static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005300_ssl_RAND_add_impl(PyObject *module, Py_buffer *view, double entropy)
Serhiy Storchaka5f31d5c2017-06-10 13:13:51 +03005301/*[clinic end generated code: output=e6dd48df9c9024e9 input=5c33017422828f5c]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005302{
Serhiy Storchaka8490f5a2015-03-20 09:00:36 +02005303 const char *buf;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02005304 Py_ssize_t len, written;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005305
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005306 buf = (const char *)view->buf;
5307 len = view->len;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02005308 do {
5309 written = Py_MIN(len, INT_MAX);
5310 RAND_add(buf, (int)written, entropy);
5311 buf += written;
5312 len -= written;
5313 } while (len);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02005314 Py_RETURN_NONE;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005315}
5316
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005317static PyObject *
Victor Stinner99c8b162011-05-24 12:05:19 +02005318PySSL_RAND(int len, int pseudo)
5319{
5320 int ok;
5321 PyObject *bytes;
5322 unsigned long err;
5323 const char *errstr;
5324 PyObject *v;
5325
Victor Stinner1e81a392013-12-19 16:47:04 +01005326 if (len < 0) {
5327 PyErr_SetString(PyExc_ValueError, "num must be positive");
5328 return NULL;
5329 }
5330
Victor Stinner99c8b162011-05-24 12:05:19 +02005331 bytes = PyBytes_FromStringAndSize(NULL, len);
5332 if (bytes == NULL)
5333 return NULL;
5334 if (pseudo) {
Christian Heimesa871f692020-06-01 08:58:14 +02005335#ifdef PY_OPENSSL_1_1_API
5336 ok = RAND_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
5337#else
Victor Stinner99c8b162011-05-24 12:05:19 +02005338 ok = RAND_pseudo_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
Christian Heimesa871f692020-06-01 08:58:14 +02005339#endif
Victor Stinner99c8b162011-05-24 12:05:19 +02005340 if (ok == 0 || ok == 1)
5341 return Py_BuildValue("NO", bytes, ok == 1 ? Py_True : Py_False);
5342 }
5343 else {
5344 ok = RAND_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
5345 if (ok == 1)
5346 return bytes;
5347 }
5348 Py_DECREF(bytes);
5349
5350 err = ERR_get_error();
5351 errstr = ERR_reason_error_string(err);
5352 v = Py_BuildValue("(ks)", err, errstr);
5353 if (v != NULL) {
5354 PyErr_SetObject(PySSLErrorObject, v);
5355 Py_DECREF(v);
5356 }
5357 return NULL;
5358}
5359
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005360/*[clinic input]
5361_ssl.RAND_bytes
5362 n: int
5363 /
5364
5365Generate n cryptographically strong pseudo-random bytes.
5366[clinic start generated code]*/
5367
Victor Stinner99c8b162011-05-24 12:05:19 +02005368static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005369_ssl_RAND_bytes_impl(PyObject *module, int n)
5370/*[clinic end generated code: output=977da635e4838bc7 input=678ddf2872dfebfc]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02005371{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005372 return PySSL_RAND(n, 0);
Victor Stinner99c8b162011-05-24 12:05:19 +02005373}
5374
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005375/*[clinic input]
5376_ssl.RAND_pseudo_bytes
5377 n: int
5378 /
5379
5380Generate n pseudo-random bytes.
5381
5382Return a pair (bytes, is_cryptographic). is_cryptographic is True
5383if the bytes generated are cryptographically strong.
5384[clinic start generated code]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02005385
5386static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005387_ssl_RAND_pseudo_bytes_impl(PyObject *module, int n)
5388/*[clinic end generated code: output=b1509e937000e52d input=58312bd53f9bbdd0]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02005389{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005390 return PySSL_RAND(n, 1);
Victor Stinner99c8b162011-05-24 12:05:19 +02005391}
5392
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005393/*[clinic input]
5394_ssl.RAND_status
5395
5396Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.
5397
5398It is necessary to seed the PRNG with RAND_add() on some platforms before
5399using the ssl() function.
5400[clinic start generated code]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02005401
5402static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005403_ssl_RAND_status_impl(PyObject *module)
5404/*[clinic end generated code: output=7e0aaa2d39fdc1ad input=8a774b02d1dc81f3]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005405{
Christian Heimes217cfd12007-12-02 14:31:20 +00005406 return PyLong_FromLong(RAND_status());
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005407}
5408
Benjamin Petersonb8a2f512016-07-06 23:55:15 -07005409#ifndef OPENSSL_NO_EGD
Christian Heimesa5d07652016-09-24 10:48:05 +02005410/* LCOV_EXCL_START */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005411/*[clinic input]
5412_ssl.RAND_egd
5413 path: object(converter="PyUnicode_FSConverter")
5414 /
5415
5416Queries the entropy gather daemon (EGD) on the socket named by 'path'.
5417
5418Returns number of bytes read. Raises SSLError if connection to EGD
5419fails or if it does not provide enough data to seed PRNG.
5420[clinic start generated code]*/
5421
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005422static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005423_ssl_RAND_egd_impl(PyObject *module, PyObject *path)
5424/*[clinic end generated code: output=02a67c7c367f52fa input=1aeb7eb948312195]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005425{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005426 int bytes = RAND_egd(PyBytes_AsString(path));
Victor Stinnerf9faaad2010-05-16 21:36:37 +00005427 Py_DECREF(path);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005428 if (bytes == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00005429 PyErr_SetString(PySSLErrorObject,
5430 "EGD connection failed or EGD did not return "
5431 "enough data to seed the PRNG");
5432 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005433 }
Christian Heimes217cfd12007-12-02 14:31:20 +00005434 return PyLong_FromLong(bytes);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005435}
Christian Heimesa5d07652016-09-24 10:48:05 +02005436/* LCOV_EXCL_STOP */
Benjamin Petersonb8a2f512016-07-06 23:55:15 -07005437#endif /* OPENSSL_NO_EGD */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005438
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005439
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005440
5441/*[clinic input]
5442_ssl.get_default_verify_paths
5443
5444Return search paths and environment vars that are used by SSLContext's set_default_verify_paths() to load default CAs.
5445
5446The values are 'cert_file_env', 'cert_file', 'cert_dir_env', 'cert_dir'.
5447[clinic start generated code]*/
Christian Heimes6d7ad132013-06-09 18:02:55 +02005448
5449static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005450_ssl_get_default_verify_paths_impl(PyObject *module)
5451/*[clinic end generated code: output=e5b62a466271928b input=5210c953d98c3eb5]*/
Christian Heimes6d7ad132013-06-09 18:02:55 +02005452{
5453 PyObject *ofile_env = NULL;
5454 PyObject *ofile = NULL;
5455 PyObject *odir_env = NULL;
5456 PyObject *odir = NULL;
5457
Benjamin Petersond113c962015-07-18 10:59:13 -07005458#define CONVERT(info, target) { \
Christian Heimes6d7ad132013-06-09 18:02:55 +02005459 const char *tmp = (info); \
5460 target = NULL; \
5461 if (!tmp) { Py_INCREF(Py_None); target = Py_None; } \
5462 else if ((target = PyUnicode_DecodeFSDefault(tmp)) == NULL) { \
5463 target = PyBytes_FromString(tmp); } \
5464 if (!target) goto error; \
Benjamin Peterson025a1fd2015-11-14 15:12:38 -08005465 }
Christian Heimes6d7ad132013-06-09 18:02:55 +02005466
Benjamin Petersond113c962015-07-18 10:59:13 -07005467 CONVERT(X509_get_default_cert_file_env(), ofile_env);
5468 CONVERT(X509_get_default_cert_file(), ofile);
5469 CONVERT(X509_get_default_cert_dir_env(), odir_env);
5470 CONVERT(X509_get_default_cert_dir(), odir);
5471#undef CONVERT
Christian Heimes6d7ad132013-06-09 18:02:55 +02005472
Christian Heimes200bb1b2013-06-14 15:14:29 +02005473 return Py_BuildValue("NNNN", ofile_env, ofile, odir_env, odir);
Christian Heimes6d7ad132013-06-09 18:02:55 +02005474
5475 error:
5476 Py_XDECREF(ofile_env);
5477 Py_XDECREF(ofile);
5478 Py_XDECREF(odir_env);
5479 Py_XDECREF(odir);
5480 return NULL;
5481}
5482
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005483static PyObject*
5484asn1obj2py(ASN1_OBJECT *obj)
5485{
5486 int nid;
5487 const char *ln, *sn;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005488
5489 nid = OBJ_obj2nid(obj);
5490 if (nid == NID_undef) {
5491 PyErr_Format(PyExc_ValueError, "Unknown object");
5492 return NULL;
5493 }
5494 sn = OBJ_nid2sn(nid);
5495 ln = OBJ_nid2ln(nid);
Serhiy Storchakae503ca52017-09-05 01:28:53 +03005496 return Py_BuildValue("issN", nid, sn, ln, _asn1obj2py(obj, 1));
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005497}
5498
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005499/*[clinic input]
5500_ssl.txt2obj
5501 txt: str
5502 name: bool = False
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005503
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005504Lookup NID, short name, long name and OID of an ASN1_OBJECT.
5505
5506By default objects are looked up by OID. With name=True short and
5507long name are also matched.
5508[clinic start generated code]*/
5509
5510static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005511_ssl_txt2obj_impl(PyObject *module, const char *txt, int name)
5512/*[clinic end generated code: output=c38e3991347079c1 input=1c1e7d0aa7c48602]*/
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005513{
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005514 PyObject *result = NULL;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005515 ASN1_OBJECT *obj;
5516
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005517 obj = OBJ_txt2obj(txt, name ? 0 : 1);
5518 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01005519 PyErr_Format(PyExc_ValueError, "unknown object '%.100s'", txt);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005520 return NULL;
5521 }
5522 result = asn1obj2py(obj);
5523 ASN1_OBJECT_free(obj);
5524 return result;
5525}
5526
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005527/*[clinic input]
5528_ssl.nid2obj
5529 nid: int
5530 /
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005531
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005532Lookup NID, short name, long name and OID of an ASN1_OBJECT by NID.
5533[clinic start generated code]*/
5534
5535static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005536_ssl_nid2obj_impl(PyObject *module, int nid)
5537/*[clinic end generated code: output=4a98ab691cd4f84a input=51787a3bee7d8f98]*/
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005538{
5539 PyObject *result = NULL;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005540 ASN1_OBJECT *obj;
5541
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005542 if (nid < NID_undef) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01005543 PyErr_SetString(PyExc_ValueError, "NID must be positive.");
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005544 return NULL;
5545 }
5546 obj = OBJ_nid2obj(nid);
5547 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01005548 PyErr_Format(PyExc_ValueError, "unknown NID %i", nid);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005549 return NULL;
5550 }
5551 result = asn1obj2py(obj);
5552 ASN1_OBJECT_free(obj);
5553 return result;
5554}
5555
Christian Heimes46bebee2013-06-09 19:03:31 +02005556#ifdef _MSC_VER
Christian Heimes44109d72013-11-22 01:51:30 +01005557
5558static PyObject*
5559certEncodingType(DWORD encodingType)
5560{
5561 static PyObject *x509_asn = NULL;
5562 static PyObject *pkcs_7_asn = NULL;
5563
5564 if (x509_asn == NULL) {
5565 x509_asn = PyUnicode_InternFromString("x509_asn");
5566 if (x509_asn == NULL)
5567 return NULL;
5568 }
5569 if (pkcs_7_asn == NULL) {
5570 pkcs_7_asn = PyUnicode_InternFromString("pkcs_7_asn");
5571 if (pkcs_7_asn == NULL)
5572 return NULL;
5573 }
5574 switch(encodingType) {
5575 case X509_ASN_ENCODING:
5576 Py_INCREF(x509_asn);
5577 return x509_asn;
5578 case PKCS_7_ASN_ENCODING:
5579 Py_INCREF(pkcs_7_asn);
5580 return pkcs_7_asn;
5581 default:
5582 return PyLong_FromLong(encodingType);
5583 }
5584}
5585
5586static PyObject*
5587parseKeyUsage(PCCERT_CONTEXT pCertCtx, DWORD flags)
5588{
5589 CERT_ENHKEY_USAGE *usage;
5590 DWORD size, error, i;
5591 PyObject *retval;
5592
5593 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, NULL, &size)) {
5594 error = GetLastError();
5595 if (error == CRYPT_E_NOT_FOUND) {
5596 Py_RETURN_TRUE;
5597 }
5598 return PyErr_SetFromWindowsErr(error);
5599 }
5600
5601 usage = (CERT_ENHKEY_USAGE*)PyMem_Malloc(size);
5602 if (usage == NULL) {
5603 return PyErr_NoMemory();
5604 }
5605
5606 /* Now get the actual enhanced usage property */
5607 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, usage, &size)) {
5608 PyMem_Free(usage);
5609 error = GetLastError();
5610 if (error == CRYPT_E_NOT_FOUND) {
5611 Py_RETURN_TRUE;
5612 }
5613 return PyErr_SetFromWindowsErr(error);
5614 }
Christian Heimes915cd3f2019-09-09 18:06:55 +02005615 retval = PyFrozenSet_New(NULL);
Christian Heimes44109d72013-11-22 01:51:30 +01005616 if (retval == NULL) {
5617 goto error;
5618 }
5619 for (i = 0; i < usage->cUsageIdentifier; ++i) {
5620 if (usage->rgpszUsageIdentifier[i]) {
5621 PyObject *oid;
5622 int err;
5623 oid = PyUnicode_FromString(usage->rgpszUsageIdentifier[i]);
5624 if (oid == NULL) {
5625 Py_CLEAR(retval);
5626 goto error;
5627 }
5628 err = PySet_Add(retval, oid);
5629 Py_DECREF(oid);
5630 if (err == -1) {
5631 Py_CLEAR(retval);
5632 goto error;
5633 }
5634 }
5635 }
5636 error:
5637 PyMem_Free(usage);
5638 return retval;
5639}
5640
kctherookied93fbbf2019-03-29 00:59:06 +07005641static HCERTSTORE
5642ssl_collect_certificates(const char *store_name)
5643{
5644/* this function collects the system certificate stores listed in
5645 * system_stores into a collection certificate store for being
5646 * enumerated. The store must be readable to be added to the
5647 * store collection.
5648 */
5649
5650 HCERTSTORE hCollectionStore = NULL, hSystemStore = NULL;
5651 static DWORD system_stores[] = {
5652 CERT_SYSTEM_STORE_LOCAL_MACHINE,
5653 CERT_SYSTEM_STORE_LOCAL_MACHINE_ENTERPRISE,
5654 CERT_SYSTEM_STORE_LOCAL_MACHINE_GROUP_POLICY,
5655 CERT_SYSTEM_STORE_CURRENT_USER,
5656 CERT_SYSTEM_STORE_CURRENT_USER_GROUP_POLICY,
5657 CERT_SYSTEM_STORE_SERVICES,
5658 CERT_SYSTEM_STORE_USERS};
5659 size_t i, storesAdded;
5660 BOOL result;
5661
5662 hCollectionStore = CertOpenStore(CERT_STORE_PROV_COLLECTION, 0,
5663 (HCRYPTPROV)NULL, 0, NULL);
5664 if (!hCollectionStore) {
5665 return NULL;
5666 }
5667 storesAdded = 0;
5668 for (i = 0; i < sizeof(system_stores) / sizeof(DWORD); i++) {
5669 hSystemStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0,
5670 (HCRYPTPROV)NULL,
5671 CERT_STORE_READONLY_FLAG |
5672 system_stores[i], store_name);
5673 if (hSystemStore) {
5674 result = CertAddStoreToCollection(hCollectionStore, hSystemStore,
5675 CERT_PHYSICAL_STORE_ADD_ENABLE_FLAG, 0);
5676 if (result) {
5677 ++storesAdded;
5678 }
neoneneed701292019-09-09 21:33:43 +09005679 CertCloseStore(hSystemStore, 0); /* flag must be 0 */
kctherookied93fbbf2019-03-29 00:59:06 +07005680 }
5681 }
5682 if (storesAdded == 0) {
5683 CertCloseStore(hCollectionStore, CERT_CLOSE_STORE_FORCE_FLAG);
5684 return NULL;
5685 }
5686
5687 return hCollectionStore;
5688}
5689
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005690/*[clinic input]
5691_ssl.enum_certificates
5692 store_name: str
5693
5694Retrieve certificates from Windows' cert store.
5695
5696store_name may be one of 'CA', 'ROOT' or 'MY'. The system may provide
5697more cert storages, too. The function returns a list of (bytes,
5698encoding_type, trust) tuples. The encoding_type flag can be interpreted
5699with X509_ASN_ENCODING or PKCS_7_ASN_ENCODING. The trust setting is either
5700a set of OIDs or the boolean True.
5701[clinic start generated code]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00005702
Christian Heimes46bebee2013-06-09 19:03:31 +02005703static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005704_ssl_enum_certificates_impl(PyObject *module, const char *store_name)
5705/*[clinic end generated code: output=5134dc8bb3a3c893 input=915f60d70461ea4e]*/
Christian Heimes46bebee2013-06-09 19:03:31 +02005706{
kctherookied93fbbf2019-03-29 00:59:06 +07005707 HCERTSTORE hCollectionStore = NULL;
Christian Heimes44109d72013-11-22 01:51:30 +01005708 PCCERT_CONTEXT pCertCtx = NULL;
5709 PyObject *keyusage = NULL, *cert = NULL, *enc = NULL, *tup = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02005710 PyObject *result = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02005711
Christian Heimes915cd3f2019-09-09 18:06:55 +02005712 result = PySet_New(NULL);
Christian Heimes44109d72013-11-22 01:51:30 +01005713 if (result == NULL) {
5714 return NULL;
5715 }
kctherookied93fbbf2019-03-29 00:59:06 +07005716 hCollectionStore = ssl_collect_certificates(store_name);
5717 if (hCollectionStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02005718 Py_DECREF(result);
5719 return PyErr_SetFromWindowsErr(GetLastError());
5720 }
5721
kctherookied93fbbf2019-03-29 00:59:06 +07005722 while (pCertCtx = CertEnumCertificatesInStore(hCollectionStore, pCertCtx)) {
Christian Heimes44109d72013-11-22 01:51:30 +01005723 cert = PyBytes_FromStringAndSize((const char*)pCertCtx->pbCertEncoded,
5724 pCertCtx->cbCertEncoded);
5725 if (!cert) {
5726 Py_CLEAR(result);
5727 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02005728 }
Christian Heimes44109d72013-11-22 01:51:30 +01005729 if ((enc = certEncodingType(pCertCtx->dwCertEncodingType)) == NULL) {
5730 Py_CLEAR(result);
5731 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02005732 }
Christian Heimes44109d72013-11-22 01:51:30 +01005733 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG);
5734 if (keyusage == Py_True) {
5735 Py_DECREF(keyusage);
5736 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_EXT_ONLY_ENHKEY_USAGE_FLAG);
Christian Heimes46bebee2013-06-09 19:03:31 +02005737 }
Christian Heimes44109d72013-11-22 01:51:30 +01005738 if (keyusage == NULL) {
5739 Py_CLEAR(result);
5740 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02005741 }
Christian Heimes44109d72013-11-22 01:51:30 +01005742 if ((tup = PyTuple_New(3)) == NULL) {
5743 Py_CLEAR(result);
5744 break;
5745 }
5746 PyTuple_SET_ITEM(tup, 0, cert);
5747 cert = NULL;
5748 PyTuple_SET_ITEM(tup, 1, enc);
5749 enc = NULL;
5750 PyTuple_SET_ITEM(tup, 2, keyusage);
5751 keyusage = NULL;
Christian Heimes915cd3f2019-09-09 18:06:55 +02005752 if (PySet_Add(result, tup) == -1) {
5753 Py_CLEAR(result);
5754 Py_CLEAR(tup);
5755 break;
Christian Heimes44109d72013-11-22 01:51:30 +01005756 }
5757 Py_CLEAR(tup);
5758 }
5759 if (pCertCtx) {
5760 /* loop ended with an error, need to clean up context manually */
5761 CertFreeCertificateContext(pCertCtx);
Christian Heimes46bebee2013-06-09 19:03:31 +02005762 }
5763
5764 /* In error cases cert, enc and tup may not be NULL */
5765 Py_XDECREF(cert);
5766 Py_XDECREF(enc);
Christian Heimes44109d72013-11-22 01:51:30 +01005767 Py_XDECREF(keyusage);
Christian Heimes46bebee2013-06-09 19:03:31 +02005768 Py_XDECREF(tup);
5769
kctherookied93fbbf2019-03-29 00:59:06 +07005770 /* CERT_CLOSE_STORE_FORCE_FLAG forces freeing of memory for all contexts
5771 associated with the store, in this case our collection store and the
5772 associated system stores. */
5773 if (!CertCloseStore(hCollectionStore, CERT_CLOSE_STORE_FORCE_FLAG)) {
Christian Heimes46bebee2013-06-09 19:03:31 +02005774 /* This error case might shadow another exception.*/
Christian Heimes44109d72013-11-22 01:51:30 +01005775 Py_XDECREF(result);
5776 return PyErr_SetFromWindowsErr(GetLastError());
5777 }
kctherookied93fbbf2019-03-29 00:59:06 +07005778
Christian Heimes915cd3f2019-09-09 18:06:55 +02005779 /* convert set to list */
5780 if (result == NULL) {
5781 return NULL;
5782 } else {
5783 PyObject *lst = PySequence_List(result);
5784 Py_DECREF(result);
5785 return lst;
5786 }
Christian Heimes44109d72013-11-22 01:51:30 +01005787}
5788
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005789/*[clinic input]
5790_ssl.enum_crls
5791 store_name: str
5792
5793Retrieve CRLs from Windows' cert store.
5794
5795store_name may be one of 'CA', 'ROOT' or 'MY'. The system may provide
5796more cert storages, too. The function returns a list of (bytes,
5797encoding_type) tuples. The encoding_type flag can be interpreted with
5798X509_ASN_ENCODING or PKCS_7_ASN_ENCODING.
5799[clinic start generated code]*/
Christian Heimes44109d72013-11-22 01:51:30 +01005800
5801static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005802_ssl_enum_crls_impl(PyObject *module, const char *store_name)
5803/*[clinic end generated code: output=bce467f60ccd03b6 input=a1f1d7629f1c5d3d]*/
Christian Heimes44109d72013-11-22 01:51:30 +01005804{
kctherookied93fbbf2019-03-29 00:59:06 +07005805 HCERTSTORE hCollectionStore = NULL;
Christian Heimes44109d72013-11-22 01:51:30 +01005806 PCCRL_CONTEXT pCrlCtx = NULL;
5807 PyObject *crl = NULL, *enc = NULL, *tup = NULL;
5808 PyObject *result = NULL;
5809
Christian Heimes915cd3f2019-09-09 18:06:55 +02005810 result = PySet_New(NULL);
Christian Heimes44109d72013-11-22 01:51:30 +01005811 if (result == NULL) {
5812 return NULL;
5813 }
kctherookied93fbbf2019-03-29 00:59:06 +07005814 hCollectionStore = ssl_collect_certificates(store_name);
5815 if (hCollectionStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02005816 Py_DECREF(result);
5817 return PyErr_SetFromWindowsErr(GetLastError());
5818 }
Christian Heimes44109d72013-11-22 01:51:30 +01005819
kctherookied93fbbf2019-03-29 00:59:06 +07005820 while (pCrlCtx = CertEnumCRLsInStore(hCollectionStore, pCrlCtx)) {
Christian Heimes44109d72013-11-22 01:51:30 +01005821 crl = PyBytes_FromStringAndSize((const char*)pCrlCtx->pbCrlEncoded,
5822 pCrlCtx->cbCrlEncoded);
5823 if (!crl) {
5824 Py_CLEAR(result);
5825 break;
5826 }
5827 if ((enc = certEncodingType(pCrlCtx->dwCertEncodingType)) == NULL) {
5828 Py_CLEAR(result);
5829 break;
5830 }
5831 if ((tup = PyTuple_New(2)) == NULL) {
5832 Py_CLEAR(result);
5833 break;
5834 }
5835 PyTuple_SET_ITEM(tup, 0, crl);
5836 crl = NULL;
5837 PyTuple_SET_ITEM(tup, 1, enc);
5838 enc = NULL;
5839
Christian Heimes915cd3f2019-09-09 18:06:55 +02005840 if (PySet_Add(result, tup) == -1) {
5841 Py_CLEAR(result);
5842 Py_CLEAR(tup);
5843 break;
Christian Heimes44109d72013-11-22 01:51:30 +01005844 }
5845 Py_CLEAR(tup);
Christian Heimes46bebee2013-06-09 19:03:31 +02005846 }
Christian Heimes44109d72013-11-22 01:51:30 +01005847 if (pCrlCtx) {
5848 /* loop ended with an error, need to clean up context manually */
5849 CertFreeCRLContext(pCrlCtx);
5850 }
5851
5852 /* In error cases cert, enc and tup may not be NULL */
5853 Py_XDECREF(crl);
5854 Py_XDECREF(enc);
5855 Py_XDECREF(tup);
5856
kctherookied93fbbf2019-03-29 00:59:06 +07005857 /* CERT_CLOSE_STORE_FORCE_FLAG forces freeing of memory for all contexts
5858 associated with the store, in this case our collection store and the
5859 associated system stores. */
5860 if (!CertCloseStore(hCollectionStore, CERT_CLOSE_STORE_FORCE_FLAG)) {
Christian Heimes44109d72013-11-22 01:51:30 +01005861 /* This error case might shadow another exception.*/
5862 Py_XDECREF(result);
5863 return PyErr_SetFromWindowsErr(GetLastError());
5864 }
Christian Heimes915cd3f2019-09-09 18:06:55 +02005865 /* convert set to list */
5866 if (result == NULL) {
5867 return NULL;
5868 } else {
5869 PyObject *lst = PySequence_List(result);
5870 Py_DECREF(result);
5871 return lst;
5872 }
Christian Heimes46bebee2013-06-09 19:03:31 +02005873}
Christian Heimes44109d72013-11-22 01:51:30 +01005874
5875#endif /* _MSC_VER */
Bill Janssen40a0f662008-08-12 16:56:25 +00005876
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005877/* List of functions exported by this module. */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005878static PyMethodDef PySSL_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005879 _SSL__TEST_DECODE_CERT_METHODDEF
5880 _SSL_RAND_ADD_METHODDEF
5881 _SSL_RAND_BYTES_METHODDEF
5882 _SSL_RAND_PSEUDO_BYTES_METHODDEF
5883 _SSL_RAND_EGD_METHODDEF
5884 _SSL_RAND_STATUS_METHODDEF
5885 _SSL_GET_DEFAULT_VERIFY_PATHS_METHODDEF
5886 _SSL_ENUM_CERTIFICATES_METHODDEF
5887 _SSL_ENUM_CRLS_METHODDEF
5888 _SSL_TXT2OBJ_METHODDEF
5889 _SSL_NID2OBJ_METHODDEF
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005890 {NULL, NULL} /* Sentinel */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005891};
5892
5893
Christian Heimes598894f2016-09-05 23:19:05 +02005894#ifdef HAVE_OPENSSL_CRYPTO_LOCK
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005895
5896/* an implementation of OpenSSL threading operations in terms
Christian Heimes598894f2016-09-05 23:19:05 +02005897 * of the Python C thread library
5898 * Only used up to 1.0.2. OpenSSL 1.1.0+ has its own locking code.
5899 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005900
5901static PyThread_type_lock *_ssl_locks = NULL;
5902
Christian Heimes4d98ca92013-08-19 17:36:29 +02005903#if OPENSSL_VERSION_NUMBER >= 0x10000000
5904/* use new CRYPTO_THREADID API. */
5905static void
5906_ssl_threadid_callback(CRYPTO_THREADID *id)
5907{
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +02005908 CRYPTO_THREADID_set_numeric(id, PyThread_get_thread_ident());
Christian Heimes4d98ca92013-08-19 17:36:29 +02005909}
5910#else
5911/* deprecated CRYPTO_set_id_callback() API. */
5912static unsigned long
5913_ssl_thread_id_function (void) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005914 return PyThread_get_thread_ident();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005915}
Christian Heimes4d98ca92013-08-19 17:36:29 +02005916#endif
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005917
Bill Janssen6e027db2007-11-15 22:23:56 +00005918static void _ssl_thread_locking_function
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005919 (int mode, int n, const char *file, int line) {
5920 /* this function is needed to perform locking on shared data
5921 structures. (Note that OpenSSL uses a number of global data
5922 structures that will be implicitly shared whenever multiple
5923 threads use OpenSSL.) Multi-threaded applications will
5924 crash at random if it is not set.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005925
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005926 locking_function() must be able to handle up to
5927 CRYPTO_num_locks() different mutex locks. It sets the n-th
5928 lock if mode & CRYPTO_LOCK, and releases it otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005929
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005930 file and line are the file number of the function setting the
5931 lock. They can be useful for debugging.
5932 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005933
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005934 if ((_ssl_locks == NULL) ||
5935 (n < 0) || ((unsigned)n >= _ssl_locks_count))
5936 return;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005937
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005938 if (mode & CRYPTO_LOCK) {
5939 PyThread_acquire_lock(_ssl_locks[n], 1);
5940 } else {
5941 PyThread_release_lock(_ssl_locks[n]);
5942 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005943}
5944
5945static int _setup_ssl_threads(void) {
5946
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005947 unsigned int i;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005948
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005949 if (_ssl_locks == NULL) {
5950 _ssl_locks_count = CRYPTO_num_locks();
Christian Heimesf6365e32016-09-13 20:48:13 +02005951 _ssl_locks = PyMem_Calloc(_ssl_locks_count,
5952 sizeof(PyThread_type_lock));
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02005953 if (_ssl_locks == NULL) {
5954 PyErr_NoMemory();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005955 return 0;
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02005956 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005957 for (i = 0; i < _ssl_locks_count; i++) {
5958 _ssl_locks[i] = PyThread_allocate_lock();
5959 if (_ssl_locks[i] == NULL) {
5960 unsigned int j;
5961 for (j = 0; j < i; j++) {
5962 PyThread_free_lock(_ssl_locks[j]);
5963 }
Victor Stinnerb6404912013-07-07 16:21:41 +02005964 PyMem_Free(_ssl_locks);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005965 return 0;
5966 }
5967 }
5968 CRYPTO_set_locking_callback(_ssl_thread_locking_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02005969#if OPENSSL_VERSION_NUMBER >= 0x10000000
5970 CRYPTO_THREADID_set_callback(_ssl_threadid_callback);
5971#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005972 CRYPTO_set_id_callback(_ssl_thread_id_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02005973#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005974 }
5975 return 1;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005976}
5977
Antoine Pitroua6a4dc82017-09-07 18:56:24 +02005978#endif /* HAVE_OPENSSL_CRYPTO_LOCK for OpenSSL < 1.1.0 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005979
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005980PyDoc_STRVAR(module_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005981"Implementation module for SSL socket operations. See the socket module\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005982for documentation.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005983
Martin v. Löwis1a214512008-06-11 05:26:20 +00005984
5985static struct PyModuleDef _sslmodule = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005986 PyModuleDef_HEAD_INIT,
5987 "_ssl",
5988 module_doc,
5989 -1,
5990 PySSL_methods,
5991 NULL,
5992 NULL,
5993 NULL,
5994 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00005995};
5996
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02005997
5998static void
5999parse_openssl_version(unsigned long libver,
6000 unsigned int *major, unsigned int *minor,
6001 unsigned int *fix, unsigned int *patch,
6002 unsigned int *status)
6003{
6004 *status = libver & 0xF;
6005 libver >>= 4;
6006 *patch = libver & 0xFF;
6007 libver >>= 8;
6008 *fix = libver & 0xFF;
6009 libver >>= 8;
6010 *minor = libver & 0xFF;
6011 libver >>= 8;
6012 *major = libver & 0xFF;
6013}
6014
Mark Hammondfe51c6d2002-08-02 02:27:13 +00006015PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00006016PyInit__ssl(void)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00006017{
Christian Heimesb3ad0e52017-09-08 12:00:19 -07006018 PyObject *m, *d, *r, *bases;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006019 unsigned long libver;
6020 unsigned int major, minor, fix, patch, status;
6021 PySocketModule_APIObject *socket_api;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02006022 struct py_ssl_error_code *errcode;
6023 struct py_ssl_library_code *libcode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00006024
Antoine Pitrou152efa22010-05-16 18:19:27 +00006025 if (PyType_Ready(&PySSLContext_Type) < 0)
6026 return NULL;
6027 if (PyType_Ready(&PySSLSocket_Type) < 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006028 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02006029 if (PyType_Ready(&PySSLMemoryBIO_Type) < 0)
6030 return NULL;
Christian Heimes99a65702016-09-10 23:44:53 +02006031 if (PyType_Ready(&PySSLSession_Type) < 0)
6032 return NULL;
6033
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00006034
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006035 m = PyModule_Create(&_sslmodule);
6036 if (m == NULL)
6037 return NULL;
6038 d = PyModule_GetDict(m);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00006039
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006040 /* Load _socket module and its C API */
6041 socket_api = PySocketModule_ImportModuleAndAPI();
6042 if (!socket_api)
6043 return NULL;
6044 PySocketModule = *socket_api;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00006045
Christian Heimesc941e622017-09-05 15:47:11 +02006046#ifndef OPENSSL_VERSION_1_1
6047 /* Load all algorithms and initialize cpuid */
6048 OPENSSL_add_all_algorithms_noconf();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006049 /* Init OpenSSL */
6050 SSL_load_error_strings();
6051 SSL_library_init();
Christian Heimesc941e622017-09-05 15:47:11 +02006052#endif
6053
Christian Heimes598894f2016-09-05 23:19:05 +02006054#ifdef HAVE_OPENSSL_CRYPTO_LOCK
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006055 /* note that this will start threading if not already started */
6056 if (!_setup_ssl_threads()) {
6057 return NULL;
6058 }
Christian Heimesc087a262020-05-15 20:55:25 +02006059#elif OPENSSL_VERSION_1_1
Christian Heimes598894f2016-09-05 23:19:05 +02006060 /* OpenSSL 1.1.0 builtin thread support is enabled */
6061 _ssl_locks_count++;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00006062#endif
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00006063
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006064 /* Add symbols to module dict */
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02006065 sslerror_type_slots[0].pfunc = PyExc_OSError;
6066 PySSLErrorObject = PyType_FromSpec(&sslerror_type_spec);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006067 if (PySSLErrorObject == NULL)
6068 return NULL;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02006069
Christian Heimesb3ad0e52017-09-08 12:00:19 -07006070 /* ssl.CertificateError used to be a subclass of ValueError */
6071 bases = Py_BuildValue("OO", PySSLErrorObject, PyExc_ValueError);
6072 if (bases == NULL)
6073 return NULL;
6074 PySSLCertVerificationErrorObject = PyErr_NewExceptionWithDoc(
6075 "ssl.SSLCertVerificationError", SSLCertVerificationError_doc,
6076 bases, NULL);
6077 Py_DECREF(bases);
Antoine Pitrou41032a62011-10-27 23:56:55 +02006078 PySSLZeroReturnErrorObject = PyErr_NewExceptionWithDoc(
6079 "ssl.SSLZeroReturnError", SSLZeroReturnError_doc,
6080 PySSLErrorObject, NULL);
6081 PySSLWantReadErrorObject = PyErr_NewExceptionWithDoc(
6082 "ssl.SSLWantReadError", SSLWantReadError_doc,
6083 PySSLErrorObject, NULL);
6084 PySSLWantWriteErrorObject = PyErr_NewExceptionWithDoc(
6085 "ssl.SSLWantWriteError", SSLWantWriteError_doc,
6086 PySSLErrorObject, NULL);
6087 PySSLSyscallErrorObject = PyErr_NewExceptionWithDoc(
6088 "ssl.SSLSyscallError", SSLSyscallError_doc,
6089 PySSLErrorObject, NULL);
6090 PySSLEOFErrorObject = PyErr_NewExceptionWithDoc(
6091 "ssl.SSLEOFError", SSLEOFError_doc,
6092 PySSLErrorObject, NULL);
Christian Heimesb3ad0e52017-09-08 12:00:19 -07006093 if (PySSLCertVerificationErrorObject == NULL
6094 || PySSLZeroReturnErrorObject == NULL
Antoine Pitrou41032a62011-10-27 23:56:55 +02006095 || PySSLWantReadErrorObject == NULL
6096 || PySSLWantWriteErrorObject == NULL
6097 || PySSLSyscallErrorObject == NULL
6098 || PySSLEOFErrorObject == NULL)
6099 return NULL;
6100 if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0
Christian Heimesb3ad0e52017-09-08 12:00:19 -07006101 || PyDict_SetItemString(d, "SSLCertVerificationError",
6102 PySSLCertVerificationErrorObject) != 0
Antoine Pitrou41032a62011-10-27 23:56:55 +02006103 || PyDict_SetItemString(d, "SSLZeroReturnError", PySSLZeroReturnErrorObject) != 0
6104 || PyDict_SetItemString(d, "SSLWantReadError", PySSLWantReadErrorObject) != 0
6105 || PyDict_SetItemString(d, "SSLWantWriteError", PySSLWantWriteErrorObject) != 0
6106 || PyDict_SetItemString(d, "SSLSyscallError", PySSLSyscallErrorObject) != 0
6107 || PyDict_SetItemString(d, "SSLEOFError", PySSLEOFErrorObject) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006108 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00006109 if (PyDict_SetItemString(d, "_SSLContext",
6110 (PyObject *)&PySSLContext_Type) != 0)
6111 return NULL;
6112 if (PyDict_SetItemString(d, "_SSLSocket",
6113 (PyObject *)&PySSLSocket_Type) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006114 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02006115 if (PyDict_SetItemString(d, "MemoryBIO",
6116 (PyObject *)&PySSLMemoryBIO_Type) != 0)
6117 return NULL;
Christian Heimes99a65702016-09-10 23:44:53 +02006118 if (PyDict_SetItemString(d, "SSLSession",
6119 (PyObject *)&PySSLSession_Type) != 0)
6120 return NULL;
6121
Christian Heimes892d66e2018-01-29 14:10:18 +01006122 PyModule_AddStringConstant(m, "_DEFAULT_CIPHERS",
6123 PY_SSL_DEFAULT_CIPHER_STRING);
6124
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006125 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
6126 PY_SSL_ERROR_ZERO_RETURN);
6127 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
6128 PY_SSL_ERROR_WANT_READ);
6129 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
6130 PY_SSL_ERROR_WANT_WRITE);
6131 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
6132 PY_SSL_ERROR_WANT_X509_LOOKUP);
6133 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
6134 PY_SSL_ERROR_SYSCALL);
6135 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
6136 PY_SSL_ERROR_SSL);
6137 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
6138 PY_SSL_ERROR_WANT_CONNECT);
6139 /* non ssl.h errorcodes */
6140 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
6141 PY_SSL_ERROR_EOF);
6142 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
6143 PY_SSL_ERROR_INVALID_ERROR_CODE);
6144 /* cert requirements */
6145 PyModule_AddIntConstant(m, "CERT_NONE",
6146 PY_SSL_CERT_NONE);
6147 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
6148 PY_SSL_CERT_OPTIONAL);
6149 PyModule_AddIntConstant(m, "CERT_REQUIRED",
6150 PY_SSL_CERT_REQUIRED);
Christian Heimes22587792013-11-21 23:56:13 +01006151 /* CRL verification for verification_flags */
6152 PyModule_AddIntConstant(m, "VERIFY_DEFAULT",
6153 0);
6154 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_LEAF",
6155 X509_V_FLAG_CRL_CHECK);
6156 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_CHAIN",
6157 X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
6158 PyModule_AddIntConstant(m, "VERIFY_X509_STRICT",
6159 X509_V_FLAG_X509_STRICT);
Benjamin Peterson990fcaa2015-03-04 22:49:41 -05006160#ifdef X509_V_FLAG_TRUSTED_FIRST
6161 PyModule_AddIntConstant(m, "VERIFY_X509_TRUSTED_FIRST",
6162 X509_V_FLAG_TRUSTED_FIRST);
6163#endif
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00006164
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01006165 /* Alert Descriptions from ssl.h */
6166 /* note RESERVED constants no longer intended for use have been removed */
6167 /* http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-6 */
6168
6169#define ADD_AD_CONSTANT(s) \
6170 PyModule_AddIntConstant(m, "ALERT_DESCRIPTION_"#s, \
6171 SSL_AD_##s)
6172
6173 ADD_AD_CONSTANT(CLOSE_NOTIFY);
6174 ADD_AD_CONSTANT(UNEXPECTED_MESSAGE);
6175 ADD_AD_CONSTANT(BAD_RECORD_MAC);
6176 ADD_AD_CONSTANT(RECORD_OVERFLOW);
6177 ADD_AD_CONSTANT(DECOMPRESSION_FAILURE);
6178 ADD_AD_CONSTANT(HANDSHAKE_FAILURE);
6179 ADD_AD_CONSTANT(BAD_CERTIFICATE);
6180 ADD_AD_CONSTANT(UNSUPPORTED_CERTIFICATE);
6181 ADD_AD_CONSTANT(CERTIFICATE_REVOKED);
6182 ADD_AD_CONSTANT(CERTIFICATE_EXPIRED);
6183 ADD_AD_CONSTANT(CERTIFICATE_UNKNOWN);
6184 ADD_AD_CONSTANT(ILLEGAL_PARAMETER);
6185 ADD_AD_CONSTANT(UNKNOWN_CA);
6186 ADD_AD_CONSTANT(ACCESS_DENIED);
6187 ADD_AD_CONSTANT(DECODE_ERROR);
6188 ADD_AD_CONSTANT(DECRYPT_ERROR);
6189 ADD_AD_CONSTANT(PROTOCOL_VERSION);
6190 ADD_AD_CONSTANT(INSUFFICIENT_SECURITY);
6191 ADD_AD_CONSTANT(INTERNAL_ERROR);
6192 ADD_AD_CONSTANT(USER_CANCELLED);
6193 ADD_AD_CONSTANT(NO_RENEGOTIATION);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01006194 /* Not all constants are in old OpenSSL versions */
Antoine Pitrou912fbff2013-03-30 16:29:32 +01006195#ifdef SSL_AD_UNSUPPORTED_EXTENSION
6196 ADD_AD_CONSTANT(UNSUPPORTED_EXTENSION);
6197#endif
6198#ifdef SSL_AD_CERTIFICATE_UNOBTAINABLE
6199 ADD_AD_CONSTANT(CERTIFICATE_UNOBTAINABLE);
6200#endif
6201#ifdef SSL_AD_UNRECOGNIZED_NAME
6202 ADD_AD_CONSTANT(UNRECOGNIZED_NAME);
6203#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01006204#ifdef SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE
6205 ADD_AD_CONSTANT(BAD_CERTIFICATE_STATUS_RESPONSE);
6206#endif
6207#ifdef SSL_AD_BAD_CERTIFICATE_HASH_VALUE
6208 ADD_AD_CONSTANT(BAD_CERTIFICATE_HASH_VALUE);
6209#endif
6210#ifdef SSL_AD_UNKNOWN_PSK_IDENTITY
6211 ADD_AD_CONSTANT(UNKNOWN_PSK_IDENTITY);
6212#endif
6213
6214#undef ADD_AD_CONSTANT
6215
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006216 /* protocol versions */
Victor Stinner3de49192011-05-09 00:42:58 +02006217#ifndef OPENSSL_NO_SSL2
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006218 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
6219 PY_SSL_VERSION_SSL2);
Victor Stinner3de49192011-05-09 00:42:58 +02006220#endif
Benjamin Petersone32467c2014-12-05 21:59:35 -05006221#ifndef OPENSSL_NO_SSL3
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006222 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
6223 PY_SSL_VERSION_SSL3);
Benjamin Petersone32467c2014-12-05 21:59:35 -05006224#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006225 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
Christian Heimes598894f2016-09-05 23:19:05 +02006226 PY_SSL_VERSION_TLS);
6227 PyModule_AddIntConstant(m, "PROTOCOL_TLS",
6228 PY_SSL_VERSION_TLS);
Christian Heimes5fe668c2016-09-12 00:01:11 +02006229 PyModule_AddIntConstant(m, "PROTOCOL_TLS_CLIENT",
6230 PY_SSL_VERSION_TLS_CLIENT);
6231 PyModule_AddIntConstant(m, "PROTOCOL_TLS_SERVER",
6232 PY_SSL_VERSION_TLS_SERVER);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006233 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
6234 PY_SSL_VERSION_TLS1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01006235 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_1",
6236 PY_SSL_VERSION_TLS1_1);
6237 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_2",
6238 PY_SSL_VERSION_TLS1_2);
Antoine Pitrou04f6a322010-04-05 21:40:07 +00006239
Antoine Pitroub5218772010-05-21 09:56:06 +00006240 /* protocol options */
Antoine Pitrou3f366312012-01-27 09:50:45 +01006241 PyModule_AddIntConstant(m, "OP_ALL",
6242 SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
Antoine Pitroub5218772010-05-21 09:56:06 +00006243 PyModule_AddIntConstant(m, "OP_NO_SSLv2", SSL_OP_NO_SSLv2);
6244 PyModule_AddIntConstant(m, "OP_NO_SSLv3", SSL_OP_NO_SSLv3);
6245 PyModule_AddIntConstant(m, "OP_NO_TLSv1", SSL_OP_NO_TLSv1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01006246 PyModule_AddIntConstant(m, "OP_NO_TLSv1_1", SSL_OP_NO_TLSv1_1);
6247 PyModule_AddIntConstant(m, "OP_NO_TLSv1_2", SSL_OP_NO_TLSv1_2);
Christian Heimescb5b68a2017-09-07 18:07:00 -07006248#ifdef SSL_OP_NO_TLSv1_3
6249 PyModule_AddIntConstant(m, "OP_NO_TLSv1_3", SSL_OP_NO_TLSv1_3);
6250#else
6251 PyModule_AddIntConstant(m, "OP_NO_TLSv1_3", 0);
6252#endif
Antoine Pitrou6db49442011-12-19 13:27:11 +01006253 PyModule_AddIntConstant(m, "OP_CIPHER_SERVER_PREFERENCE",
6254 SSL_OP_CIPHER_SERVER_PREFERENCE);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01006255 PyModule_AddIntConstant(m, "OP_SINGLE_DH_USE", SSL_OP_SINGLE_DH_USE);
Christian Heimes99a65702016-09-10 23:44:53 +02006256 PyModule_AddIntConstant(m, "OP_NO_TICKET", SSL_OP_NO_TICKET);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01006257#ifdef SSL_OP_SINGLE_ECDH_USE
Antoine Pitrou923df6f2011-12-19 17:16:51 +01006258 PyModule_AddIntConstant(m, "OP_SINGLE_ECDH_USE", SSL_OP_SINGLE_ECDH_USE);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01006259#endif
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01006260#ifdef SSL_OP_NO_COMPRESSION
6261 PyModule_AddIntConstant(m, "OP_NO_COMPRESSION",
6262 SSL_OP_NO_COMPRESSION);
6263#endif
Christian Heimes05d9fe32018-02-27 08:55:39 +01006264#ifdef SSL_OP_ENABLE_MIDDLEBOX_COMPAT
6265 PyModule_AddIntConstant(m, "OP_ENABLE_MIDDLEBOX_COMPAT",
6266 SSL_OP_ENABLE_MIDDLEBOX_COMPAT);
6267#endif
Christian Heimes67c48012018-05-15 16:25:40 -04006268#ifdef SSL_OP_NO_RENEGOTIATION
6269 PyModule_AddIntConstant(m, "OP_NO_RENEGOTIATION",
6270 SSL_OP_NO_RENEGOTIATION);
6271#endif
Antoine Pitroub5218772010-05-21 09:56:06 +00006272
Christian Heimes61d478c2018-01-27 15:51:38 +01006273#ifdef X509_CHECK_FLAG_ALWAYS_CHECK_SUBJECT
6274 PyModule_AddIntConstant(m, "HOSTFLAG_ALWAYS_CHECK_SUBJECT",
6275 X509_CHECK_FLAG_ALWAYS_CHECK_SUBJECT);
6276#endif
6277#ifdef X509_CHECK_FLAG_NEVER_CHECK_SUBJECT
6278 PyModule_AddIntConstant(m, "HOSTFLAG_NEVER_CHECK_SUBJECT",
6279 X509_CHECK_FLAG_NEVER_CHECK_SUBJECT);
6280#endif
6281#ifdef X509_CHECK_FLAG_NO_WILDCARDS
6282 PyModule_AddIntConstant(m, "HOSTFLAG_NO_WILDCARDS",
6283 X509_CHECK_FLAG_NO_WILDCARDS);
6284#endif
6285#ifdef X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS
6286 PyModule_AddIntConstant(m, "HOSTFLAG_NO_PARTIAL_WILDCARDS",
6287 X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS);
6288#endif
6289#ifdef X509_CHECK_FLAG_MULTI_LABEL_WILDCARDS
6290 PyModule_AddIntConstant(m, "HOSTFLAG_MULTI_LABEL_WILDCARDS",
6291 X509_CHECK_FLAG_MULTI_LABEL_WILDCARDS);
6292#endif
6293#ifdef X509_CHECK_FLAG_SINGLE_LABEL_SUBDOMAINS
6294 PyModule_AddIntConstant(m, "HOSTFLAG_SINGLE_LABEL_SUBDOMAINS",
6295 X509_CHECK_FLAG_SINGLE_LABEL_SUBDOMAINS);
6296#endif
6297
Christian Heimes698dde12018-02-27 11:54:43 +01006298 /* protocol versions */
6299 PyModule_AddIntConstant(m, "PROTO_MINIMUM_SUPPORTED",
6300 PY_PROTO_MINIMUM_SUPPORTED);
6301 PyModule_AddIntConstant(m, "PROTO_MAXIMUM_SUPPORTED",
6302 PY_PROTO_MAXIMUM_SUPPORTED);
6303 PyModule_AddIntConstant(m, "PROTO_SSLv3", PY_PROTO_SSLv3);
6304 PyModule_AddIntConstant(m, "PROTO_TLSv1", PY_PROTO_TLSv1);
6305 PyModule_AddIntConstant(m, "PROTO_TLSv1_1", PY_PROTO_TLSv1_1);
6306 PyModule_AddIntConstant(m, "PROTO_TLSv1_2", PY_PROTO_TLSv1_2);
6307 PyModule_AddIntConstant(m, "PROTO_TLSv1_3", PY_PROTO_TLSv1_3);
Antoine Pitroud5323212010-10-22 18:19:07 +00006308
Victor Stinnerb37672d2018-11-22 03:37:50 +01006309#define addbool(m, key, value) \
6310 do { \
6311 PyObject *bool_obj = (value) ? Py_True : Py_False; \
6312 Py_INCREF(bool_obj); \
6313 PyModule_AddObject((m), (key), bool_obj); \
6314 } while (0)
Christian Heimes698dde12018-02-27 11:54:43 +01006315
6316#if HAVE_SNI
6317 addbool(m, "HAS_SNI", 1);
Antoine Pitrou501da612011-12-21 09:27:41 +01006318#else
Christian Heimes698dde12018-02-27 11:54:43 +01006319 addbool(m, "HAS_SNI", 0);
Antoine Pitrou501da612011-12-21 09:27:41 +01006320#endif
Christian Heimes698dde12018-02-27 11:54:43 +01006321
6322 addbool(m, "HAS_TLS_UNIQUE", 1);
6323
6324#ifndef OPENSSL_NO_ECDH
6325 addbool(m, "HAS_ECDH", 1);
6326#else
6327 addbool(m, "HAS_ECDH", 0);
6328#endif
Antoine Pitrou501da612011-12-21 09:27:41 +01006329
Christian Heimes29eab552018-02-25 12:31:33 +01006330#if HAVE_NPN
Christian Heimes698dde12018-02-27 11:54:43 +01006331 addbool(m, "HAS_NPN", 1);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01006332#else
Christian Heimes698dde12018-02-27 11:54:43 +01006333 addbool(m, "HAS_NPN", 0);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01006334#endif
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01006335
Christian Heimes29eab552018-02-25 12:31:33 +01006336#if HAVE_ALPN
Christian Heimes698dde12018-02-27 11:54:43 +01006337 addbool(m, "HAS_ALPN", 1);
Benjamin Petersoncca27322015-01-23 16:35:37 -05006338#else
Christian Heimes698dde12018-02-27 11:54:43 +01006339 addbool(m, "HAS_ALPN", 0);
Benjamin Petersoncca27322015-01-23 16:35:37 -05006340#endif
Christian Heimes698dde12018-02-27 11:54:43 +01006341
6342#if defined(SSL2_VERSION) && !defined(OPENSSL_NO_SSL2)
6343 addbool(m, "HAS_SSLv2", 1);
6344#else
6345 addbool(m, "HAS_SSLv2", 0);
6346#endif
6347
6348#if defined(SSL3_VERSION) && !defined(OPENSSL_NO_SSL3)
6349 addbool(m, "HAS_SSLv3", 1);
6350#else
6351 addbool(m, "HAS_SSLv3", 0);
6352#endif
6353
6354#if defined(TLS1_VERSION) && !defined(OPENSSL_NO_TLS1)
6355 addbool(m, "HAS_TLSv1", 1);
6356#else
6357 addbool(m, "HAS_TLSv1", 0);
6358#endif
6359
6360#if defined(TLS1_1_VERSION) && !defined(OPENSSL_NO_TLS1_1)
6361 addbool(m, "HAS_TLSv1_1", 1);
6362#else
6363 addbool(m, "HAS_TLSv1_1", 0);
6364#endif
6365
6366#if defined(TLS1_2_VERSION) && !defined(OPENSSL_NO_TLS1_2)
6367 addbool(m, "HAS_TLSv1_2", 1);
6368#else
6369 addbool(m, "HAS_TLSv1_2", 0);
6370#endif
Benjamin Petersoncca27322015-01-23 16:35:37 -05006371
Christian Heimescb5b68a2017-09-07 18:07:00 -07006372#if defined(TLS1_3_VERSION) && !defined(OPENSSL_NO_TLS1_3)
Christian Heimes698dde12018-02-27 11:54:43 +01006373 addbool(m, "HAS_TLSv1_3", 1);
Christian Heimescb5b68a2017-09-07 18:07:00 -07006374#else
Christian Heimes698dde12018-02-27 11:54:43 +01006375 addbool(m, "HAS_TLSv1_3", 0);
Christian Heimescb5b68a2017-09-07 18:07:00 -07006376#endif
Christian Heimescb5b68a2017-09-07 18:07:00 -07006377
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02006378 /* Mappings for error codes */
6379 err_codes_to_names = PyDict_New();
6380 err_names_to_codes = PyDict_New();
6381 if (err_codes_to_names == NULL || err_names_to_codes == NULL)
6382 return NULL;
6383 errcode = error_codes;
6384 while (errcode->mnemonic != NULL) {
6385 PyObject *mnemo, *key;
6386 mnemo = PyUnicode_FromString(errcode->mnemonic);
6387 key = Py_BuildValue("ii", errcode->library, errcode->reason);
6388 if (mnemo == NULL || key == NULL)
6389 return NULL;
6390 if (PyDict_SetItem(err_codes_to_names, key, mnemo))
6391 return NULL;
6392 if (PyDict_SetItem(err_names_to_codes, mnemo, key))
6393 return NULL;
6394 Py_DECREF(key);
6395 Py_DECREF(mnemo);
6396 errcode++;
6397 }
6398 if (PyModule_AddObject(m, "err_codes_to_names", err_codes_to_names))
6399 return NULL;
6400 if (PyModule_AddObject(m, "err_names_to_codes", err_names_to_codes))
6401 return NULL;
6402
6403 lib_codes_to_names = PyDict_New();
6404 if (lib_codes_to_names == NULL)
6405 return NULL;
6406 libcode = library_codes;
6407 while (libcode->library != NULL) {
6408 PyObject *mnemo, *key;
6409 key = PyLong_FromLong(libcode->code);
6410 mnemo = PyUnicode_FromString(libcode->library);
6411 if (key == NULL || mnemo == NULL)
6412 return NULL;
6413 if (PyDict_SetItem(lib_codes_to_names, key, mnemo))
6414 return NULL;
6415 Py_DECREF(key);
6416 Py_DECREF(mnemo);
6417 libcode++;
6418 }
6419 if (PyModule_AddObject(m, "lib_codes_to_names", lib_codes_to_names))
6420 return NULL;
Victor Stinner4569cd52013-06-23 14:58:43 +02006421
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006422 /* OpenSSL version */
6423 /* SSLeay() gives us the version of the library linked against,
6424 which could be different from the headers version.
6425 */
Christian Heimesa871f692020-06-01 08:58:14 +02006426 libver = OpenSSL_version_num();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006427 r = PyLong_FromUnsignedLong(libver);
6428 if (r == NULL)
6429 return NULL;
6430 if (PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r))
6431 return NULL;
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02006432 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006433 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
6434 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r))
6435 return NULL;
Christian Heimesa871f692020-06-01 08:58:14 +02006436 r = PyUnicode_FromString(OpenSSL_version(OPENSSL_VERSION));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006437 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r))
6438 return NULL;
Antoine Pitrou04f6a322010-04-05 21:40:07 +00006439
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02006440 libver = OPENSSL_VERSION_NUMBER;
6441 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
6442 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
6443 if (r == NULL || PyModule_AddObject(m, "_OPENSSL_API_VERSION", r))
6444 return NULL;
6445
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006446 return m;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00006447}