blob: cb8f04a900a06e8de9b467ad63bdb1eac03e8c63 [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 }
Dima Tisnek495bd032020-08-16 02:01:19 +0900808 else {
809 p = PY_SSL_ERROR_EOF;
810 type = PySSLEOFErrorObject;
811 errstr = "EOF occurred in violation of protocol";
812 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000813 } else { /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000814 p = PY_SSL_ERROR_SYSCALL;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200815 type = PySSLSyscallErrorObject;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000816 errstr = "Some I/O error occurred";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000817 }
818 } else {
819 p = PY_SSL_ERROR_SYSCALL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000820 }
821 break;
822 }
823 case SSL_ERROR_SSL:
824 {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000825 p = PY_SSL_ERROR_SSL;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700826 if (e == 0) {
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200827 /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000828 errstr = "A failure in the SSL library occurred";
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700829 }
830 if (ERR_GET_LIB(e) == ERR_LIB_SSL &&
831 ERR_GET_REASON(e) == SSL_R_CERTIFICATE_VERIFY_FAILED) {
832 type = PySSLCertVerificationErrorObject;
833 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000834 break;
835 }
836 default:
837 p = PY_SSL_ERROR_INVALID_ERROR_CODE;
838 errstr = "Invalid error code";
839 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000840 }
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700841 fill_and_set_sslerror(sslsock, type, p, errstr, lineno, e);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000842 ERR_clear_error();
Christian Heimesc7f70692019-05-31 11:44:05 +0200843 PySSL_ChainExceptions(sslsock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000844 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000845}
846
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000847static PyObject *
Serhiy Storchakaef1585e2015-12-25 20:01:53 +0200848_setSSLError (const char *errstr, int errcode, const char *filename, int lineno) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000849
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200850 if (errstr == NULL)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000851 errcode = ERR_peek_last_error();
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200852 else
853 errcode = 0;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700854 fill_and_set_sslerror(NULL, PySSLErrorObject, errcode, errstr, lineno, errcode);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000855 ERR_clear_error();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000856 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000857}
858
Christian Heimes61d478c2018-01-27 15:51:38 +0100859/*
860 * SSL objects
861 */
862
863static int
864_ssl_configure_hostname(PySSLSocket *self, const char* server_hostname)
865{
866 int retval = -1;
867 ASN1_OCTET_STRING *ip;
868 PyObject *hostname;
869 size_t len;
870
871 assert(server_hostname);
872
873 /* Disable OpenSSL's special mode with leading dot in hostname:
874 * When name starts with a dot (e.g ".example.com"), it will be
875 * matched by a certificate valid for any sub-domain of name.
876 */
877 len = strlen(server_hostname);
878 if (len == 0 || *server_hostname == '.') {
879 PyErr_SetString(
880 PyExc_ValueError,
881 "server_hostname cannot be an empty string or start with a "
882 "leading dot.");
883 return retval;
884 }
885
886 /* inet_pton is not available on all platforms. */
887 ip = a2i_IPADDRESS(server_hostname);
888 if (ip == NULL) {
889 ERR_clear_error();
890 }
891
Christian Heimes11a14932018-02-24 02:35:08 +0100892 hostname = PyUnicode_Decode(server_hostname, len, "ascii", "strict");
Christian Heimes61d478c2018-01-27 15:51:38 +0100893 if (hostname == NULL) {
894 goto error;
895 }
896 self->server_hostname = hostname;
897
898 /* Only send SNI extension for non-IP hostnames */
899 if (ip == NULL) {
900 if (!SSL_set_tlsext_host_name(self->ssl, server_hostname)) {
901 _setSSLError(NULL, 0, __FILE__, __LINE__);
902 }
903 }
904 if (self->ctx->check_hostname) {
905 X509_VERIFY_PARAM *param = SSL_get0_param(self->ssl);
906 if (ip == NULL) {
Christian Heimesd02ac252018-03-25 12:36:13 +0200907 if (!X509_VERIFY_PARAM_set1_host(param, server_hostname,
908 strlen(server_hostname))) {
Christian Heimes61d478c2018-01-27 15:51:38 +0100909 _setSSLError(NULL, 0, __FILE__, __LINE__);
910 goto error;
911 }
912 } else {
Christian Heimesa871f692020-06-01 08:58:14 +0200913 if (!X509_VERIFY_PARAM_set1_ip(param, ASN1_STRING_get0_data(ip),
Christian Heimes61d478c2018-01-27 15:51:38 +0100914 ASN1_STRING_length(ip))) {
915 _setSSLError(NULL, 0, __FILE__, __LINE__);
916 goto error;
917 }
918 }
919 }
920 retval = 0;
921 error:
922 if (ip != NULL) {
923 ASN1_OCTET_STRING_free(ip);
924 }
925 return retval;
926}
927
Antoine Pitrou152efa22010-05-16 18:19:27 +0000928static PySSLSocket *
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100929newPySSLSocket(PySSLContext *sslctx, PySocketSockObject *sock,
Antoine Pitroud5323212010-10-22 18:19:07 +0000930 enum py_ssl_server_or_client socket_type,
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200931 char *server_hostname,
Christian Heimes141c5e82018-02-24 21:10:57 +0100932 PyObject *owner, PyObject *session,
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200933 PySSLMemoryBIO *inbio, PySSLMemoryBIO *outbio)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000934{
Antoine Pitrou152efa22010-05-16 18:19:27 +0000935 PySSLSocket *self;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100936 SSL_CTX *ctx = sslctx->ctx;
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700937 _PySSLError err = { 0 };
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000938
Antoine Pitrou152efa22010-05-16 18:19:27 +0000939 self = PyObject_New(PySSLSocket, &PySSLSocket_Type);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000940 if (self == NULL)
941 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000942
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000943 self->ssl = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000944 self->Socket = NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100945 self->ctx = sslctx;
Nathaniel J. Smith65ece7c2017-06-07 23:30:43 -0700946 Py_INCREF(sslctx);
Antoine Pitrou860aee72013-09-29 19:52:45 +0200947 self->shutdown_seen_zero = 0;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200948 self->owner = NULL;
Benjamin Peterson81b9ecd2016-08-15 21:55:37 -0700949 self->server_hostname = NULL;
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700950 self->err = err;
Christian Heimesc7f70692019-05-31 11:44:05 +0200951 self->exc_type = NULL;
952 self->exc_value = NULL;
953 self->exc_tb = NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200954
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000955 /* Make sure the SSL error state is initialized */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000956 ERR_clear_error();
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000957
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000958 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitrou152efa22010-05-16 18:19:27 +0000959 self->ssl = SSL_new(ctx);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000960 PySSL_END_ALLOW_THREADS
Zackery Spytz4c49da02018-12-07 03:11:30 -0700961 if (self->ssl == NULL) {
962 Py_DECREF(self);
963 _setSSLError(NULL, 0, __FILE__, __LINE__);
964 return NULL;
965 }
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200966 SSL_set_app_data(self->ssl, self);
967 if (sock) {
968 SSL_set_fd(self->ssl, Py_SAFE_DOWNCAST(sock->sock_fd, SOCKET_T, int));
969 } else {
970 /* BIOs are reference counted and SSL_set_bio borrows our reference.
971 * To prevent a double free in memory_bio_dealloc() we need to take an
972 * extra reference here. */
Christian Heimes598894f2016-09-05 23:19:05 +0200973 BIO_up_ref(inbio->bio);
974 BIO_up_ref(outbio->bio);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200975 SSL_set_bio(self->ssl, inbio->bio, outbio->bio);
976 }
Alex Gaynorf0422422018-05-14 11:51:45 -0400977 SSL_set_mode(self->ssl,
978 SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER | SSL_MODE_AUTO_RETRY);
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000979
Christian Heimesf0f59302019-07-01 08:29:17 +0200980#ifdef TLS1_3_VERSION
981 if (sslctx->post_handshake_auth == 1) {
982 if (socket_type == PY_SSL_SERVER) {
983 /* bpo-37428: OpenSSL does not ignore SSL_VERIFY_POST_HANDSHAKE.
984 * Set SSL_VERIFY_POST_HANDSHAKE flag only for server sockets and
985 * only in combination with SSL_VERIFY_PEER flag. */
986 int mode = SSL_get_verify_mode(self->ssl);
987 if (mode & SSL_VERIFY_PEER) {
988 int (*verify_cb)(int, X509_STORE_CTX *) = NULL;
989 verify_cb = SSL_get_verify_callback(self->ssl);
990 mode |= SSL_VERIFY_POST_HANDSHAKE;
991 SSL_set_verify(self->ssl, mode, verify_cb);
992 }
993 } else {
994 /* client socket */
995 SSL_set_post_handshake_auth(self->ssl, 1);
996 }
997 }
998#endif
999
Christian Heimes61d478c2018-01-27 15:51:38 +01001000 if (server_hostname != NULL) {
1001 if (_ssl_configure_hostname(self, server_hostname) < 0) {
1002 Py_DECREF(self);
1003 return NULL;
1004 }
1005 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001006 /* If the socket is in non-blocking mode or timeout mode, set the BIO
1007 * to non-blocking mode (blocking is the default)
1008 */
Victor Stinnere2452312015-03-28 03:00:46 +01001009 if (sock && sock->sock_timeout >= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001010 BIO_set_nbio(SSL_get_rbio(self->ssl), 1);
1011 BIO_set_nbio(SSL_get_wbio(self->ssl), 1);
1012 }
Guido van Rossum4f707ac2003-01-31 18:13:18 +00001013
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001014 PySSL_BEGIN_ALLOW_THREADS
1015 if (socket_type == PY_SSL_CLIENT)
1016 SSL_set_connect_state(self->ssl);
1017 else
1018 SSL_set_accept_state(self->ssl);
1019 PySSL_END_ALLOW_THREADS
Martin v. Löwis09c35f72002-07-28 09:57:45 +00001020
Antoine Pitroud6494802011-07-21 01:11:30 +02001021 self->socket_type = socket_type;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001022 if (sock != NULL) {
1023 self->Socket = PyWeakref_NewRef((PyObject *) sock, NULL);
1024 if (self->Socket == NULL) {
1025 Py_DECREF(self);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001026 return NULL;
1027 }
Victor Stinnera9eb38f2013-10-31 16:35:38 +01001028 }
Christian Heimes141c5e82018-02-24 21:10:57 +01001029 if (owner && owner != Py_None) {
1030 if (PySSL_set_owner(self, owner, NULL) == -1) {
1031 Py_DECREF(self);
1032 return NULL;
1033 }
1034 }
1035 if (session && session != Py_None) {
1036 if (PySSL_set_session(self, session, NULL) == -1) {
1037 Py_DECREF(self);
1038 return NULL;
1039 }
1040 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001041 return self;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001042}
1043
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001044/* SSL object methods */
1045
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001046/*[clinic input]
1047_ssl._SSLSocket.do_handshake
1048[clinic start generated code]*/
1049
1050static PyObject *
1051_ssl__SSLSocket_do_handshake_impl(PySSLSocket *self)
1052/*[clinic end generated code: output=6c0898a8936548f6 input=d2d737de3df018c8]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001053{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001054 int ret;
Steve Dowerc6fd1c12018-09-17 11:34:47 -07001055 _PySSLError err;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001056 int sockstate, nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001057 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02001058 _PyTime_t timeout, deadline = 0;
1059 int has_timeout;
Antoine Pitroud3f8ab82010-04-24 21:26:44 +00001060
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001061 if (sock) {
1062 if (((PyObject*)sock) == Py_None) {
1063 _setSSLError("Underlying socket connection gone",
1064 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1065 return NULL;
1066 }
1067 Py_INCREF(sock);
1068
1069 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01001070 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001071 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1072 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001073 }
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001074
Victor Stinner14690702015-04-06 22:46:13 +02001075 timeout = GET_SOCKET_TIMEOUT(sock);
1076 has_timeout = (timeout > 0);
1077 if (has_timeout)
1078 deadline = _PyTime_GetMonotonicClock() + timeout;
1079
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001080 /* Actually negotiate SSL connection */
1081 /* XXX If SSL_do_handshake() returns 0, it's also a failure. */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001082 do {
Bill Janssen6e027db2007-11-15 22:23:56 +00001083 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001084 ret = SSL_do_handshake(self->ssl);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07001085 err = _PySSL_errno(ret < 1, self->ssl, ret);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001086 PySSL_END_ALLOW_THREADS
Steve Dowerc6fd1c12018-09-17 11:34:47 -07001087 self->err = err;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001088
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001089 if (PyErr_CheckSignals())
1090 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001091
Victor Stinner14690702015-04-06 22:46:13 +02001092 if (has_timeout)
1093 timeout = deadline - _PyTime_GetMonotonicClock();
1094
Steve Dowerc6fd1c12018-09-17 11:34:47 -07001095 if (err.ssl == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +02001096 sockstate = PySSL_select(sock, 0, timeout);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07001097 } else if (err.ssl == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +02001098 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001099 } else {
1100 sockstate = SOCKET_OPERATION_OK;
1101 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001102
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001103 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001104 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitrou525807b2010-05-12 14:05:24 +00001105 ERRSTR("The handshake operation timed out"));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001106 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001107 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1108 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +00001109 ERRSTR("Underlying socket has been closed."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001110 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001111 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1112 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +00001113 ERRSTR("Underlying socket too large for select()."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001114 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001115 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1116 break;
1117 }
Steve Dowerc6fd1c12018-09-17 11:34:47 -07001118 } while (err.ssl == SSL_ERROR_WANT_READ ||
1119 err.ssl == SSL_ERROR_WANT_WRITE);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001120 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001121 if (ret < 1)
1122 return PySSL_SetError(self, ret, __FILE__, __LINE__);
Christian Heimesc7f70692019-05-31 11:44:05 +02001123 if (PySSL_ChainExceptions(self) < 0)
1124 return NULL;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001125 Py_RETURN_NONE;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001126error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001127 Py_XDECREF(sock);
Christian Heimesc7f70692019-05-31 11:44:05 +02001128 PySSL_ChainExceptions(self);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001129 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001130}
1131
Thomas Woutersed03b412007-08-28 21:37:11 +00001132static PyObject *
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001133_asn1obj2py(const ASN1_OBJECT *name, int no_name)
1134{
1135 char buf[X509_NAME_MAXLEN];
1136 char *namebuf = buf;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001137 int buflen;
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001138 PyObject *name_obj = NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001139
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001140 buflen = OBJ_obj2txt(namebuf, X509_NAME_MAXLEN, name, no_name);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001141 if (buflen < 0) {
1142 _setSSLError(NULL, 0, __FILE__, __LINE__);
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001143 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001144 }
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001145 /* initial buffer is too small for oid + terminating null byte */
1146 if (buflen > X509_NAME_MAXLEN - 1) {
1147 /* make OBJ_obj2txt() calculate the required buflen */
1148 buflen = OBJ_obj2txt(NULL, 0, name, no_name);
1149 /* allocate len + 1 for terminating NULL byte */
1150 namebuf = PyMem_Malloc(buflen + 1);
1151 if (namebuf == NULL) {
1152 PyErr_NoMemory();
1153 return NULL;
1154 }
1155 buflen = OBJ_obj2txt(namebuf, buflen + 1, name, no_name);
1156 if (buflen < 0) {
1157 _setSSLError(NULL, 0, __FILE__, __LINE__);
1158 goto done;
1159 }
1160 }
1161 if (!buflen && no_name) {
1162 Py_INCREF(Py_None);
1163 name_obj = Py_None;
1164 }
1165 else {
1166 name_obj = PyUnicode_FromStringAndSize(namebuf, buflen);
1167 }
1168
1169 done:
1170 if (buf != namebuf) {
1171 PyMem_Free(namebuf);
1172 }
1173 return name_obj;
1174}
1175
1176static PyObject *
1177_create_tuple_for_attribute(ASN1_OBJECT *name, ASN1_STRING *value)
1178{
1179 Py_ssize_t buflen;
1180 unsigned char *valuebuf = NULL;
1181 PyObject *attr;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001182
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001183 buflen = ASN1_STRING_to_UTF8(&valuebuf, value);
1184 if (buflen < 0) {
1185 _setSSLError(NULL, 0, __FILE__, __LINE__);
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001186 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001187 }
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001188 attr = Py_BuildValue("Ns#", _asn1obj2py(name, 0), valuebuf, buflen);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001189 OPENSSL_free(valuebuf);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001190 return attr;
Thomas Woutersed03b412007-08-28 21:37:11 +00001191}
1192
1193static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001194_create_tuple_for_X509_NAME (X509_NAME *xname)
Thomas Woutersed03b412007-08-28 21:37:11 +00001195{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001196 PyObject *dn = NULL; /* tuple which represents the "distinguished name" */
1197 PyObject *rdn = NULL; /* tuple to hold a "relative distinguished name" */
1198 PyObject *rdnt;
1199 PyObject *attr = NULL; /* tuple to hold an attribute */
1200 int entry_count = X509_NAME_entry_count(xname);
1201 X509_NAME_ENTRY *entry;
1202 ASN1_OBJECT *name;
1203 ASN1_STRING *value;
1204 int index_counter;
1205 int rdn_level = -1;
1206 int retcode;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001207
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001208 dn = PyList_New(0);
1209 if (dn == NULL)
1210 return NULL;
1211 /* now create another tuple to hold the top-level RDN */
1212 rdn = PyList_New(0);
1213 if (rdn == NULL)
1214 goto fail0;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001215
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001216 for (index_counter = 0;
1217 index_counter < entry_count;
1218 index_counter++)
1219 {
1220 entry = X509_NAME_get_entry(xname, index_counter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001221
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001222 /* check to see if we've gotten to a new RDN */
1223 if (rdn_level >= 0) {
Christian Heimes598894f2016-09-05 23:19:05 +02001224 if (rdn_level != X509_NAME_ENTRY_set(entry)) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001225 /* yes, new RDN */
1226 /* add old RDN to DN */
1227 rdnt = PyList_AsTuple(rdn);
1228 Py_DECREF(rdn);
1229 if (rdnt == NULL)
1230 goto fail0;
1231 retcode = PyList_Append(dn, rdnt);
1232 Py_DECREF(rdnt);
1233 if (retcode < 0)
1234 goto fail0;
1235 /* create new RDN */
1236 rdn = PyList_New(0);
1237 if (rdn == NULL)
1238 goto fail0;
1239 }
1240 }
Christian Heimes598894f2016-09-05 23:19:05 +02001241 rdn_level = X509_NAME_ENTRY_set(entry);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001242
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001243 /* now add this attribute to the current RDN */
1244 name = X509_NAME_ENTRY_get_object(entry);
1245 value = X509_NAME_ENTRY_get_data(entry);
1246 attr = _create_tuple_for_attribute(name, value);
1247 /*
1248 fprintf(stderr, "RDN level %d, attribute %s: %s\n",
1249 entry->set,
1250 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 0)),
1251 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 1)));
1252 */
1253 if (attr == NULL)
1254 goto fail1;
1255 retcode = PyList_Append(rdn, attr);
1256 Py_DECREF(attr);
1257 if (retcode < 0)
1258 goto fail1;
1259 }
1260 /* now, there's typically a dangling RDN */
Antoine Pitrou2f5a1632012-02-15 22:25:27 +01001261 if (rdn != NULL) {
1262 if (PyList_GET_SIZE(rdn) > 0) {
1263 rdnt = PyList_AsTuple(rdn);
1264 Py_DECREF(rdn);
1265 if (rdnt == NULL)
1266 goto fail0;
1267 retcode = PyList_Append(dn, rdnt);
1268 Py_DECREF(rdnt);
1269 if (retcode < 0)
1270 goto fail0;
1271 }
1272 else {
1273 Py_DECREF(rdn);
1274 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001275 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001276
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001277 /* convert list to tuple */
1278 rdnt = PyList_AsTuple(dn);
1279 Py_DECREF(dn);
1280 if (rdnt == NULL)
1281 return NULL;
1282 return rdnt;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001283
1284 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001285 Py_XDECREF(rdn);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001286
1287 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001288 Py_XDECREF(dn);
1289 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001290}
1291
1292static PyObject *
1293_get_peer_alt_names (X509 *certificate) {
Guido van Rossumf06628b2007-11-21 20:01:53 +00001294
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001295 /* this code follows the procedure outlined in
1296 OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print()
1297 function to extract the STACK_OF(GENERAL_NAME),
1298 then iterates through the stack to add the
1299 names. */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001300
Alex Gaynorb87c0df2017-06-06 07:53:11 -04001301 int j;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001302 PyObject *peer_alt_names = Py_None;
Christian Heimes60bf2fc2013-09-05 16:04:35 +02001303 PyObject *v = NULL, *t;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001304 GENERAL_NAMES *names = NULL;
1305 GENERAL_NAME *name;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001306 BIO *biobuf = NULL;
1307 char buf[2048];
1308 char *vptr;
1309 int len;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001310
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001311 if (certificate == NULL)
1312 return peer_alt_names;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001313
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001314 /* get a memory buffer */
1315 biobuf = BIO_new(BIO_s_mem());
Zackery Spytz4c49da02018-12-07 03:11:30 -07001316 if (biobuf == NULL) {
1317 PyErr_SetString(PySSLErrorObject, "failed to allocate BIO");
1318 return NULL;
1319 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001320
Alex Gaynorb87c0df2017-06-06 07:53:11 -04001321 names = (GENERAL_NAMES *)X509_get_ext_d2i(
1322 certificate, NID_subject_alt_name, NULL, NULL);
1323 if (names != NULL) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001324 if (peer_alt_names == Py_None) {
1325 peer_alt_names = PyList_New(0);
1326 if (peer_alt_names == NULL)
1327 goto fail;
1328 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001329
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001330 for(j = 0; j < sk_GENERAL_NAME_num(names); j++) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001331 /* get a rendering of each name in the set of names */
Christian Heimes824f7f32013-08-17 00:54:47 +02001332 int gntype;
1333 ASN1_STRING *as = NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001334
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001335 name = sk_GENERAL_NAME_value(names, j);
Christian Heimes474afdd2013-08-17 17:18:56 +02001336 gntype = name->type;
Christian Heimes824f7f32013-08-17 00:54:47 +02001337 switch (gntype) {
1338 case GEN_DIRNAME:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001339 /* we special-case DirName as a tuple of
1340 tuples of attributes */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001341
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001342 t = PyTuple_New(2);
1343 if (t == NULL) {
1344 goto fail;
1345 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001346
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001347 v = PyUnicode_FromString("DirName");
1348 if (v == NULL) {
1349 Py_DECREF(t);
1350 goto fail;
1351 }
1352 PyTuple_SET_ITEM(t, 0, v);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001353
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001354 v = _create_tuple_for_X509_NAME (name->d.dirn);
1355 if (v == NULL) {
1356 Py_DECREF(t);
1357 goto fail;
1358 }
1359 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +02001360 break;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001361
Christian Heimes824f7f32013-08-17 00:54:47 +02001362 case GEN_EMAIL:
1363 case GEN_DNS:
1364 case GEN_URI:
1365 /* GENERAL_NAME_print() doesn't handle NULL bytes in ASN1_string
1366 correctly, CVE-2013-4238 */
1367 t = PyTuple_New(2);
1368 if (t == NULL)
1369 goto fail;
1370 switch (gntype) {
1371 case GEN_EMAIL:
1372 v = PyUnicode_FromString("email");
1373 as = name->d.rfc822Name;
1374 break;
1375 case GEN_DNS:
1376 v = PyUnicode_FromString("DNS");
1377 as = name->d.dNSName;
1378 break;
1379 case GEN_URI:
1380 v = PyUnicode_FromString("URI");
1381 as = name->d.uniformResourceIdentifier;
1382 break;
1383 }
1384 if (v == NULL) {
1385 Py_DECREF(t);
1386 goto fail;
1387 }
1388 PyTuple_SET_ITEM(t, 0, v);
Christian Heimesa871f692020-06-01 08:58:14 +02001389 v = PyUnicode_FromStringAndSize((char *)ASN1_STRING_get0_data(as),
Christian Heimes824f7f32013-08-17 00:54:47 +02001390 ASN1_STRING_length(as));
1391 if (v == NULL) {
1392 Py_DECREF(t);
1393 goto fail;
1394 }
1395 PyTuple_SET_ITEM(t, 1, v);
1396 break;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001397
Christian Heimes1c03abd2016-09-06 23:25:35 +02001398 case GEN_RID:
1399 t = PyTuple_New(2);
1400 if (t == NULL)
1401 goto fail;
1402
1403 v = PyUnicode_FromString("Registered ID");
1404 if (v == NULL) {
1405 Py_DECREF(t);
1406 goto fail;
1407 }
1408 PyTuple_SET_ITEM(t, 0, v);
1409
1410 len = i2t_ASN1_OBJECT(buf, sizeof(buf)-1, name->d.rid);
1411 if (len < 0) {
1412 Py_DECREF(t);
1413 _setSSLError(NULL, 0, __FILE__, __LINE__);
1414 goto fail;
1415 } else if (len >= (int)sizeof(buf)) {
1416 v = PyUnicode_FromString("<INVALID>");
1417 } else {
1418 v = PyUnicode_FromStringAndSize(buf, len);
1419 }
1420 if (v == NULL) {
1421 Py_DECREF(t);
1422 goto fail;
1423 }
1424 PyTuple_SET_ITEM(t, 1, v);
1425 break;
1426
Christian Heimes2b7de662019-12-07 17:59:36 +01001427 case GEN_IPADD:
1428 /* OpenSSL < 3.0.0 adds a trailing \n to IPv6. 3.0.0 removed
1429 * the trailing newline. Remove it in all versions
1430 */
1431 t = PyTuple_New(2);
1432 if (t == NULL)
1433 goto fail;
1434
1435 v = PyUnicode_FromString("IP Address");
1436 if (v == NULL) {
1437 Py_DECREF(t);
1438 goto fail;
1439 }
1440 PyTuple_SET_ITEM(t, 0, v);
1441
1442 if (name->d.ip->length == 4) {
1443 unsigned char *p = name->d.ip->data;
1444 v = PyUnicode_FromFormat(
1445 "%d.%d.%d.%d",
1446 p[0], p[1], p[2], p[3]
1447 );
1448 } else if (name->d.ip->length == 16) {
1449 /* PyUnicode_FromFormat() does not support %X */
1450 unsigned char *p = name->d.ip->data;
1451 len = sprintf(
1452 buf,
1453 "%X:%X:%X:%X:%X:%X:%X:%X",
1454 p[0] << 8 | p[1],
1455 p[2] << 8 | p[3],
1456 p[4] << 8 | p[5],
1457 p[6] << 8 | p[7],
1458 p[8] << 8 | p[9],
1459 p[10] << 8 | p[11],
1460 p[12] << 8 | p[13],
1461 p[14] << 8 | p[15]
1462 );
1463 v = PyUnicode_FromStringAndSize(buf, len);
1464 } else {
1465 v = PyUnicode_FromString("<invalid>");
1466 }
1467
1468 if (v == NULL) {
1469 Py_DECREF(t);
1470 goto fail;
1471 }
1472 PyTuple_SET_ITEM(t, 1, v);
1473 break;
1474
Christian Heimes824f7f32013-08-17 00:54:47 +02001475 default:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001476 /* for everything else, we use the OpenSSL print form */
Christian Heimes824f7f32013-08-17 00:54:47 +02001477 switch (gntype) {
1478 /* check for new general name type */
1479 case GEN_OTHERNAME:
1480 case GEN_X400:
1481 case GEN_EDIPARTY:
Christian Heimes824f7f32013-08-17 00:54:47 +02001482 case GEN_RID:
1483 break;
1484 default:
1485 if (PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
1486 "Unknown general name type %d",
1487 gntype) == -1) {
1488 goto fail;
1489 }
1490 break;
1491 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001492 (void) BIO_reset(biobuf);
1493 GENERAL_NAME_print(biobuf, name);
1494 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1495 if (len < 0) {
1496 _setSSLError(NULL, 0, __FILE__, __LINE__);
1497 goto fail;
1498 }
1499 vptr = strchr(buf, ':');
Christian Heimes1c03abd2016-09-06 23:25:35 +02001500 if (vptr == NULL) {
1501 PyErr_Format(PyExc_ValueError,
1502 "Invalid value %.200s",
1503 buf);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001504 goto fail;
Christian Heimes1c03abd2016-09-06 23:25:35 +02001505 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001506 t = PyTuple_New(2);
1507 if (t == NULL)
1508 goto fail;
1509 v = PyUnicode_FromStringAndSize(buf, (vptr - buf));
1510 if (v == NULL) {
1511 Py_DECREF(t);
1512 goto fail;
1513 }
1514 PyTuple_SET_ITEM(t, 0, v);
1515 v = PyUnicode_FromStringAndSize((vptr + 1),
1516 (len - (vptr - buf + 1)));
1517 if (v == NULL) {
1518 Py_DECREF(t);
1519 goto fail;
1520 }
1521 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +02001522 break;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001523 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001524
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001525 /* and add that rendering to the list */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001526
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001527 if (PyList_Append(peer_alt_names, t) < 0) {
1528 Py_DECREF(t);
1529 goto fail;
1530 }
1531 Py_DECREF(t);
1532 }
Antoine Pitrou116d6b92011-11-23 01:39:19 +01001533 sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001534 }
1535 BIO_free(biobuf);
1536 if (peer_alt_names != Py_None) {
1537 v = PyList_AsTuple(peer_alt_names);
1538 Py_DECREF(peer_alt_names);
1539 return v;
1540 } else {
1541 return peer_alt_names;
1542 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001543
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001544
1545 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001546 if (biobuf != NULL)
1547 BIO_free(biobuf);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001548
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001549 if (peer_alt_names != Py_None) {
1550 Py_XDECREF(peer_alt_names);
1551 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001552
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001553 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001554}
1555
1556static PyObject *
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001557_get_aia_uri(X509 *certificate, int nid) {
1558 PyObject *lst = NULL, *ostr = NULL;
1559 int i, result;
1560 AUTHORITY_INFO_ACCESS *info;
1561
1562 info = X509_get_ext_d2i(certificate, NID_info_access, NULL, NULL);
Benjamin Petersonf0c90382015-11-14 15:12:18 -08001563 if (info == NULL)
1564 return Py_None;
1565 if (sk_ACCESS_DESCRIPTION_num(info) == 0) {
1566 AUTHORITY_INFO_ACCESS_free(info);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001567 return Py_None;
1568 }
1569
1570 if ((lst = PyList_New(0)) == NULL) {
1571 goto fail;
1572 }
1573
1574 for (i = 0; i < sk_ACCESS_DESCRIPTION_num(info); i++) {
1575 ACCESS_DESCRIPTION *ad = sk_ACCESS_DESCRIPTION_value(info, i);
1576 ASN1_IA5STRING *uri;
1577
1578 if ((OBJ_obj2nid(ad->method) != nid) ||
1579 (ad->location->type != GEN_URI)) {
1580 continue;
1581 }
1582 uri = ad->location->d.uniformResourceIdentifier;
1583 ostr = PyUnicode_FromStringAndSize((char *)uri->data,
1584 uri->length);
1585 if (ostr == NULL) {
1586 goto fail;
1587 }
1588 result = PyList_Append(lst, ostr);
1589 Py_DECREF(ostr);
1590 if (result < 0) {
1591 goto fail;
1592 }
1593 }
1594 AUTHORITY_INFO_ACCESS_free(info);
1595
1596 /* convert to tuple or None */
1597 if (PyList_Size(lst) == 0) {
1598 Py_DECREF(lst);
1599 return Py_None;
1600 } else {
1601 PyObject *tup;
1602 tup = PyList_AsTuple(lst);
1603 Py_DECREF(lst);
1604 return tup;
1605 }
1606
1607 fail:
1608 AUTHORITY_INFO_ACCESS_free(info);
Christian Heimes18fc7be2013-11-21 23:57:49 +01001609 Py_XDECREF(lst);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001610 return NULL;
1611}
1612
1613static PyObject *
1614_get_crl_dp(X509 *certificate) {
1615 STACK_OF(DIST_POINT) *dps;
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001616 int i, j;
1617 PyObject *lst, *res = NULL;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001618
Christian Heimes598894f2016-09-05 23:19:05 +02001619 dps = X509_get_ext_d2i(certificate, NID_crl_distribution_points, NULL, NULL);
Christian Heimes949ec142013-11-21 16:26:51 +01001620
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001621 if (dps == NULL)
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001622 return Py_None;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001623
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001624 lst = PyList_New(0);
1625 if (lst == NULL)
1626 goto done;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001627
1628 for (i=0; i < sk_DIST_POINT_num(dps); i++) {
1629 DIST_POINT *dp;
1630 STACK_OF(GENERAL_NAME) *gns;
1631
1632 dp = sk_DIST_POINT_value(dps, i);
Christian Heimesa37f5242019-01-15 23:47:42 +01001633 if (dp->distpoint == NULL) {
1634 /* Ignore empty DP value, CVE-2019-5010 */
1635 continue;
1636 }
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001637 gns = dp->distpoint->name.fullname;
1638
1639 for (j=0; j < sk_GENERAL_NAME_num(gns); j++) {
1640 GENERAL_NAME *gn;
1641 ASN1_IA5STRING *uri;
1642 PyObject *ouri;
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001643 int err;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001644
1645 gn = sk_GENERAL_NAME_value(gns, j);
1646 if (gn->type != GEN_URI) {
1647 continue;
1648 }
1649 uri = gn->d.uniformResourceIdentifier;
1650 ouri = PyUnicode_FromStringAndSize((char *)uri->data,
1651 uri->length);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001652 if (ouri == NULL)
1653 goto done;
1654
1655 err = PyList_Append(lst, ouri);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001656 Py_DECREF(ouri);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001657 if (err < 0)
1658 goto done;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001659 }
1660 }
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001661
1662 /* Convert to tuple. */
1663 res = (PyList_GET_SIZE(lst) > 0) ? PyList_AsTuple(lst) : Py_None;
1664
1665 done:
1666 Py_XDECREF(lst);
Olivier Vielpeau2849cc32017-04-14 21:06:07 -04001667 CRL_DIST_POINTS_free(dps);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001668 return res;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001669}
1670
1671static PyObject *
Antoine Pitroufb046912010-11-09 20:21:19 +00001672_decode_certificate(X509 *certificate) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001673
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001674 PyObject *retval = NULL;
1675 BIO *biobuf = NULL;
1676 PyObject *peer;
1677 PyObject *peer_alt_names = NULL;
1678 PyObject *issuer;
1679 PyObject *version;
1680 PyObject *sn_obj;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001681 PyObject *obj;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001682 ASN1_INTEGER *serialNumber;
1683 char buf[2048];
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001684 int len, result;
Christian Heimesa871f692020-06-01 08:58:14 +02001685 const ASN1_TIME *notBefore, *notAfter;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001686 PyObject *pnotBefore, *pnotAfter;
Thomas Woutersed03b412007-08-28 21:37:11 +00001687
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001688 retval = PyDict_New();
1689 if (retval == NULL)
1690 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001691
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001692 peer = _create_tuple_for_X509_NAME(
1693 X509_get_subject_name(certificate));
1694 if (peer == NULL)
1695 goto fail0;
1696 if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) {
1697 Py_DECREF(peer);
1698 goto fail0;
1699 }
1700 Py_DECREF(peer);
Thomas Woutersed03b412007-08-28 21:37:11 +00001701
Antoine Pitroufb046912010-11-09 20:21:19 +00001702 issuer = _create_tuple_for_X509_NAME(
1703 X509_get_issuer_name(certificate));
1704 if (issuer == NULL)
1705 goto fail0;
1706 if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001707 Py_DECREF(issuer);
Antoine Pitroufb046912010-11-09 20:21:19 +00001708 goto fail0;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001709 }
Antoine Pitroufb046912010-11-09 20:21:19 +00001710 Py_DECREF(issuer);
1711
1712 version = PyLong_FromLong(X509_get_version(certificate) + 1);
Christian Heimes5962bef2013-07-26 15:51:18 +02001713 if (version == NULL)
1714 goto fail0;
Antoine Pitroufb046912010-11-09 20:21:19 +00001715 if (PyDict_SetItemString(retval, "version", version) < 0) {
1716 Py_DECREF(version);
1717 goto fail0;
1718 }
1719 Py_DECREF(version);
Guido van Rossumf06628b2007-11-21 20:01:53 +00001720
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001721 /* get a memory buffer */
1722 biobuf = BIO_new(BIO_s_mem());
Zackery Spytz4c49da02018-12-07 03:11:30 -07001723 if (biobuf == NULL) {
1724 PyErr_SetString(PySSLErrorObject, "failed to allocate BIO");
1725 goto fail0;
1726 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001727
Antoine Pitroufb046912010-11-09 20:21:19 +00001728 (void) BIO_reset(biobuf);
1729 serialNumber = X509_get_serialNumber(certificate);
1730 /* should not exceed 20 octets, 160 bits, so buf is big enough */
1731 i2a_ASN1_INTEGER(biobuf, serialNumber);
1732 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1733 if (len < 0) {
1734 _setSSLError(NULL, 0, __FILE__, __LINE__);
1735 goto fail1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001736 }
Antoine Pitroufb046912010-11-09 20:21:19 +00001737 sn_obj = PyUnicode_FromStringAndSize(buf, len);
1738 if (sn_obj == NULL)
1739 goto fail1;
1740 if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) {
1741 Py_DECREF(sn_obj);
1742 goto fail1;
1743 }
1744 Py_DECREF(sn_obj);
1745
1746 (void) BIO_reset(biobuf);
Christian Heimesa871f692020-06-01 08:58:14 +02001747 notBefore = X509_get0_notBefore(certificate);
Antoine Pitroufb046912010-11-09 20:21:19 +00001748 ASN1_TIME_print(biobuf, notBefore);
1749 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1750 if (len < 0) {
1751 _setSSLError(NULL, 0, __FILE__, __LINE__);
1752 goto fail1;
1753 }
1754 pnotBefore = PyUnicode_FromStringAndSize(buf, len);
1755 if (pnotBefore == NULL)
1756 goto fail1;
1757 if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) {
1758 Py_DECREF(pnotBefore);
1759 goto fail1;
1760 }
1761 Py_DECREF(pnotBefore);
Thomas Woutersed03b412007-08-28 21:37:11 +00001762
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001763 (void) BIO_reset(biobuf);
Christian Heimesa871f692020-06-01 08:58:14 +02001764 notAfter = X509_get0_notAfter(certificate);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001765 ASN1_TIME_print(biobuf, notAfter);
1766 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1767 if (len < 0) {
1768 _setSSLError(NULL, 0, __FILE__, __LINE__);
1769 goto fail1;
1770 }
1771 pnotAfter = PyUnicode_FromStringAndSize(buf, len);
1772 if (pnotAfter == NULL)
1773 goto fail1;
1774 if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) {
1775 Py_DECREF(pnotAfter);
1776 goto fail1;
1777 }
1778 Py_DECREF(pnotAfter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001779
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001780 /* Now look for subjectAltName */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001781
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001782 peer_alt_names = _get_peer_alt_names(certificate);
1783 if (peer_alt_names == NULL)
1784 goto fail1;
1785 else if (peer_alt_names != Py_None) {
1786 if (PyDict_SetItemString(retval, "subjectAltName",
1787 peer_alt_names) < 0) {
1788 Py_DECREF(peer_alt_names);
1789 goto fail1;
1790 }
1791 Py_DECREF(peer_alt_names);
1792 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001793
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001794 /* Authority Information Access: OCSP URIs */
1795 obj = _get_aia_uri(certificate, NID_ad_OCSP);
1796 if (obj == NULL) {
1797 goto fail1;
1798 } else if (obj != Py_None) {
1799 result = PyDict_SetItemString(retval, "OCSP", obj);
1800 Py_DECREF(obj);
1801 if (result < 0) {
1802 goto fail1;
1803 }
1804 }
1805
1806 obj = _get_aia_uri(certificate, NID_ad_ca_issuers);
1807 if (obj == NULL) {
1808 goto fail1;
1809 } else if (obj != Py_None) {
1810 result = PyDict_SetItemString(retval, "caIssuers", obj);
1811 Py_DECREF(obj);
1812 if (result < 0) {
1813 goto fail1;
1814 }
1815 }
1816
1817 /* CDP (CRL distribution points) */
1818 obj = _get_crl_dp(certificate);
1819 if (obj == NULL) {
1820 goto fail1;
1821 } else if (obj != Py_None) {
1822 result = PyDict_SetItemString(retval, "crlDistributionPoints", obj);
1823 Py_DECREF(obj);
1824 if (result < 0) {
1825 goto fail1;
1826 }
1827 }
1828
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001829 BIO_free(biobuf);
1830 return retval;
Thomas Woutersed03b412007-08-28 21:37:11 +00001831
1832 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001833 if (biobuf != NULL)
1834 BIO_free(biobuf);
Thomas Woutersed03b412007-08-28 21:37:11 +00001835 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001836 Py_XDECREF(retval);
1837 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001838}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001839
Christian Heimes9a5395a2013-06-17 15:44:12 +02001840static PyObject *
1841_certificate_to_der(X509 *certificate)
1842{
1843 unsigned char *bytes_buf = NULL;
1844 int len;
1845 PyObject *retval;
1846
1847 bytes_buf = NULL;
1848 len = i2d_X509(certificate, &bytes_buf);
1849 if (len < 0) {
1850 _setSSLError(NULL, 0, __FILE__, __LINE__);
1851 return NULL;
1852 }
1853 /* this is actually an immutable bytes sequence */
1854 retval = PyBytes_FromStringAndSize((const char *) bytes_buf, len);
1855 OPENSSL_free(bytes_buf);
1856 return retval;
1857}
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001858
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001859/*[clinic input]
1860_ssl._test_decode_cert
1861 path: object(converter="PyUnicode_FSConverter")
1862 /
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001863
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001864[clinic start generated code]*/
1865
1866static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001867_ssl__test_decode_cert_impl(PyObject *module, PyObject *path)
1868/*[clinic end generated code: output=96becb9abb23c091 input=cdeaaf02d4346628]*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001869{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001870 PyObject *retval = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001871 X509 *x=NULL;
1872 BIO *cert;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001873
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001874 if ((cert=BIO_new(BIO_s_file())) == NULL) {
1875 PyErr_SetString(PySSLErrorObject,
1876 "Can't malloc memory to read file");
1877 goto fail0;
1878 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001879
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001880 if (BIO_read_filename(cert, PyBytes_AsString(path)) <= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001881 PyErr_SetString(PySSLErrorObject,
1882 "Can't open file");
1883 goto fail0;
1884 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001885
Alex Gaynor40dad952019-08-15 08:31:28 -04001886 x = PEM_read_bio_X509(cert, NULL, NULL, NULL);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001887 if (x == NULL) {
1888 PyErr_SetString(PySSLErrorObject,
1889 "Error decoding PEM-encoded file");
1890 goto fail0;
1891 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001892
Antoine Pitroufb046912010-11-09 20:21:19 +00001893 retval = _decode_certificate(x);
Mark Dickinsonee55df52010-08-03 18:31:54 +00001894 X509_free(x);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001895
1896 fail0:
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001897 Py_DECREF(path);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001898 if (cert != NULL) BIO_free(cert);
1899 return retval;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001900}
1901
1902
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001903/*[clinic input]
Christian Heimes141c5e82018-02-24 21:10:57 +01001904_ssl._SSLSocket.getpeercert
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001905 der as binary_mode: bool = False
1906 /
1907
1908Returns the certificate for the peer.
1909
1910If no certificate was provided, returns None. If a certificate was
1911provided, but not validated, returns an empty dictionary. Otherwise
1912returns a dict containing information about the peer certificate.
1913
1914If the optional argument is True, returns a DER-encoded copy of the
1915peer certificate, or None if no certificate was provided. This will
1916return the certificate even if it wasn't validated.
1917[clinic start generated code]*/
1918
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001919static PyObject *
Christian Heimes141c5e82018-02-24 21:10:57 +01001920_ssl__SSLSocket_getpeercert_impl(PySSLSocket *self, int binary_mode)
1921/*[clinic end generated code: output=1f0ab66dfb693c88 input=c0fbe802e57629b7]*/
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001922{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001923 int verification;
Christian Heimes66dc33b2017-05-23 16:02:02 -07001924 X509 *peer_cert;
1925 PyObject *result;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001926
Christian Heimes66dc33b2017-05-23 16:02:02 -07001927 if (!SSL_is_init_finished(self->ssl)) {
Antoine Pitrou20b85552013-09-29 19:50:53 +02001928 PyErr_SetString(PyExc_ValueError,
1929 "handshake not done yet");
1930 return NULL;
1931 }
Christian Heimes66dc33b2017-05-23 16:02:02 -07001932 peer_cert = SSL_get_peer_certificate(self->ssl);
1933 if (peer_cert == NULL)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001934 Py_RETURN_NONE;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001935
Antoine Pitrou721738f2012-08-15 23:20:39 +02001936 if (binary_mode) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001937 /* return cert in DER-encoded format */
Christian Heimes66dc33b2017-05-23 16:02:02 -07001938 result = _certificate_to_der(peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001939 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00001940 verification = SSL_CTX_get_verify_mode(SSL_get_SSL_CTX(self->ssl));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001941 if ((verification & SSL_VERIFY_PEER) == 0)
Christian Heimes66dc33b2017-05-23 16:02:02 -07001942 result = PyDict_New();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001943 else
Christian Heimes66dc33b2017-05-23 16:02:02 -07001944 result = _decode_certificate(peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001945 }
Christian Heimes66dc33b2017-05-23 16:02:02 -07001946 X509_free(peer_cert);
1947 return result;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001948}
1949
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001950static PyObject *
1951cipher_to_tuple(const SSL_CIPHER *cipher)
1952{
1953 const char *cipher_name, *cipher_protocol;
1954 PyObject *v, *retval = PyTuple_New(3);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001955 if (retval == NULL)
1956 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001957
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001958 cipher_name = SSL_CIPHER_get_name(cipher);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001959 if (cipher_name == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001960 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001961 PyTuple_SET_ITEM(retval, 0, Py_None);
1962 } else {
1963 v = PyUnicode_FromString(cipher_name);
1964 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001965 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001966 PyTuple_SET_ITEM(retval, 0, v);
1967 }
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001968
1969 cipher_protocol = SSL_CIPHER_get_version(cipher);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001970 if (cipher_protocol == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001971 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001972 PyTuple_SET_ITEM(retval, 1, Py_None);
1973 } else {
1974 v = PyUnicode_FromString(cipher_protocol);
1975 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001976 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001977 PyTuple_SET_ITEM(retval, 1, v);
1978 }
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001979
1980 v = PyLong_FromLong(SSL_CIPHER_get_bits(cipher, NULL));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001981 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001982 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001983 PyTuple_SET_ITEM(retval, 2, v);
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001984
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001985 return retval;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001986
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001987 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001988 Py_DECREF(retval);
1989 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001990}
1991
Christian Heimes25bfcd52016-09-06 00:04:45 +02001992#if OPENSSL_VERSION_NUMBER >= 0x10002000UL
1993static PyObject *
1994cipher_to_dict(const SSL_CIPHER *cipher)
1995{
1996 const char *cipher_name, *cipher_protocol;
1997
1998 unsigned long cipher_id;
1999 int alg_bits, strength_bits, len;
2000 char buf[512] = {0};
2001#if OPENSSL_VERSION_1_1
2002 int aead, nid;
2003 const char *skcipher = NULL, *digest = NULL, *kx = NULL, *auth = NULL;
2004#endif
Christian Heimes25bfcd52016-09-06 00:04:45 +02002005
2006 /* can be NULL */
2007 cipher_name = SSL_CIPHER_get_name(cipher);
2008 cipher_protocol = SSL_CIPHER_get_version(cipher);
2009 cipher_id = SSL_CIPHER_get_id(cipher);
2010 SSL_CIPHER_description(cipher, buf, sizeof(buf) - 1);
Segev Finer5cff6372017-07-27 01:19:17 +03002011 /* Downcast to avoid a warning. Safe since buf is always 512 bytes */
2012 len = (int)strlen(buf);
Christian Heimes25bfcd52016-09-06 00:04:45 +02002013 if (len > 1 && buf[len-1] == '\n')
2014 buf[len-1] = '\0';
2015 strength_bits = SSL_CIPHER_get_bits(cipher, &alg_bits);
2016
2017#if OPENSSL_VERSION_1_1
2018 aead = SSL_CIPHER_is_aead(cipher);
2019 nid = SSL_CIPHER_get_cipher_nid(cipher);
2020 skcipher = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
2021 nid = SSL_CIPHER_get_digest_nid(cipher);
2022 digest = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
2023 nid = SSL_CIPHER_get_kx_nid(cipher);
2024 kx = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
2025 nid = SSL_CIPHER_get_auth_nid(cipher);
2026 auth = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
2027#endif
2028
Victor Stinner410b9882016-09-12 12:00:23 +02002029 return Py_BuildValue(
Christian Heimes25bfcd52016-09-06 00:04:45 +02002030 "{sksssssssisi"
2031#if OPENSSL_VERSION_1_1
2032 "sOssssssss"
2033#endif
2034 "}",
2035 "id", cipher_id,
2036 "name", cipher_name,
2037 "protocol", cipher_protocol,
2038 "description", buf,
2039 "strength_bits", strength_bits,
2040 "alg_bits", alg_bits
2041#if OPENSSL_VERSION_1_1
2042 ,"aead", aead ? Py_True : Py_False,
2043 "symmetric", skcipher,
2044 "digest", digest,
2045 "kea", kx,
2046 "auth", auth
2047#endif
2048 );
Christian Heimes25bfcd52016-09-06 00:04:45 +02002049}
2050#endif
2051
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002052/*[clinic input]
2053_ssl._SSLSocket.shared_ciphers
2054[clinic start generated code]*/
2055
2056static PyObject *
2057_ssl__SSLSocket_shared_ciphers_impl(PySSLSocket *self)
2058/*[clinic end generated code: output=3d174ead2e42c4fd input=0bfe149da8fe6306]*/
Benjamin Peterson4cb17812015-01-07 11:14:26 -06002059{
2060 STACK_OF(SSL_CIPHER) *ciphers;
2061 int i;
2062 PyObject *res;
2063
Christian Heimes598894f2016-09-05 23:19:05 +02002064 ciphers = SSL_get_ciphers(self->ssl);
2065 if (!ciphers)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06002066 Py_RETURN_NONE;
Benjamin Peterson4cb17812015-01-07 11:14:26 -06002067 res = PyList_New(sk_SSL_CIPHER_num(ciphers));
2068 if (!res)
2069 return NULL;
2070 for (i = 0; i < sk_SSL_CIPHER_num(ciphers); i++) {
2071 PyObject *tup = cipher_to_tuple(sk_SSL_CIPHER_value(ciphers, i));
2072 if (!tup) {
2073 Py_DECREF(res);
2074 return NULL;
2075 }
2076 PyList_SET_ITEM(res, i, tup);
2077 }
2078 return res;
2079}
2080
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002081/*[clinic input]
2082_ssl._SSLSocket.cipher
2083[clinic start generated code]*/
2084
2085static PyObject *
2086_ssl__SSLSocket_cipher_impl(PySSLSocket *self)
2087/*[clinic end generated code: output=376417c16d0e5815 input=548fb0e27243796d]*/
Benjamin Peterson4cb17812015-01-07 11:14:26 -06002088{
2089 const SSL_CIPHER *current;
2090
2091 if (self->ssl == NULL)
2092 Py_RETURN_NONE;
2093 current = SSL_get_current_cipher(self->ssl);
2094 if (current == NULL)
2095 Py_RETURN_NONE;
2096 return cipher_to_tuple(current);
2097}
2098
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002099/*[clinic input]
2100_ssl._SSLSocket.version
2101[clinic start generated code]*/
2102
2103static PyObject *
2104_ssl__SSLSocket_version_impl(PySSLSocket *self)
2105/*[clinic end generated code: output=178aed33193b2cdb input=900186a503436fd6]*/
Antoine Pitrou47e40422014-09-04 21:00:10 +02002106{
2107 const char *version;
2108
2109 if (self->ssl == NULL)
2110 Py_RETURN_NONE;
Christian Heimes68771112017-09-05 21:55:40 -07002111 if (!SSL_is_init_finished(self->ssl)) {
2112 /* handshake not finished */
2113 Py_RETURN_NONE;
2114 }
Antoine Pitrou47e40422014-09-04 21:00:10 +02002115 version = SSL_get_version(self->ssl);
2116 if (!strcmp(version, "unknown"))
2117 Py_RETURN_NONE;
2118 return PyUnicode_FromString(version);
2119}
2120
Christian Heimes29eab552018-02-25 12:31:33 +01002121#if HAVE_NPN
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002122/*[clinic input]
2123_ssl._SSLSocket.selected_npn_protocol
2124[clinic start generated code]*/
2125
2126static PyObject *
2127_ssl__SSLSocket_selected_npn_protocol_impl(PySSLSocket *self)
2128/*[clinic end generated code: output=b91d494cd207ecf6 input=c28fde139204b826]*/
2129{
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002130 const unsigned char *out;
2131 unsigned int outlen;
2132
Victor Stinner4569cd52013-06-23 14:58:43 +02002133 SSL_get0_next_proto_negotiated(self->ssl,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002134 &out, &outlen);
2135
2136 if (out == NULL)
2137 Py_RETURN_NONE;
Benjamin Petersoncca27322015-01-23 16:35:37 -05002138 return PyUnicode_FromStringAndSize((char *)out, outlen);
2139}
2140#endif
2141
Christian Heimes29eab552018-02-25 12:31:33 +01002142#if HAVE_ALPN
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002143/*[clinic input]
2144_ssl._SSLSocket.selected_alpn_protocol
2145[clinic start generated code]*/
2146
2147static PyObject *
2148_ssl__SSLSocket_selected_alpn_protocol_impl(PySSLSocket *self)
2149/*[clinic end generated code: output=ec33688b303d250f input=442de30e35bc2913]*/
2150{
Benjamin Petersoncca27322015-01-23 16:35:37 -05002151 const unsigned char *out;
2152 unsigned int outlen;
2153
2154 SSL_get0_alpn_selected(self->ssl, &out, &outlen);
2155
2156 if (out == NULL)
2157 Py_RETURN_NONE;
2158 return PyUnicode_FromStringAndSize((char *)out, outlen);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002159}
2160#endif
2161
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002162/*[clinic input]
2163_ssl._SSLSocket.compression
2164[clinic start generated code]*/
2165
2166static PyObject *
2167_ssl__SSLSocket_compression_impl(PySSLSocket *self)
2168/*[clinic end generated code: output=bd16cb1bb4646ae7 input=5d059d0a2bbc32c8]*/
2169{
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01002170#ifdef OPENSSL_NO_COMP
2171 Py_RETURN_NONE;
2172#else
2173 const COMP_METHOD *comp_method;
2174 const char *short_name;
2175
2176 if (self->ssl == NULL)
2177 Py_RETURN_NONE;
2178 comp_method = SSL_get_current_compression(self->ssl);
Christian Heimes598894f2016-09-05 23:19:05 +02002179 if (comp_method == NULL || COMP_get_type(comp_method) == NID_undef)
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01002180 Py_RETURN_NONE;
Christian Heimes281e5f82016-09-06 01:10:39 +02002181 short_name = OBJ_nid2sn(COMP_get_type(comp_method));
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01002182 if (short_name == NULL)
2183 Py_RETURN_NONE;
2184 return PyUnicode_DecodeFSDefault(short_name);
2185#endif
2186}
2187
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002188static PySSLContext *PySSL_get_context(PySSLSocket *self, void *closure) {
2189 Py_INCREF(self->ctx);
2190 return self->ctx;
2191}
2192
2193static int PySSL_set_context(PySSLSocket *self, PyObject *value,
2194 void *closure) {
2195
2196 if (PyObject_TypeCheck(value, &PySSLContext_Type)) {
Antoine Pitrou912fbff2013-03-30 16:29:32 +01002197#if !HAVE_SNI
2198 PyErr_SetString(PyExc_NotImplementedError, "setting a socket's "
2199 "context is not supported by your OpenSSL library");
Antoine Pitrou41f8c4f2013-03-30 16:36:54 +01002200 return -1;
Antoine Pitrou912fbff2013-03-30 16:29:32 +01002201#else
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002202 Py_INCREF(value);
Serhiy Storchaka57a01d32016-04-10 18:05:40 +03002203 Py_SETREF(self->ctx, (PySSLContext *)value);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002204 SSL_set_SSL_CTX(self->ssl, self->ctx->ctx);
Antoine Pitrou912fbff2013-03-30 16:29:32 +01002205#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002206 } else {
Ned Deily4531ec72018-06-11 20:26:28 -04002207 PyErr_SetString(PyExc_TypeError, "The value must be a SSLContext");
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002208 return -1;
2209 }
2210
2211 return 0;
2212}
2213
2214PyDoc_STRVAR(PySSL_set_context_doc,
2215"_setter_context(ctx)\n\
2216\
2217This changes the context associated with the SSLSocket. This is typically\n\
Christian Heimes11a14932018-02-24 02:35:08 +01002218used from within a callback function set by the sni_callback\n\
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002219on the SSLContext to change the certificate information associated with the\n\
2220SSLSocket before the cryptographic exchange handshake messages\n");
2221
2222
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002223static PyObject *
2224PySSL_get_server_side(PySSLSocket *self, void *c)
2225{
2226 return PyBool_FromLong(self->socket_type == PY_SSL_SERVER);
2227}
2228
2229PyDoc_STRVAR(PySSL_get_server_side_doc,
2230"Whether this is a server-side socket.");
2231
2232static PyObject *
2233PySSL_get_server_hostname(PySSLSocket *self, void *c)
2234{
2235 if (self->server_hostname == NULL)
2236 Py_RETURN_NONE;
2237 Py_INCREF(self->server_hostname);
2238 return self->server_hostname;
2239}
2240
2241PyDoc_STRVAR(PySSL_get_server_hostname_doc,
2242"The currently set server hostname (for SNI).");
2243
2244static PyObject *
2245PySSL_get_owner(PySSLSocket *self, void *c)
2246{
2247 PyObject *owner;
2248
2249 if (self->owner == NULL)
2250 Py_RETURN_NONE;
2251
2252 owner = PyWeakref_GetObject(self->owner);
2253 Py_INCREF(owner);
2254 return owner;
2255}
2256
2257static int
2258PySSL_set_owner(PySSLSocket *self, PyObject *value, void *c)
2259{
Serhiy Storchaka48842712016-04-06 09:45:48 +03002260 Py_XSETREF(self->owner, PyWeakref_NewRef(value, NULL));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002261 if (self->owner == NULL)
2262 return -1;
2263 return 0;
2264}
2265
2266PyDoc_STRVAR(PySSL_get_owner_doc,
2267"The Python-level owner of this object.\
2268Passed as \"self\" in servername callback.");
2269
Christian Heimesc7f70692019-05-31 11:44:05 +02002270static int
2271PySSL_traverse(PySSLSocket *self, visitproc visit, void *arg)
2272{
2273 Py_VISIT(self->exc_type);
2274 Py_VISIT(self->exc_value);
2275 Py_VISIT(self->exc_tb);
2276 return 0;
2277}
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002278
Christian Heimesc7f70692019-05-31 11:44:05 +02002279static int
2280PySSL_clear(PySSLSocket *self)
2281{
2282 Py_CLEAR(self->exc_type);
2283 Py_CLEAR(self->exc_value);
2284 Py_CLEAR(self->exc_tb);
2285 return 0;
2286}
2287
2288static void
2289PySSL_dealloc(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002290{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002291 if (self->ssl)
2292 SSL_free(self->ssl);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002293 Py_XDECREF(self->Socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002294 Py_XDECREF(self->ctx);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002295 Py_XDECREF(self->server_hostname);
2296 Py_XDECREF(self->owner);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002297 PyObject_Del(self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002298}
2299
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002300/* If the socket has a timeout, do a select()/poll() on the socket.
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002301 The argument writing indicates the direction.
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00002302 Returns one of the possibilities in the timeout_state enum (above).
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002303 */
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00002304
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002305static int
Victor Stinner14690702015-04-06 22:46:13 +02002306PySSL_select(PySocketSockObject *s, int writing, _PyTime_t timeout)
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002307{
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002308 int rc;
2309#ifdef HAVE_POLL
2310 struct pollfd pollfd;
2311 _PyTime_t ms;
2312#else
2313 int nfds;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002314 fd_set fds;
2315 struct timeval tv;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002316#endif
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002317
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002318 /* Nothing to do unless we're in timeout mode (not non-blocking) */
Victor Stinner14690702015-04-06 22:46:13 +02002319 if ((s == NULL) || (timeout == 0))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002320 return SOCKET_IS_NONBLOCKING;
Victor Stinner14690702015-04-06 22:46:13 +02002321 else if (timeout < 0) {
2322 if (s->sock_timeout > 0)
2323 return SOCKET_HAS_TIMED_OUT;
2324 else
2325 return SOCKET_IS_BLOCKING;
2326 }
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002327
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002328 /* Guard against closed socket */
Victor Stinner524714e2016-07-22 17:43:59 +02002329 if (s->sock_fd == INVALID_SOCKET)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002330 return SOCKET_HAS_BEEN_CLOSED;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002331
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002332 /* Prefer poll, if available, since you can poll() any fd
2333 * which can't be done with select(). */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002334#ifdef HAVE_POLL
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002335 pollfd.fd = s->sock_fd;
2336 pollfd.events = writing ? POLLOUT : POLLIN;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002337
Victor Stinner14690702015-04-06 22:46:13 +02002338 /* timeout is in seconds, poll() uses milliseconds */
2339 ms = (int)_PyTime_AsMilliseconds(timeout, _PyTime_ROUND_CEILING);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002340 assert(ms <= INT_MAX);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002341
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002342 PySSL_BEGIN_ALLOW_THREADS
2343 rc = poll(&pollfd, 1, (int)ms);
2344 PySSL_END_ALLOW_THREADS
2345#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002346 /* Guard against socket too large for select*/
Charles-François Nataliaa26b272011-08-28 17:51:43 +02002347 if (!_PyIsSelectable_fd(s->sock_fd))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002348 return SOCKET_TOO_LARGE_FOR_SELECT;
Neal Norwitz082b2df2006-02-07 07:04:46 +00002349
Victor Stinner14690702015-04-06 22:46:13 +02002350 _PyTime_AsTimeval_noraise(timeout, &tv, _PyTime_ROUND_CEILING);
Victor Stinnere2452312015-03-28 03:00:46 +01002351
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002352 FD_ZERO(&fds);
2353 FD_SET(s->sock_fd, &fds);
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002354
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002355 /* Wait until the socket becomes ready */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002356 PySSL_BEGIN_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002357 nfds = Py_SAFE_DOWNCAST(s->sock_fd+1, SOCKET_T, int);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002358 if (writing)
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002359 rc = select(nfds, NULL, &fds, NULL, &tv);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002360 else
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002361 rc = select(nfds, &fds, NULL, NULL, &tv);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002362 PySSL_END_ALLOW_THREADS
Bill Janssen6e027db2007-11-15 22:23:56 +00002363#endif
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002364
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002365 /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
2366 (when we are able to write or when there's something to read) */
2367 return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002368}
2369
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002370/*[clinic input]
2371_ssl._SSLSocket.write
2372 b: Py_buffer
2373 /
2374
2375Writes the bytes-like object b into the SSL object.
2376
2377Returns the number of bytes written.
2378[clinic start generated code]*/
2379
2380static PyObject *
2381_ssl__SSLSocket_write_impl(PySSLSocket *self, Py_buffer *b)
2382/*[clinic end generated code: output=aa7a6be5527358d8 input=77262d994fe5100a]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002383{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002384 int len;
2385 int sockstate;
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002386 _PySSLError err;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002387 int nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002388 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002389 _PyTime_t timeout, deadline = 0;
2390 int has_timeout;
Bill Janssen54cc54c2007-12-14 22:08:56 +00002391
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002392 if (sock != NULL) {
2393 if (((PyObject*)sock) == Py_None) {
2394 _setSSLError("Underlying socket connection gone",
2395 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2396 return NULL;
2397 }
2398 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002399 }
2400
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002401 if (b->len > INT_MAX) {
Victor Stinner6efa9652013-06-25 00:42:31 +02002402 PyErr_Format(PyExc_OverflowError,
2403 "string longer than %d bytes", INT_MAX);
2404 goto error;
2405 }
2406
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002407 if (sock != NULL) {
2408 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002409 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002410 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2411 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
2412 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002413
Victor Stinner14690702015-04-06 22:46:13 +02002414 timeout = GET_SOCKET_TIMEOUT(sock);
2415 has_timeout = (timeout > 0);
2416 if (has_timeout)
2417 deadline = _PyTime_GetMonotonicClock() + timeout;
2418
2419 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002420 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002421 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002422 "The write operation timed out");
2423 goto error;
2424 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
2425 PyErr_SetString(PySSLErrorObject,
2426 "Underlying socket has been closed.");
2427 goto error;
2428 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
2429 PyErr_SetString(PySSLErrorObject,
2430 "Underlying socket too large for select().");
2431 goto error;
2432 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002433
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002434 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002435 PySSL_BEGIN_ALLOW_THREADS
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002436 len = SSL_write(self->ssl, b->buf, (int)b->len);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002437 err = _PySSL_errno(len <= 0, self->ssl, len);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002438 PySSL_END_ALLOW_THREADS
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002439 self->err = err;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002440
2441 if (PyErr_CheckSignals())
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002442 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002443
Victor Stinner14690702015-04-06 22:46:13 +02002444 if (has_timeout)
2445 timeout = deadline - _PyTime_GetMonotonicClock();
2446
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002447 if (err.ssl == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +02002448 sockstate = PySSL_select(sock, 0, timeout);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002449 } else if (err.ssl == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +02002450 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002451 } else {
2452 sockstate = SOCKET_OPERATION_OK;
2453 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002454
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002455 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002456 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002457 "The write operation timed out");
2458 goto error;
2459 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
2460 PyErr_SetString(PySSLErrorObject,
2461 "Underlying socket has been closed.");
2462 goto error;
2463 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
2464 break;
2465 }
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002466 } while (err.ssl == SSL_ERROR_WANT_READ ||
2467 err.ssl == SSL_ERROR_WANT_WRITE);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002468
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002469 Py_XDECREF(sock);
Christian Heimesc7f70692019-05-31 11:44:05 +02002470 if (len <= 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002471 return PySSL_SetError(self, len, __FILE__, __LINE__);
Christian Heimesc7f70692019-05-31 11:44:05 +02002472 if (PySSL_ChainExceptions(self) < 0)
2473 return NULL;
2474 return PyLong_FromLong(len);
Antoine Pitrou7d7aede2009-11-25 18:55:32 +00002475error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002476 Py_XDECREF(sock);
Christian Heimesc7f70692019-05-31 11:44:05 +02002477 PySSL_ChainExceptions(self);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002478 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002479}
2480
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002481/*[clinic input]
2482_ssl._SSLSocket.pending
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002483
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002484Returns the number of already decrypted bytes available for read, pending on the connection.
2485[clinic start generated code]*/
2486
2487static PyObject *
2488_ssl__SSLSocket_pending_impl(PySSLSocket *self)
2489/*[clinic end generated code: output=983d9fecdc308a83 input=2b77487d6dfd597f]*/
Bill Janssen6e027db2007-11-15 22:23:56 +00002490{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002491 int count = 0;
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002492 _PySSLError err;
Bill Janssen6e027db2007-11-15 22:23:56 +00002493
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002494 PySSL_BEGIN_ALLOW_THREADS
2495 count = SSL_pending(self->ssl);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002496 err = _PySSL_errno(count < 0, self->ssl, count);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002497 PySSL_END_ALLOW_THREADS
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002498 self->err = err;
2499
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002500 if (count < 0)
2501 return PySSL_SetError(self, count, __FILE__, __LINE__);
2502 else
2503 return PyLong_FromLong(count);
Bill Janssen6e027db2007-11-15 22:23:56 +00002504}
2505
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002506/*[clinic input]
2507_ssl._SSLSocket.read
2508 size as len: int
2509 [
Larry Hastingsdbfdc382015-05-04 06:59:46 -07002510 buffer: Py_buffer(accept={rwbuffer})
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002511 ]
2512 /
Bill Janssen6e027db2007-11-15 22:23:56 +00002513
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002514Read up to size bytes from the SSL socket.
2515[clinic start generated code]*/
2516
2517static PyObject *
2518_ssl__SSLSocket_read_impl(PySSLSocket *self, int len, int group_right_1,
2519 Py_buffer *buffer)
Larry Hastingsdbfdc382015-05-04 06:59:46 -07002520/*[clinic end generated code: output=00097776cec2a0af input=ff157eb918d0905b]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002521{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002522 PyObject *dest = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002523 char *mem;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002524 int count;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002525 int sockstate;
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002526 _PySSLError err;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002527 int nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002528 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002529 _PyTime_t timeout, deadline = 0;
2530 int has_timeout;
Bill Janssen54cc54c2007-12-14 22:08:56 +00002531
Martin Panter5503d472016-03-27 05:35:19 +00002532 if (!group_right_1 && len < 0) {
2533 PyErr_SetString(PyExc_ValueError, "size should not be negative");
2534 return NULL;
2535 }
2536
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002537 if (sock != NULL) {
2538 if (((PyObject*)sock) == Py_None) {
2539 _setSSLError("Underlying socket connection gone",
2540 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2541 return NULL;
2542 }
2543 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002544 }
2545
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002546 if (!group_right_1) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002547 dest = PyBytes_FromStringAndSize(NULL, len);
2548 if (dest == NULL)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002549 goto error;
Martin Panterbed7f1a2016-07-11 00:17:13 +00002550 if (len == 0) {
2551 Py_XDECREF(sock);
2552 return dest;
2553 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002554 mem = PyBytes_AS_STRING(dest);
2555 }
2556 else {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002557 mem = buffer->buf;
2558 if (len <= 0 || len > buffer->len) {
2559 len = (int) buffer->len;
2560 if (buffer->len != len) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002561 PyErr_SetString(PyExc_OverflowError,
2562 "maximum length can't fit in a C 'int'");
2563 goto error;
2564 }
Martin Panterbed7f1a2016-07-11 00:17:13 +00002565 if (len == 0) {
2566 count = 0;
2567 goto done;
2568 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002569 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002570 }
2571
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002572 if (sock != NULL) {
2573 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002574 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002575 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2576 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
2577 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002578
Victor Stinner14690702015-04-06 22:46:13 +02002579 timeout = GET_SOCKET_TIMEOUT(sock);
2580 has_timeout = (timeout > 0);
2581 if (has_timeout)
2582 deadline = _PyTime_GetMonotonicClock() + timeout;
2583
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002584 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002585 PySSL_BEGIN_ALLOW_THREADS
2586 count = SSL_read(self->ssl, mem, len);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002587 err = _PySSL_errno(count <= 0, self->ssl, count);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002588 PySSL_END_ALLOW_THREADS
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002589 self->err = err;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002590
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002591 if (PyErr_CheckSignals())
2592 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002593
Victor Stinner14690702015-04-06 22:46:13 +02002594 if (has_timeout)
2595 timeout = deadline - _PyTime_GetMonotonicClock();
2596
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002597 if (err.ssl == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +02002598 sockstate = PySSL_select(sock, 0, timeout);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002599 } else if (err.ssl == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +02002600 sockstate = PySSL_select(sock, 1, timeout);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002601 } else if (err.ssl == SSL_ERROR_ZERO_RETURN &&
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002602 SSL_get_shutdown(self->ssl) == SSL_RECEIVED_SHUTDOWN)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002603 {
2604 count = 0;
2605 goto done;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002606 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002607 else
2608 sockstate = SOCKET_OPERATION_OK;
2609
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002610 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002611 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002612 "The read operation timed out");
2613 goto error;
2614 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
2615 break;
2616 }
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002617 } while (err.ssl == SSL_ERROR_WANT_READ ||
2618 err.ssl == SSL_ERROR_WANT_WRITE);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002619
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002620 if (count <= 0) {
2621 PySSL_SetError(self, count, __FILE__, __LINE__);
2622 goto error;
2623 }
Christian Heimesc7f70692019-05-31 11:44:05 +02002624 if (self->exc_type != NULL)
2625 goto error;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002626
2627done:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002628 Py_XDECREF(sock);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002629 if (!group_right_1) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002630 _PyBytes_Resize(&dest, count);
2631 return dest;
2632 }
2633 else {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002634 return PyLong_FromLong(count);
2635 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002636
2637error:
Christian Heimesc7f70692019-05-31 11:44:05 +02002638 PySSL_ChainExceptions(self);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002639 Py_XDECREF(sock);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002640 if (!group_right_1)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002641 Py_XDECREF(dest);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002642 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002643}
2644
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002645/*[clinic input]
2646_ssl._SSLSocket.shutdown
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002647
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002648Does the SSL shutdown handshake with the remote end.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002649[clinic start generated code]*/
2650
2651static PyObject *
2652_ssl__SSLSocket_shutdown_impl(PySSLSocket *self)
Christian Heimes141c5e82018-02-24 21:10:57 +01002653/*[clinic end generated code: output=ca1aa7ed9d25ca42 input=11d39e69b0a2bf4a]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00002654{
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002655 _PySSLError err;
2656 int sockstate, nonblocking, ret;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002657 int zeros = 0;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002658 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002659 _PyTime_t timeout, deadline = 0;
2660 int has_timeout;
Bill Janssen40a0f662008-08-12 16:56:25 +00002661
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002662 if (sock != NULL) {
2663 /* Guard against closed socket */
Victor Stinner524714e2016-07-22 17:43:59 +02002664 if ((((PyObject*)sock) == Py_None) || (sock->sock_fd == INVALID_SOCKET)) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002665 _setSSLError("Underlying socket connection gone",
2666 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2667 return NULL;
2668 }
2669 Py_INCREF(sock);
2670
2671 /* Just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002672 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002673 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2674 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002675 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002676
Victor Stinner14690702015-04-06 22:46:13 +02002677 timeout = GET_SOCKET_TIMEOUT(sock);
2678 has_timeout = (timeout > 0);
2679 if (has_timeout)
2680 deadline = _PyTime_GetMonotonicClock() + timeout;
2681
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002682 while (1) {
2683 PySSL_BEGIN_ALLOW_THREADS
2684 /* Disable read-ahead so that unwrap can work correctly.
2685 * Otherwise OpenSSL might read in too much data,
2686 * eating clear text data that happens to be
2687 * transmitted after the SSL shutdown.
Ezio Melotti85a86292013-08-17 16:57:41 +03002688 * Should be safe to call repeatedly every time this
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002689 * function is used and the shutdown_seen_zero != 0
2690 * condition is met.
2691 */
2692 if (self->shutdown_seen_zero)
2693 SSL_set_read_ahead(self->ssl, 0);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002694 ret = SSL_shutdown(self->ssl);
2695 err = _PySSL_errno(ret < 0, self->ssl, ret);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002696 PySSL_END_ALLOW_THREADS
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002697 self->err = err;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002698
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002699 /* If err == 1, a secure shutdown with SSL_shutdown() is complete */
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002700 if (ret > 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002701 break;
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002702 if (ret == 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002703 /* Don't loop endlessly; instead preserve legacy
2704 behaviour of trying SSL_shutdown() only twice.
2705 This looks necessary for OpenSSL < 0.9.8m */
2706 if (++zeros > 1)
2707 break;
2708 /* Shutdown was sent, now try receiving */
2709 self->shutdown_seen_zero = 1;
2710 continue;
Bill Janssen40a0f662008-08-12 16:56:25 +00002711 }
2712
Victor Stinner14690702015-04-06 22:46:13 +02002713 if (has_timeout)
2714 timeout = deadline - _PyTime_GetMonotonicClock();
2715
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002716 /* Possibly retry shutdown until timeout or failure */
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002717 if (err.ssl == SSL_ERROR_WANT_READ)
Victor Stinner14690702015-04-06 22:46:13 +02002718 sockstate = PySSL_select(sock, 0, timeout);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002719 else if (err.ssl == SSL_ERROR_WANT_WRITE)
Victor Stinner14690702015-04-06 22:46:13 +02002720 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002721 else
2722 break;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002723
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002724 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002725 if (err.ssl == SSL_ERROR_WANT_READ)
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002726 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002727 "The read operation timed out");
2728 else
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002729 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002730 "The write operation timed out");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002731 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002732 }
2733 else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
2734 PyErr_SetString(PySSLErrorObject,
2735 "Underlying socket too large for select().");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002736 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002737 }
2738 else if (sockstate != SOCKET_OPERATION_OK)
2739 /* Retain the SSL error code */
2740 break;
2741 }
Nathaniel J. Smithc0da5822018-09-21 21:44:12 -07002742 if (ret < 0) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002743 Py_XDECREF(sock);
Christian Heimesc7f70692019-05-31 11:44:05 +02002744 PySSL_SetError(self, ret, __FILE__, __LINE__);
2745 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002746 }
Christian Heimesc7f70692019-05-31 11:44:05 +02002747 if (self->exc_type != NULL)
2748 goto error;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002749 if (sock)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002750 /* It's already INCREF'ed */
2751 return (PyObject *) sock;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002752 else
2753 Py_RETURN_NONE;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002754
2755error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002756 Py_XDECREF(sock);
Christian Heimesc7f70692019-05-31 11:44:05 +02002757 PySSL_ChainExceptions(self);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002758 return NULL;
Bill Janssen40a0f662008-08-12 16:56:25 +00002759}
2760
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002761/*[clinic input]
Christian Heimes141c5e82018-02-24 21:10:57 +01002762_ssl._SSLSocket.get_channel_binding
2763 cb_type: str = "tls-unique"
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002764
Christian Heimes141c5e82018-02-24 21:10:57 +01002765Get channel binding data for current connection.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002766
Christian Heimes141c5e82018-02-24 21:10:57 +01002767Raise ValueError if the requested `cb_type` is not supported. Return bytes
2768of the data or None if the data is not available (e.g. before the handshake).
2769Only 'tls-unique' channel binding data from RFC 5929 is supported.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002770[clinic start generated code]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00002771
Antoine Pitroud6494802011-07-21 01:11:30 +02002772static PyObject *
Christian Heimes141c5e82018-02-24 21:10:57 +01002773_ssl__SSLSocket_get_channel_binding_impl(PySSLSocket *self,
2774 const char *cb_type)
2775/*[clinic end generated code: output=34bac9acb6a61d31 input=08b7e43b99c17d41]*/
Antoine Pitroud6494802011-07-21 01:11:30 +02002776{
Antoine Pitroud6494802011-07-21 01:11:30 +02002777 char buf[PySSL_CB_MAXLEN];
Victor Stinner9ee02032013-06-23 15:08:23 +02002778 size_t len;
Antoine Pitroud6494802011-07-21 01:11:30 +02002779
Christian Heimes141c5e82018-02-24 21:10:57 +01002780 if (strcmp(cb_type, "tls-unique") == 0) {
2781 if (SSL_session_reused(self->ssl) ^ !self->socket_type) {
2782 /* if session is resumed XOR we are the client */
2783 len = SSL_get_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2784 }
2785 else {
2786 /* if a new session XOR we are the server */
2787 len = SSL_get_peer_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2788 }
Antoine Pitroud6494802011-07-21 01:11:30 +02002789 }
2790 else {
Christian Heimes141c5e82018-02-24 21:10:57 +01002791 PyErr_Format(
2792 PyExc_ValueError,
2793 "'%s' channel binding type not implemented",
2794 cb_type
2795 );
2796 return NULL;
Antoine Pitroud6494802011-07-21 01:11:30 +02002797 }
2798
2799 /* It cannot be negative in current OpenSSL version as of July 2011 */
Antoine Pitroud6494802011-07-21 01:11:30 +02002800 if (len == 0)
2801 Py_RETURN_NONE;
2802
Christian Heimes141c5e82018-02-24 21:10:57 +01002803 return PyBytes_FromStringAndSize(buf, len);
Antoine Pitroud6494802011-07-21 01:11:30 +02002804}
2805
Christian Heimes9fb051f2018-09-23 08:32:31 +02002806/*[clinic input]
2807_ssl._SSLSocket.verify_client_post_handshake
2808
2809Initiate TLS 1.3 post-handshake authentication
2810[clinic start generated code]*/
2811
2812static PyObject *
2813_ssl__SSLSocket_verify_client_post_handshake_impl(PySSLSocket *self)
2814/*[clinic end generated code: output=532147f3b1341425 input=6bfa874810a3d889]*/
2815{
2816#ifdef TLS1_3_VERSION
2817 int err = SSL_verify_client_post_handshake(self->ssl);
2818 if (err == 0)
2819 return _setSSLError(NULL, 0, __FILE__, __LINE__);
2820 else
2821 Py_RETURN_NONE;
2822#else
2823 PyErr_SetString(PyExc_NotImplementedError,
2824 "Post-handshake auth is not supported by your "
2825 "OpenSSL version.");
2826 return NULL;
2827#endif
2828}
2829
Christian Heimes99a65702016-09-10 23:44:53 +02002830#ifdef OPENSSL_VERSION_1_1
2831
2832static SSL_SESSION*
2833_ssl_session_dup(SSL_SESSION *session) {
2834 SSL_SESSION *newsession = NULL;
2835 int slen;
2836 unsigned char *senc = NULL, *p;
2837 const unsigned char *const_p;
2838
2839 if (session == NULL) {
2840 PyErr_SetString(PyExc_ValueError, "Invalid session");
2841 goto error;
2842 }
2843
2844 /* get length */
2845 slen = i2d_SSL_SESSION(session, NULL);
2846 if (slen == 0 || slen > 0xFF00) {
2847 PyErr_SetString(PyExc_ValueError, "i2d() failed.");
2848 goto error;
2849 }
2850 if ((senc = PyMem_Malloc(slen)) == NULL) {
2851 PyErr_NoMemory();
2852 goto error;
2853 }
2854 p = senc;
2855 if (!i2d_SSL_SESSION(session, &p)) {
2856 PyErr_SetString(PyExc_ValueError, "i2d() failed.");
2857 goto error;
2858 }
2859 const_p = senc;
2860 newsession = d2i_SSL_SESSION(NULL, &const_p, slen);
2861 if (session == NULL) {
2862 goto error;
2863 }
2864 PyMem_Free(senc);
2865 return newsession;
2866 error:
2867 if (senc != NULL) {
2868 PyMem_Free(senc);
2869 }
2870 return NULL;
2871}
2872#endif
2873
2874static PyObject *
2875PySSL_get_session(PySSLSocket *self, void *closure) {
2876 /* get_session can return sessions from a server-side connection,
2877 * it does not check for handshake done or client socket. */
2878 PySSLSession *pysess;
2879 SSL_SESSION *session;
2880
2881#ifdef OPENSSL_VERSION_1_1
2882 /* duplicate session as workaround for session bug in OpenSSL 1.1.0,
2883 * https://github.com/openssl/openssl/issues/1550 */
2884 session = SSL_get0_session(self->ssl); /* borrowed reference */
2885 if (session == NULL) {
2886 Py_RETURN_NONE;
2887 }
2888 if ((session = _ssl_session_dup(session)) == NULL) {
2889 return NULL;
2890 }
2891#else
2892 session = SSL_get1_session(self->ssl);
2893 if (session == NULL) {
2894 Py_RETURN_NONE;
2895 }
2896#endif
Christian Heimesa5d07652016-09-24 10:48:05 +02002897 pysess = PyObject_GC_New(PySSLSession, &PySSLSession_Type);
Christian Heimes99a65702016-09-10 23:44:53 +02002898 if (pysess == NULL) {
2899 SSL_SESSION_free(session);
2900 return NULL;
2901 }
2902
2903 assert(self->ctx);
2904 pysess->ctx = self->ctx;
2905 Py_INCREF(pysess->ctx);
2906 pysess->session = session;
Christian Heimesa5d07652016-09-24 10:48:05 +02002907 PyObject_GC_Track(pysess);
Christian Heimes99a65702016-09-10 23:44:53 +02002908 return (PyObject *)pysess;
2909}
2910
2911static int PySSL_set_session(PySSLSocket *self, PyObject *value,
2912 void *closure)
2913 {
2914 PySSLSession *pysess;
2915#ifdef OPENSSL_VERSION_1_1
2916 SSL_SESSION *session;
2917#endif
2918 int result;
2919
2920 if (!PySSLSession_Check(value)) {
Ned Deily4531ec72018-06-11 20:26:28 -04002921 PyErr_SetString(PyExc_TypeError, "Value is not a SSLSession.");
Christian Heimes99a65702016-09-10 23:44:53 +02002922 return -1;
2923 }
2924 pysess = (PySSLSession *)value;
2925
2926 if (self->ctx->ctx != pysess->ctx->ctx) {
2927 PyErr_SetString(PyExc_ValueError,
2928 "Session refers to a different SSLContext.");
2929 return -1;
2930 }
2931 if (self->socket_type != PY_SSL_CLIENT) {
2932 PyErr_SetString(PyExc_ValueError,
2933 "Cannot set session for server-side SSLSocket.");
2934 return -1;
2935 }
Christian Heimes66dc33b2017-05-23 16:02:02 -07002936 if (SSL_is_init_finished(self->ssl)) {
Christian Heimes99a65702016-09-10 23:44:53 +02002937 PyErr_SetString(PyExc_ValueError,
2938 "Cannot set session after handshake.");
2939 return -1;
2940 }
2941#ifdef OPENSSL_VERSION_1_1
2942 /* duplicate session */
2943 if ((session = _ssl_session_dup(pysess->session)) == NULL) {
2944 return -1;
2945 }
2946 result = SSL_set_session(self->ssl, session);
2947 /* free duplicate, SSL_set_session() bumps ref count */
2948 SSL_SESSION_free(session);
2949#else
2950 result = SSL_set_session(self->ssl, pysess->session);
2951#endif
2952 if (result == 0) {
2953 _setSSLError(NULL, 0, __FILE__, __LINE__);
2954 return -1;
2955 }
2956 return 0;
2957}
2958
2959PyDoc_STRVAR(PySSL_set_session_doc,
2960"_setter_session(session)\n\
2961\
2962Get / set SSLSession.");
2963
2964static PyObject *
2965PySSL_get_session_reused(PySSLSocket *self, void *closure) {
2966 if (SSL_session_reused(self->ssl)) {
2967 Py_RETURN_TRUE;
2968 } else {
2969 Py_RETURN_FALSE;
2970 }
2971}
2972
2973PyDoc_STRVAR(PySSL_get_session_reused_doc,
2974"Was the client session reused during handshake?");
2975
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002976static PyGetSetDef ssl_getsetlist[] = {
2977 {"context", (getter) PySSL_get_context,
2978 (setter) PySSL_set_context, PySSL_set_context_doc},
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002979 {"server_side", (getter) PySSL_get_server_side, NULL,
2980 PySSL_get_server_side_doc},
2981 {"server_hostname", (getter) PySSL_get_server_hostname, NULL,
2982 PySSL_get_server_hostname_doc},
2983 {"owner", (getter) PySSL_get_owner, (setter) PySSL_set_owner,
2984 PySSL_get_owner_doc},
Christian Heimes99a65702016-09-10 23:44:53 +02002985 {"session", (getter) PySSL_get_session,
2986 (setter) PySSL_set_session, PySSL_set_session_doc},
2987 {"session_reused", (getter) PySSL_get_session_reused, NULL,
2988 PySSL_get_session_reused_doc},
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002989 {NULL}, /* sentinel */
2990};
2991
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002992static PyMethodDef PySSLMethods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002993 _SSL__SSLSOCKET_DO_HANDSHAKE_METHODDEF
2994 _SSL__SSLSOCKET_WRITE_METHODDEF
2995 _SSL__SSLSOCKET_READ_METHODDEF
2996 _SSL__SSLSOCKET_PENDING_METHODDEF
Christian Heimes141c5e82018-02-24 21:10:57 +01002997 _SSL__SSLSOCKET_GETPEERCERT_METHODDEF
2998 _SSL__SSLSOCKET_GET_CHANNEL_BINDING_METHODDEF
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002999 _SSL__SSLSOCKET_CIPHER_METHODDEF
3000 _SSL__SSLSOCKET_SHARED_CIPHERS_METHODDEF
3001 _SSL__SSLSOCKET_VERSION_METHODDEF
3002 _SSL__SSLSOCKET_SELECTED_NPN_PROTOCOL_METHODDEF
3003 _SSL__SSLSOCKET_SELECTED_ALPN_PROTOCOL_METHODDEF
3004 _SSL__SSLSOCKET_COMPRESSION_METHODDEF
3005 _SSL__SSLSOCKET_SHUTDOWN_METHODDEF
Christian Heimes9fb051f2018-09-23 08:32:31 +02003006 _SSL__SSLSOCKET_VERIFY_CLIENT_POST_HANDSHAKE_METHODDEF
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003007 {NULL, NULL}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003008};
3009
Antoine Pitrou152efa22010-05-16 18:19:27 +00003010static PyTypeObject PySSLSocket_Type = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003011 PyVarObject_HEAD_INIT(NULL, 0)
Antoine Pitrou152efa22010-05-16 18:19:27 +00003012 "_ssl._SSLSocket", /*tp_name*/
3013 sizeof(PySSLSocket), /*tp_basicsize*/
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003014 0, /*tp_itemsize*/
3015 /* methods */
3016 (destructor)PySSL_dealloc, /*tp_dealloc*/
Jeroen Demeyer530f5062019-05-31 04:13:39 +02003017 0, /*tp_vectorcall_offset*/
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003018 0, /*tp_getattr*/
3019 0, /*tp_setattr*/
Jeroen Demeyer530f5062019-05-31 04:13:39 +02003020 0, /*tp_as_async*/
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003021 0, /*tp_repr*/
3022 0, /*tp_as_number*/
3023 0, /*tp_as_sequence*/
3024 0, /*tp_as_mapping*/
3025 0, /*tp_hash*/
3026 0, /*tp_call*/
3027 0, /*tp_str*/
3028 0, /*tp_getattro*/
3029 0, /*tp_setattro*/
3030 0, /*tp_as_buffer*/
3031 Py_TPFLAGS_DEFAULT, /*tp_flags*/
3032 0, /*tp_doc*/
Christian Heimesc7f70692019-05-31 11:44:05 +02003033 (traverseproc) PySSL_traverse, /*tp_traverse*/
3034 (inquiry) PySSL_clear, /*tp_clear*/
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003035 0, /*tp_richcompare*/
3036 0, /*tp_weaklistoffset*/
3037 0, /*tp_iter*/
3038 0, /*tp_iternext*/
3039 PySSLMethods, /*tp_methods*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003040 0, /*tp_members*/
3041 ssl_getsetlist, /*tp_getset*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003042};
3043
Antoine Pitrou152efa22010-05-16 18:19:27 +00003044
3045/*
3046 * _SSLContext objects
3047 */
3048
Christian Heimes5fe668c2016-09-12 00:01:11 +02003049static int
Christian Heimes9fb051f2018-09-23 08:32:31 +02003050_set_verify_mode(PySSLContext *self, enum py_ssl_cert_requirements n)
Christian Heimes5fe668c2016-09-12 00:01:11 +02003051{
3052 int mode;
3053 int (*verify_cb)(int, X509_STORE_CTX *) = NULL;
3054
3055 switch(n) {
3056 case PY_SSL_CERT_NONE:
3057 mode = SSL_VERIFY_NONE;
3058 break;
3059 case PY_SSL_CERT_OPTIONAL:
3060 mode = SSL_VERIFY_PEER;
3061 break;
3062 case PY_SSL_CERT_REQUIRED:
3063 mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
3064 break;
3065 default:
3066 PyErr_SetString(PyExc_ValueError,
3067 "invalid value for verify_mode");
3068 return -1;
3069 }
Christian Heimesf0f59302019-07-01 08:29:17 +02003070
3071 /* bpo-37428: newPySSLSocket() sets SSL_VERIFY_POST_HANDSHAKE flag for
3072 * server sockets and SSL_set_post_handshake_auth() for client. */
3073
Christian Heimes5fe668c2016-09-12 00:01:11 +02003074 /* keep current verify cb */
Christian Heimes9fb051f2018-09-23 08:32:31 +02003075 verify_cb = SSL_CTX_get_verify_callback(self->ctx);
3076 SSL_CTX_set_verify(self->ctx, mode, verify_cb);
Christian Heimes5fe668c2016-09-12 00:01:11 +02003077 return 0;
3078}
3079
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003080/*[clinic input]
3081@classmethod
3082_ssl._SSLContext.__new__
3083 protocol as proto_version: int
3084 /
3085[clinic start generated code]*/
3086
Antoine Pitrou152efa22010-05-16 18:19:27 +00003087static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003088_ssl__SSLContext_impl(PyTypeObject *type, int proto_version)
3089/*[clinic end generated code: output=2cf0d7a0741b6bd1 input=8d58a805b95fc534]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003090{
Antoine Pitrou152efa22010-05-16 18:19:27 +00003091 PySSLContext *self;
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01003092 long options;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003093 SSL_CTX *ctx = NULL;
Christian Heimes61d478c2018-01-27 15:51:38 +01003094 X509_VERIFY_PARAM *params;
Christian Heimes358cfd42016-09-10 22:43:48 +02003095 int result;
Berker Peksagdfcb0412016-04-14 16:48:48 +03003096#if defined(SSL_MODE_RELEASE_BUFFERS)
Benjamin Peterson3b1a8b32016-01-07 21:37:37 -08003097 unsigned long libver;
Berker Peksagdfcb0412016-04-14 16:48:48 +03003098#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00003099
Antoine Pitrou152efa22010-05-16 18:19:27 +00003100 PySSL_BEGIN_ALLOW_THREADS
Christian Heimes6e8cda92020-05-16 03:33:05 +02003101 switch(proto_version) {
3102#if defined(SSL3_VERSION) && !defined(OPENSSL_NO_SSL3)
3103 case PY_SSL_VERSION_SSL3:
Antoine Pitrou152efa22010-05-16 18:19:27 +00003104 ctx = SSL_CTX_new(SSLv3_method());
Christian Heimes6e8cda92020-05-16 03:33:05 +02003105 break;
Benjamin Petersone32467c2014-12-05 21:59:35 -05003106#endif
Christian Heimesa871f692020-06-01 08:58:14 +02003107#if (defined(TLS1_VERSION) && \
3108 !defined(OPENSSL_NO_TLS1) && \
3109 !defined(OPENSSL_NO_TLS1_METHOD))
Christian Heimes6e8cda92020-05-16 03:33:05 +02003110 case PY_SSL_VERSION_TLS1:
3111 ctx = SSL_CTX_new(TLSv1_method());
3112 break;
Victor Stinner3de49192011-05-09 00:42:58 +02003113#endif
Christian Heimesa871f692020-06-01 08:58:14 +02003114#if (defined(TLS1_1_VERSION) && \
3115 !defined(OPENSSL_NO_TLS1_1) && \
3116 !defined(OPENSSL_NO_TLS1_1_METHOD))
Christian Heimes6e8cda92020-05-16 03:33:05 +02003117 case PY_SSL_VERSION_TLS1_1:
3118 ctx = SSL_CTX_new(TLSv1_1_method());
3119 break;
3120#endif
Christian Heimesa871f692020-06-01 08:58:14 +02003121#if (defined(TLS1_2_VERSION) && \
3122 !defined(OPENSSL_NO_TLS1_2) && \
3123 !defined(OPENSSL_NO_TLS1_2_METHOD))
Christian Heimes6e8cda92020-05-16 03:33:05 +02003124 case PY_SSL_VERSION_TLS1_2:
3125 ctx = SSL_CTX_new(TLSv1_2_method());
3126 break;
3127#endif
3128 case PY_SSL_VERSION_TLS:
3129 /* SSLv23 */
Christian Heimes598894f2016-09-05 23:19:05 +02003130 ctx = SSL_CTX_new(TLS_method());
Christian Heimes6e8cda92020-05-16 03:33:05 +02003131 break;
3132 case PY_SSL_VERSION_TLS_CLIENT:
Christian Heimes5fe668c2016-09-12 00:01:11 +02003133 ctx = SSL_CTX_new(TLS_client_method());
Christian Heimes6e8cda92020-05-16 03:33:05 +02003134 break;
3135 case PY_SSL_VERSION_TLS_SERVER:
Christian Heimes5fe668c2016-09-12 00:01:11 +02003136 ctx = SSL_CTX_new(TLS_server_method());
Christian Heimes6e8cda92020-05-16 03:33:05 +02003137 break;
3138 default:
Antoine Pitrou152efa22010-05-16 18:19:27 +00003139 proto_version = -1;
Christian Heimes6e8cda92020-05-16 03:33:05 +02003140 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003141 PySSL_END_ALLOW_THREADS
3142
3143 if (proto_version == -1) {
3144 PyErr_SetString(PyExc_ValueError,
Christian Heimes6e8cda92020-05-16 03:33:05 +02003145 "invalid or unsupported protocol version");
Antoine Pitrou152efa22010-05-16 18:19:27 +00003146 return NULL;
3147 }
3148 if (ctx == NULL) {
Christian Heimes17c9ac92017-09-07 14:14:00 -07003149 _setSSLError(NULL, 0, __FILE__, __LINE__);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003150 return NULL;
3151 }
3152
3153 assert(type != NULL && type->tp_alloc != NULL);
3154 self = (PySSLContext *) type->tp_alloc(type, 0);
3155 if (self == NULL) {
3156 SSL_CTX_free(ctx);
3157 return NULL;
3158 }
3159 self->ctx = ctx;
Christian Heimes61d478c2018-01-27 15:51:38 +01003160 self->hostflags = X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS;
Christian Heimes11a14932018-02-24 02:35:08 +01003161 self->protocol = proto_version;
Christian Heimesc7f70692019-05-31 11:44:05 +02003162 self->msg_cb = NULL;
3163#ifdef HAVE_OPENSSL_KEYLOG
3164 self->keylog_filename = NULL;
3165 self->keylog_bio = NULL;
3166#endif
Christian Heimes29eab552018-02-25 12:31:33 +01003167#if HAVE_NPN
Christian Heimes5cb31c92012-09-20 12:42:54 +02003168 self->npn_protocols = NULL;
3169#endif
Christian Heimes29eab552018-02-25 12:31:33 +01003170#if HAVE_ALPN
Benjamin Petersoncca27322015-01-23 16:35:37 -05003171 self->alpn_protocols = NULL;
3172#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003173#ifndef OPENSSL_NO_TLSEXT
Christian Heimes11a14932018-02-24 02:35:08 +01003174 self->set_sni_cb = NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003175#endif
Christian Heimes1aa9a752013-12-02 02:41:19 +01003176 /* Don't check host name by default */
Christian Heimes5fe668c2016-09-12 00:01:11 +02003177 if (proto_version == PY_SSL_VERSION_TLS_CLIENT) {
3178 self->check_hostname = 1;
Christian Heimes9fb051f2018-09-23 08:32:31 +02003179 if (_set_verify_mode(self, PY_SSL_CERT_REQUIRED) == -1) {
Christian Heimes5fe668c2016-09-12 00:01:11 +02003180 Py_DECREF(self);
3181 return NULL;
3182 }
3183 } else {
3184 self->check_hostname = 0;
Christian Heimes9fb051f2018-09-23 08:32:31 +02003185 if (_set_verify_mode(self, PY_SSL_CERT_NONE) == -1) {
Christian Heimes5fe668c2016-09-12 00:01:11 +02003186 Py_DECREF(self);
3187 return NULL;
3188 }
3189 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003190 /* Defaults */
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01003191 options = SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
3192 if (proto_version != PY_SSL_VERSION_SSL2)
3193 options |= SSL_OP_NO_SSLv2;
Benjamin Petersona9dcdab2015-11-11 22:38:41 -08003194 if (proto_version != PY_SSL_VERSION_SSL3)
3195 options |= SSL_OP_NO_SSLv3;
Christian Heimes358cfd42016-09-10 22:43:48 +02003196 /* Minimal security flags for server and client side context.
3197 * Client sockets ignore server-side parameters. */
3198#ifdef SSL_OP_NO_COMPRESSION
3199 options |= SSL_OP_NO_COMPRESSION;
3200#endif
3201#ifdef SSL_OP_CIPHER_SERVER_PREFERENCE
3202 options |= SSL_OP_CIPHER_SERVER_PREFERENCE;
3203#endif
3204#ifdef SSL_OP_SINGLE_DH_USE
3205 options |= SSL_OP_SINGLE_DH_USE;
3206#endif
3207#ifdef SSL_OP_SINGLE_ECDH_USE
3208 options |= SSL_OP_SINGLE_ECDH_USE;
3209#endif
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01003210 SSL_CTX_set_options(self->ctx, options);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003211
Semen Zhydenko1295e112017-10-15 21:28:31 +02003212 /* A bare minimum cipher list without completely broken cipher suites.
Christian Heimes358cfd42016-09-10 22:43:48 +02003213 * It's far from perfect but gives users a better head start. */
3214 if (proto_version != PY_SSL_VERSION_SSL2) {
Christian Heimes892d66e2018-01-29 14:10:18 +01003215#if PY_SSL_DEFAULT_CIPHERS == 2
3216 /* stick to OpenSSL's default settings */
3217 result = 1;
3218#else
3219 result = SSL_CTX_set_cipher_list(ctx, PY_SSL_DEFAULT_CIPHER_STRING);
3220#endif
Christian Heimes358cfd42016-09-10 22:43:48 +02003221 } else {
3222 /* SSLv2 needs MD5 */
3223 result = SSL_CTX_set_cipher_list(ctx, "HIGH:!aNULL:!eNULL");
3224 }
3225 if (result == 0) {
3226 Py_DECREF(self);
3227 ERR_clear_error();
3228 PyErr_SetString(PySSLErrorObject,
3229 "No cipher can be selected.");
3230 return NULL;
3231 }
3232
Benjamin Peterson3b1a8b32016-01-07 21:37:37 -08003233#if defined(SSL_MODE_RELEASE_BUFFERS)
3234 /* Set SSL_MODE_RELEASE_BUFFERS. This potentially greatly reduces memory
3235 usage for no cost at all. However, don't do this for OpenSSL versions
3236 between 1.0.1 and 1.0.1h or 1.0.0 and 1.0.0m, which are affected by CVE
3237 2014-0198. I can't find exactly which beta fixed this CVE, so be
3238 conservative and assume it wasn't fixed until release. We do this check
3239 at runtime to avoid problems from the dynamic linker.
3240 See #25672 for more on this. */
Christian Heimesa871f692020-06-01 08:58:14 +02003241 libver = OpenSSL_version_num();
Benjamin Peterson3b1a8b32016-01-07 21:37:37 -08003242 if (!(libver >= 0x10001000UL && libver < 0x1000108fUL) &&
3243 !(libver >= 0x10000000UL && libver < 0x100000dfUL)) {
3244 SSL_CTX_set_mode(self->ctx, SSL_MODE_RELEASE_BUFFERS);
3245 }
3246#endif
3247
3248
Donald Stufft8ae264c2017-03-02 11:45:29 -05003249#if !defined(OPENSSL_NO_ECDH) && !defined(OPENSSL_VERSION_1_1)
Antoine Pitrou0bebbc32014-03-22 18:13:50 +01003250 /* Allow automatic ECDH curve selection (on OpenSSL 1.0.2+), or use
3251 prime256v1 by default. This is Apache mod_ssl's initialization
Christian Heimes598894f2016-09-05 23:19:05 +02003252 policy, so we should be safe. OpenSSL 1.1 has it enabled by default.
3253 */
Donald Stufft8ae264c2017-03-02 11:45:29 -05003254#if defined(SSL_CTX_set_ecdh_auto)
Antoine Pitrou0bebbc32014-03-22 18:13:50 +01003255 SSL_CTX_set_ecdh_auto(self->ctx, 1);
3256#else
3257 {
3258 EC_KEY *key = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
3259 SSL_CTX_set_tmp_ecdh(self->ctx, key);
3260 EC_KEY_free(key);
3261 }
3262#endif
3263#endif
3264
Antoine Pitroufc113ee2010-10-13 12:46:13 +00003265#define SID_CTX "Python"
3266 SSL_CTX_set_session_id_context(self->ctx, (const unsigned char *) SID_CTX,
3267 sizeof(SID_CTX));
3268#undef SID_CTX
3269
Christian Heimes61d478c2018-01-27 15:51:38 +01003270 params = SSL_CTX_get0_param(self->ctx);
Benjamin Petersonfdb19712015-03-04 22:11:12 -05003271#ifdef X509_V_FLAG_TRUSTED_FIRST
Christian Heimes61d478c2018-01-27 15:51:38 +01003272 /* Improve trust chain building when cross-signed intermediate
3273 certificates are present. See https://bugs.python.org/issue23476. */
3274 X509_VERIFY_PARAM_set_flags(params, X509_V_FLAG_TRUSTED_FIRST);
Benjamin Petersonfdb19712015-03-04 22:11:12 -05003275#endif
Christian Heimes61d478c2018-01-27 15:51:38 +01003276 X509_VERIFY_PARAM_set_hostflags(params, self->hostflags);
Benjamin Petersonfdb19712015-03-04 22:11:12 -05003277
Christian Heimes9fb051f2018-09-23 08:32:31 +02003278#ifdef TLS1_3_VERSION
3279 self->post_handshake_auth = 0;
3280 SSL_CTX_set_post_handshake_auth(self->ctx, self->post_handshake_auth);
3281#endif
3282
Antoine Pitrou152efa22010-05-16 18:19:27 +00003283 return (PyObject *)self;
3284}
3285
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003286static int
3287context_traverse(PySSLContext *self, visitproc visit, void *arg)
3288{
3289#ifndef OPENSSL_NO_TLSEXT
Christian Heimes11a14932018-02-24 02:35:08 +01003290 Py_VISIT(self->set_sni_cb);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003291#endif
Christian Heimesc7f70692019-05-31 11:44:05 +02003292 Py_VISIT(self->msg_cb);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003293 return 0;
3294}
3295
3296static int
3297context_clear(PySSLContext *self)
3298{
3299#ifndef OPENSSL_NO_TLSEXT
Christian Heimes11a14932018-02-24 02:35:08 +01003300 Py_CLEAR(self->set_sni_cb);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003301#endif
Christian Heimesc7f70692019-05-31 11:44:05 +02003302 Py_CLEAR(self->msg_cb);
3303#ifdef HAVE_OPENSSL_KEYLOG
3304 Py_CLEAR(self->keylog_filename);
3305 if (self->keylog_bio != NULL) {
3306 PySSL_BEGIN_ALLOW_THREADS
3307 BIO_free_all(self->keylog_bio);
3308 PySSL_END_ALLOW_THREADS
3309 self->keylog_bio = NULL;
3310 }
3311#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003312 return 0;
3313}
3314
Antoine Pitrou152efa22010-05-16 18:19:27 +00003315static void
3316context_dealloc(PySSLContext *self)
3317{
INADA Naokia6296d32017-08-24 14:55:17 +09003318 /* bpo-31095: UnTrack is needed before calling any callbacks */
3319 PyObject_GC_UnTrack(self);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003320 context_clear(self);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003321 SSL_CTX_free(self->ctx);
Christian Heimes29eab552018-02-25 12:31:33 +01003322#if HAVE_NPN
Benjamin Petersoncca27322015-01-23 16:35:37 -05003323 PyMem_FREE(self->npn_protocols);
3324#endif
Christian Heimes29eab552018-02-25 12:31:33 +01003325#if HAVE_ALPN
Benjamin Petersoncca27322015-01-23 16:35:37 -05003326 PyMem_FREE(self->alpn_protocols);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003327#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00003328 Py_TYPE(self)->tp_free(self);
3329}
3330
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003331/*[clinic input]
3332_ssl._SSLContext.set_ciphers
3333 cipherlist: str
3334 /
3335[clinic start generated code]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003336
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003337static PyObject *
3338_ssl__SSLContext_set_ciphers_impl(PySSLContext *self, const char *cipherlist)
3339/*[clinic end generated code: output=3a3162f3557c0f3f input=a7ac931b9f3ca7fc]*/
3340{
3341 int ret = SSL_CTX_set_cipher_list(self->ctx, cipherlist);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003342 if (ret == 0) {
Antoine Pitrou65ec8ae2010-05-16 19:56:32 +00003343 /* Clearing the error queue is necessary on some OpenSSL versions,
3344 otherwise the error will be reported again when another SSL call
3345 is done. */
3346 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00003347 PyErr_SetString(PySSLErrorObject,
3348 "No cipher can be selected.");
3349 return NULL;
3350 }
3351 Py_RETURN_NONE;
3352}
3353
Christian Heimes25bfcd52016-09-06 00:04:45 +02003354#if OPENSSL_VERSION_NUMBER >= 0x10002000UL
3355/*[clinic input]
3356_ssl._SSLContext.get_ciphers
3357[clinic start generated code]*/
3358
3359static PyObject *
3360_ssl__SSLContext_get_ciphers_impl(PySSLContext *self)
3361/*[clinic end generated code: output=a56e4d68a406dfc4 input=a2aadc9af89b79c5]*/
3362{
3363 SSL *ssl = NULL;
3364 STACK_OF(SSL_CIPHER) *sk = NULL;
Christian Heimes99a65702016-09-10 23:44:53 +02003365 const SSL_CIPHER *cipher;
Christian Heimes25bfcd52016-09-06 00:04:45 +02003366 int i=0;
3367 PyObject *result = NULL, *dct;
3368
3369 ssl = SSL_new(self->ctx);
3370 if (ssl == NULL) {
3371 _setSSLError(NULL, 0, __FILE__, __LINE__);
3372 goto exit;
3373 }
3374 sk = SSL_get_ciphers(ssl);
3375
3376 result = PyList_New(sk_SSL_CIPHER_num(sk));
3377 if (result == NULL) {
3378 goto exit;
3379 }
3380
3381 for (i = 0; i < sk_SSL_CIPHER_num(sk); i++) {
3382 cipher = sk_SSL_CIPHER_value(sk, i);
3383 dct = cipher_to_dict(cipher);
3384 if (dct == NULL) {
3385 Py_CLEAR(result);
3386 goto exit;
3387 }
3388 PyList_SET_ITEM(result, i, dct);
3389 }
3390
3391 exit:
3392 if (ssl != NULL)
3393 SSL_free(ssl);
3394 return result;
3395
3396}
3397#endif
3398
3399
Christian Heimes29eab552018-02-25 12:31:33 +01003400#if HAVE_NPN || HAVE_ALPN
Benjamin Petersoncca27322015-01-23 16:35:37 -05003401static int
Benjamin Peterson88615022015-01-23 17:30:26 -05003402do_protocol_selection(int alpn, unsigned char **out, unsigned char *outlen,
3403 const unsigned char *server_protocols, unsigned int server_protocols_len,
3404 const unsigned char *client_protocols, unsigned int client_protocols_len)
Benjamin Petersoncca27322015-01-23 16:35:37 -05003405{
Benjamin Peterson88615022015-01-23 17:30:26 -05003406 int ret;
3407 if (client_protocols == NULL) {
3408 client_protocols = (unsigned char *)"";
3409 client_protocols_len = 0;
3410 }
3411 if (server_protocols == NULL) {
3412 server_protocols = (unsigned char *)"";
3413 server_protocols_len = 0;
Benjamin Petersoncca27322015-01-23 16:35:37 -05003414 }
3415
Benjamin Peterson88615022015-01-23 17:30:26 -05003416 ret = SSL_select_next_proto(out, outlen,
3417 server_protocols, server_protocols_len,
3418 client_protocols, client_protocols_len);
3419 if (alpn && ret != OPENSSL_NPN_NEGOTIATED)
3420 return SSL_TLSEXT_ERR_NOACK;
Benjamin Petersoncca27322015-01-23 16:35:37 -05003421
3422 return SSL_TLSEXT_ERR_OK;
3423}
Melvyn Sopacuab2d096b2017-09-04 23:35:15 +02003424#endif
Benjamin Petersoncca27322015-01-23 16:35:37 -05003425
Christian Heimes29eab552018-02-25 12:31:33 +01003426#if HAVE_NPN
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003427/* this callback gets passed to SSL_CTX_set_next_protos_advertise_cb */
3428static int
Victor Stinner4569cd52013-06-23 14:58:43 +02003429_advertiseNPN_cb(SSL *s,
3430 const unsigned char **data, unsigned int *len,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003431 void *args)
3432{
3433 PySSLContext *ssl_ctx = (PySSLContext *) args;
3434
3435 if (ssl_ctx->npn_protocols == NULL) {
Benjamin Petersoncca27322015-01-23 16:35:37 -05003436 *data = (unsigned char *)"";
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003437 *len = 0;
3438 } else {
Benjamin Petersoncca27322015-01-23 16:35:37 -05003439 *data = ssl_ctx->npn_protocols;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003440 *len = ssl_ctx->npn_protocols_len;
3441 }
3442
3443 return SSL_TLSEXT_ERR_OK;
3444}
3445/* this callback gets passed to SSL_CTX_set_next_proto_select_cb */
3446static int
Victor Stinner4569cd52013-06-23 14:58:43 +02003447_selectNPN_cb(SSL *s,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003448 unsigned char **out, unsigned char *outlen,
3449 const unsigned char *server, unsigned int server_len,
3450 void *args)
3451{
Benjamin Petersoncca27322015-01-23 16:35:37 -05003452 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Peterson88615022015-01-23 17:30:26 -05003453 return do_protocol_selection(0, out, outlen, server, server_len,
Benjamin Petersoncca27322015-01-23 16:35:37 -05003454 ctx->npn_protocols, ctx->npn_protocols_len);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003455}
3456#endif
3457
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003458/*[clinic input]
3459_ssl._SSLContext._set_npn_protocols
3460 protos: Py_buffer
3461 /
3462[clinic start generated code]*/
3463
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003464static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003465_ssl__SSLContext__set_npn_protocols_impl(PySSLContext *self,
3466 Py_buffer *protos)
3467/*[clinic end generated code: output=72b002c3324390c6 input=319fcb66abf95bd7]*/
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003468{
Christian Heimes29eab552018-02-25 12:31:33 +01003469#if HAVE_NPN
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003470 PyMem_Free(self->npn_protocols);
3471 self->npn_protocols = PyMem_Malloc(protos->len);
3472 if (self->npn_protocols == NULL)
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003473 return PyErr_NoMemory();
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003474 memcpy(self->npn_protocols, protos->buf, protos->len);
3475 self->npn_protocols_len = (int) protos->len;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003476
3477 /* set both server and client callbacks, because the context can
3478 * be used to create both types of sockets */
3479 SSL_CTX_set_next_protos_advertised_cb(self->ctx,
3480 _advertiseNPN_cb,
3481 self);
3482 SSL_CTX_set_next_proto_select_cb(self->ctx,
3483 _selectNPN_cb,
3484 self);
3485
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003486 Py_RETURN_NONE;
3487#else
3488 PyErr_SetString(PyExc_NotImplementedError,
3489 "The NPN extension requires OpenSSL 1.0.1 or later.");
3490 return NULL;
3491#endif
3492}
3493
Christian Heimes29eab552018-02-25 12:31:33 +01003494#if HAVE_ALPN
Benjamin Petersoncca27322015-01-23 16:35:37 -05003495static int
3496_selectALPN_cb(SSL *s,
3497 const unsigned char **out, unsigned char *outlen,
3498 const unsigned char *client_protocols, unsigned int client_protocols_len,
3499 void *args)
3500{
3501 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Peterson88615022015-01-23 17:30:26 -05003502 return do_protocol_selection(1, (unsigned char **)out, outlen,
3503 ctx->alpn_protocols, ctx->alpn_protocols_len,
3504 client_protocols, client_protocols_len);
Benjamin Petersoncca27322015-01-23 16:35:37 -05003505}
3506#endif
3507
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003508/*[clinic input]
3509_ssl._SSLContext._set_alpn_protocols
3510 protos: Py_buffer
3511 /
3512[clinic start generated code]*/
3513
Benjamin Petersoncca27322015-01-23 16:35:37 -05003514static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003515_ssl__SSLContext__set_alpn_protocols_impl(PySSLContext *self,
3516 Py_buffer *protos)
3517/*[clinic end generated code: output=87599a7f76651a9b input=9bba964595d519be]*/
Benjamin Petersoncca27322015-01-23 16:35:37 -05003518{
Christian Heimes29eab552018-02-25 12:31:33 +01003519#if HAVE_ALPN
Victor Stinner5a615592017-09-14 01:10:30 -07003520 if ((size_t)protos->len > UINT_MAX) {
Segev Finer5cff6372017-07-27 01:19:17 +03003521 PyErr_Format(PyExc_OverflowError,
Serhiy Storchakad53fe5f2019-03-13 22:59:55 +02003522 "protocols longer than %u bytes", UINT_MAX);
Segev Finer5cff6372017-07-27 01:19:17 +03003523 return NULL;
3524 }
3525
Benjamin Petersoncca27322015-01-23 16:35:37 -05003526 PyMem_FREE(self->alpn_protocols);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003527 self->alpn_protocols = PyMem_Malloc(protos->len);
Benjamin Petersoncca27322015-01-23 16:35:37 -05003528 if (!self->alpn_protocols)
3529 return PyErr_NoMemory();
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003530 memcpy(self->alpn_protocols, protos->buf, protos->len);
Segev Finer5cff6372017-07-27 01:19:17 +03003531 self->alpn_protocols_len = (unsigned int)protos->len;
Benjamin Petersoncca27322015-01-23 16:35:37 -05003532
3533 if (SSL_CTX_set_alpn_protos(self->ctx, self->alpn_protocols, self->alpn_protocols_len))
3534 return PyErr_NoMemory();
3535 SSL_CTX_set_alpn_select_cb(self->ctx, _selectALPN_cb, self);
3536
Benjamin Petersoncca27322015-01-23 16:35:37 -05003537 Py_RETURN_NONE;
3538#else
3539 PyErr_SetString(PyExc_NotImplementedError,
3540 "The ALPN extension requires OpenSSL 1.0.2 or later.");
3541 return NULL;
3542#endif
3543}
3544
Antoine Pitrou152efa22010-05-16 18:19:27 +00003545static PyObject *
3546get_verify_mode(PySSLContext *self, void *c)
3547{
Christian Heimes9fb051f2018-09-23 08:32:31 +02003548 /* ignore SSL_VERIFY_CLIENT_ONCE and SSL_VERIFY_POST_HANDSHAKE */
3549 int mask = (SSL_VERIFY_NONE | SSL_VERIFY_PEER |
3550 SSL_VERIFY_FAIL_IF_NO_PEER_CERT);
3551 switch (SSL_CTX_get_verify_mode(self->ctx) & mask) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003552 case SSL_VERIFY_NONE:
3553 return PyLong_FromLong(PY_SSL_CERT_NONE);
3554 case SSL_VERIFY_PEER:
3555 return PyLong_FromLong(PY_SSL_CERT_OPTIONAL);
3556 case SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT:
3557 return PyLong_FromLong(PY_SSL_CERT_REQUIRED);
3558 }
3559 PyErr_SetString(PySSLErrorObject,
3560 "invalid return value from SSL_CTX_get_verify_mode");
3561 return NULL;
3562}
3563
3564static int
3565set_verify_mode(PySSLContext *self, PyObject *arg, void *c)
3566{
Christian Heimes5fe668c2016-09-12 00:01:11 +02003567 int n;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003568 if (!PyArg_Parse(arg, "i", &n))
3569 return -1;
Christian Heimes5fe668c2016-09-12 00:01:11 +02003570 if (n == PY_SSL_CERT_NONE && self->check_hostname) {
Christian Heimes1aa9a752013-12-02 02:41:19 +01003571 PyErr_SetString(PyExc_ValueError,
3572 "Cannot set verify_mode to CERT_NONE when "
3573 "check_hostname is enabled.");
3574 return -1;
3575 }
Christian Heimes9fb051f2018-09-23 08:32:31 +02003576 return _set_verify_mode(self, n);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003577}
3578
3579static PyObject *
Christian Heimes22587792013-11-21 23:56:13 +01003580get_verify_flags(PySSLContext *self, void *c)
3581{
Christian Heimes598894f2016-09-05 23:19:05 +02003582 X509_VERIFY_PARAM *param;
Christian Heimes22587792013-11-21 23:56:13 +01003583 unsigned long flags;
3584
Christian Heimes61d478c2018-01-27 15:51:38 +01003585 param = SSL_CTX_get0_param(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02003586 flags = X509_VERIFY_PARAM_get_flags(param);
Christian Heimes22587792013-11-21 23:56:13 +01003587 return PyLong_FromUnsignedLong(flags);
3588}
3589
3590static int
3591set_verify_flags(PySSLContext *self, PyObject *arg, void *c)
3592{
Christian Heimes598894f2016-09-05 23:19:05 +02003593 X509_VERIFY_PARAM *param;
Christian Heimes22587792013-11-21 23:56:13 +01003594 unsigned long new_flags, flags, set, clear;
3595
3596 if (!PyArg_Parse(arg, "k", &new_flags))
3597 return -1;
Christian Heimes61d478c2018-01-27 15:51:38 +01003598 param = SSL_CTX_get0_param(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02003599 flags = X509_VERIFY_PARAM_get_flags(param);
Christian Heimes22587792013-11-21 23:56:13 +01003600 clear = flags & ~new_flags;
3601 set = ~flags & new_flags;
3602 if (clear) {
Christian Heimes598894f2016-09-05 23:19:05 +02003603 if (!X509_VERIFY_PARAM_clear_flags(param, clear)) {
Christian Heimes22587792013-11-21 23:56:13 +01003604 _setSSLError(NULL, 0, __FILE__, __LINE__);
3605 return -1;
3606 }
3607 }
3608 if (set) {
Christian Heimes598894f2016-09-05 23:19:05 +02003609 if (!X509_VERIFY_PARAM_set_flags(param, set)) {
Christian Heimes22587792013-11-21 23:56:13 +01003610 _setSSLError(NULL, 0, __FILE__, __LINE__);
3611 return -1;
3612 }
3613 }
3614 return 0;
3615}
3616
Christian Heimes698dde12018-02-27 11:54:43 +01003617/* Getter and setter for protocol version */
3618#if defined(SSL_CTRL_GET_MAX_PROTO_VERSION)
3619
3620
3621static int
3622set_min_max_proto_version(PySSLContext *self, PyObject *arg, int what)
3623{
3624 long v;
3625 int result;
3626
3627 if (!PyArg_Parse(arg, "l", &v))
3628 return -1;
3629 if (v > INT_MAX) {
3630 PyErr_SetString(PyExc_OverflowError, "Option is too long");
3631 return -1;
3632 }
3633
3634 switch(self->protocol) {
3635 case PY_SSL_VERSION_TLS_CLIENT: /* fall through */
3636 case PY_SSL_VERSION_TLS_SERVER: /* fall through */
3637 case PY_SSL_VERSION_TLS:
3638 break;
3639 default:
3640 PyErr_SetString(
3641 PyExc_ValueError,
3642 "The context's protocol doesn't support modification of "
3643 "highest and lowest version."
3644 );
3645 return -1;
3646 }
3647
3648 if (what == 0) {
3649 switch(v) {
3650 case PY_PROTO_MINIMUM_SUPPORTED:
3651 v = 0;
3652 break;
3653 case PY_PROTO_MAXIMUM_SUPPORTED:
3654 /* Emulate max for set_min_proto_version */
3655 v = PY_PROTO_MAXIMUM_AVAILABLE;
3656 break;
3657 default:
3658 break;
3659 }
3660 result = SSL_CTX_set_min_proto_version(self->ctx, v);
3661 }
3662 else {
3663 switch(v) {
3664 case PY_PROTO_MAXIMUM_SUPPORTED:
3665 v = 0;
3666 break;
3667 case PY_PROTO_MINIMUM_SUPPORTED:
3668 /* Emulate max for set_min_proto_version */
3669 v = PY_PROTO_MINIMUM_AVAILABLE;
3670 break;
3671 default:
3672 break;
3673 }
3674 result = SSL_CTX_set_max_proto_version(self->ctx, v);
3675 }
3676 if (result == 0) {
3677 PyErr_Format(PyExc_ValueError,
3678 "Unsupported protocol version 0x%x", v);
3679 return -1;
3680 }
3681 return 0;
3682}
3683
3684static PyObject *
3685get_minimum_version(PySSLContext *self, void *c)
3686{
3687 int v = SSL_CTX_ctrl(self->ctx, SSL_CTRL_GET_MIN_PROTO_VERSION, 0, NULL);
3688 if (v == 0) {
3689 v = PY_PROTO_MINIMUM_SUPPORTED;
3690 }
3691 return PyLong_FromLong(v);
3692}
3693
3694static int
3695set_minimum_version(PySSLContext *self, PyObject *arg, void *c)
3696{
3697 return set_min_max_proto_version(self, arg, 0);
3698}
3699
3700static PyObject *
3701get_maximum_version(PySSLContext *self, void *c)
3702{
3703 int v = SSL_CTX_ctrl(self->ctx, SSL_CTRL_GET_MAX_PROTO_VERSION, 0, NULL);
3704 if (v == 0) {
3705 v = PY_PROTO_MAXIMUM_SUPPORTED;
3706 }
3707 return PyLong_FromLong(v);
3708}
3709
3710static int
3711set_maximum_version(PySSLContext *self, PyObject *arg, void *c)
3712{
3713 return set_min_max_proto_version(self, arg, 1);
3714}
3715#endif /* SSL_CTRL_GET_MAX_PROTO_VERSION */
3716
Christian Heimes78c7d522019-06-03 21:00:10 +02003717#if (OPENSSL_VERSION_NUMBER >= 0x10101000L) && !defined(LIBRESSL_VERSION_NUMBER)
3718static PyObject *
3719get_num_tickets(PySSLContext *self, void *c)
3720{
Victor Stinner76611c72019-07-09 13:30:52 +02003721 return PyLong_FromSize_t(SSL_CTX_get_num_tickets(self->ctx));
Christian Heimes78c7d522019-06-03 21:00:10 +02003722}
3723
3724static int
3725set_num_tickets(PySSLContext *self, PyObject *arg, void *c)
3726{
3727 long num;
3728 if (!PyArg_Parse(arg, "l", &num))
3729 return -1;
3730 if (num < 0) {
3731 PyErr_SetString(PyExc_ValueError, "value must be non-negative");
3732 return -1;
3733 }
3734 if (self->protocol != PY_SSL_VERSION_TLS_SERVER) {
3735 PyErr_SetString(PyExc_ValueError,
3736 "SSLContext is not a server context.");
3737 return -1;
3738 }
3739 if (SSL_CTX_set_num_tickets(self->ctx, num) != 1) {
3740 PyErr_SetString(PyExc_ValueError, "failed to set num tickets.");
3741 return -1;
3742 }
3743 return 0;
3744}
3745
3746PyDoc_STRVAR(PySSLContext_num_tickets_doc,
3747"Control the number of TLSv1.3 session tickets");
3748#endif /* OpenSSL 1.1.1 */
3749
matthewhughes9348e836bb2020-07-17 09:59:15 +01003750#if (OPENSSL_VERSION_NUMBER >= 0x10100000L) && !defined(LIBRESSL_VERSION_NUMBER)
3751static PyObject *
3752get_security_level(PySSLContext *self, void *c)
3753{
3754 return PyLong_FromLong(SSL_CTX_get_security_level(self->ctx));
3755}
3756PyDoc_STRVAR(PySSLContext_security_level_doc, "The current security level");
3757#endif /* OpenSSL 1.1.0 */
3758
Christian Heimes22587792013-11-21 23:56:13 +01003759static PyObject *
Antoine Pitroub5218772010-05-21 09:56:06 +00003760get_options(PySSLContext *self, void *c)
3761{
3762 return PyLong_FromLong(SSL_CTX_get_options(self->ctx));
3763}
3764
3765static int
3766set_options(PySSLContext *self, PyObject *arg, void *c)
3767{
3768 long new_opts, opts, set, clear;
3769 if (!PyArg_Parse(arg, "l", &new_opts))
3770 return -1;
3771 opts = SSL_CTX_get_options(self->ctx);
3772 clear = opts & ~new_opts;
3773 set = ~opts & new_opts;
3774 if (clear) {
3775#ifdef HAVE_SSL_CTX_CLEAR_OPTIONS
3776 SSL_CTX_clear_options(self->ctx, clear);
3777#else
3778 PyErr_SetString(PyExc_ValueError,
3779 "can't clear options before OpenSSL 0.9.8m");
3780 return -1;
3781#endif
3782 }
3783 if (set)
3784 SSL_CTX_set_options(self->ctx, set);
3785 return 0;
3786}
3787
Christian Heimes1aa9a752013-12-02 02:41:19 +01003788static PyObject *
Christian Heimes61d478c2018-01-27 15:51:38 +01003789get_host_flags(PySSLContext *self, void *c)
3790{
3791 return PyLong_FromUnsignedLong(self->hostflags);
3792}
3793
3794static int
3795set_host_flags(PySSLContext *self, PyObject *arg, void *c)
3796{
3797 X509_VERIFY_PARAM *param;
3798 unsigned int new_flags = 0;
3799
3800 if (!PyArg_Parse(arg, "I", &new_flags))
3801 return -1;
3802
3803 param = SSL_CTX_get0_param(self->ctx);
3804 self->hostflags = new_flags;
3805 X509_VERIFY_PARAM_set_hostflags(param, new_flags);
3806 return 0;
3807}
3808
3809static PyObject *
Christian Heimes1aa9a752013-12-02 02:41:19 +01003810get_check_hostname(PySSLContext *self, void *c)
3811{
3812 return PyBool_FromLong(self->check_hostname);
3813}
3814
3815static int
3816set_check_hostname(PySSLContext *self, PyObject *arg, void *c)
3817{
3818 int check_hostname;
3819 if (!PyArg_Parse(arg, "p", &check_hostname))
3820 return -1;
3821 if (check_hostname &&
3822 SSL_CTX_get_verify_mode(self->ctx) == SSL_VERIFY_NONE) {
Christian Heimese82c0342017-09-15 20:29:57 +02003823 /* check_hostname = True sets verify_mode = CERT_REQUIRED */
Christian Heimes9fb051f2018-09-23 08:32:31 +02003824 if (_set_verify_mode(self, PY_SSL_CERT_REQUIRED) == -1) {
Christian Heimese82c0342017-09-15 20:29:57 +02003825 return -1;
3826 }
Christian Heimes1aa9a752013-12-02 02:41:19 +01003827 }
3828 self->check_hostname = check_hostname;
3829 return 0;
3830}
3831
Christian Heimes11a14932018-02-24 02:35:08 +01003832static PyObject *
Christian Heimes9fb051f2018-09-23 08:32:31 +02003833get_post_handshake_auth(PySSLContext *self, void *c) {
3834#if TLS1_3_VERSION
3835 return PyBool_FromLong(self->post_handshake_auth);
3836#else
3837 Py_RETURN_NONE;
3838#endif
3839}
3840
3841#if TLS1_3_VERSION
3842static int
3843set_post_handshake_auth(PySSLContext *self, PyObject *arg, void *c) {
Zackery Spytz842acaa2018-12-17 07:52:45 -07003844 if (arg == NULL) {
3845 PyErr_SetString(PyExc_AttributeError, "cannot delete attribute");
3846 return -1;
3847 }
Christian Heimes9fb051f2018-09-23 08:32:31 +02003848 int pha = PyObject_IsTrue(arg);
3849
3850 if (pha == -1) {
3851 return -1;
3852 }
3853 self->post_handshake_auth = pha;
3854
Christian Heimesf0f59302019-07-01 08:29:17 +02003855 /* bpo-37428: newPySSLSocket() sets SSL_VERIFY_POST_HANDSHAKE flag for
3856 * server sockets and SSL_set_post_handshake_auth() for client. */
Christian Heimes9fb051f2018-09-23 08:32:31 +02003857
3858 return 0;
3859}
3860#endif
3861
3862static PyObject *
Christian Heimes11a14932018-02-24 02:35:08 +01003863get_protocol(PySSLContext *self, void *c) {
3864 return PyLong_FromLong(self->protocol);
3865}
Christian Heimes1aa9a752013-12-02 02:41:19 +01003866
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003867typedef struct {
3868 PyThreadState *thread_state;
3869 PyObject *callable;
3870 char *password;
Victor Stinner9ee02032013-06-23 15:08:23 +02003871 int size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003872 int error;
3873} _PySSLPasswordInfo;
3874
3875static int
3876_pwinfo_set(_PySSLPasswordInfo *pw_info, PyObject* password,
3877 const char *bad_type_error)
3878{
3879 /* Set the password and size fields of a _PySSLPasswordInfo struct
3880 from a unicode, bytes, or byte array object.
3881 The password field will be dynamically allocated and must be freed
3882 by the caller */
3883 PyObject *password_bytes = NULL;
3884 const char *data = NULL;
3885 Py_ssize_t size;
3886
3887 if (PyUnicode_Check(password)) {
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03003888 password_bytes = PyUnicode_AsUTF8String(password);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003889 if (!password_bytes) {
3890 goto error;
3891 }
3892 data = PyBytes_AS_STRING(password_bytes);
3893 size = PyBytes_GET_SIZE(password_bytes);
3894 } else if (PyBytes_Check(password)) {
3895 data = PyBytes_AS_STRING(password);
3896 size = PyBytes_GET_SIZE(password);
3897 } else if (PyByteArray_Check(password)) {
3898 data = PyByteArray_AS_STRING(password);
3899 size = PyByteArray_GET_SIZE(password);
3900 } else {
3901 PyErr_SetString(PyExc_TypeError, bad_type_error);
3902 goto error;
3903 }
3904
Victor Stinner9ee02032013-06-23 15:08:23 +02003905 if (size > (Py_ssize_t)INT_MAX) {
3906 PyErr_Format(PyExc_ValueError,
3907 "password cannot be longer than %d bytes", INT_MAX);
3908 goto error;
3909 }
3910
Victor Stinner11ebff22013-07-07 17:07:52 +02003911 PyMem_Free(pw_info->password);
3912 pw_info->password = PyMem_Malloc(size);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003913 if (!pw_info->password) {
3914 PyErr_SetString(PyExc_MemoryError,
3915 "unable to allocate password buffer");
3916 goto error;
3917 }
3918 memcpy(pw_info->password, data, size);
Victor Stinner9ee02032013-06-23 15:08:23 +02003919 pw_info->size = (int)size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003920
3921 Py_XDECREF(password_bytes);
3922 return 1;
3923
3924error:
3925 Py_XDECREF(password_bytes);
3926 return 0;
3927}
3928
3929static int
3930_password_callback(char *buf, int size, int rwflag, void *userdata)
3931{
3932 _PySSLPasswordInfo *pw_info = (_PySSLPasswordInfo*) userdata;
3933 PyObject *fn_ret = NULL;
3934
3935 PySSL_END_ALLOW_THREADS_S(pw_info->thread_state);
3936
3937 if (pw_info->callable) {
Victor Stinnerf17c3de2016-12-06 18:46:19 +01003938 fn_ret = _PyObject_CallNoArg(pw_info->callable);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003939 if (!fn_ret) {
3940 /* TODO: It would be nice to move _ctypes_add_traceback() into the
3941 core python API, so we could use it to add a frame here */
3942 goto error;
3943 }
3944
3945 if (!_pwinfo_set(pw_info, fn_ret,
3946 "password callback must return a string")) {
3947 goto error;
3948 }
3949 Py_CLEAR(fn_ret);
3950 }
3951
3952 if (pw_info->size > size) {
3953 PyErr_Format(PyExc_ValueError,
3954 "password cannot be longer than %d bytes", size);
3955 goto error;
3956 }
3957
3958 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
3959 memcpy(buf, pw_info->password, pw_info->size);
3960 return pw_info->size;
3961
3962error:
3963 Py_XDECREF(fn_ret);
3964 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
3965 pw_info->error = 1;
3966 return -1;
3967}
3968
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003969/*[clinic input]
3970_ssl._SSLContext.load_cert_chain
3971 certfile: object
Serhiy Storchaka279f4462019-09-14 12:24:05 +03003972 keyfile: object = None
3973 password: object = None
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003974
3975[clinic start generated code]*/
3976
Antoine Pitroub5218772010-05-21 09:56:06 +00003977static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003978_ssl__SSLContext_load_cert_chain_impl(PySSLContext *self, PyObject *certfile,
3979 PyObject *keyfile, PyObject *password)
Serhiy Storchaka279f4462019-09-14 12:24:05 +03003980/*[clinic end generated code: output=9480bc1c380e2095 input=30bc7e967ea01a58]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003981{
Antoine Pitrou152efa22010-05-16 18:19:27 +00003982 PyObject *certfile_bytes = NULL, *keyfile_bytes = NULL;
Christian Heimes598894f2016-09-05 23:19:05 +02003983 pem_password_cb *orig_passwd_cb = SSL_CTX_get_default_passwd_cb(self->ctx);
3984 void *orig_passwd_userdata = SSL_CTX_get_default_passwd_cb_userdata(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003985 _PySSLPasswordInfo pw_info = { NULL, NULL, NULL, 0, 0 };
Antoine Pitrou152efa22010-05-16 18:19:27 +00003986 int r;
3987
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003988 errno = 0;
Antoine Pitrou67e8e562010-09-01 20:55:41 +00003989 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00003990 if (keyfile == Py_None)
3991 keyfile = NULL;
3992 if (!PyUnicode_FSConverter(certfile, &certfile_bytes)) {
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03003993 if (PyErr_ExceptionMatches(PyExc_TypeError)) {
3994 PyErr_SetString(PyExc_TypeError,
3995 "certfile should be a valid filesystem path");
3996 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003997 return NULL;
3998 }
3999 if (keyfile && !PyUnicode_FSConverter(keyfile, &keyfile_bytes)) {
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03004000 if (PyErr_ExceptionMatches(PyExc_TypeError)) {
4001 PyErr_SetString(PyExc_TypeError,
4002 "keyfile should be a valid filesystem path");
4003 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00004004 goto error;
4005 }
Serhiy Storchaka279f4462019-09-14 12:24:05 +03004006 if (password != Py_None) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02004007 if (PyCallable_Check(password)) {
4008 pw_info.callable = password;
4009 } else if (!_pwinfo_set(&pw_info, password,
4010 "password should be a string or callable")) {
4011 goto error;
4012 }
4013 SSL_CTX_set_default_passwd_cb(self->ctx, _password_callback);
4014 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, &pw_info);
4015 }
4016 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00004017 r = SSL_CTX_use_certificate_chain_file(self->ctx,
4018 PyBytes_AS_STRING(certfile_bytes));
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02004019 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00004020 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02004021 if (pw_info.error) {
4022 ERR_clear_error();
4023 /* the password callback has already set the error information */
4024 }
4025 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00004026 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03004027 PyErr_SetFromErrno(PyExc_OSError);
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00004028 }
4029 else {
4030 _setSSLError(NULL, 0, __FILE__, __LINE__);
4031 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00004032 goto error;
4033 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02004034 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou9c254862011-04-03 18:15:34 +02004035 r = SSL_CTX_use_PrivateKey_file(self->ctx,
Antoine Pitrou152efa22010-05-16 18:19:27 +00004036 PyBytes_AS_STRING(keyfile ? keyfile_bytes : certfile_bytes),
4037 SSL_FILETYPE_PEM);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02004038 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
4039 Py_CLEAR(keyfile_bytes);
4040 Py_CLEAR(certfile_bytes);
Antoine Pitrou152efa22010-05-16 18:19:27 +00004041 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02004042 if (pw_info.error) {
4043 ERR_clear_error();
4044 /* the password callback has already set the error information */
4045 }
4046 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00004047 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03004048 PyErr_SetFromErrno(PyExc_OSError);
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00004049 }
4050 else {
4051 _setSSLError(NULL, 0, __FILE__, __LINE__);
4052 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02004053 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004054 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02004055 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00004056 r = SSL_CTX_check_private_key(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02004057 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00004058 if (r != 1) {
4059 _setSSLError(NULL, 0, __FILE__, __LINE__);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02004060 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004061 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02004062 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
4063 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02004064 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00004065 Py_RETURN_NONE;
4066
4067error:
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02004068 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
4069 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02004070 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00004071 Py_XDECREF(keyfile_bytes);
4072 Py_XDECREF(certfile_bytes);
4073 return NULL;
4074}
4075
Christian Heimesefff7062013-11-21 03:35:02 +01004076/* internal helper function, returns -1 on error
4077 */
4078static int
Serhiy Storchaka8f87eef2020-04-12 14:58:27 +03004079_add_ca_certs(PySSLContext *self, const void *data, Py_ssize_t len,
Christian Heimesefff7062013-11-21 03:35:02 +01004080 int filetype)
4081{
4082 BIO *biobuf = NULL;
4083 X509_STORE *store;
4084 int retval = 0, err, loaded = 0;
4085
4086 assert(filetype == SSL_FILETYPE_ASN1 || filetype == SSL_FILETYPE_PEM);
4087
4088 if (len <= 0) {
4089 PyErr_SetString(PyExc_ValueError,
4090 "Empty certificate data");
4091 return -1;
4092 } else if (len > INT_MAX) {
4093 PyErr_SetString(PyExc_OverflowError,
4094 "Certificate data is too long.");
4095 return -1;
4096 }
4097
Christian Heimes1dbf61f2013-11-22 00:34:18 +01004098 biobuf = BIO_new_mem_buf(data, (int)len);
Christian Heimesefff7062013-11-21 03:35:02 +01004099 if (biobuf == NULL) {
4100 _setSSLError("Can't allocate buffer", 0, __FILE__, __LINE__);
4101 return -1;
4102 }
4103
4104 store = SSL_CTX_get_cert_store(self->ctx);
4105 assert(store != NULL);
4106
4107 while (1) {
4108 X509 *cert = NULL;
4109 int r;
4110
4111 if (filetype == SSL_FILETYPE_ASN1) {
4112 cert = d2i_X509_bio(biobuf, NULL);
4113 } else {
4114 cert = PEM_read_bio_X509(biobuf, NULL,
Christian Heimes598894f2016-09-05 23:19:05 +02004115 SSL_CTX_get_default_passwd_cb(self->ctx),
4116 SSL_CTX_get_default_passwd_cb_userdata(self->ctx)
4117 );
Christian Heimesefff7062013-11-21 03:35:02 +01004118 }
4119 if (cert == NULL) {
4120 break;
4121 }
4122 r = X509_STORE_add_cert(store, cert);
4123 X509_free(cert);
4124 if (!r) {
4125 err = ERR_peek_last_error();
4126 if ((ERR_GET_LIB(err) == ERR_LIB_X509) &&
4127 (ERR_GET_REASON(err) == X509_R_CERT_ALREADY_IN_HASH_TABLE)) {
4128 /* cert already in hash table, not an error */
4129 ERR_clear_error();
4130 } else {
4131 break;
4132 }
4133 }
4134 loaded++;
4135 }
4136
4137 err = ERR_peek_last_error();
4138 if ((filetype == SSL_FILETYPE_ASN1) &&
4139 (loaded > 0) &&
4140 (ERR_GET_LIB(err) == ERR_LIB_ASN1) &&
4141 (ERR_GET_REASON(err) == ASN1_R_HEADER_TOO_LONG)) {
4142 /* EOF ASN1 file, not an error */
4143 ERR_clear_error();
4144 retval = 0;
4145 } else if ((filetype == SSL_FILETYPE_PEM) &&
4146 (loaded > 0) &&
4147 (ERR_GET_LIB(err) == ERR_LIB_PEM) &&
4148 (ERR_GET_REASON(err) == PEM_R_NO_START_LINE)) {
4149 /* EOF PEM file, not an error */
4150 ERR_clear_error();
4151 retval = 0;
4152 } else {
4153 _setSSLError(NULL, 0, __FILE__, __LINE__);
4154 retval = -1;
4155 }
4156
4157 BIO_free(biobuf);
4158 return retval;
4159}
4160
4161
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004162/*[clinic input]
4163_ssl._SSLContext.load_verify_locations
Serhiy Storchaka279f4462019-09-14 12:24:05 +03004164 cafile: object = None
4165 capath: object = None
4166 cadata: object = None
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004167
4168[clinic start generated code]*/
4169
Antoine Pitrou152efa22010-05-16 18:19:27 +00004170static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004171_ssl__SSLContext_load_verify_locations_impl(PySSLContext *self,
4172 PyObject *cafile,
4173 PyObject *capath,
4174 PyObject *cadata)
Serhiy Storchaka279f4462019-09-14 12:24:05 +03004175/*[clinic end generated code: output=454c7e41230ca551 input=42ecfe258233e194]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004176{
Antoine Pitrou152efa22010-05-16 18:19:27 +00004177 PyObject *cafile_bytes = NULL, *capath_bytes = NULL;
4178 const char *cafile_buf = NULL, *capath_buf = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01004179 int r = 0, ok = 1;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004180
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00004181 errno = 0;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004182 if (cafile == Py_None)
4183 cafile = NULL;
4184 if (capath == Py_None)
4185 capath = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01004186 if (cadata == Py_None)
4187 cadata = NULL;
4188
4189 if (cafile == NULL && capath == NULL && cadata == NULL) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00004190 PyErr_SetString(PyExc_TypeError,
Christian Heimesefff7062013-11-21 03:35:02 +01004191 "cafile, capath and cadata cannot be all omitted");
4192 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004193 }
4194 if (cafile && !PyUnicode_FSConverter(cafile, &cafile_bytes)) {
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03004195 if (PyErr_ExceptionMatches(PyExc_TypeError)) {
4196 PyErr_SetString(PyExc_TypeError,
4197 "cafile should be a valid filesystem path");
4198 }
Christian Heimesefff7062013-11-21 03:35:02 +01004199 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004200 }
4201 if (capath && !PyUnicode_FSConverter(capath, &capath_bytes)) {
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03004202 if (PyErr_ExceptionMatches(PyExc_TypeError)) {
4203 PyErr_SetString(PyExc_TypeError,
4204 "capath should be a valid filesystem path");
4205 }
Christian Heimesefff7062013-11-21 03:35:02 +01004206 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004207 }
Christian Heimesefff7062013-11-21 03:35:02 +01004208
4209 /* validata cadata type and load cadata */
4210 if (cadata) {
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03004211 if (PyUnicode_Check(cadata)) {
4212 PyObject *cadata_ascii = PyUnicode_AsASCIIString(cadata);
4213 if (cadata_ascii == NULL) {
4214 if (PyErr_ExceptionMatches(PyExc_UnicodeEncodeError)) {
4215 goto invalid_cadata;
4216 }
4217 goto error;
4218 }
4219 r = _add_ca_certs(self,
4220 PyBytes_AS_STRING(cadata_ascii),
4221 PyBytes_GET_SIZE(cadata_ascii),
4222 SSL_FILETYPE_PEM);
4223 Py_DECREF(cadata_ascii);
4224 if (r == -1) {
4225 goto error;
4226 }
4227 }
4228 else if (PyObject_CheckBuffer(cadata)) {
4229 Py_buffer buf;
4230 if (PyObject_GetBuffer(cadata, &buf, PyBUF_SIMPLE)) {
4231 goto error;
4232 }
Christian Heimesefff7062013-11-21 03:35:02 +01004233 if (!PyBuffer_IsContiguous(&buf, 'C') || buf.ndim > 1) {
4234 PyBuffer_Release(&buf);
4235 PyErr_SetString(PyExc_TypeError,
4236 "cadata should be a contiguous buffer with "
4237 "a single dimension");
4238 goto error;
4239 }
4240 r = _add_ca_certs(self, buf.buf, buf.len, SSL_FILETYPE_ASN1);
4241 PyBuffer_Release(&buf);
4242 if (r == -1) {
4243 goto error;
4244 }
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03004245 }
4246 else {
4247 invalid_cadata:
4248 PyErr_SetString(PyExc_TypeError,
4249 "cadata should be an ASCII string or a "
4250 "bytes-like object");
4251 goto error;
Christian Heimesefff7062013-11-21 03:35:02 +01004252 }
4253 }
4254
4255 /* load cafile or capath */
4256 if (cafile || capath) {
4257 if (cafile)
4258 cafile_buf = PyBytes_AS_STRING(cafile_bytes);
4259 if (capath)
4260 capath_buf = PyBytes_AS_STRING(capath_bytes);
4261 PySSL_BEGIN_ALLOW_THREADS
4262 r = SSL_CTX_load_verify_locations(self->ctx, cafile_buf, capath_buf);
4263 PySSL_END_ALLOW_THREADS
4264 if (r != 1) {
Christian Heimesefff7062013-11-21 03:35:02 +01004265 if (errno != 0) {
4266 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03004267 PyErr_SetFromErrno(PyExc_OSError);
Christian Heimesefff7062013-11-21 03:35:02 +01004268 }
4269 else {
4270 _setSSLError(NULL, 0, __FILE__, __LINE__);
4271 }
4272 goto error;
4273 }
4274 }
4275 goto end;
4276
4277 error:
4278 ok = 0;
4279 end:
Antoine Pitrou152efa22010-05-16 18:19:27 +00004280 Py_XDECREF(cafile_bytes);
4281 Py_XDECREF(capath_bytes);
Christian Heimesefff7062013-11-21 03:35:02 +01004282 if (ok) {
4283 Py_RETURN_NONE;
4284 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00004285 return NULL;
4286 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00004287}
4288
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004289/*[clinic input]
4290_ssl._SSLContext.load_dh_params
4291 path as filepath: object
4292 /
4293
4294[clinic start generated code]*/
4295
Antoine Pitrou152efa22010-05-16 18:19:27 +00004296static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004297_ssl__SSLContext_load_dh_params(PySSLContext *self, PyObject *filepath)
4298/*[clinic end generated code: output=1c8e57a38e055af0 input=c8871f3c796ae1d6]*/
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004299{
4300 FILE *f;
4301 DH *dh;
4302
Victor Stinnerdaf45552013-08-28 00:53:59 +02004303 f = _Py_fopen_obj(filepath, "rb");
Victor Stinnere42ccd22015-03-18 01:39:23 +01004304 if (f == NULL)
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004305 return NULL;
Victor Stinnere42ccd22015-03-18 01:39:23 +01004306
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004307 errno = 0;
4308 PySSL_BEGIN_ALLOW_THREADS
4309 dh = PEM_read_DHparams(f, NULL, NULL, NULL);
Antoine Pitrou457a2292013-01-12 21:43:45 +01004310 fclose(f);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004311 PySSL_END_ALLOW_THREADS
4312 if (dh == NULL) {
4313 if (errno != 0) {
4314 ERR_clear_error();
4315 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
4316 }
4317 else {
4318 _setSSLError(NULL, 0, __FILE__, __LINE__);
4319 }
4320 return NULL;
4321 }
Zackery Spytzaebc0492020-07-07 22:21:58 -06004322 if (!SSL_CTX_set_tmp_dh(self->ctx, dh)) {
4323 DH_free(dh);
4324 return _setSSLError(NULL, 0, __FILE__, __LINE__);
4325 }
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004326 DH_free(dh);
4327 Py_RETURN_NONE;
4328}
4329
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004330/*[clinic input]
4331_ssl._SSLContext._wrap_socket
4332 sock: object(subclass_of="PySocketModule.Sock_Type")
4333 server_side: int
4334 server_hostname as hostname_obj: object = None
Christian Heimes141c5e82018-02-24 21:10:57 +01004335 *
4336 owner: object = None
4337 session: object = None
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004338
4339[clinic start generated code]*/
4340
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004341static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004342_ssl__SSLContext__wrap_socket_impl(PySSLContext *self, PyObject *sock,
Christian Heimes141c5e82018-02-24 21:10:57 +01004343 int server_side, PyObject *hostname_obj,
4344 PyObject *owner, PyObject *session)
4345/*[clinic end generated code: output=f103f238633940b4 input=957d5006183d1894]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004346{
Antoine Pitroud5323212010-10-22 18:19:07 +00004347 char *hostname = NULL;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004348 PyObject *res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004349
Antoine Pitroud5323212010-10-22 18:19:07 +00004350 /* server_hostname is either None (or absent), or to be encoded
Christian Heimesd02ac252018-03-25 12:36:13 +02004351 as IDN A-label (ASCII str) without NULL bytes. */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004352 if (hostname_obj != Py_None) {
Christian Heimes11a14932018-02-24 02:35:08 +01004353 if (!PyArg_Parse(hostname_obj, "es", "ascii", &hostname))
Antoine Pitroud5323212010-10-22 18:19:07 +00004354 return NULL;
Antoine Pitroud5323212010-10-22 18:19:07 +00004355 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00004356
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004357 res = (PyObject *) newPySSLSocket(self, (PySocketSockObject *)sock,
4358 server_side, hostname,
Christian Heimes141c5e82018-02-24 21:10:57 +01004359 owner, session,
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004360 NULL, NULL);
Antoine Pitroud5323212010-10-22 18:19:07 +00004361 if (hostname != NULL)
4362 PyMem_Free(hostname);
4363 return res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004364}
4365
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004366/*[clinic input]
4367_ssl._SSLContext._wrap_bio
4368 incoming: object(subclass_of="&PySSLMemoryBIO_Type", type="PySSLMemoryBIO *")
4369 outgoing: object(subclass_of="&PySSLMemoryBIO_Type", type="PySSLMemoryBIO *")
4370 server_side: int
4371 server_hostname as hostname_obj: object = None
Christian Heimes141c5e82018-02-24 21:10:57 +01004372 *
4373 owner: object = None
4374 session: object = None
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004375
4376[clinic start generated code]*/
4377
Antoine Pitroub0182c82010-10-12 20:09:02 +00004378static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004379_ssl__SSLContext__wrap_bio_impl(PySSLContext *self, PySSLMemoryBIO *incoming,
4380 PySSLMemoryBIO *outgoing, int server_side,
Christian Heimes141c5e82018-02-24 21:10:57 +01004381 PyObject *hostname_obj, PyObject *owner,
4382 PyObject *session)
4383/*[clinic end generated code: output=5c5d6d9b41f99332 input=8cf22f4d586ac56a]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004384{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004385 char *hostname = NULL;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004386 PyObject *res;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004387
4388 /* server_hostname is either None (or absent), or to be encoded
Christian Heimesd02ac252018-03-25 12:36:13 +02004389 as IDN A-label (ASCII str) without NULL bytes. */
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004390 if (hostname_obj != Py_None) {
Christian Heimes11a14932018-02-24 02:35:08 +01004391 if (!PyArg_Parse(hostname_obj, "es", "ascii", &hostname))
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004392 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004393 }
4394
4395 res = (PyObject *) newPySSLSocket(self, NULL, server_side, hostname,
Christian Heimes141c5e82018-02-24 21:10:57 +01004396 owner, session,
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004397 incoming, outgoing);
4398
4399 PyMem_Free(hostname);
4400 return res;
4401}
4402
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004403/*[clinic input]
4404_ssl._SSLContext.session_stats
4405[clinic start generated code]*/
4406
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004407static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004408_ssl__SSLContext_session_stats_impl(PySSLContext *self)
4409/*[clinic end generated code: output=0d96411c42893bfb input=7e0a81fb11102c8b]*/
Antoine Pitroub0182c82010-10-12 20:09:02 +00004410{
4411 int r;
4412 PyObject *value, *stats = PyDict_New();
4413 if (!stats)
4414 return NULL;
4415
4416#define ADD_STATS(SSL_NAME, KEY_NAME) \
4417 value = PyLong_FromLong(SSL_CTX_sess_ ## SSL_NAME (self->ctx)); \
4418 if (value == NULL) \
4419 goto error; \
4420 r = PyDict_SetItemString(stats, KEY_NAME, value); \
4421 Py_DECREF(value); \
4422 if (r < 0) \
4423 goto error;
4424
4425 ADD_STATS(number, "number");
4426 ADD_STATS(connect, "connect");
4427 ADD_STATS(connect_good, "connect_good");
4428 ADD_STATS(connect_renegotiate, "connect_renegotiate");
4429 ADD_STATS(accept, "accept");
4430 ADD_STATS(accept_good, "accept_good");
4431 ADD_STATS(accept_renegotiate, "accept_renegotiate");
4432 ADD_STATS(accept, "accept");
4433 ADD_STATS(hits, "hits");
4434 ADD_STATS(misses, "misses");
4435 ADD_STATS(timeouts, "timeouts");
4436 ADD_STATS(cache_full, "cache_full");
4437
4438#undef ADD_STATS
4439
4440 return stats;
4441
4442error:
4443 Py_DECREF(stats);
4444 return NULL;
4445}
4446
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004447/*[clinic input]
4448_ssl._SSLContext.set_default_verify_paths
4449[clinic start generated code]*/
4450
Antoine Pitrou664c2d12010-11-17 20:29:42 +00004451static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004452_ssl__SSLContext_set_default_verify_paths_impl(PySSLContext *self)
4453/*[clinic end generated code: output=0bee74e6e09deaaa input=35f3408021463d74]*/
Antoine Pitrou664c2d12010-11-17 20:29:42 +00004454{
4455 if (!SSL_CTX_set_default_verify_paths(self->ctx)) {
4456 _setSSLError(NULL, 0, __FILE__, __LINE__);
4457 return NULL;
4458 }
4459 Py_RETURN_NONE;
4460}
4461
Antoine Pitrou501da612011-12-21 09:27:41 +01004462#ifndef OPENSSL_NO_ECDH
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004463/*[clinic input]
4464_ssl._SSLContext.set_ecdh_curve
4465 name: object
4466 /
4467
4468[clinic start generated code]*/
4469
Antoine Pitrou923df6f2011-12-19 17:16:51 +01004470static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004471_ssl__SSLContext_set_ecdh_curve(PySSLContext *self, PyObject *name)
4472/*[clinic end generated code: output=23022c196e40d7d2 input=c2bafb6f6e34726b]*/
Antoine Pitrou923df6f2011-12-19 17:16:51 +01004473{
4474 PyObject *name_bytes;
4475 int nid;
4476 EC_KEY *key;
4477
4478 if (!PyUnicode_FSConverter(name, &name_bytes))
4479 return NULL;
4480 assert(PyBytes_Check(name_bytes));
4481 nid = OBJ_sn2nid(PyBytes_AS_STRING(name_bytes));
4482 Py_DECREF(name_bytes);
4483 if (nid == 0) {
4484 PyErr_Format(PyExc_ValueError,
4485 "unknown elliptic curve name %R", name);
4486 return NULL;
4487 }
4488 key = EC_KEY_new_by_curve_name(nid);
4489 if (key == NULL) {
4490 _setSSLError(NULL, 0, __FILE__, __LINE__);
4491 return NULL;
4492 }
4493 SSL_CTX_set_tmp_ecdh(self->ctx, key);
4494 EC_KEY_free(key);
4495 Py_RETURN_NONE;
4496}
Antoine Pitrou501da612011-12-21 09:27:41 +01004497#endif
Antoine Pitrou923df6f2011-12-19 17:16:51 +01004498
Antoine Pitrou912fbff2013-03-30 16:29:32 +01004499#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004500static int
4501_servername_callback(SSL *s, int *al, void *args)
4502{
4503 int ret;
4504 PySSLContext *ssl_ctx = (PySSLContext *) args;
4505 PySSLSocket *ssl;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004506 PyObject *result;
4507 /* The high-level ssl.SSLSocket object */
4508 PyObject *ssl_socket;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004509 const char *servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
Stefan Krah20d60802013-01-17 17:07:17 +01004510 PyGILState_STATE gstate = PyGILState_Ensure();
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004511
Christian Heimes11a14932018-02-24 02:35:08 +01004512 if (ssl_ctx->set_sni_cb == NULL) {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004513 /* remove race condition in this the call back while if removing the
4514 * callback is in progress */
4515 PyGILState_Release(gstate);
Antoine Pitrou5dd12a52013-01-06 15:25:36 +01004516 return SSL_TLSEXT_ERR_OK;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004517 }
4518
4519 ssl = SSL_get_app_data(s);
4520 assert(PySSLSocket_Check(ssl));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004521
Serhiy Storchakaf51d7152015-11-02 14:40:41 +02004522 /* The servername callback expects an argument that represents the current
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004523 * SSL connection and that has a .context attribute that can be changed to
4524 * identify the requested hostname. Since the official API is the Python
4525 * level API we want to pass the callback a Python level object rather than
4526 * a _ssl.SSLSocket instance. If there's an "owner" (typically an
4527 * SSLObject) that will be passed. Otherwise if there's a socket then that
4528 * will be passed. If both do not exist only then the C-level object is
4529 * passed. */
4530 if (ssl->owner)
4531 ssl_socket = PyWeakref_GetObject(ssl->owner);
4532 else if (ssl->Socket)
4533 ssl_socket = PyWeakref_GetObject(ssl->Socket);
4534 else
4535 ssl_socket = (PyObject *) ssl;
4536
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004537 Py_INCREF(ssl_socket);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004538 if (ssl_socket == Py_None)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004539 goto error;
Victor Stinner7e001512013-06-25 00:44:31 +02004540
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004541 if (servername == NULL) {
Christian Heimes11a14932018-02-24 02:35:08 +01004542 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_sni_cb, ssl_socket,
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004543 Py_None, ssl_ctx, NULL);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004544 }
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004545 else {
Christian Heimes11a14932018-02-24 02:35:08 +01004546 PyObject *servername_bytes;
4547 PyObject *servername_str;
4548
4549 servername_bytes = PyBytes_FromString(servername);
4550 if (servername_bytes == NULL) {
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004551 PyErr_WriteUnraisable((PyObject *) ssl_ctx);
4552 goto error;
4553 }
Christian Heimes11a14932018-02-24 02:35:08 +01004554 /* server_hostname was encoded to an A-label by our caller; put it
4555 * back into a str object, but still as an A-label (bpo-28414)
4556 */
4557 servername_str = PyUnicode_FromEncodedObject(servername_bytes, "ascii", NULL);
Christian Heimes11a14932018-02-24 02:35:08 +01004558 if (servername_str == NULL) {
4559 PyErr_WriteUnraisable(servername_bytes);
Zackery Spytzee96f322020-07-09 04:00:21 -06004560 Py_DECREF(servername_bytes);
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004561 goto error;
4562 }
Zackery Spytzee96f322020-07-09 04:00:21 -06004563 Py_DECREF(servername_bytes);
Christian Heimes11a14932018-02-24 02:35:08 +01004564 result = PyObject_CallFunctionObjArgs(
4565 ssl_ctx->set_sni_cb, ssl_socket, servername_str,
4566 ssl_ctx, NULL);
4567 Py_DECREF(servername_str);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004568 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004569 Py_DECREF(ssl_socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004570
4571 if (result == NULL) {
Christian Heimes11a14932018-02-24 02:35:08 +01004572 PyErr_WriteUnraisable(ssl_ctx->set_sni_cb);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004573 *al = SSL_AD_HANDSHAKE_FAILURE;
4574 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
4575 }
4576 else {
Christian Heimes11a14932018-02-24 02:35:08 +01004577 /* Result may be None, a SSLContext or an integer
4578 * None and SSLContext are OK, integer or other values are an error.
4579 */
4580 if (result == Py_None) {
4581 ret = SSL_TLSEXT_ERR_OK;
4582 } else {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004583 *al = (int) PyLong_AsLong(result);
4584 if (PyErr_Occurred()) {
4585 PyErr_WriteUnraisable(result);
4586 *al = SSL_AD_INTERNAL_ERROR;
4587 }
4588 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
4589 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004590 Py_DECREF(result);
4591 }
4592
4593 PyGILState_Release(gstate);
4594 return ret;
4595
4596error:
4597 Py_DECREF(ssl_socket);
4598 *al = SSL_AD_INTERNAL_ERROR;
4599 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
4600 PyGILState_Release(gstate);
4601 return ret;
4602}
Antoine Pitroua5963382013-03-30 16:39:00 +01004603#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004604
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004605static PyObject *
Christian Heimes11a14932018-02-24 02:35:08 +01004606get_sni_callback(PySSLContext *self, void *c)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004607{
Christian Heimes11a14932018-02-24 02:35:08 +01004608 PyObject *cb = self->set_sni_cb;
4609 if (cb == NULL) {
4610 Py_RETURN_NONE;
4611 }
4612 Py_INCREF(cb);
4613 return cb;
4614}
4615
4616static int
4617set_sni_callback(PySSLContext *self, PyObject *arg, void *c)
4618{
4619 if (self->protocol == PY_SSL_VERSION_TLS_CLIENT) {
4620 PyErr_SetString(PyExc_ValueError,
4621 "sni_callback cannot be set on TLS_CLIENT context");
4622 return -1;
4623 }
Antoine Pitrou912fbff2013-03-30 16:29:32 +01004624#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Christian Heimes11a14932018-02-24 02:35:08 +01004625 Py_CLEAR(self->set_sni_cb);
4626 if (arg == Py_None) {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004627 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
4628 }
4629 else {
Christian Heimes11a14932018-02-24 02:35:08 +01004630 if (!PyCallable_Check(arg)) {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004631 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
4632 PyErr_SetString(PyExc_TypeError,
4633 "not a callable object");
Christian Heimes11a14932018-02-24 02:35:08 +01004634 return -1;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004635 }
Christian Heimes11a14932018-02-24 02:35:08 +01004636 Py_INCREF(arg);
4637 self->set_sni_cb = arg;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004638 SSL_CTX_set_tlsext_servername_callback(self->ctx, _servername_callback);
4639 SSL_CTX_set_tlsext_servername_arg(self->ctx, self);
4640 }
Christian Heimes11a14932018-02-24 02:35:08 +01004641 return 0;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004642#else
4643 PyErr_SetString(PyExc_NotImplementedError,
4644 "The TLS extension servername callback, "
4645 "SSL_CTX_set_tlsext_servername_callback, "
4646 "is not in the current OpenSSL library.");
Christian Heimes11a14932018-02-24 02:35:08 +01004647 return -1;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004648#endif
4649}
4650
Christian Heimes11a14932018-02-24 02:35:08 +01004651PyDoc_STRVAR(PySSLContext_sni_callback_doc,
4652"Set a callback that will be called when a server name is provided by the SSL/TLS client in the SNI extension.\n\
4653\n\
4654If the argument is None then the callback is disabled. The method is called\n\
4655with the SSLSocket, the server name as a string, and the SSLContext object.\n\
4656See RFC 6066 for details of the SNI extension.");
4657
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004658/*[clinic input]
4659_ssl._SSLContext.cert_store_stats
4660
4661Returns quantities of loaded X.509 certificates.
4662
4663X.509 certificates with a CA extension and certificate revocation lists
4664inside the context's cert store.
4665
4666NOTE: Certificates in a capath directory aren't loaded unless they have
4667been used at least once.
4668[clinic start generated code]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004669
4670static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004671_ssl__SSLContext_cert_store_stats_impl(PySSLContext *self)
4672/*[clinic end generated code: output=5f356f4d9cca874d input=eb40dd0f6d0e40cf]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004673{
4674 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02004675 STACK_OF(X509_OBJECT) *objs;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004676 X509_OBJECT *obj;
Christian Heimes598894f2016-09-05 23:19:05 +02004677 int x509 = 0, crl = 0, ca = 0, i;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004678
4679 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02004680 objs = X509_STORE_get0_objects(store);
4681 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
4682 obj = sk_X509_OBJECT_value(objs, i);
4683 switch (X509_OBJECT_get_type(obj)) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004684 case X509_LU_X509:
4685 x509++;
Christian Heimes598894f2016-09-05 23:19:05 +02004686 if (X509_check_ca(X509_OBJECT_get0_X509(obj))) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004687 ca++;
4688 }
4689 break;
4690 case X509_LU_CRL:
4691 crl++;
4692 break;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004693 default:
4694 /* Ignore X509_LU_FAIL, X509_LU_RETRY, X509_LU_PKEY.
4695 * As far as I can tell they are internal states and never
4696 * stored in a cert store */
4697 break;
4698 }
4699 }
4700 return Py_BuildValue("{sisisi}", "x509", x509, "crl", crl,
4701 "x509_ca", ca);
4702}
4703
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004704/*[clinic input]
4705_ssl._SSLContext.get_ca_certs
4706 binary_form: bool = False
4707
4708Returns a list of dicts with information of loaded CA certs.
4709
4710If the optional argument is True, returns a DER-encoded copy of the CA
4711certificate.
4712
4713NOTE: Certificates in a capath directory aren't loaded unless they have
4714been used at least once.
4715[clinic start generated code]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004716
4717static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004718_ssl__SSLContext_get_ca_certs_impl(PySSLContext *self, int binary_form)
4719/*[clinic end generated code: output=0d58f148f37e2938 input=6887b5a09b7f9076]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004720{
4721 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02004722 STACK_OF(X509_OBJECT) *objs;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004723 PyObject *ci = NULL, *rlist = NULL;
4724 int i;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004725
4726 if ((rlist = PyList_New(0)) == NULL) {
4727 return NULL;
4728 }
4729
4730 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02004731 objs = X509_STORE_get0_objects(store);
4732 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004733 X509_OBJECT *obj;
4734 X509 *cert;
4735
Christian Heimes598894f2016-09-05 23:19:05 +02004736 obj = sk_X509_OBJECT_value(objs, i);
4737 if (X509_OBJECT_get_type(obj) != X509_LU_X509) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004738 /* not a x509 cert */
4739 continue;
4740 }
4741 /* CA for any purpose */
Christian Heimes598894f2016-09-05 23:19:05 +02004742 cert = X509_OBJECT_get0_X509(obj);
Christian Heimes9a5395a2013-06-17 15:44:12 +02004743 if (!X509_check_ca(cert)) {
4744 continue;
4745 }
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004746 if (binary_form) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004747 ci = _certificate_to_der(cert);
4748 } else {
4749 ci = _decode_certificate(cert);
4750 }
4751 if (ci == NULL) {
4752 goto error;
4753 }
4754 if (PyList_Append(rlist, ci) == -1) {
4755 goto error;
4756 }
4757 Py_CLEAR(ci);
4758 }
4759 return rlist;
4760
4761 error:
4762 Py_XDECREF(ci);
4763 Py_XDECREF(rlist);
4764 return NULL;
4765}
4766
4767
Antoine Pitrou152efa22010-05-16 18:19:27 +00004768static PyGetSetDef context_getsetlist[] = {
Christian Heimes1aa9a752013-12-02 02:41:19 +01004769 {"check_hostname", (getter) get_check_hostname,
4770 (setter) set_check_hostname, NULL},
Christian Heimes61d478c2018-01-27 15:51:38 +01004771 {"_host_flags", (getter) get_host_flags,
4772 (setter) set_host_flags, NULL},
Christian Heimes698dde12018-02-27 11:54:43 +01004773#if SSL_CTRL_GET_MAX_PROTO_VERSION
4774 {"minimum_version", (getter) get_minimum_version,
4775 (setter) set_minimum_version, NULL},
4776 {"maximum_version", (getter) get_maximum_version,
4777 (setter) set_maximum_version, NULL},
4778#endif
Christian Heimesc7f70692019-05-31 11:44:05 +02004779#ifdef HAVE_OPENSSL_KEYLOG
4780 {"keylog_filename", (getter) _PySSLContext_get_keylog_filename,
4781 (setter) _PySSLContext_set_keylog_filename, NULL},
4782#endif
4783 {"_msg_callback", (getter) _PySSLContext_get_msg_callback,
4784 (setter) _PySSLContext_set_msg_callback, NULL},
Christian Heimes11a14932018-02-24 02:35:08 +01004785 {"sni_callback", (getter) get_sni_callback,
Christian Heimes698dde12018-02-27 11:54:43 +01004786 (setter) set_sni_callback, PySSLContext_sni_callback_doc},
Christian Heimes78c7d522019-06-03 21:00:10 +02004787#if (OPENSSL_VERSION_NUMBER >= 0x10101000L) && !defined(LIBRESSL_VERSION_NUMBER)
4788 {"num_tickets", (getter) get_num_tickets,
4789 (setter) set_num_tickets, PySSLContext_num_tickets_doc},
4790#endif
Antoine Pitroub5218772010-05-21 09:56:06 +00004791 {"options", (getter) get_options,
4792 (setter) set_options, NULL},
Christian Heimes9fb051f2018-09-23 08:32:31 +02004793 {"post_handshake_auth", (getter) get_post_handshake_auth,
4794#ifdef TLS1_3_VERSION
4795 (setter) set_post_handshake_auth,
4796#else
4797 NULL,
4798#endif
4799 NULL},
Christian Heimes11a14932018-02-24 02:35:08 +01004800 {"protocol", (getter) get_protocol,
4801 NULL, NULL},
Christian Heimes22587792013-11-21 23:56:13 +01004802 {"verify_flags", (getter) get_verify_flags,
4803 (setter) set_verify_flags, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00004804 {"verify_mode", (getter) get_verify_mode,
4805 (setter) set_verify_mode, NULL},
matthewhughes9348e836bb2020-07-17 09:59:15 +01004806#if (OPENSSL_VERSION_NUMBER >= 0x10100000L) && !defined(LIBRESSL_VERSION_NUMBER)
4807 {"security_level", (getter) get_security_level,
4808 NULL, PySSLContext_security_level_doc},
4809#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00004810 {NULL}, /* sentinel */
4811};
4812
4813static struct PyMethodDef context_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004814 _SSL__SSLCONTEXT__WRAP_SOCKET_METHODDEF
4815 _SSL__SSLCONTEXT__WRAP_BIO_METHODDEF
4816 _SSL__SSLCONTEXT_SET_CIPHERS_METHODDEF
4817 _SSL__SSLCONTEXT__SET_ALPN_PROTOCOLS_METHODDEF
4818 _SSL__SSLCONTEXT__SET_NPN_PROTOCOLS_METHODDEF
4819 _SSL__SSLCONTEXT_LOAD_CERT_CHAIN_METHODDEF
4820 _SSL__SSLCONTEXT_LOAD_DH_PARAMS_METHODDEF
4821 _SSL__SSLCONTEXT_LOAD_VERIFY_LOCATIONS_METHODDEF
4822 _SSL__SSLCONTEXT_SESSION_STATS_METHODDEF
4823 _SSL__SSLCONTEXT_SET_DEFAULT_VERIFY_PATHS_METHODDEF
4824 _SSL__SSLCONTEXT_SET_ECDH_CURVE_METHODDEF
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004825 _SSL__SSLCONTEXT_CERT_STORE_STATS_METHODDEF
4826 _SSL__SSLCONTEXT_GET_CA_CERTS_METHODDEF
Christian Heimes25bfcd52016-09-06 00:04:45 +02004827 _SSL__SSLCONTEXT_GET_CIPHERS_METHODDEF
Antoine Pitrou152efa22010-05-16 18:19:27 +00004828 {NULL, NULL} /* sentinel */
4829};
4830
4831static PyTypeObject PySSLContext_Type = {
4832 PyVarObject_HEAD_INIT(NULL, 0)
4833 "_ssl._SSLContext", /*tp_name*/
4834 sizeof(PySSLContext), /*tp_basicsize*/
4835 0, /*tp_itemsize*/
4836 (destructor)context_dealloc, /*tp_dealloc*/
Jeroen Demeyer530f5062019-05-31 04:13:39 +02004837 0, /*tp_vectorcall_offset*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004838 0, /*tp_getattr*/
4839 0, /*tp_setattr*/
Jeroen Demeyer530f5062019-05-31 04:13:39 +02004840 0, /*tp_as_async*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004841 0, /*tp_repr*/
4842 0, /*tp_as_number*/
4843 0, /*tp_as_sequence*/
4844 0, /*tp_as_mapping*/
4845 0, /*tp_hash*/
4846 0, /*tp_call*/
4847 0, /*tp_str*/
4848 0, /*tp_getattro*/
4849 0, /*tp_setattro*/
4850 0, /*tp_as_buffer*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004851 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004852 0, /*tp_doc*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004853 (traverseproc) context_traverse, /*tp_traverse*/
4854 (inquiry) context_clear, /*tp_clear*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004855 0, /*tp_richcompare*/
4856 0, /*tp_weaklistoffset*/
4857 0, /*tp_iter*/
4858 0, /*tp_iternext*/
4859 context_methods, /*tp_methods*/
4860 0, /*tp_members*/
4861 context_getsetlist, /*tp_getset*/
4862 0, /*tp_base*/
4863 0, /*tp_dict*/
4864 0, /*tp_descr_get*/
4865 0, /*tp_descr_set*/
4866 0, /*tp_dictoffset*/
4867 0, /*tp_init*/
4868 0, /*tp_alloc*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004869 _ssl__SSLContext, /*tp_new*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004870};
4871
4872
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004873/*
4874 * MemoryBIO objects
4875 */
4876
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004877/*[clinic input]
4878@classmethod
4879_ssl.MemoryBIO.__new__
4880
4881[clinic start generated code]*/
4882
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004883static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004884_ssl_MemoryBIO_impl(PyTypeObject *type)
4885/*[clinic end generated code: output=8820a58db78330ac input=26d22e4909ecb1b5]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004886{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004887 BIO *bio;
4888 PySSLMemoryBIO *self;
4889
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004890 bio = BIO_new(BIO_s_mem());
4891 if (bio == NULL) {
4892 PyErr_SetString(PySSLErrorObject,
4893 "failed to allocate BIO");
4894 return NULL;
4895 }
4896 /* Since our BIO is non-blocking an empty read() does not indicate EOF,
4897 * just that no data is currently available. The SSL routines should retry
4898 * the read, which we can achieve by calling BIO_set_retry_read(). */
4899 BIO_set_retry_read(bio);
4900 BIO_set_mem_eof_return(bio, -1);
4901
4902 assert(type != NULL && type->tp_alloc != NULL);
4903 self = (PySSLMemoryBIO *) type->tp_alloc(type, 0);
4904 if (self == NULL) {
4905 BIO_free(bio);
4906 return NULL;
4907 }
4908 self->bio = bio;
4909 self->eof_written = 0;
4910
4911 return (PyObject *) self;
4912}
4913
4914static void
4915memory_bio_dealloc(PySSLMemoryBIO *self)
4916{
4917 BIO_free(self->bio);
4918 Py_TYPE(self)->tp_free(self);
4919}
4920
4921static PyObject *
4922memory_bio_get_pending(PySSLMemoryBIO *self, void *c)
4923{
Segev Finer5cff6372017-07-27 01:19:17 +03004924 return PyLong_FromSize_t(BIO_ctrl_pending(self->bio));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004925}
4926
4927PyDoc_STRVAR(PySSL_memory_bio_pending_doc,
4928"The number of bytes pending in the memory BIO.");
4929
4930static PyObject *
4931memory_bio_get_eof(PySSLMemoryBIO *self, void *c)
4932{
4933 return PyBool_FromLong((BIO_ctrl_pending(self->bio) == 0)
4934 && self->eof_written);
4935}
4936
4937PyDoc_STRVAR(PySSL_memory_bio_eof_doc,
4938"Whether the memory BIO is at EOF.");
4939
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004940/*[clinic input]
4941_ssl.MemoryBIO.read
4942 size as len: int = -1
4943 /
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004944
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004945Read up to size bytes from the memory BIO.
4946
4947If size is not specified, read the entire buffer.
4948If the return value is an empty bytes instance, this means either
4949EOF or that no data is available. Use the "eof" property to
4950distinguish between the two.
4951[clinic start generated code]*/
4952
4953static PyObject *
4954_ssl_MemoryBIO_read_impl(PySSLMemoryBIO *self, int len)
4955/*[clinic end generated code: output=a657aa1e79cd01b3 input=574d7be06a902366]*/
4956{
4957 int avail, nbytes;
4958 PyObject *result;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004959
Segev Finer5cff6372017-07-27 01:19:17 +03004960 avail = (int)Py_MIN(BIO_ctrl_pending(self->bio), INT_MAX);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004961 if ((len < 0) || (len > avail))
4962 len = avail;
4963
4964 result = PyBytes_FromStringAndSize(NULL, len);
4965 if ((result == NULL) || (len == 0))
4966 return result;
4967
4968 nbytes = BIO_read(self->bio, PyBytes_AS_STRING(result), len);
Zackery Spytz365ad2e2018-10-06 11:41:45 -06004969 if (nbytes < 0) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004970 Py_DECREF(result);
Zackery Spytz365ad2e2018-10-06 11:41:45 -06004971 _setSSLError(NULL, 0, __FILE__, __LINE__);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004972 return NULL;
4973 }
4974
Zackery Spytz365ad2e2018-10-06 11:41:45 -06004975 /* There should never be any short reads but check anyway. */
4976 if (nbytes < len) {
4977 _PyBytes_Resize(&result, nbytes);
4978 }
4979
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004980 return result;
4981}
4982
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004983/*[clinic input]
4984_ssl.MemoryBIO.write
4985 b: Py_buffer
4986 /
4987
4988Writes the bytes b into the memory BIO.
4989
4990Returns the number of bytes written.
4991[clinic start generated code]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004992
4993static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004994_ssl_MemoryBIO_write_impl(PySSLMemoryBIO *self, Py_buffer *b)
4995/*[clinic end generated code: output=156ec59110d75935 input=e45757b3e17c4808]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004996{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004997 int nbytes;
4998
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004999 if (b->len > INT_MAX) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005000 PyErr_Format(PyExc_OverflowError,
5001 "string longer than %d bytes", INT_MAX);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005002 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005003 }
5004
5005 if (self->eof_written) {
5006 PyErr_SetString(PySSLErrorObject,
5007 "cannot write() after write_eof()");
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005008 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005009 }
5010
Segev Finer5cff6372017-07-27 01:19:17 +03005011 nbytes = BIO_write(self->bio, b->buf, (int)b->len);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005012 if (nbytes < 0) {
5013 _setSSLError(NULL, 0, __FILE__, __LINE__);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005014 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005015 }
5016
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005017 return PyLong_FromLong(nbytes);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005018}
5019
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005020/*[clinic input]
5021_ssl.MemoryBIO.write_eof
5022
5023Write an EOF marker to the memory BIO.
5024
5025When all data has been read, the "eof" property will be True.
5026[clinic start generated code]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005027
5028static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005029_ssl_MemoryBIO_write_eof_impl(PySSLMemoryBIO *self)
5030/*[clinic end generated code: output=d4106276ccd1ed34 input=56a945f1d29e8bd6]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005031{
5032 self->eof_written = 1;
5033 /* After an EOF is written, a zero return from read() should be a real EOF
5034 * i.e. it should not be retried. Clear the SHOULD_RETRY flag. */
5035 BIO_clear_retry_flags(self->bio);
5036 BIO_set_mem_eof_return(self->bio, 0);
5037
5038 Py_RETURN_NONE;
5039}
5040
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005041static PyGetSetDef memory_bio_getsetlist[] = {
5042 {"pending", (getter) memory_bio_get_pending, NULL,
5043 PySSL_memory_bio_pending_doc},
5044 {"eof", (getter) memory_bio_get_eof, NULL,
5045 PySSL_memory_bio_eof_doc},
5046 {NULL}, /* sentinel */
5047};
5048
5049static struct PyMethodDef memory_bio_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005050 _SSL_MEMORYBIO_READ_METHODDEF
5051 _SSL_MEMORYBIO_WRITE_METHODDEF
5052 _SSL_MEMORYBIO_WRITE_EOF_METHODDEF
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005053 {NULL, NULL} /* sentinel */
5054};
5055
5056static PyTypeObject PySSLMemoryBIO_Type = {
5057 PyVarObject_HEAD_INIT(NULL, 0)
5058 "_ssl.MemoryBIO", /*tp_name*/
5059 sizeof(PySSLMemoryBIO), /*tp_basicsize*/
5060 0, /*tp_itemsize*/
5061 (destructor)memory_bio_dealloc, /*tp_dealloc*/
Jeroen Demeyer530f5062019-05-31 04:13:39 +02005062 0, /*tp_vectorcall_offset*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005063 0, /*tp_getattr*/
5064 0, /*tp_setattr*/
Jeroen Demeyer530f5062019-05-31 04:13:39 +02005065 0, /*tp_as_async*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005066 0, /*tp_repr*/
5067 0, /*tp_as_number*/
5068 0, /*tp_as_sequence*/
5069 0, /*tp_as_mapping*/
5070 0, /*tp_hash*/
5071 0, /*tp_call*/
5072 0, /*tp_str*/
5073 0, /*tp_getattro*/
5074 0, /*tp_setattro*/
5075 0, /*tp_as_buffer*/
5076 Py_TPFLAGS_DEFAULT, /*tp_flags*/
5077 0, /*tp_doc*/
5078 0, /*tp_traverse*/
5079 0, /*tp_clear*/
5080 0, /*tp_richcompare*/
5081 0, /*tp_weaklistoffset*/
5082 0, /*tp_iter*/
5083 0, /*tp_iternext*/
5084 memory_bio_methods, /*tp_methods*/
5085 0, /*tp_members*/
5086 memory_bio_getsetlist, /*tp_getset*/
5087 0, /*tp_base*/
5088 0, /*tp_dict*/
5089 0, /*tp_descr_get*/
5090 0, /*tp_descr_set*/
5091 0, /*tp_dictoffset*/
5092 0, /*tp_init*/
5093 0, /*tp_alloc*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005094 _ssl_MemoryBIO, /*tp_new*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005095};
5096
Antoine Pitrou152efa22010-05-16 18:19:27 +00005097
Christian Heimes99a65702016-09-10 23:44:53 +02005098/*
5099 * SSL Session object
5100 */
5101
5102static void
5103PySSLSession_dealloc(PySSLSession *self)
5104{
INADA Naokia6296d32017-08-24 14:55:17 +09005105 /* bpo-31095: UnTrack is needed before calling any callbacks */
Christian Heimesa5d07652016-09-24 10:48:05 +02005106 PyObject_GC_UnTrack(self);
Christian Heimes99a65702016-09-10 23:44:53 +02005107 Py_XDECREF(self->ctx);
5108 if (self->session != NULL) {
5109 SSL_SESSION_free(self->session);
5110 }
Christian Heimesa5d07652016-09-24 10:48:05 +02005111 PyObject_GC_Del(self);
Christian Heimes99a65702016-09-10 23:44:53 +02005112}
5113
5114static PyObject *
5115PySSLSession_richcompare(PyObject *left, PyObject *right, int op)
5116{
5117 int result;
5118
5119 if (left == NULL || right == NULL) {
5120 PyErr_BadInternalCall();
5121 return NULL;
5122 }
5123
5124 if (!PySSLSession_Check(left) || !PySSLSession_Check(right)) {
5125 Py_RETURN_NOTIMPLEMENTED;
5126 }
5127
5128 if (left == right) {
5129 result = 0;
5130 } else {
5131 const unsigned char *left_id, *right_id;
5132 unsigned int left_len, right_len;
5133 left_id = SSL_SESSION_get_id(((PySSLSession *)left)->session,
5134 &left_len);
5135 right_id = SSL_SESSION_get_id(((PySSLSession *)right)->session,
5136 &right_len);
5137 if (left_len == right_len) {
5138 result = memcmp(left_id, right_id, left_len);
5139 } else {
5140 result = 1;
5141 }
5142 }
5143
5144 switch (op) {
5145 case Py_EQ:
5146 if (result == 0) {
5147 Py_RETURN_TRUE;
5148 } else {
5149 Py_RETURN_FALSE;
5150 }
5151 break;
5152 case Py_NE:
5153 if (result != 0) {
5154 Py_RETURN_TRUE;
5155 } else {
5156 Py_RETURN_FALSE;
5157 }
5158 break;
5159 case Py_LT:
5160 case Py_LE:
5161 case Py_GT:
5162 case Py_GE:
5163 Py_RETURN_NOTIMPLEMENTED;
5164 break;
5165 default:
5166 PyErr_BadArgument();
5167 return NULL;
5168 }
5169}
5170
5171static int
5172PySSLSession_traverse(PySSLSession *self, visitproc visit, void *arg)
5173{
5174 Py_VISIT(self->ctx);
5175 return 0;
5176}
5177
5178static int
5179PySSLSession_clear(PySSLSession *self)
5180{
5181 Py_CLEAR(self->ctx);
5182 return 0;
5183}
5184
5185
5186static PyObject *
5187PySSLSession_get_time(PySSLSession *self, void *closure) {
5188 return PyLong_FromLong(SSL_SESSION_get_time(self->session));
5189}
5190
5191PyDoc_STRVAR(PySSLSession_get_time_doc,
5192"Session creation time (seconds since epoch).");
5193
5194
5195static PyObject *
5196PySSLSession_get_timeout(PySSLSession *self, void *closure) {
5197 return PyLong_FromLong(SSL_SESSION_get_timeout(self->session));
5198}
5199
5200PyDoc_STRVAR(PySSLSession_get_timeout_doc,
5201"Session timeout (delta in seconds).");
5202
5203
5204static PyObject *
5205PySSLSession_get_ticket_lifetime_hint(PySSLSession *self, void *closure) {
5206 unsigned long hint = SSL_SESSION_get_ticket_lifetime_hint(self->session);
5207 return PyLong_FromUnsignedLong(hint);
5208}
5209
5210PyDoc_STRVAR(PySSLSession_get_ticket_lifetime_hint_doc,
5211"Ticket life time hint.");
5212
5213
5214static PyObject *
5215PySSLSession_get_session_id(PySSLSession *self, void *closure) {
5216 const unsigned char *id;
5217 unsigned int len;
5218 id = SSL_SESSION_get_id(self->session, &len);
5219 return PyBytes_FromStringAndSize((const char *)id, len);
5220}
5221
5222PyDoc_STRVAR(PySSLSession_get_session_id_doc,
5223"Session id");
5224
5225
5226static PyObject *
5227PySSLSession_get_has_ticket(PySSLSession *self, void *closure) {
5228 if (SSL_SESSION_has_ticket(self->session)) {
5229 Py_RETURN_TRUE;
5230 } else {
5231 Py_RETURN_FALSE;
5232 }
5233}
5234
5235PyDoc_STRVAR(PySSLSession_get_has_ticket_doc,
5236"Does the session contain a ticket?");
5237
5238
5239static PyGetSetDef PySSLSession_getsetlist[] = {
5240 {"has_ticket", (getter) PySSLSession_get_has_ticket, NULL,
5241 PySSLSession_get_has_ticket_doc},
5242 {"id", (getter) PySSLSession_get_session_id, NULL,
5243 PySSLSession_get_session_id_doc},
5244 {"ticket_lifetime_hint", (getter) PySSLSession_get_ticket_lifetime_hint,
5245 NULL, PySSLSession_get_ticket_lifetime_hint_doc},
5246 {"time", (getter) PySSLSession_get_time, NULL,
5247 PySSLSession_get_time_doc},
5248 {"timeout", (getter) PySSLSession_get_timeout, NULL,
5249 PySSLSession_get_timeout_doc},
5250 {NULL}, /* sentinel */
5251};
5252
5253static PyTypeObject PySSLSession_Type = {
5254 PyVarObject_HEAD_INIT(NULL, 0)
5255 "_ssl.Session", /*tp_name*/
5256 sizeof(PySSLSession), /*tp_basicsize*/
5257 0, /*tp_itemsize*/
5258 (destructor)PySSLSession_dealloc, /*tp_dealloc*/
Jeroen Demeyer530f5062019-05-31 04:13:39 +02005259 0, /*tp_vectorcall_offset*/
Christian Heimes99a65702016-09-10 23:44:53 +02005260 0, /*tp_getattr*/
5261 0, /*tp_setattr*/
Jeroen Demeyer530f5062019-05-31 04:13:39 +02005262 0, /*tp_as_async*/
Christian Heimes99a65702016-09-10 23:44:53 +02005263 0, /*tp_repr*/
5264 0, /*tp_as_number*/
5265 0, /*tp_as_sequence*/
5266 0, /*tp_as_mapping*/
5267 0, /*tp_hash*/
5268 0, /*tp_call*/
5269 0, /*tp_str*/
5270 0, /*tp_getattro*/
5271 0, /*tp_setattro*/
5272 0, /*tp_as_buffer*/
Christian Heimesa5d07652016-09-24 10:48:05 +02005273 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
Christian Heimes99a65702016-09-10 23:44:53 +02005274 0, /*tp_doc*/
5275 (traverseproc)PySSLSession_traverse, /*tp_traverse*/
5276 (inquiry)PySSLSession_clear, /*tp_clear*/
5277 PySSLSession_richcompare, /*tp_richcompare*/
5278 0, /*tp_weaklistoffset*/
5279 0, /*tp_iter*/
5280 0, /*tp_iternext*/
5281 0, /*tp_methods*/
5282 0, /*tp_members*/
5283 PySSLSession_getsetlist, /*tp_getset*/
5284};
5285
5286
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005287/* helper routines for seeding the SSL PRNG */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005288/*[clinic input]
5289_ssl.RAND_add
Larry Hastingsdbfdc382015-05-04 06:59:46 -07005290 string as view: Py_buffer(accept={str, buffer})
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005291 entropy: double
5292 /
5293
5294Mix string into the OpenSSL PRNG state.
5295
5296entropy (a float) is a lower bound on the entropy contained in
Chandan Kumar63c2c8a2017-06-09 15:13:58 +05305297string. See RFC 4086.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005298[clinic start generated code]*/
5299
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005300static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005301_ssl_RAND_add_impl(PyObject *module, Py_buffer *view, double entropy)
Serhiy Storchaka5f31d5c2017-06-10 13:13:51 +03005302/*[clinic end generated code: output=e6dd48df9c9024e9 input=5c33017422828f5c]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005303{
Serhiy Storchaka8490f5a2015-03-20 09:00:36 +02005304 const char *buf;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02005305 Py_ssize_t len, written;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005306
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005307 buf = (const char *)view->buf;
5308 len = view->len;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02005309 do {
5310 written = Py_MIN(len, INT_MAX);
5311 RAND_add(buf, (int)written, entropy);
5312 buf += written;
5313 len -= written;
5314 } while (len);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02005315 Py_RETURN_NONE;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005316}
5317
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005318static PyObject *
Victor Stinner99c8b162011-05-24 12:05:19 +02005319PySSL_RAND(int len, int pseudo)
5320{
5321 int ok;
5322 PyObject *bytes;
5323 unsigned long err;
5324 const char *errstr;
5325 PyObject *v;
5326
Victor Stinner1e81a392013-12-19 16:47:04 +01005327 if (len < 0) {
5328 PyErr_SetString(PyExc_ValueError, "num must be positive");
5329 return NULL;
5330 }
5331
Victor Stinner99c8b162011-05-24 12:05:19 +02005332 bytes = PyBytes_FromStringAndSize(NULL, len);
5333 if (bytes == NULL)
5334 return NULL;
5335 if (pseudo) {
Christian Heimesa871f692020-06-01 08:58:14 +02005336#ifdef PY_OPENSSL_1_1_API
5337 ok = RAND_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
5338#else
Victor Stinner99c8b162011-05-24 12:05:19 +02005339 ok = RAND_pseudo_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
Christian Heimesa871f692020-06-01 08:58:14 +02005340#endif
Victor Stinner99c8b162011-05-24 12:05:19 +02005341 if (ok == 0 || ok == 1)
5342 return Py_BuildValue("NO", bytes, ok == 1 ? Py_True : Py_False);
5343 }
5344 else {
5345 ok = RAND_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
5346 if (ok == 1)
5347 return bytes;
5348 }
5349 Py_DECREF(bytes);
5350
5351 err = ERR_get_error();
5352 errstr = ERR_reason_error_string(err);
5353 v = Py_BuildValue("(ks)", err, errstr);
5354 if (v != NULL) {
5355 PyErr_SetObject(PySSLErrorObject, v);
5356 Py_DECREF(v);
5357 }
5358 return NULL;
5359}
5360
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005361/*[clinic input]
5362_ssl.RAND_bytes
5363 n: int
5364 /
5365
5366Generate n cryptographically strong pseudo-random bytes.
5367[clinic start generated code]*/
5368
Victor Stinner99c8b162011-05-24 12:05:19 +02005369static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005370_ssl_RAND_bytes_impl(PyObject *module, int n)
5371/*[clinic end generated code: output=977da635e4838bc7 input=678ddf2872dfebfc]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02005372{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005373 return PySSL_RAND(n, 0);
Victor Stinner99c8b162011-05-24 12:05:19 +02005374}
5375
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005376/*[clinic input]
5377_ssl.RAND_pseudo_bytes
5378 n: int
5379 /
5380
5381Generate n pseudo-random bytes.
5382
5383Return a pair (bytes, is_cryptographic). is_cryptographic is True
5384if the bytes generated are cryptographically strong.
5385[clinic start generated code]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02005386
5387static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005388_ssl_RAND_pseudo_bytes_impl(PyObject *module, int n)
5389/*[clinic end generated code: output=b1509e937000e52d input=58312bd53f9bbdd0]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02005390{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005391 return PySSL_RAND(n, 1);
Victor Stinner99c8b162011-05-24 12:05:19 +02005392}
5393
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005394/*[clinic input]
5395_ssl.RAND_status
5396
5397Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.
5398
5399It is necessary to seed the PRNG with RAND_add() on some platforms before
5400using the ssl() function.
5401[clinic start generated code]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02005402
5403static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005404_ssl_RAND_status_impl(PyObject *module)
5405/*[clinic end generated code: output=7e0aaa2d39fdc1ad input=8a774b02d1dc81f3]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005406{
Christian Heimes217cfd12007-12-02 14:31:20 +00005407 return PyLong_FromLong(RAND_status());
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005408}
5409
Benjamin Petersonb8a2f512016-07-06 23:55:15 -07005410#ifndef OPENSSL_NO_EGD
Christian Heimesa5d07652016-09-24 10:48:05 +02005411/* LCOV_EXCL_START */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005412/*[clinic input]
5413_ssl.RAND_egd
5414 path: object(converter="PyUnicode_FSConverter")
5415 /
5416
5417Queries the entropy gather daemon (EGD) on the socket named by 'path'.
5418
5419Returns number of bytes read. Raises SSLError if connection to EGD
5420fails or if it does not provide enough data to seed PRNG.
5421[clinic start generated code]*/
5422
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005423static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005424_ssl_RAND_egd_impl(PyObject *module, PyObject *path)
5425/*[clinic end generated code: output=02a67c7c367f52fa input=1aeb7eb948312195]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005426{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005427 int bytes = RAND_egd(PyBytes_AsString(path));
Victor Stinnerf9faaad2010-05-16 21:36:37 +00005428 Py_DECREF(path);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005429 if (bytes == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00005430 PyErr_SetString(PySSLErrorObject,
5431 "EGD connection failed or EGD did not return "
5432 "enough data to seed the PRNG");
5433 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005434 }
Christian Heimes217cfd12007-12-02 14:31:20 +00005435 return PyLong_FromLong(bytes);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005436}
Christian Heimesa5d07652016-09-24 10:48:05 +02005437/* LCOV_EXCL_STOP */
Benjamin Petersonb8a2f512016-07-06 23:55:15 -07005438#endif /* OPENSSL_NO_EGD */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005439
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005440
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005441
5442/*[clinic input]
5443_ssl.get_default_verify_paths
5444
5445Return search paths and environment vars that are used by SSLContext's set_default_verify_paths() to load default CAs.
5446
5447The values are 'cert_file_env', 'cert_file', 'cert_dir_env', 'cert_dir'.
5448[clinic start generated code]*/
Christian Heimes6d7ad132013-06-09 18:02:55 +02005449
5450static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005451_ssl_get_default_verify_paths_impl(PyObject *module)
5452/*[clinic end generated code: output=e5b62a466271928b input=5210c953d98c3eb5]*/
Christian Heimes6d7ad132013-06-09 18:02:55 +02005453{
5454 PyObject *ofile_env = NULL;
5455 PyObject *ofile = NULL;
5456 PyObject *odir_env = NULL;
5457 PyObject *odir = NULL;
5458
Benjamin Petersond113c962015-07-18 10:59:13 -07005459#define CONVERT(info, target) { \
Christian Heimes6d7ad132013-06-09 18:02:55 +02005460 const char *tmp = (info); \
5461 target = NULL; \
5462 if (!tmp) { Py_INCREF(Py_None); target = Py_None; } \
5463 else if ((target = PyUnicode_DecodeFSDefault(tmp)) == NULL) { \
5464 target = PyBytes_FromString(tmp); } \
5465 if (!target) goto error; \
Benjamin Peterson025a1fd2015-11-14 15:12:38 -08005466 }
Christian Heimes6d7ad132013-06-09 18:02:55 +02005467
Benjamin Petersond113c962015-07-18 10:59:13 -07005468 CONVERT(X509_get_default_cert_file_env(), ofile_env);
5469 CONVERT(X509_get_default_cert_file(), ofile);
5470 CONVERT(X509_get_default_cert_dir_env(), odir_env);
5471 CONVERT(X509_get_default_cert_dir(), odir);
5472#undef CONVERT
Christian Heimes6d7ad132013-06-09 18:02:55 +02005473
Christian Heimes200bb1b2013-06-14 15:14:29 +02005474 return Py_BuildValue("NNNN", ofile_env, ofile, odir_env, odir);
Christian Heimes6d7ad132013-06-09 18:02:55 +02005475
5476 error:
5477 Py_XDECREF(ofile_env);
5478 Py_XDECREF(ofile);
5479 Py_XDECREF(odir_env);
5480 Py_XDECREF(odir);
5481 return NULL;
5482}
5483
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005484static PyObject*
5485asn1obj2py(ASN1_OBJECT *obj)
5486{
5487 int nid;
5488 const char *ln, *sn;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005489
5490 nid = OBJ_obj2nid(obj);
5491 if (nid == NID_undef) {
5492 PyErr_Format(PyExc_ValueError, "Unknown object");
5493 return NULL;
5494 }
5495 sn = OBJ_nid2sn(nid);
5496 ln = OBJ_nid2ln(nid);
Serhiy Storchakae503ca52017-09-05 01:28:53 +03005497 return Py_BuildValue("issN", nid, sn, ln, _asn1obj2py(obj, 1));
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005498}
5499
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005500/*[clinic input]
5501_ssl.txt2obj
5502 txt: str
5503 name: bool = False
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005504
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005505Lookup NID, short name, long name and OID of an ASN1_OBJECT.
5506
5507By default objects are looked up by OID. With name=True short and
5508long name are also matched.
5509[clinic start generated code]*/
5510
5511static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005512_ssl_txt2obj_impl(PyObject *module, const char *txt, int name)
5513/*[clinic end generated code: output=c38e3991347079c1 input=1c1e7d0aa7c48602]*/
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005514{
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005515 PyObject *result = NULL;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005516 ASN1_OBJECT *obj;
5517
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005518 obj = OBJ_txt2obj(txt, name ? 0 : 1);
5519 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01005520 PyErr_Format(PyExc_ValueError, "unknown object '%.100s'", txt);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005521 return NULL;
5522 }
5523 result = asn1obj2py(obj);
5524 ASN1_OBJECT_free(obj);
5525 return result;
5526}
5527
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005528/*[clinic input]
5529_ssl.nid2obj
5530 nid: int
5531 /
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005532
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005533Lookup NID, short name, long name and OID of an ASN1_OBJECT by NID.
5534[clinic start generated code]*/
5535
5536static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005537_ssl_nid2obj_impl(PyObject *module, int nid)
5538/*[clinic end generated code: output=4a98ab691cd4f84a input=51787a3bee7d8f98]*/
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005539{
5540 PyObject *result = NULL;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005541 ASN1_OBJECT *obj;
5542
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005543 if (nid < NID_undef) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01005544 PyErr_SetString(PyExc_ValueError, "NID must be positive.");
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005545 return NULL;
5546 }
5547 obj = OBJ_nid2obj(nid);
5548 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01005549 PyErr_Format(PyExc_ValueError, "unknown NID %i", nid);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005550 return NULL;
5551 }
5552 result = asn1obj2py(obj);
5553 ASN1_OBJECT_free(obj);
5554 return result;
5555}
5556
Christian Heimes46bebee2013-06-09 19:03:31 +02005557#ifdef _MSC_VER
Christian Heimes44109d72013-11-22 01:51:30 +01005558
5559static PyObject*
5560certEncodingType(DWORD encodingType)
5561{
5562 static PyObject *x509_asn = NULL;
5563 static PyObject *pkcs_7_asn = NULL;
5564
5565 if (x509_asn == NULL) {
5566 x509_asn = PyUnicode_InternFromString("x509_asn");
5567 if (x509_asn == NULL)
5568 return NULL;
5569 }
5570 if (pkcs_7_asn == NULL) {
5571 pkcs_7_asn = PyUnicode_InternFromString("pkcs_7_asn");
5572 if (pkcs_7_asn == NULL)
5573 return NULL;
5574 }
5575 switch(encodingType) {
5576 case X509_ASN_ENCODING:
5577 Py_INCREF(x509_asn);
5578 return x509_asn;
5579 case PKCS_7_ASN_ENCODING:
5580 Py_INCREF(pkcs_7_asn);
5581 return pkcs_7_asn;
5582 default:
5583 return PyLong_FromLong(encodingType);
5584 }
5585}
5586
5587static PyObject*
5588parseKeyUsage(PCCERT_CONTEXT pCertCtx, DWORD flags)
5589{
5590 CERT_ENHKEY_USAGE *usage;
5591 DWORD size, error, i;
5592 PyObject *retval;
5593
5594 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, NULL, &size)) {
5595 error = GetLastError();
5596 if (error == CRYPT_E_NOT_FOUND) {
5597 Py_RETURN_TRUE;
5598 }
5599 return PyErr_SetFromWindowsErr(error);
5600 }
5601
5602 usage = (CERT_ENHKEY_USAGE*)PyMem_Malloc(size);
5603 if (usage == NULL) {
5604 return PyErr_NoMemory();
5605 }
5606
5607 /* Now get the actual enhanced usage property */
5608 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, usage, &size)) {
5609 PyMem_Free(usage);
5610 error = GetLastError();
5611 if (error == CRYPT_E_NOT_FOUND) {
5612 Py_RETURN_TRUE;
5613 }
5614 return PyErr_SetFromWindowsErr(error);
5615 }
Christian Heimes915cd3f2019-09-09 18:06:55 +02005616 retval = PyFrozenSet_New(NULL);
Christian Heimes44109d72013-11-22 01:51:30 +01005617 if (retval == NULL) {
5618 goto error;
5619 }
5620 for (i = 0; i < usage->cUsageIdentifier; ++i) {
5621 if (usage->rgpszUsageIdentifier[i]) {
5622 PyObject *oid;
5623 int err;
5624 oid = PyUnicode_FromString(usage->rgpszUsageIdentifier[i]);
5625 if (oid == NULL) {
5626 Py_CLEAR(retval);
5627 goto error;
5628 }
5629 err = PySet_Add(retval, oid);
5630 Py_DECREF(oid);
5631 if (err == -1) {
5632 Py_CLEAR(retval);
5633 goto error;
5634 }
5635 }
5636 }
5637 error:
5638 PyMem_Free(usage);
5639 return retval;
5640}
5641
kctherookied93fbbf2019-03-29 00:59:06 +07005642static HCERTSTORE
5643ssl_collect_certificates(const char *store_name)
5644{
5645/* this function collects the system certificate stores listed in
5646 * system_stores into a collection certificate store for being
5647 * enumerated. The store must be readable to be added to the
5648 * store collection.
5649 */
5650
5651 HCERTSTORE hCollectionStore = NULL, hSystemStore = NULL;
5652 static DWORD system_stores[] = {
5653 CERT_SYSTEM_STORE_LOCAL_MACHINE,
5654 CERT_SYSTEM_STORE_LOCAL_MACHINE_ENTERPRISE,
5655 CERT_SYSTEM_STORE_LOCAL_MACHINE_GROUP_POLICY,
5656 CERT_SYSTEM_STORE_CURRENT_USER,
5657 CERT_SYSTEM_STORE_CURRENT_USER_GROUP_POLICY,
5658 CERT_SYSTEM_STORE_SERVICES,
5659 CERT_SYSTEM_STORE_USERS};
5660 size_t i, storesAdded;
5661 BOOL result;
5662
5663 hCollectionStore = CertOpenStore(CERT_STORE_PROV_COLLECTION, 0,
5664 (HCRYPTPROV)NULL, 0, NULL);
5665 if (!hCollectionStore) {
5666 return NULL;
5667 }
5668 storesAdded = 0;
5669 for (i = 0; i < sizeof(system_stores) / sizeof(DWORD); i++) {
5670 hSystemStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0,
5671 (HCRYPTPROV)NULL,
5672 CERT_STORE_READONLY_FLAG |
5673 system_stores[i], store_name);
5674 if (hSystemStore) {
5675 result = CertAddStoreToCollection(hCollectionStore, hSystemStore,
5676 CERT_PHYSICAL_STORE_ADD_ENABLE_FLAG, 0);
5677 if (result) {
5678 ++storesAdded;
5679 }
neoneneed701292019-09-09 21:33:43 +09005680 CertCloseStore(hSystemStore, 0); /* flag must be 0 */
kctherookied93fbbf2019-03-29 00:59:06 +07005681 }
5682 }
5683 if (storesAdded == 0) {
5684 CertCloseStore(hCollectionStore, CERT_CLOSE_STORE_FORCE_FLAG);
5685 return NULL;
5686 }
5687
5688 return hCollectionStore;
5689}
5690
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005691/*[clinic input]
5692_ssl.enum_certificates
5693 store_name: str
5694
5695Retrieve certificates from Windows' cert store.
5696
5697store_name may be one of 'CA', 'ROOT' or 'MY'. The system may provide
5698more cert storages, too. The function returns a list of (bytes,
5699encoding_type, trust) tuples. The encoding_type flag can be interpreted
5700with X509_ASN_ENCODING or PKCS_7_ASN_ENCODING. The trust setting is either
5701a set of OIDs or the boolean True.
5702[clinic start generated code]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00005703
Christian Heimes46bebee2013-06-09 19:03:31 +02005704static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005705_ssl_enum_certificates_impl(PyObject *module, const char *store_name)
5706/*[clinic end generated code: output=5134dc8bb3a3c893 input=915f60d70461ea4e]*/
Christian Heimes46bebee2013-06-09 19:03:31 +02005707{
kctherookied93fbbf2019-03-29 00:59:06 +07005708 HCERTSTORE hCollectionStore = NULL;
Christian Heimes44109d72013-11-22 01:51:30 +01005709 PCCERT_CONTEXT pCertCtx = NULL;
5710 PyObject *keyusage = NULL, *cert = NULL, *enc = NULL, *tup = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02005711 PyObject *result = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02005712
Christian Heimes915cd3f2019-09-09 18:06:55 +02005713 result = PySet_New(NULL);
Christian Heimes44109d72013-11-22 01:51:30 +01005714 if (result == NULL) {
5715 return NULL;
5716 }
kctherookied93fbbf2019-03-29 00:59:06 +07005717 hCollectionStore = ssl_collect_certificates(store_name);
5718 if (hCollectionStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02005719 Py_DECREF(result);
5720 return PyErr_SetFromWindowsErr(GetLastError());
5721 }
5722
kctherookied93fbbf2019-03-29 00:59:06 +07005723 while (pCertCtx = CertEnumCertificatesInStore(hCollectionStore, pCertCtx)) {
Christian Heimes44109d72013-11-22 01:51:30 +01005724 cert = PyBytes_FromStringAndSize((const char*)pCertCtx->pbCertEncoded,
5725 pCertCtx->cbCertEncoded);
5726 if (!cert) {
5727 Py_CLEAR(result);
5728 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02005729 }
Christian Heimes44109d72013-11-22 01:51:30 +01005730 if ((enc = certEncodingType(pCertCtx->dwCertEncodingType)) == NULL) {
5731 Py_CLEAR(result);
5732 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02005733 }
Christian Heimes44109d72013-11-22 01:51:30 +01005734 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG);
5735 if (keyusage == Py_True) {
5736 Py_DECREF(keyusage);
5737 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_EXT_ONLY_ENHKEY_USAGE_FLAG);
Christian Heimes46bebee2013-06-09 19:03:31 +02005738 }
Christian Heimes44109d72013-11-22 01:51:30 +01005739 if (keyusage == NULL) {
5740 Py_CLEAR(result);
5741 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02005742 }
Christian Heimes44109d72013-11-22 01:51:30 +01005743 if ((tup = PyTuple_New(3)) == NULL) {
5744 Py_CLEAR(result);
5745 break;
5746 }
5747 PyTuple_SET_ITEM(tup, 0, cert);
5748 cert = NULL;
5749 PyTuple_SET_ITEM(tup, 1, enc);
5750 enc = NULL;
5751 PyTuple_SET_ITEM(tup, 2, keyusage);
5752 keyusage = NULL;
Christian Heimes915cd3f2019-09-09 18:06:55 +02005753 if (PySet_Add(result, tup) == -1) {
5754 Py_CLEAR(result);
5755 Py_CLEAR(tup);
5756 break;
Christian Heimes44109d72013-11-22 01:51:30 +01005757 }
5758 Py_CLEAR(tup);
5759 }
5760 if (pCertCtx) {
5761 /* loop ended with an error, need to clean up context manually */
5762 CertFreeCertificateContext(pCertCtx);
Christian Heimes46bebee2013-06-09 19:03:31 +02005763 }
5764
5765 /* In error cases cert, enc and tup may not be NULL */
5766 Py_XDECREF(cert);
5767 Py_XDECREF(enc);
Christian Heimes44109d72013-11-22 01:51:30 +01005768 Py_XDECREF(keyusage);
Christian Heimes46bebee2013-06-09 19:03:31 +02005769 Py_XDECREF(tup);
5770
kctherookied93fbbf2019-03-29 00:59:06 +07005771 /* CERT_CLOSE_STORE_FORCE_FLAG forces freeing of memory for all contexts
5772 associated with the store, in this case our collection store and the
5773 associated system stores. */
5774 if (!CertCloseStore(hCollectionStore, CERT_CLOSE_STORE_FORCE_FLAG)) {
Christian Heimes46bebee2013-06-09 19:03:31 +02005775 /* This error case might shadow another exception.*/
Christian Heimes44109d72013-11-22 01:51:30 +01005776 Py_XDECREF(result);
5777 return PyErr_SetFromWindowsErr(GetLastError());
5778 }
kctherookied93fbbf2019-03-29 00:59:06 +07005779
Christian Heimes915cd3f2019-09-09 18:06:55 +02005780 /* convert set to list */
5781 if (result == NULL) {
5782 return NULL;
5783 } else {
5784 PyObject *lst = PySequence_List(result);
5785 Py_DECREF(result);
5786 return lst;
5787 }
Christian Heimes44109d72013-11-22 01:51:30 +01005788}
5789
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005790/*[clinic input]
5791_ssl.enum_crls
5792 store_name: str
5793
5794Retrieve CRLs from Windows' cert store.
5795
5796store_name may be one of 'CA', 'ROOT' or 'MY'. The system may provide
5797more cert storages, too. The function returns a list of (bytes,
5798encoding_type) tuples. The encoding_type flag can be interpreted with
5799X509_ASN_ENCODING or PKCS_7_ASN_ENCODING.
5800[clinic start generated code]*/
Christian Heimes44109d72013-11-22 01:51:30 +01005801
5802static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005803_ssl_enum_crls_impl(PyObject *module, const char *store_name)
5804/*[clinic end generated code: output=bce467f60ccd03b6 input=a1f1d7629f1c5d3d]*/
Christian Heimes44109d72013-11-22 01:51:30 +01005805{
kctherookied93fbbf2019-03-29 00:59:06 +07005806 HCERTSTORE hCollectionStore = NULL;
Christian Heimes44109d72013-11-22 01:51:30 +01005807 PCCRL_CONTEXT pCrlCtx = NULL;
5808 PyObject *crl = NULL, *enc = NULL, *tup = NULL;
5809 PyObject *result = NULL;
5810
Christian Heimes915cd3f2019-09-09 18:06:55 +02005811 result = PySet_New(NULL);
Christian Heimes44109d72013-11-22 01:51:30 +01005812 if (result == NULL) {
5813 return NULL;
5814 }
kctherookied93fbbf2019-03-29 00:59:06 +07005815 hCollectionStore = ssl_collect_certificates(store_name);
5816 if (hCollectionStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02005817 Py_DECREF(result);
5818 return PyErr_SetFromWindowsErr(GetLastError());
5819 }
Christian Heimes44109d72013-11-22 01:51:30 +01005820
kctherookied93fbbf2019-03-29 00:59:06 +07005821 while (pCrlCtx = CertEnumCRLsInStore(hCollectionStore, pCrlCtx)) {
Christian Heimes44109d72013-11-22 01:51:30 +01005822 crl = PyBytes_FromStringAndSize((const char*)pCrlCtx->pbCrlEncoded,
5823 pCrlCtx->cbCrlEncoded);
5824 if (!crl) {
5825 Py_CLEAR(result);
5826 break;
5827 }
5828 if ((enc = certEncodingType(pCrlCtx->dwCertEncodingType)) == NULL) {
5829 Py_CLEAR(result);
5830 break;
5831 }
5832 if ((tup = PyTuple_New(2)) == NULL) {
5833 Py_CLEAR(result);
5834 break;
5835 }
5836 PyTuple_SET_ITEM(tup, 0, crl);
5837 crl = NULL;
5838 PyTuple_SET_ITEM(tup, 1, enc);
5839 enc = NULL;
5840
Christian Heimes915cd3f2019-09-09 18:06:55 +02005841 if (PySet_Add(result, tup) == -1) {
5842 Py_CLEAR(result);
5843 Py_CLEAR(tup);
5844 break;
Christian Heimes44109d72013-11-22 01:51:30 +01005845 }
5846 Py_CLEAR(tup);
Christian Heimes46bebee2013-06-09 19:03:31 +02005847 }
Christian Heimes44109d72013-11-22 01:51:30 +01005848 if (pCrlCtx) {
5849 /* loop ended with an error, need to clean up context manually */
5850 CertFreeCRLContext(pCrlCtx);
5851 }
5852
5853 /* In error cases cert, enc and tup may not be NULL */
5854 Py_XDECREF(crl);
5855 Py_XDECREF(enc);
5856 Py_XDECREF(tup);
5857
kctherookied93fbbf2019-03-29 00:59:06 +07005858 /* CERT_CLOSE_STORE_FORCE_FLAG forces freeing of memory for all contexts
5859 associated with the store, in this case our collection store and the
5860 associated system stores. */
5861 if (!CertCloseStore(hCollectionStore, CERT_CLOSE_STORE_FORCE_FLAG)) {
Christian Heimes44109d72013-11-22 01:51:30 +01005862 /* This error case might shadow another exception.*/
5863 Py_XDECREF(result);
5864 return PyErr_SetFromWindowsErr(GetLastError());
5865 }
Christian Heimes915cd3f2019-09-09 18:06:55 +02005866 /* convert set to list */
5867 if (result == NULL) {
5868 return NULL;
5869 } else {
5870 PyObject *lst = PySequence_List(result);
5871 Py_DECREF(result);
5872 return lst;
5873 }
Christian Heimes46bebee2013-06-09 19:03:31 +02005874}
Christian Heimes44109d72013-11-22 01:51:30 +01005875
5876#endif /* _MSC_VER */
Bill Janssen40a0f662008-08-12 16:56:25 +00005877
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005878/* List of functions exported by this module. */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005879static PyMethodDef PySSL_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005880 _SSL__TEST_DECODE_CERT_METHODDEF
5881 _SSL_RAND_ADD_METHODDEF
5882 _SSL_RAND_BYTES_METHODDEF
5883 _SSL_RAND_PSEUDO_BYTES_METHODDEF
5884 _SSL_RAND_EGD_METHODDEF
5885 _SSL_RAND_STATUS_METHODDEF
5886 _SSL_GET_DEFAULT_VERIFY_PATHS_METHODDEF
5887 _SSL_ENUM_CERTIFICATES_METHODDEF
5888 _SSL_ENUM_CRLS_METHODDEF
5889 _SSL_TXT2OBJ_METHODDEF
5890 _SSL_NID2OBJ_METHODDEF
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005891 {NULL, NULL} /* Sentinel */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005892};
5893
5894
Christian Heimes598894f2016-09-05 23:19:05 +02005895#ifdef HAVE_OPENSSL_CRYPTO_LOCK
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005896
5897/* an implementation of OpenSSL threading operations in terms
Christian Heimes598894f2016-09-05 23:19:05 +02005898 * of the Python C thread library
5899 * Only used up to 1.0.2. OpenSSL 1.1.0+ has its own locking code.
5900 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005901
5902static PyThread_type_lock *_ssl_locks = NULL;
5903
Christian Heimes4d98ca92013-08-19 17:36:29 +02005904#if OPENSSL_VERSION_NUMBER >= 0x10000000
5905/* use new CRYPTO_THREADID API. */
5906static void
5907_ssl_threadid_callback(CRYPTO_THREADID *id)
5908{
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +02005909 CRYPTO_THREADID_set_numeric(id, PyThread_get_thread_ident());
Christian Heimes4d98ca92013-08-19 17:36:29 +02005910}
5911#else
5912/* deprecated CRYPTO_set_id_callback() API. */
5913static unsigned long
5914_ssl_thread_id_function (void) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005915 return PyThread_get_thread_ident();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005916}
Christian Heimes4d98ca92013-08-19 17:36:29 +02005917#endif
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005918
Bill Janssen6e027db2007-11-15 22:23:56 +00005919static void _ssl_thread_locking_function
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005920 (int mode, int n, const char *file, int line) {
5921 /* this function is needed to perform locking on shared data
5922 structures. (Note that OpenSSL uses a number of global data
5923 structures that will be implicitly shared whenever multiple
5924 threads use OpenSSL.) Multi-threaded applications will
5925 crash at random if it is not set.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005926
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005927 locking_function() must be able to handle up to
5928 CRYPTO_num_locks() different mutex locks. It sets the n-th
5929 lock if mode & CRYPTO_LOCK, and releases it otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005930
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005931 file and line are the file number of the function setting the
5932 lock. They can be useful for debugging.
5933 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005934
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005935 if ((_ssl_locks == NULL) ||
5936 (n < 0) || ((unsigned)n >= _ssl_locks_count))
5937 return;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005938
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005939 if (mode & CRYPTO_LOCK) {
5940 PyThread_acquire_lock(_ssl_locks[n], 1);
5941 } else {
5942 PyThread_release_lock(_ssl_locks[n]);
5943 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005944}
5945
5946static int _setup_ssl_threads(void) {
5947
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005948 unsigned int i;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005949
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005950 if (_ssl_locks == NULL) {
5951 _ssl_locks_count = CRYPTO_num_locks();
Christian Heimesf6365e32016-09-13 20:48:13 +02005952 _ssl_locks = PyMem_Calloc(_ssl_locks_count,
5953 sizeof(PyThread_type_lock));
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02005954 if (_ssl_locks == NULL) {
5955 PyErr_NoMemory();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005956 return 0;
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02005957 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005958 for (i = 0; i < _ssl_locks_count; i++) {
5959 _ssl_locks[i] = PyThread_allocate_lock();
5960 if (_ssl_locks[i] == NULL) {
5961 unsigned int j;
5962 for (j = 0; j < i; j++) {
5963 PyThread_free_lock(_ssl_locks[j]);
5964 }
Victor Stinnerb6404912013-07-07 16:21:41 +02005965 PyMem_Free(_ssl_locks);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005966 return 0;
5967 }
5968 }
5969 CRYPTO_set_locking_callback(_ssl_thread_locking_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02005970#if OPENSSL_VERSION_NUMBER >= 0x10000000
5971 CRYPTO_THREADID_set_callback(_ssl_threadid_callback);
5972#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005973 CRYPTO_set_id_callback(_ssl_thread_id_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02005974#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005975 }
5976 return 1;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005977}
5978
Antoine Pitroua6a4dc82017-09-07 18:56:24 +02005979#endif /* HAVE_OPENSSL_CRYPTO_LOCK for OpenSSL < 1.1.0 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005980
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005981PyDoc_STRVAR(module_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005982"Implementation module for SSL socket operations. See the socket module\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005983for documentation.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005984
Martin v. Löwis1a214512008-06-11 05:26:20 +00005985
5986static struct PyModuleDef _sslmodule = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005987 PyModuleDef_HEAD_INIT,
5988 "_ssl",
5989 module_doc,
5990 -1,
5991 PySSL_methods,
5992 NULL,
5993 NULL,
5994 NULL,
5995 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00005996};
5997
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02005998
5999static void
6000parse_openssl_version(unsigned long libver,
6001 unsigned int *major, unsigned int *minor,
6002 unsigned int *fix, unsigned int *patch,
6003 unsigned int *status)
6004{
6005 *status = libver & 0xF;
6006 libver >>= 4;
6007 *patch = libver & 0xFF;
6008 libver >>= 8;
6009 *fix = libver & 0xFF;
6010 libver >>= 8;
6011 *minor = libver & 0xFF;
6012 libver >>= 8;
6013 *major = libver & 0xFF;
6014}
6015
Mark Hammondfe51c6d2002-08-02 02:27:13 +00006016PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00006017PyInit__ssl(void)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00006018{
Christian Heimesb3ad0e52017-09-08 12:00:19 -07006019 PyObject *m, *d, *r, *bases;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006020 unsigned long libver;
6021 unsigned int major, minor, fix, patch, status;
6022 PySocketModule_APIObject *socket_api;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02006023 struct py_ssl_error_code *errcode;
6024 struct py_ssl_library_code *libcode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00006025
Antoine Pitrou152efa22010-05-16 18:19:27 +00006026 if (PyType_Ready(&PySSLContext_Type) < 0)
6027 return NULL;
6028 if (PyType_Ready(&PySSLSocket_Type) < 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006029 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02006030 if (PyType_Ready(&PySSLMemoryBIO_Type) < 0)
6031 return NULL;
Christian Heimes99a65702016-09-10 23:44:53 +02006032 if (PyType_Ready(&PySSLSession_Type) < 0)
6033 return NULL;
6034
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00006035
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006036 m = PyModule_Create(&_sslmodule);
6037 if (m == NULL)
6038 return NULL;
6039 d = PyModule_GetDict(m);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00006040
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006041 /* Load _socket module and its C API */
6042 socket_api = PySocketModule_ImportModuleAndAPI();
6043 if (!socket_api)
6044 return NULL;
6045 PySocketModule = *socket_api;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00006046
Christian Heimesc941e622017-09-05 15:47:11 +02006047#ifndef OPENSSL_VERSION_1_1
6048 /* Load all algorithms and initialize cpuid */
6049 OPENSSL_add_all_algorithms_noconf();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006050 /* Init OpenSSL */
6051 SSL_load_error_strings();
6052 SSL_library_init();
Christian Heimesc941e622017-09-05 15:47:11 +02006053#endif
6054
Christian Heimes598894f2016-09-05 23:19:05 +02006055#ifdef HAVE_OPENSSL_CRYPTO_LOCK
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006056 /* note that this will start threading if not already started */
6057 if (!_setup_ssl_threads()) {
6058 return NULL;
6059 }
Christian Heimesc087a262020-05-15 20:55:25 +02006060#elif OPENSSL_VERSION_1_1
Christian Heimes598894f2016-09-05 23:19:05 +02006061 /* OpenSSL 1.1.0 builtin thread support is enabled */
6062 _ssl_locks_count++;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00006063#endif
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00006064
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006065 /* Add symbols to module dict */
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02006066 sslerror_type_slots[0].pfunc = PyExc_OSError;
6067 PySSLErrorObject = PyType_FromSpec(&sslerror_type_spec);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006068 if (PySSLErrorObject == NULL)
6069 return NULL;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02006070
Christian Heimesb3ad0e52017-09-08 12:00:19 -07006071 /* ssl.CertificateError used to be a subclass of ValueError */
6072 bases = Py_BuildValue("OO", PySSLErrorObject, PyExc_ValueError);
6073 if (bases == NULL)
6074 return NULL;
6075 PySSLCertVerificationErrorObject = PyErr_NewExceptionWithDoc(
6076 "ssl.SSLCertVerificationError", SSLCertVerificationError_doc,
6077 bases, NULL);
6078 Py_DECREF(bases);
Antoine Pitrou41032a62011-10-27 23:56:55 +02006079 PySSLZeroReturnErrorObject = PyErr_NewExceptionWithDoc(
6080 "ssl.SSLZeroReturnError", SSLZeroReturnError_doc,
6081 PySSLErrorObject, NULL);
6082 PySSLWantReadErrorObject = PyErr_NewExceptionWithDoc(
6083 "ssl.SSLWantReadError", SSLWantReadError_doc,
6084 PySSLErrorObject, NULL);
6085 PySSLWantWriteErrorObject = PyErr_NewExceptionWithDoc(
6086 "ssl.SSLWantWriteError", SSLWantWriteError_doc,
6087 PySSLErrorObject, NULL);
6088 PySSLSyscallErrorObject = PyErr_NewExceptionWithDoc(
6089 "ssl.SSLSyscallError", SSLSyscallError_doc,
6090 PySSLErrorObject, NULL);
6091 PySSLEOFErrorObject = PyErr_NewExceptionWithDoc(
6092 "ssl.SSLEOFError", SSLEOFError_doc,
6093 PySSLErrorObject, NULL);
Christian Heimesb3ad0e52017-09-08 12:00:19 -07006094 if (PySSLCertVerificationErrorObject == NULL
6095 || PySSLZeroReturnErrorObject == NULL
Antoine Pitrou41032a62011-10-27 23:56:55 +02006096 || PySSLWantReadErrorObject == NULL
6097 || PySSLWantWriteErrorObject == NULL
6098 || PySSLSyscallErrorObject == NULL
6099 || PySSLEOFErrorObject == NULL)
6100 return NULL;
6101 if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0
Christian Heimesb3ad0e52017-09-08 12:00:19 -07006102 || PyDict_SetItemString(d, "SSLCertVerificationError",
6103 PySSLCertVerificationErrorObject) != 0
Antoine Pitrou41032a62011-10-27 23:56:55 +02006104 || PyDict_SetItemString(d, "SSLZeroReturnError", PySSLZeroReturnErrorObject) != 0
6105 || PyDict_SetItemString(d, "SSLWantReadError", PySSLWantReadErrorObject) != 0
6106 || PyDict_SetItemString(d, "SSLWantWriteError", PySSLWantWriteErrorObject) != 0
6107 || PyDict_SetItemString(d, "SSLSyscallError", PySSLSyscallErrorObject) != 0
6108 || PyDict_SetItemString(d, "SSLEOFError", PySSLEOFErrorObject) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006109 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00006110 if (PyDict_SetItemString(d, "_SSLContext",
6111 (PyObject *)&PySSLContext_Type) != 0)
6112 return NULL;
6113 if (PyDict_SetItemString(d, "_SSLSocket",
6114 (PyObject *)&PySSLSocket_Type) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006115 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02006116 if (PyDict_SetItemString(d, "MemoryBIO",
6117 (PyObject *)&PySSLMemoryBIO_Type) != 0)
6118 return NULL;
Christian Heimes99a65702016-09-10 23:44:53 +02006119 if (PyDict_SetItemString(d, "SSLSession",
6120 (PyObject *)&PySSLSession_Type) != 0)
6121 return NULL;
6122
Christian Heimes892d66e2018-01-29 14:10:18 +01006123 PyModule_AddStringConstant(m, "_DEFAULT_CIPHERS",
6124 PY_SSL_DEFAULT_CIPHER_STRING);
6125
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006126 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
6127 PY_SSL_ERROR_ZERO_RETURN);
6128 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
6129 PY_SSL_ERROR_WANT_READ);
6130 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
6131 PY_SSL_ERROR_WANT_WRITE);
6132 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
6133 PY_SSL_ERROR_WANT_X509_LOOKUP);
6134 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
6135 PY_SSL_ERROR_SYSCALL);
6136 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
6137 PY_SSL_ERROR_SSL);
6138 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
6139 PY_SSL_ERROR_WANT_CONNECT);
6140 /* non ssl.h errorcodes */
6141 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
6142 PY_SSL_ERROR_EOF);
6143 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
6144 PY_SSL_ERROR_INVALID_ERROR_CODE);
6145 /* cert requirements */
6146 PyModule_AddIntConstant(m, "CERT_NONE",
6147 PY_SSL_CERT_NONE);
6148 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
6149 PY_SSL_CERT_OPTIONAL);
6150 PyModule_AddIntConstant(m, "CERT_REQUIRED",
6151 PY_SSL_CERT_REQUIRED);
Christian Heimes22587792013-11-21 23:56:13 +01006152 /* CRL verification for verification_flags */
6153 PyModule_AddIntConstant(m, "VERIFY_DEFAULT",
6154 0);
6155 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_LEAF",
6156 X509_V_FLAG_CRL_CHECK);
6157 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_CHAIN",
6158 X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
6159 PyModule_AddIntConstant(m, "VERIFY_X509_STRICT",
6160 X509_V_FLAG_X509_STRICT);
Benjamin Peterson990fcaa2015-03-04 22:49:41 -05006161#ifdef X509_V_FLAG_TRUSTED_FIRST
6162 PyModule_AddIntConstant(m, "VERIFY_X509_TRUSTED_FIRST",
6163 X509_V_FLAG_TRUSTED_FIRST);
6164#endif
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00006165
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01006166 /* Alert Descriptions from ssl.h */
6167 /* note RESERVED constants no longer intended for use have been removed */
6168 /* http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-6 */
6169
6170#define ADD_AD_CONSTANT(s) \
6171 PyModule_AddIntConstant(m, "ALERT_DESCRIPTION_"#s, \
6172 SSL_AD_##s)
6173
6174 ADD_AD_CONSTANT(CLOSE_NOTIFY);
6175 ADD_AD_CONSTANT(UNEXPECTED_MESSAGE);
6176 ADD_AD_CONSTANT(BAD_RECORD_MAC);
6177 ADD_AD_CONSTANT(RECORD_OVERFLOW);
6178 ADD_AD_CONSTANT(DECOMPRESSION_FAILURE);
6179 ADD_AD_CONSTANT(HANDSHAKE_FAILURE);
6180 ADD_AD_CONSTANT(BAD_CERTIFICATE);
6181 ADD_AD_CONSTANT(UNSUPPORTED_CERTIFICATE);
6182 ADD_AD_CONSTANT(CERTIFICATE_REVOKED);
6183 ADD_AD_CONSTANT(CERTIFICATE_EXPIRED);
6184 ADD_AD_CONSTANT(CERTIFICATE_UNKNOWN);
6185 ADD_AD_CONSTANT(ILLEGAL_PARAMETER);
6186 ADD_AD_CONSTANT(UNKNOWN_CA);
6187 ADD_AD_CONSTANT(ACCESS_DENIED);
6188 ADD_AD_CONSTANT(DECODE_ERROR);
6189 ADD_AD_CONSTANT(DECRYPT_ERROR);
6190 ADD_AD_CONSTANT(PROTOCOL_VERSION);
6191 ADD_AD_CONSTANT(INSUFFICIENT_SECURITY);
6192 ADD_AD_CONSTANT(INTERNAL_ERROR);
6193 ADD_AD_CONSTANT(USER_CANCELLED);
6194 ADD_AD_CONSTANT(NO_RENEGOTIATION);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01006195 /* Not all constants are in old OpenSSL versions */
Antoine Pitrou912fbff2013-03-30 16:29:32 +01006196#ifdef SSL_AD_UNSUPPORTED_EXTENSION
6197 ADD_AD_CONSTANT(UNSUPPORTED_EXTENSION);
6198#endif
6199#ifdef SSL_AD_CERTIFICATE_UNOBTAINABLE
6200 ADD_AD_CONSTANT(CERTIFICATE_UNOBTAINABLE);
6201#endif
6202#ifdef SSL_AD_UNRECOGNIZED_NAME
6203 ADD_AD_CONSTANT(UNRECOGNIZED_NAME);
6204#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01006205#ifdef SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE
6206 ADD_AD_CONSTANT(BAD_CERTIFICATE_STATUS_RESPONSE);
6207#endif
6208#ifdef SSL_AD_BAD_CERTIFICATE_HASH_VALUE
6209 ADD_AD_CONSTANT(BAD_CERTIFICATE_HASH_VALUE);
6210#endif
6211#ifdef SSL_AD_UNKNOWN_PSK_IDENTITY
6212 ADD_AD_CONSTANT(UNKNOWN_PSK_IDENTITY);
6213#endif
6214
6215#undef ADD_AD_CONSTANT
6216
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006217 /* protocol versions */
Victor Stinner3de49192011-05-09 00:42:58 +02006218#ifndef OPENSSL_NO_SSL2
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006219 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
6220 PY_SSL_VERSION_SSL2);
Victor Stinner3de49192011-05-09 00:42:58 +02006221#endif
Benjamin Petersone32467c2014-12-05 21:59:35 -05006222#ifndef OPENSSL_NO_SSL3
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006223 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
6224 PY_SSL_VERSION_SSL3);
Benjamin Petersone32467c2014-12-05 21:59:35 -05006225#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006226 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
Christian Heimes598894f2016-09-05 23:19:05 +02006227 PY_SSL_VERSION_TLS);
6228 PyModule_AddIntConstant(m, "PROTOCOL_TLS",
6229 PY_SSL_VERSION_TLS);
Christian Heimes5fe668c2016-09-12 00:01:11 +02006230 PyModule_AddIntConstant(m, "PROTOCOL_TLS_CLIENT",
6231 PY_SSL_VERSION_TLS_CLIENT);
6232 PyModule_AddIntConstant(m, "PROTOCOL_TLS_SERVER",
6233 PY_SSL_VERSION_TLS_SERVER);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006234 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
6235 PY_SSL_VERSION_TLS1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01006236 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_1",
6237 PY_SSL_VERSION_TLS1_1);
6238 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_2",
6239 PY_SSL_VERSION_TLS1_2);
Antoine Pitrou04f6a322010-04-05 21:40:07 +00006240
Antoine Pitroub5218772010-05-21 09:56:06 +00006241 /* protocol options */
Antoine Pitrou3f366312012-01-27 09:50:45 +01006242 PyModule_AddIntConstant(m, "OP_ALL",
6243 SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
Antoine Pitroub5218772010-05-21 09:56:06 +00006244 PyModule_AddIntConstant(m, "OP_NO_SSLv2", SSL_OP_NO_SSLv2);
6245 PyModule_AddIntConstant(m, "OP_NO_SSLv3", SSL_OP_NO_SSLv3);
6246 PyModule_AddIntConstant(m, "OP_NO_TLSv1", SSL_OP_NO_TLSv1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01006247 PyModule_AddIntConstant(m, "OP_NO_TLSv1_1", SSL_OP_NO_TLSv1_1);
6248 PyModule_AddIntConstant(m, "OP_NO_TLSv1_2", SSL_OP_NO_TLSv1_2);
Christian Heimescb5b68a2017-09-07 18:07:00 -07006249#ifdef SSL_OP_NO_TLSv1_3
6250 PyModule_AddIntConstant(m, "OP_NO_TLSv1_3", SSL_OP_NO_TLSv1_3);
6251#else
6252 PyModule_AddIntConstant(m, "OP_NO_TLSv1_3", 0);
6253#endif
Antoine Pitrou6db49442011-12-19 13:27:11 +01006254 PyModule_AddIntConstant(m, "OP_CIPHER_SERVER_PREFERENCE",
6255 SSL_OP_CIPHER_SERVER_PREFERENCE);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01006256 PyModule_AddIntConstant(m, "OP_SINGLE_DH_USE", SSL_OP_SINGLE_DH_USE);
Christian Heimes99a65702016-09-10 23:44:53 +02006257 PyModule_AddIntConstant(m, "OP_NO_TICKET", SSL_OP_NO_TICKET);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01006258#ifdef SSL_OP_SINGLE_ECDH_USE
Antoine Pitrou923df6f2011-12-19 17:16:51 +01006259 PyModule_AddIntConstant(m, "OP_SINGLE_ECDH_USE", SSL_OP_SINGLE_ECDH_USE);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01006260#endif
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01006261#ifdef SSL_OP_NO_COMPRESSION
6262 PyModule_AddIntConstant(m, "OP_NO_COMPRESSION",
6263 SSL_OP_NO_COMPRESSION);
6264#endif
Christian Heimes05d9fe32018-02-27 08:55:39 +01006265#ifdef SSL_OP_ENABLE_MIDDLEBOX_COMPAT
6266 PyModule_AddIntConstant(m, "OP_ENABLE_MIDDLEBOX_COMPAT",
6267 SSL_OP_ENABLE_MIDDLEBOX_COMPAT);
6268#endif
Christian Heimes67c48012018-05-15 16:25:40 -04006269#ifdef SSL_OP_NO_RENEGOTIATION
6270 PyModule_AddIntConstant(m, "OP_NO_RENEGOTIATION",
6271 SSL_OP_NO_RENEGOTIATION);
6272#endif
Antoine Pitroub5218772010-05-21 09:56:06 +00006273
Christian Heimes61d478c2018-01-27 15:51:38 +01006274#ifdef X509_CHECK_FLAG_ALWAYS_CHECK_SUBJECT
6275 PyModule_AddIntConstant(m, "HOSTFLAG_ALWAYS_CHECK_SUBJECT",
6276 X509_CHECK_FLAG_ALWAYS_CHECK_SUBJECT);
6277#endif
6278#ifdef X509_CHECK_FLAG_NEVER_CHECK_SUBJECT
6279 PyModule_AddIntConstant(m, "HOSTFLAG_NEVER_CHECK_SUBJECT",
6280 X509_CHECK_FLAG_NEVER_CHECK_SUBJECT);
6281#endif
6282#ifdef X509_CHECK_FLAG_NO_WILDCARDS
6283 PyModule_AddIntConstant(m, "HOSTFLAG_NO_WILDCARDS",
6284 X509_CHECK_FLAG_NO_WILDCARDS);
6285#endif
6286#ifdef X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS
6287 PyModule_AddIntConstant(m, "HOSTFLAG_NO_PARTIAL_WILDCARDS",
6288 X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS);
6289#endif
6290#ifdef X509_CHECK_FLAG_MULTI_LABEL_WILDCARDS
6291 PyModule_AddIntConstant(m, "HOSTFLAG_MULTI_LABEL_WILDCARDS",
6292 X509_CHECK_FLAG_MULTI_LABEL_WILDCARDS);
6293#endif
6294#ifdef X509_CHECK_FLAG_SINGLE_LABEL_SUBDOMAINS
6295 PyModule_AddIntConstant(m, "HOSTFLAG_SINGLE_LABEL_SUBDOMAINS",
6296 X509_CHECK_FLAG_SINGLE_LABEL_SUBDOMAINS);
6297#endif
6298
Christian Heimes698dde12018-02-27 11:54:43 +01006299 /* protocol versions */
6300 PyModule_AddIntConstant(m, "PROTO_MINIMUM_SUPPORTED",
6301 PY_PROTO_MINIMUM_SUPPORTED);
6302 PyModule_AddIntConstant(m, "PROTO_MAXIMUM_SUPPORTED",
6303 PY_PROTO_MAXIMUM_SUPPORTED);
6304 PyModule_AddIntConstant(m, "PROTO_SSLv3", PY_PROTO_SSLv3);
6305 PyModule_AddIntConstant(m, "PROTO_TLSv1", PY_PROTO_TLSv1);
6306 PyModule_AddIntConstant(m, "PROTO_TLSv1_1", PY_PROTO_TLSv1_1);
6307 PyModule_AddIntConstant(m, "PROTO_TLSv1_2", PY_PROTO_TLSv1_2);
6308 PyModule_AddIntConstant(m, "PROTO_TLSv1_3", PY_PROTO_TLSv1_3);
Antoine Pitroud5323212010-10-22 18:19:07 +00006309
Victor Stinnerb37672d2018-11-22 03:37:50 +01006310#define addbool(m, key, value) \
6311 do { \
6312 PyObject *bool_obj = (value) ? Py_True : Py_False; \
6313 Py_INCREF(bool_obj); \
6314 PyModule_AddObject((m), (key), bool_obj); \
6315 } while (0)
Christian Heimes698dde12018-02-27 11:54:43 +01006316
6317#if HAVE_SNI
6318 addbool(m, "HAS_SNI", 1);
Antoine Pitrou501da612011-12-21 09:27:41 +01006319#else
Christian Heimes698dde12018-02-27 11:54:43 +01006320 addbool(m, "HAS_SNI", 0);
Antoine Pitrou501da612011-12-21 09:27:41 +01006321#endif
Christian Heimes698dde12018-02-27 11:54:43 +01006322
6323 addbool(m, "HAS_TLS_UNIQUE", 1);
6324
6325#ifndef OPENSSL_NO_ECDH
6326 addbool(m, "HAS_ECDH", 1);
6327#else
6328 addbool(m, "HAS_ECDH", 0);
6329#endif
Antoine Pitrou501da612011-12-21 09:27:41 +01006330
Christian Heimes29eab552018-02-25 12:31:33 +01006331#if HAVE_NPN
Christian Heimes698dde12018-02-27 11:54:43 +01006332 addbool(m, "HAS_NPN", 1);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01006333#else
Christian Heimes698dde12018-02-27 11:54:43 +01006334 addbool(m, "HAS_NPN", 0);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01006335#endif
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01006336
Christian Heimes29eab552018-02-25 12:31:33 +01006337#if HAVE_ALPN
Christian Heimes698dde12018-02-27 11:54:43 +01006338 addbool(m, "HAS_ALPN", 1);
Benjamin Petersoncca27322015-01-23 16:35:37 -05006339#else
Christian Heimes698dde12018-02-27 11:54:43 +01006340 addbool(m, "HAS_ALPN", 0);
Benjamin Petersoncca27322015-01-23 16:35:37 -05006341#endif
Christian Heimes698dde12018-02-27 11:54:43 +01006342
6343#if defined(SSL2_VERSION) && !defined(OPENSSL_NO_SSL2)
6344 addbool(m, "HAS_SSLv2", 1);
6345#else
6346 addbool(m, "HAS_SSLv2", 0);
6347#endif
6348
6349#if defined(SSL3_VERSION) && !defined(OPENSSL_NO_SSL3)
6350 addbool(m, "HAS_SSLv3", 1);
6351#else
6352 addbool(m, "HAS_SSLv3", 0);
6353#endif
6354
6355#if defined(TLS1_VERSION) && !defined(OPENSSL_NO_TLS1)
6356 addbool(m, "HAS_TLSv1", 1);
6357#else
6358 addbool(m, "HAS_TLSv1", 0);
6359#endif
6360
6361#if defined(TLS1_1_VERSION) && !defined(OPENSSL_NO_TLS1_1)
6362 addbool(m, "HAS_TLSv1_1", 1);
6363#else
6364 addbool(m, "HAS_TLSv1_1", 0);
6365#endif
6366
6367#if defined(TLS1_2_VERSION) && !defined(OPENSSL_NO_TLS1_2)
6368 addbool(m, "HAS_TLSv1_2", 1);
6369#else
6370 addbool(m, "HAS_TLSv1_2", 0);
6371#endif
Benjamin Petersoncca27322015-01-23 16:35:37 -05006372
Christian Heimescb5b68a2017-09-07 18:07:00 -07006373#if defined(TLS1_3_VERSION) && !defined(OPENSSL_NO_TLS1_3)
Christian Heimes698dde12018-02-27 11:54:43 +01006374 addbool(m, "HAS_TLSv1_3", 1);
Christian Heimescb5b68a2017-09-07 18:07:00 -07006375#else
Christian Heimes698dde12018-02-27 11:54:43 +01006376 addbool(m, "HAS_TLSv1_3", 0);
Christian Heimescb5b68a2017-09-07 18:07:00 -07006377#endif
Christian Heimescb5b68a2017-09-07 18:07:00 -07006378
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02006379 /* Mappings for error codes */
6380 err_codes_to_names = PyDict_New();
6381 err_names_to_codes = PyDict_New();
6382 if (err_codes_to_names == NULL || err_names_to_codes == NULL)
6383 return NULL;
6384 errcode = error_codes;
6385 while (errcode->mnemonic != NULL) {
6386 PyObject *mnemo, *key;
6387 mnemo = PyUnicode_FromString(errcode->mnemonic);
6388 key = Py_BuildValue("ii", errcode->library, errcode->reason);
6389 if (mnemo == NULL || key == NULL)
6390 return NULL;
6391 if (PyDict_SetItem(err_codes_to_names, key, mnemo))
6392 return NULL;
6393 if (PyDict_SetItem(err_names_to_codes, mnemo, key))
6394 return NULL;
6395 Py_DECREF(key);
6396 Py_DECREF(mnemo);
6397 errcode++;
6398 }
6399 if (PyModule_AddObject(m, "err_codes_to_names", err_codes_to_names))
6400 return NULL;
6401 if (PyModule_AddObject(m, "err_names_to_codes", err_names_to_codes))
6402 return NULL;
6403
6404 lib_codes_to_names = PyDict_New();
6405 if (lib_codes_to_names == NULL)
6406 return NULL;
6407 libcode = library_codes;
6408 while (libcode->library != NULL) {
6409 PyObject *mnemo, *key;
6410 key = PyLong_FromLong(libcode->code);
6411 mnemo = PyUnicode_FromString(libcode->library);
6412 if (key == NULL || mnemo == NULL)
6413 return NULL;
6414 if (PyDict_SetItem(lib_codes_to_names, key, mnemo))
6415 return NULL;
6416 Py_DECREF(key);
6417 Py_DECREF(mnemo);
6418 libcode++;
6419 }
6420 if (PyModule_AddObject(m, "lib_codes_to_names", lib_codes_to_names))
6421 return NULL;
Victor Stinner4569cd52013-06-23 14:58:43 +02006422
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006423 /* OpenSSL version */
6424 /* SSLeay() gives us the version of the library linked against,
6425 which could be different from the headers version.
6426 */
Christian Heimesa871f692020-06-01 08:58:14 +02006427 libver = OpenSSL_version_num();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006428 r = PyLong_FromUnsignedLong(libver);
6429 if (r == NULL)
6430 return NULL;
6431 if (PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r))
6432 return NULL;
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02006433 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006434 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
6435 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r))
6436 return NULL;
Christian Heimesa871f692020-06-01 08:58:14 +02006437 r = PyUnicode_FromString(OpenSSL_version(OPENSSL_VERSION));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006438 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r))
6439 return NULL;
Antoine Pitrou04f6a322010-04-05 21:40:07 +00006440
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02006441 libver = OPENSSL_VERSION_NUMBER;
6442 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
6443 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
6444 if (r == NULL || PyModule_AddObject(m, "_OPENSSL_API_VERSION", r))
6445 return NULL;
6446
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006447 return m;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00006448}