blob: b0e3c0432f51d97c82affd98aacb5bbd6990e590 [file] [log] [blame]
Thomas Woutersed03b412007-08-28 21:37:11 +00001/* SSL socket module
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002
3 SSL support based on patches by Brian E Gallew and Laszlo Kovacs.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004 Re-worked a bit by Bill Janssen to add server-side support and
Bill Janssen6e027db2007-11-15 22:23:56 +00005 certificate decoding. Chris Stawarz contributed some non-blocking
6 patches.
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00007
Thomas Wouters1b7f8912007-09-19 03:06:30 +00008 This module is imported by ssl.py. It should *not* be used
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00009 directly.
10
Thomas Wouters1b7f8912007-09-19 03:06:30 +000011 XXX should partial writes be enabled, SSL_MODE_ENABLE_PARTIAL_WRITE?
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +000012
13 XXX integrate several "shutdown modes" as suggested in
14 http://bugs.python.org/issue8108#msg102867 ?
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000015*/
16
Victor Stinner2e57b4e2014-07-01 16:37:17 +020017#define PY_SSIZE_T_CLEAN
18
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000019#include "Python.h"
Thomas Woutersed03b412007-08-28 21:37:11 +000020
Thomas Wouters1b7f8912007-09-19 03:06:30 +000021#include "pythread.h"
Christian Heimesf77b4b22013-08-21 13:26:05 +020022
Steve Dower68d663c2017-07-17 11:15:48 +020023/* Redefined below for Windows debug builds after important #includes */
24#define _PySSL_FIX_ERRNO
Christian Heimesf77b4b22013-08-21 13:26:05 +020025
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +020026#define PySSL_BEGIN_ALLOW_THREADS_S(save) \
27 do { if (_ssl_locks_count>0) { (save) = PyEval_SaveThread(); } } while (0)
28#define PySSL_END_ALLOW_THREADS_S(save) \
Steve Dower68d663c2017-07-17 11:15:48 +020029 do { if (_ssl_locks_count>0) { PyEval_RestoreThread(save); } _PySSL_FIX_ERRNO; } while (0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +000030#define PySSL_BEGIN_ALLOW_THREADS { \
Antoine Pitroucbb82eb2010-05-05 15:57:33 +000031 PyThreadState *_save = NULL; \
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +020032 PySSL_BEGIN_ALLOW_THREADS_S(_save);
33#define PySSL_BLOCK_THREADS PySSL_END_ALLOW_THREADS_S(_save);
34#define PySSL_UNBLOCK_THREADS PySSL_BEGIN_ALLOW_THREADS_S(_save);
35#define PySSL_END_ALLOW_THREADS PySSL_END_ALLOW_THREADS_S(_save); }
Thomas Wouters1b7f8912007-09-19 03:06:30 +000036
Antoine Pitrou2463e5f2013-03-28 22:24:43 +010037/* Include symbols from _socket module */
38#include "socketmodule.h"
39
40static PySocketModule_APIObject PySocketModule;
41
42#if defined(HAVE_POLL_H)
43#include <poll.h>
44#elif defined(HAVE_SYS_POLL_H)
45#include <sys/poll.h>
46#endif
47
Christian Heimes598894f2016-09-05 23:19:05 +020048/* Don't warn about deprecated functions */
49#ifdef __GNUC__
50#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
51#endif
52#ifdef __clang__
53#pragma clang diagnostic ignored "-Wdeprecated-declarations"
54#endif
55
Antoine Pitrou2463e5f2013-03-28 22:24:43 +010056/* Include OpenSSL header files */
57#include "openssl/rsa.h"
58#include "openssl/crypto.h"
59#include "openssl/x509.h"
60#include "openssl/x509v3.h"
61#include "openssl/pem.h"
62#include "openssl/ssl.h"
63#include "openssl/err.h"
64#include "openssl/rand.h"
Antoine Pitroub1fdf472014-10-05 20:41:53 +020065#include "openssl/bio.h"
Alexandru Ardeleanb3a271f2018-09-17 14:53:31 +030066#include "openssl/dh.h"
Antoine Pitrou2463e5f2013-03-28 22:24:43 +010067
Christian Heimesff5be6e2018-01-20 13:19:21 +010068#ifndef HAVE_X509_VERIFY_PARAM_SET1_HOST
Christian Heimes61d478c2018-01-27 15:51:38 +010069# ifdef LIBRESSL_VERSION_NUMBER
70# error "LibreSSL is missing X509_VERIFY_PARAM_set1_host(), see https://github.com/libressl-portable/portable/issues/381"
71# elif OPENSSL_VERSION_NUMBER > 0x1000200fL
Christian Heimesff5be6e2018-01-20 13:19:21 +010072# define HAVE_X509_VERIFY_PARAM_SET1_HOST
Christian Heimes61d478c2018-01-27 15:51:38 +010073# else
74# error "libssl is too old and does not support X509_VERIFY_PARAM_set1_host()"
Christian Heimesff5be6e2018-01-20 13:19:21 +010075# endif
76#endif
77
Christian Heimes387c7442020-05-15 22:36:51 +020078#ifndef OPENSSL_THREADS
79# error "OPENSSL_THREADS is not defined, Python requires thread-safe OpenSSL"
80#endif
81
Antoine Pitrou2463e5f2013-03-28 22:24:43 +010082/* SSL error object */
83static PyObject *PySSLErrorObject;
Christian Heimesb3ad0e52017-09-08 12:00:19 -070084static PyObject *PySSLCertVerificationErrorObject;
Antoine Pitrou2463e5f2013-03-28 22:24:43 +010085static PyObject *PySSLZeroReturnErrorObject;
86static PyObject *PySSLWantReadErrorObject;
87static PyObject *PySSLWantWriteErrorObject;
88static PyObject *PySSLSyscallErrorObject;
89static PyObject *PySSLEOFErrorObject;
90
91/* Error mappings */
92static PyObject *err_codes_to_names;
93static PyObject *err_names_to_codes;
94static PyObject *lib_codes_to_names;
95
96struct py_ssl_error_code {
97 const char *mnemonic;
98 int library, reason;
99};
100struct py_ssl_library_code {
101 const char *library;
102 int code;
103};
104
Steve Dower68d663c2017-07-17 11:15:48 +0200105#if defined(MS_WINDOWS) && defined(Py_DEBUG)
106/* Debug builds on Windows rely on getting errno directly from OpenSSL.
107 * However, because it uses a different CRT, we need to transfer the
108 * value of errno from OpenSSL into our debug CRT.
109 *
110 * Don't be fooled - this is horribly ugly code. The only reasonable
111 * alternative is to do both debug and release builds of OpenSSL, which
112 * requires much uglier code to transform their automatically generated
113 * makefile. This is the lesser of all the evils.
114 */
115
116static void _PySSLFixErrno(void) {
117 HMODULE ucrtbase = GetModuleHandleW(L"ucrtbase.dll");
118 if (!ucrtbase) {
119 /* If ucrtbase.dll is not loaded but the SSL DLLs are, we likely
120 * have a catastrophic failure, but this function is not the
121 * place to raise it. */
122 return;
123 }
124
125 typedef int *(__stdcall *errno_func)(void);
126 errno_func ssl_errno = (errno_func)GetProcAddress(ucrtbase, "_errno");
127 if (ssl_errno) {
128 errno = *ssl_errno();
129 *ssl_errno() = 0;
130 } else {
131 errno = ENOTRECOVERABLE;
132 }
133}
134
135#undef _PySSL_FIX_ERRNO
136#define _PySSL_FIX_ERRNO _PySSLFixErrno()
137#endif
138
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100139/* Include generated data (error codes) */
140#include "_ssl_data.h"
141
Christian Heimes598894f2016-09-05 23:19:05 +0200142#if (OPENSSL_VERSION_NUMBER >= 0x10100000L) && !defined(LIBRESSL_VERSION_NUMBER)
143# define OPENSSL_VERSION_1_1 1
Christian Heimes4ca07392018-03-24 15:41:37 +0100144# define PY_OPENSSL_1_1_API 1
145#endif
146
147/* LibreSSL 2.7.0 provides necessary OpenSSL 1.1.0 APIs */
148#if defined(LIBRESSL_VERSION_NUMBER) && LIBRESSL_VERSION_NUMBER >= 0x2070000fL
149# define PY_OPENSSL_1_1_API 1
Christian Heimes598894f2016-09-05 23:19:05 +0200150#endif
151
Christian Heimes470fba12013-11-28 15:12:15 +0100152/* SNI support (client- and server-side) appeared in OpenSSL 1.0.0 and 0.9.8f
Antoine Pitrou912fbff2013-03-30 16:29:32 +0100153 * This includes the SSL_set_SSL_CTX() function.
154 */
155#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
156# define HAVE_SNI 1
157#else
158# define HAVE_SNI 0
159#endif
160
Benjamin Petersond3308222015-09-27 00:09:02 -0700161#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
Christian Heimes29eab552018-02-25 12:31:33 +0100162# define HAVE_ALPN 1
163#else
164# define HAVE_ALPN 0
Benjamin Petersoncca27322015-01-23 16:35:37 -0500165#endif
166
Christian Heimes6cdb7952018-02-24 22:12:40 +0100167/* We cannot rely on OPENSSL_NO_NEXTPROTONEG because LibreSSL 2.6.1 dropped
168 * NPN support but did not set OPENSSL_NO_NEXTPROTONEG for compatibility
169 * reasons. The check for TLSEXT_TYPE_next_proto_neg works with
170 * OpenSSL 1.0.1+ and LibreSSL.
Christian Heimes29eab552018-02-25 12:31:33 +0100171 * OpenSSL 1.1.1-pre1 dropped NPN but still has TLSEXT_TYPE_next_proto_neg.
Christian Heimes6cdb7952018-02-24 22:12:40 +0100172 */
173#ifdef OPENSSL_NO_NEXTPROTONEG
Christian Heimes29eab552018-02-25 12:31:33 +0100174# define HAVE_NPN 0
175#elif (OPENSSL_VERSION_NUMBER >= 0x10101000L) && !defined(LIBRESSL_VERSION_NUMBER)
176# define HAVE_NPN 0
Christian Heimes6cdb7952018-02-24 22:12:40 +0100177#elif defined(TLSEXT_TYPE_next_proto_neg)
Christian Heimes29eab552018-02-25 12:31:33 +0100178# define HAVE_NPN 1
Christian Heimes6cdb7952018-02-24 22:12:40 +0100179#else
Christian Heimes29eab552018-02-25 12:31:33 +0100180# define HAVE_NPN 0
181#endif
Christian Heimes6cdb7952018-02-24 22:12:40 +0100182
Christian Heimesc7f70692019-05-31 11:44:05 +0200183#if (OPENSSL_VERSION_NUMBER >= 0x10101000L) && !defined(LIBRESSL_VERSION_NUMBER)
184#define HAVE_OPENSSL_KEYLOG 1
185#endif
186
Victor Stinner524714e2016-07-22 17:43:59 +0200187#ifndef INVALID_SOCKET /* MS defines this */
188#define INVALID_SOCKET (-1)
189#endif
190
Christian Heimes4ca07392018-03-24 15:41:37 +0100191/* OpenSSL 1.0.2 and LibreSSL needs extra code for locking */
192#ifndef OPENSSL_VERSION_1_1
193#define HAVE_OPENSSL_CRYPTO_LOCK
194#endif
195
196#if defined(OPENSSL_VERSION_1_1) && !defined(OPENSSL_NO_SSL2)
Christian Heimes598894f2016-09-05 23:19:05 +0200197#define OPENSSL_NO_SSL2
198#endif
Christian Heimes4ca07392018-03-24 15:41:37 +0100199
200#ifndef PY_OPENSSL_1_1_API
201/* OpenSSL 1.1 API shims for OpenSSL < 1.1.0 and LibreSSL < 2.7.0 */
Christian Heimes598894f2016-09-05 23:19:05 +0200202
203#define TLS_method SSLv23_method
Christian Heimes5fe668c2016-09-12 00:01:11 +0200204#define TLS_client_method SSLv23_client_method
205#define TLS_server_method SSLv23_server_method
Christian Heimes598894f2016-09-05 23:19:05 +0200206
207static int X509_NAME_ENTRY_set(const X509_NAME_ENTRY *ne)
208{
209 return ne->set;
210}
211
212#ifndef OPENSSL_NO_COMP
Christian Heimesa5d07652016-09-24 10:48:05 +0200213/* LCOV_EXCL_START */
Christian Heimes598894f2016-09-05 23:19:05 +0200214static int COMP_get_type(const COMP_METHOD *meth)
215{
216 return meth->type;
217}
Christian Heimes1a63b9f2016-09-24 12:07:21 +0200218/* LCOV_EXCL_STOP */
Christian Heimes598894f2016-09-05 23:19:05 +0200219#endif
220
221static pem_password_cb *SSL_CTX_get_default_passwd_cb(SSL_CTX *ctx)
222{
223 return ctx->default_passwd_callback;
224}
225
226static void *SSL_CTX_get_default_passwd_cb_userdata(SSL_CTX *ctx)
227{
228 return ctx->default_passwd_callback_userdata;
229}
230
231static int X509_OBJECT_get_type(X509_OBJECT *x)
232{
233 return x->type;
234}
235
236static X509 *X509_OBJECT_get0_X509(X509_OBJECT *x)
237{
238 return x->data.x509;
239}
240
241static int BIO_up_ref(BIO *b)
242{
243 CRYPTO_add(&b->references, 1, CRYPTO_LOCK_BIO);
244 return 1;
245}
246
247static STACK_OF(X509_OBJECT) *X509_STORE_get0_objects(X509_STORE *store) {
248 return store->objs;
249}
250
Christian Heimes99a65702016-09-10 23:44:53 +0200251static int
252SSL_SESSION_has_ticket(const SSL_SESSION *s)
253{
254 return (s->tlsext_ticklen > 0) ? 1 : 0;
255}
256
257static unsigned long
258SSL_SESSION_get_ticket_lifetime_hint(const SSL_SESSION *s)
259{
260 return s->tlsext_tick_lifetime_hint;
261}
262
Christian Heimes4ca07392018-03-24 15:41:37 +0100263#endif /* OpenSSL < 1.1.0 or LibreSSL < 2.7.0 */
Christian Heimes598894f2016-09-05 23:19:05 +0200264
Christian Heimes892d66e2018-01-29 14:10:18 +0100265/* Default cipher suites */
266#ifndef PY_SSL_DEFAULT_CIPHERS
267#define PY_SSL_DEFAULT_CIPHERS 1
268#endif
269
270#if PY_SSL_DEFAULT_CIPHERS == 0
271 #ifndef PY_SSL_DEFAULT_CIPHER_STRING
272 #error "Py_SSL_DEFAULT_CIPHERS 0 needs Py_SSL_DEFAULT_CIPHER_STRING"
273 #endif
274#elif PY_SSL_DEFAULT_CIPHERS == 1
Stéphane Wirtel07fbbfd2018-10-05 16:17:18 +0200275/* Python custom selection of sensible cipher suites
Christian Heimes892d66e2018-01-29 14:10:18 +0100276 * DEFAULT: OpenSSL's default cipher list. Since 1.0.2 the list is in sensible order.
277 * !aNULL:!eNULL: really no NULL ciphers
278 * !MD5:!3DES:!DES:!RC4:!IDEA:!SEED: no weak or broken algorithms on old OpenSSL versions.
279 * !aDSS: no authentication with discrete logarithm DSA algorithm
280 * !SRP:!PSK: no secure remote password or pre-shared key authentication
281 */
282 #define PY_SSL_DEFAULT_CIPHER_STRING "DEFAULT:!aNULL:!eNULL:!MD5:!3DES:!DES:!RC4:!IDEA:!SEED:!aDSS:!SRP:!PSK"
283#elif PY_SSL_DEFAULT_CIPHERS == 2
284/* Ignored in SSLContext constructor, only used to as _ssl.DEFAULT_CIPHER_STRING */
285 #define PY_SSL_DEFAULT_CIPHER_STRING SSL_DEFAULT_CIPHER_LIST
286#else
287 #error "Unsupported PY_SSL_DEFAULT_CIPHERS"
288#endif
289
Christian Heimes598894f2016-09-05 23:19:05 +0200290
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000291enum py_ssl_error {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000292 /* these mirror ssl.h */
293 PY_SSL_ERROR_NONE,
294 PY_SSL_ERROR_SSL,
295 PY_SSL_ERROR_WANT_READ,
296 PY_SSL_ERROR_WANT_WRITE,
297 PY_SSL_ERROR_WANT_X509_LOOKUP,
298 PY_SSL_ERROR_SYSCALL, /* look at error stack/return value/errno */
299 PY_SSL_ERROR_ZERO_RETURN,
300 PY_SSL_ERROR_WANT_CONNECT,
301 /* start of non ssl.h errorcodes */
302 PY_SSL_ERROR_EOF, /* special case of SSL_ERROR_SYSCALL */
303 PY_SSL_ERROR_NO_SOCKET, /* socket has been GC'd */
304 PY_SSL_ERROR_INVALID_ERROR_CODE
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000305};
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000306
Thomas Woutersed03b412007-08-28 21:37:11 +0000307enum py_ssl_server_or_client {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000308 PY_SSL_CLIENT,
309 PY_SSL_SERVER
Thomas Woutersed03b412007-08-28 21:37:11 +0000310};
311
312enum py_ssl_cert_requirements {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000313 PY_SSL_CERT_NONE,
314 PY_SSL_CERT_OPTIONAL,
315 PY_SSL_CERT_REQUIRED
Thomas Woutersed03b412007-08-28 21:37:11 +0000316};
317
318enum py_ssl_version {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000319 PY_SSL_VERSION_SSL2,
Victor Stinner3de49192011-05-09 00:42:58 +0200320 PY_SSL_VERSION_SSL3=1,
Christian Heimes5fe668c2016-09-12 00:01:11 +0200321 PY_SSL_VERSION_TLS, /* SSLv23 */
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100322 PY_SSL_VERSION_TLS1,
323 PY_SSL_VERSION_TLS1_1,
Christian Heimes5fe668c2016-09-12 00:01:11 +0200324 PY_SSL_VERSION_TLS1_2,
Christian Heimes5fe668c2016-09-12 00:01:11 +0200325 PY_SSL_VERSION_TLS_CLIENT=0x10,
326 PY_SSL_VERSION_TLS_SERVER,
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100327};
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200328
Christian Heimes698dde12018-02-27 11:54:43 +0100329enum py_proto_version {
330 PY_PROTO_MINIMUM_SUPPORTED = -2,
331 PY_PROTO_SSLv3 = SSL3_VERSION,
332 PY_PROTO_TLSv1 = TLS1_VERSION,
333 PY_PROTO_TLSv1_1 = TLS1_1_VERSION,
334 PY_PROTO_TLSv1_2 = TLS1_2_VERSION,
335#ifdef TLS1_3_VERSION
336 PY_PROTO_TLSv1_3 = TLS1_3_VERSION,
337#else
338 PY_PROTO_TLSv1_3 = 0x304,
339#endif
340 PY_PROTO_MAXIMUM_SUPPORTED = -1,
341
342/* OpenSSL has no dedicated API to set the minimum version to the maximum
343 * available version, and the other way around. We have to figure out the
344 * minimum and maximum available version on our own and hope for the best.
345 */
346#if defined(SSL3_VERSION) && !defined(OPENSSL_NO_SSL3)
347 PY_PROTO_MINIMUM_AVAILABLE = PY_PROTO_SSLv3,
348#elif defined(TLS1_VERSION) && !defined(OPENSSL_NO_TLS1)
349 PY_PROTO_MINIMUM_AVAILABLE = PY_PROTO_TLSv1,
350#elif defined(TLS1_1_VERSION) && !defined(OPENSSL_NO_TLS1_1)
351 PY_PROTO_MINIMUM_AVAILABLE = PY_PROTO_TLSv1_1,
352#elif defined(TLS1_2_VERSION) && !defined(OPENSSL_NO_TLS1_2)
353 PY_PROTO_MINIMUM_AVAILABLE = PY_PROTO_TLSv1_2,
354#elif defined(TLS1_3_VERSION) && !defined(OPENSSL_NO_TLS1_3)
355 PY_PROTO_MINIMUM_AVAILABLE = PY_PROTO_TLSv1_3,
356#else
357 #error "PY_PROTO_MINIMUM_AVAILABLE not found"
358#endif
359
360#if defined(TLS1_3_VERSION) && !defined(OPENSSL_NO_TLS1_3)
361 PY_PROTO_MAXIMUM_AVAILABLE = PY_PROTO_TLSv1_3,
362#elif defined(TLS1_2_VERSION) && !defined(OPENSSL_NO_TLS1_2)
363 PY_PROTO_MAXIMUM_AVAILABLE = PY_PROTO_TLSv1_2,
364#elif defined(TLS1_1_VERSION) && !defined(OPENSSL_NO_TLS1_1)
365 PY_PROTO_MAXIMUM_AVAILABLE = PY_PROTO_TLSv1_1,
366#elif defined(TLS1_VERSION) && !defined(OPENSSL_NO_TLS1)
367 PY_PROTO_MAXIMUM_AVAILABLE = PY_PROTO_TLSv1,
368#elif defined(SSL3_VERSION) && !defined(OPENSSL_NO_SSL3)
369 PY_PROTO_MAXIMUM_AVAILABLE = PY_PROTO_SSLv3,
370#else
371 #error "PY_PROTO_MAXIMUM_AVAILABLE not found"
372#endif
373};
374
375
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000376/* serves as a flag to see whether we've initialized the SSL thread support. */
377/* 0 means no, greater than 0 means yes */
378
379static unsigned int _ssl_locks_count = 0;
380
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000381/* SSL socket object */
382
383#define X509_NAME_MAXLEN 256
384
Gregory P. Smithbd4dacb2010-10-13 03:53:21 +0000385/* SSL_CTX_clear_options() and SSL_clear_options() were first added in
386 * OpenSSL 0.9.8m but do not appear in some 0.9.9-dev versions such the
387 * 0.9.9 from "May 2008" that NetBSD 5.0 uses. */
388#if OPENSSL_VERSION_NUMBER >= 0x009080dfL && OPENSSL_VERSION_NUMBER != 0x00909000L
Antoine Pitroub5218772010-05-21 09:56:06 +0000389# define HAVE_SSL_CTX_CLEAR_OPTIONS
390#else
391# undef HAVE_SSL_CTX_CLEAR_OPTIONS
392#endif
393
Antoine Pitroud6494802011-07-21 01:11:30 +0200394/* In case of 'tls-unique' it will be 12 bytes for TLS, 36 bytes for
395 * older SSL, but let's be safe */
396#define PySSL_CB_MAXLEN 128
397
Antoine Pitroua9bf2ac2012-02-17 18:47:54 +0100398
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000399typedef struct {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000400 PyObject_HEAD
Antoine Pitrou152efa22010-05-16 18:19:27 +0000401 SSL_CTX *ctx;
Christian Heimes29eab552018-02-25 12:31:33 +0100402#if HAVE_NPN
Benjamin Petersoncca27322015-01-23 16:35:37 -0500403 unsigned char *npn_protocols;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100404 int npn_protocols_len;
405#endif
Christian Heimes29eab552018-02-25 12:31:33 +0100406#if HAVE_ALPN
Benjamin Petersoncca27322015-01-23 16:35:37 -0500407 unsigned char *alpn_protocols;
Segev Finer5cff6372017-07-27 01:19:17 +0300408 unsigned int alpn_protocols_len;
Benjamin Petersoncca27322015-01-23 16:35:37 -0500409#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100410#ifndef OPENSSL_NO_TLSEXT
Christian Heimes11a14932018-02-24 02:35:08 +0100411 PyObject *set_sni_cb;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100412#endif
Christian Heimes1aa9a752013-12-02 02:41:19 +0100413 int check_hostname;
Christian Heimes61d478c2018-01-27 15:51:38 +0100414 /* OpenSSL has no API to get hostflags from X509_VERIFY_PARAM* struct.
415 * We have to maintain our own copy. OpenSSL's hostflags default to 0.
416 */
417 unsigned int hostflags;
Christian Heimes11a14932018-02-24 02:35:08 +0100418 int protocol;
Christian Heimes9fb051f2018-09-23 08:32:31 +0200419#ifdef TLS1_3_VERSION
420 int post_handshake_auth;
421#endif
Christian Heimesc7f70692019-05-31 11:44:05 +0200422 PyObject *msg_cb;
423#ifdef HAVE_OPENSSL_KEYLOG
424 PyObject *keylog_filename;
425 BIO *keylog_bio;
426#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +0000427} PySSLContext;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000428
Antoine Pitrou152efa22010-05-16 18:19:27 +0000429typedef struct {
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700430 int ssl; /* last seen error from SSL */
431 int c; /* last seen error from libc */
432#ifdef MS_WINDOWS
433 int ws; /* last seen error from winsock */
434#endif
435} _PySSLError;
436
437typedef struct {
Antoine Pitrou152efa22010-05-16 18:19:27 +0000438 PyObject_HEAD
439 PyObject *Socket; /* weakref to socket on which we're layered */
440 SSL *ssl;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100441 PySSLContext *ctx; /* weakref to SSL context */
Antoine Pitrou20b85552013-09-29 19:50:53 +0200442 char shutdown_seen_zero;
Antoine Pitroud6494802011-07-21 01:11:30 +0200443 enum py_ssl_server_or_client socket_type;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200444 PyObject *owner; /* Python level "owner" passed to servername callback */
445 PyObject *server_hostname;
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700446 _PySSLError err; /* last seen error from various sources */
Christian Heimesc7f70692019-05-31 11:44:05 +0200447 /* Some SSL callbacks don't have error reporting. Callback wrappers
448 * store exception information on the socket. The handshake, read, write,
449 * and shutdown methods check for chained exceptions.
450 */
451 PyObject *exc_type;
452 PyObject *exc_value;
453 PyObject *exc_tb;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000454} PySSLSocket;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000455
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200456typedef struct {
457 PyObject_HEAD
458 BIO *bio;
459 int eof_written;
460} PySSLMemoryBIO;
461
Christian Heimes99a65702016-09-10 23:44:53 +0200462typedef struct {
463 PyObject_HEAD
464 SSL_SESSION *session;
465 PySSLContext *ctx;
466} PySSLSession;
467
Antoine Pitrou152efa22010-05-16 18:19:27 +0000468static PyTypeObject PySSLContext_Type;
469static PyTypeObject PySSLSocket_Type;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200470static PyTypeObject PySSLMemoryBIO_Type;
Christian Heimes99a65702016-09-10 23:44:53 +0200471static PyTypeObject PySSLSession_Type;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000472
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700473static inline _PySSLError _PySSL_errno(int failed, const SSL *ssl, int retcode)
474{
475 _PySSLError err = { 0 };
476 if (failed) {
Steve Dowere6eb48c2017-09-08 15:16:15 -0700477#ifdef MS_WINDOWS
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700478 err.ws = WSAGetLastError();
479 _PySSL_FIX_ERRNO;
Steve Dowere6eb48c2017-09-08 15:16:15 -0700480#endif
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700481 err.c = errno;
482 err.ssl = SSL_get_error(ssl, retcode);
483 }
484 return err;
485}
Steve Dowere6eb48c2017-09-08 15:16:15 -0700486
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +0300487/*[clinic input]
488module _ssl
489class _ssl._SSLContext "PySSLContext *" "&PySSLContext_Type"
490class _ssl._SSLSocket "PySSLSocket *" "&PySSLSocket_Type"
491class _ssl.MemoryBIO "PySSLMemoryBIO *" "&PySSLMemoryBIO_Type"
Christian Heimes99a65702016-09-10 23:44:53 +0200492class _ssl.SSLSession "PySSLSession *" "&PySSLSession_Type"
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +0300493[clinic start generated code]*/
Christian Heimes99a65702016-09-10 23:44:53 +0200494/*[clinic end generated code: output=da39a3ee5e6b4b0d input=bdc67fafeeaa8109]*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +0300495
496#include "clinic/_ssl.c.h"
497
Victor Stinner14690702015-04-06 22:46:13 +0200498static int PySSL_select(PySocketSockObject *s, int writing, _PyTime_t timeout);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000499
Christian Heimes141c5e82018-02-24 21:10:57 +0100500static int PySSL_set_owner(PySSLSocket *, PyObject *, void *);
501static int PySSL_set_session(PySSLSocket *, PyObject *, void *);
Antoine Pitrou152efa22010-05-16 18:19:27 +0000502#define PySSLSocket_Check(v) (Py_TYPE(v) == &PySSLSocket_Type)
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200503#define PySSLMemoryBIO_Check(v) (Py_TYPE(v) == &PySSLMemoryBIO_Type)
Christian Heimes99a65702016-09-10 23:44:53 +0200504#define PySSLSession_Check(v) (Py_TYPE(v) == &PySSLSession_Type)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000505
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000506typedef enum {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000507 SOCKET_IS_NONBLOCKING,
508 SOCKET_IS_BLOCKING,
509 SOCKET_HAS_TIMED_OUT,
510 SOCKET_HAS_BEEN_CLOSED,
511 SOCKET_TOO_LARGE_FOR_SELECT,
512 SOCKET_OPERATION_OK
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000513} timeout_state;
514
Thomas Woutersed03b412007-08-28 21:37:11 +0000515/* Wrap error strings with filename and line # */
Thomas Woutersed03b412007-08-28 21:37:11 +0000516#define ERRSTR1(x,y,z) (x ":" y ": " z)
Victor Stinner45e8e2f2014-05-14 17:24:35 +0200517#define ERRSTR(x) ERRSTR1("_ssl.c", Py_STRINGIFY(__LINE__), x)
Thomas Woutersed03b412007-08-28 21:37:11 +0000518
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200519/* Get the socket from a PySSLSocket, if it has one */
520#define GET_SOCKET(obj) ((obj)->Socket ? \
521 (PySocketSockObject *) PyWeakref_GetObject((obj)->Socket) : NULL)
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200522
Victor Stinner14690702015-04-06 22:46:13 +0200523/* If sock is NULL, use a timeout of 0 second */
524#define GET_SOCKET_TIMEOUT(sock) \
525 ((sock != NULL) ? (sock)->sock_timeout : 0)
526
Christian Heimesc7f70692019-05-31 11:44:05 +0200527#include "_ssl/debughelpers.c"
528
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200529/*
530 * SSL errors.
531 */
532
533PyDoc_STRVAR(SSLError_doc,
534"An error occurred in the SSL implementation.");
535
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700536PyDoc_STRVAR(SSLCertVerificationError_doc,
537"A certificate could not be verified.");
538
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200539PyDoc_STRVAR(SSLZeroReturnError_doc,
540"SSL/TLS session closed cleanly.");
541
542PyDoc_STRVAR(SSLWantReadError_doc,
543"Non-blocking SSL socket needs to read more data\n"
544"before the requested operation can be completed.");
545
546PyDoc_STRVAR(SSLWantWriteError_doc,
547"Non-blocking SSL socket needs to write more data\n"
548"before the requested operation can be completed.");
549
550PyDoc_STRVAR(SSLSyscallError_doc,
551"System error when attempting SSL operation.");
552
553PyDoc_STRVAR(SSLEOFError_doc,
554"SSL/TLS connection terminated abruptly.");
555
556static PyObject *
557SSLError_str(PyOSErrorObject *self)
558{
559 if (self->strerror != NULL && PyUnicode_Check(self->strerror)) {
560 Py_INCREF(self->strerror);
561 return self->strerror;
562 }
563 else
564 return PyObject_Str(self->args);
565}
566
567static PyType_Slot sslerror_type_slots[] = {
568 {Py_tp_base, NULL}, /* Filled out in module init as it's not a constant */
Inada Naoki926b0cb2019-04-17 08:39:46 +0900569 {Py_tp_doc, (void*)SSLError_doc},
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200570 {Py_tp_str, SSLError_str},
571 {0, 0},
572};
573
574static PyType_Spec sslerror_type_spec = {
575 "ssl.SSLError",
576 sizeof(PyOSErrorObject),
577 0,
578 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
579 sslerror_type_slots
580};
581
582static void
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700583fill_and_set_sslerror(PySSLSocket *sslsock, PyObject *type, int ssl_errno,
584 const char *errstr, int lineno, unsigned long errcode)
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200585{
586 PyObject *err_value = NULL, *reason_obj = NULL, *lib_obj = NULL;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700587 PyObject *verify_obj = NULL, *verify_code_obj = NULL;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200588 PyObject *init_value, *msg, *key;
589 _Py_IDENTIFIER(reason);
590 _Py_IDENTIFIER(library);
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700591 _Py_IDENTIFIER(verify_message);
592 _Py_IDENTIFIER(verify_code);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200593
594 if (errcode != 0) {
595 int lib, reason;
596
597 lib = ERR_GET_LIB(errcode);
598 reason = ERR_GET_REASON(errcode);
599 key = Py_BuildValue("ii", lib, reason);
600 if (key == NULL)
601 goto fail;
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +0300602 reason_obj = PyDict_GetItemWithError(err_codes_to_names, key);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200603 Py_DECREF(key);
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +0300604 if (reason_obj == NULL && PyErr_Occurred()) {
605 goto fail;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200606 }
607 key = PyLong_FromLong(lib);
608 if (key == NULL)
609 goto fail;
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +0300610 lib_obj = PyDict_GetItemWithError(lib_codes_to_names, key);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200611 Py_DECREF(key);
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +0300612 if (lib_obj == NULL && PyErr_Occurred()) {
613 goto fail;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200614 }
615 if (errstr == NULL)
616 errstr = ERR_reason_error_string(errcode);
617 }
618 if (errstr == NULL)
619 errstr = "unknown error";
620
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700621 /* verify code for cert validation error */
622 if ((sslsock != NULL) && (type == PySSLCertVerificationErrorObject)) {
623 const char *verify_str = NULL;
624 long verify_code;
625
626 verify_code = SSL_get_verify_result(sslsock->ssl);
627 verify_code_obj = PyLong_FromLong(verify_code);
628 if (verify_code_obj == NULL) {
629 goto fail;
630 }
631
632 switch (verify_code) {
Christian Heimes09153602017-09-08 14:47:58 -0700633#ifdef X509_V_ERR_HOSTNAME_MISMATCH
634 /* OpenSSL >= 1.0.2, LibreSSL >= 2.5.3 */
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700635 case X509_V_ERR_HOSTNAME_MISMATCH:
636 verify_obj = PyUnicode_FromFormat(
637 "Hostname mismatch, certificate is not valid for '%S'.",
638 sslsock->server_hostname
639 );
640 break;
Christian Heimes09153602017-09-08 14:47:58 -0700641#endif
642#ifdef X509_V_ERR_IP_ADDRESS_MISMATCH
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700643 case X509_V_ERR_IP_ADDRESS_MISMATCH:
644 verify_obj = PyUnicode_FromFormat(
645 "IP address mismatch, certificate is not valid for '%S'.",
646 sslsock->server_hostname
647 );
648 break;
Christian Heimes09153602017-09-08 14:47:58 -0700649#endif
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700650 default:
651 verify_str = X509_verify_cert_error_string(verify_code);
652 if (verify_str != NULL) {
653 verify_obj = PyUnicode_FromString(verify_str);
654 } else {
655 verify_obj = Py_None;
656 Py_INCREF(verify_obj);
657 }
658 break;
659 }
660 if (verify_obj == NULL) {
661 goto fail;
662 }
663 }
664
665 if (verify_obj && reason_obj && lib_obj)
666 msg = PyUnicode_FromFormat("[%S: %S] %s: %S (_ssl.c:%d)",
667 lib_obj, reason_obj, errstr, verify_obj,
668 lineno);
669 else if (reason_obj && lib_obj)
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200670 msg = PyUnicode_FromFormat("[%S: %S] %s (_ssl.c:%d)",
671 lib_obj, reason_obj, errstr, lineno);
672 else if (lib_obj)
673 msg = PyUnicode_FromFormat("[%S] %s (_ssl.c:%d)",
674 lib_obj, errstr, lineno);
675 else
676 msg = PyUnicode_FromFormat("%s (_ssl.c:%d)", errstr, lineno);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200677 if (msg == NULL)
678 goto fail;
Victor Stinnerba9be472013-10-31 15:00:24 +0100679
Paul Monsonfb7e7502019-05-15 15:38:55 -0700680 init_value = Py_BuildValue("iN", ERR_GET_REASON(ssl_errno), msg);
Victor Stinnerba9be472013-10-31 15:00:24 +0100681 if (init_value == NULL)
682 goto fail;
683
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200684 err_value = PyObject_CallObject(type, init_value);
685 Py_DECREF(init_value);
686 if (err_value == NULL)
687 goto fail;
Victor Stinnerba9be472013-10-31 15:00:24 +0100688
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200689 if (reason_obj == NULL)
690 reason_obj = Py_None;
691 if (_PyObject_SetAttrId(err_value, &PyId_reason, reason_obj))
692 goto fail;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700693
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200694 if (lib_obj == NULL)
695 lib_obj = Py_None;
696 if (_PyObject_SetAttrId(err_value, &PyId_library, lib_obj))
697 goto fail;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700698
699 if ((sslsock != NULL) && (type == PySSLCertVerificationErrorObject)) {
700 /* Only set verify code / message for SSLCertVerificationError */
701 if (_PyObject_SetAttrId(err_value, &PyId_verify_code,
702 verify_code_obj))
703 goto fail;
704 if (_PyObject_SetAttrId(err_value, &PyId_verify_message, verify_obj))
705 goto fail;
706 }
707
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200708 PyErr_SetObject(type, err_value);
709fail:
710 Py_XDECREF(err_value);
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700711 Py_XDECREF(verify_code_obj);
712 Py_XDECREF(verify_obj);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200713}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000714
Christian Heimesc7f70692019-05-31 11:44:05 +0200715static int
716PySSL_ChainExceptions(PySSLSocket *sslsock) {
717 if (sslsock->exc_type == NULL)
718 return 0;
719
720 _PyErr_ChainExceptions(sslsock->exc_type, sslsock->exc_value, sslsock->exc_tb);
721 sslsock->exc_type = NULL;
722 sslsock->exc_value = NULL;
723 sslsock->exc_tb = NULL;
724 return -1;
725}
726
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000727static PyObject *
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700728PySSL_SetError(PySSLSocket *sslsock, int ret, const char *filename, int lineno)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000729{
Antoine Pitrou41032a62011-10-27 23:56:55 +0200730 PyObject *type = PySSLErrorObject;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200731 char *errstr = NULL;
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700732 _PySSLError err;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000733 enum py_ssl_error p = PY_SSL_ERROR_NONE;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200734 unsigned long e = 0;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000735
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000736 assert(ret <= 0);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200737 e = ERR_peek_last_error();
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000738
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700739 if (sslsock->ssl != NULL) {
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700740 err = sslsock->err;
Thomas Woutersed03b412007-08-28 21:37:11 +0000741
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700742 switch (err.ssl) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000743 case SSL_ERROR_ZERO_RETURN:
Antoine Pitrou41032a62011-10-27 23:56:55 +0200744 errstr = "TLS/SSL connection has been closed (EOF)";
745 type = PySSLZeroReturnErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000746 p = PY_SSL_ERROR_ZERO_RETURN;
747 break;
748 case SSL_ERROR_WANT_READ:
749 errstr = "The operation did not complete (read)";
Antoine Pitrou41032a62011-10-27 23:56:55 +0200750 type = PySSLWantReadErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000751 p = PY_SSL_ERROR_WANT_READ;
752 break;
753 case SSL_ERROR_WANT_WRITE:
754 p = PY_SSL_ERROR_WANT_WRITE;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200755 type = PySSLWantWriteErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000756 errstr = "The operation did not complete (write)";
757 break;
758 case SSL_ERROR_WANT_X509_LOOKUP:
759 p = PY_SSL_ERROR_WANT_X509_LOOKUP;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000760 errstr = "The operation did not complete (X509 lookup)";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000761 break;
762 case SSL_ERROR_WANT_CONNECT:
763 p = PY_SSL_ERROR_WANT_CONNECT;
764 errstr = "The operation did not complete (connect)";
765 break;
766 case SSL_ERROR_SYSCALL:
767 {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000768 if (e == 0) {
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700769 PySocketSockObject *s = GET_SOCKET(sslsock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000770 if (ret == 0 || (((PyObject *)s) == Py_None)) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000771 p = PY_SSL_ERROR_EOF;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200772 type = PySSLEOFErrorObject;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000773 errstr = "EOF occurred in violation of protocol";
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200774 } else if (s && ret == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000775 /* underlying BIO reported an I/O error */
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000776 ERR_clear_error();
Steve Dowere6eb48c2017-09-08 15:16:15 -0700777#ifdef MS_WINDOWS
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700778 if (err.ws) {
779 return PyErr_SetFromWindowsErr(err.ws);
780 }
Steve Dowere6eb48c2017-09-08 15:16:15 -0700781#endif
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700782 if (err.c) {
783 errno = err.c;
Steve Dowere6eb48c2017-09-08 15:16:15 -0700784 return PyErr_SetFromErrno(PyExc_OSError);
785 }
786 Py_INCREF(s);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200787 s->errorhandler();
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000788 Py_DECREF(s);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200789 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000790 } else { /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000791 p = PY_SSL_ERROR_SYSCALL;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200792 type = PySSLSyscallErrorObject;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000793 errstr = "Some I/O error occurred";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000794 }
795 } else {
796 p = PY_SSL_ERROR_SYSCALL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000797 }
798 break;
799 }
800 case SSL_ERROR_SSL:
801 {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000802 p = PY_SSL_ERROR_SSL;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700803 if (e == 0) {
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200804 /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000805 errstr = "A failure in the SSL library occurred";
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700806 }
807 if (ERR_GET_LIB(e) == ERR_LIB_SSL &&
808 ERR_GET_REASON(e) == SSL_R_CERTIFICATE_VERIFY_FAILED) {
809 type = PySSLCertVerificationErrorObject;
810 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000811 break;
812 }
813 default:
814 p = PY_SSL_ERROR_INVALID_ERROR_CODE;
815 errstr = "Invalid error code";
816 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000817 }
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700818 fill_and_set_sslerror(sslsock, type, p, errstr, lineno, e);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000819 ERR_clear_error();
Christian Heimesc7f70692019-05-31 11:44:05 +0200820 PySSL_ChainExceptions(sslsock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000821 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000822}
823
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000824static PyObject *
Serhiy Storchakaef1585e2015-12-25 20:01:53 +0200825_setSSLError (const char *errstr, int errcode, const char *filename, int lineno) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000826
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200827 if (errstr == NULL)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000828 errcode = ERR_peek_last_error();
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200829 else
830 errcode = 0;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700831 fill_and_set_sslerror(NULL, PySSLErrorObject, errcode, errstr, lineno, errcode);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000832 ERR_clear_error();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000833 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000834}
835
Christian Heimes61d478c2018-01-27 15:51:38 +0100836/*
837 * SSL objects
838 */
839
840static int
841_ssl_configure_hostname(PySSLSocket *self, const char* server_hostname)
842{
843 int retval = -1;
844 ASN1_OCTET_STRING *ip;
845 PyObject *hostname;
846 size_t len;
847
848 assert(server_hostname);
849
850 /* Disable OpenSSL's special mode with leading dot in hostname:
851 * When name starts with a dot (e.g ".example.com"), it will be
852 * matched by a certificate valid for any sub-domain of name.
853 */
854 len = strlen(server_hostname);
855 if (len == 0 || *server_hostname == '.') {
856 PyErr_SetString(
857 PyExc_ValueError,
858 "server_hostname cannot be an empty string or start with a "
859 "leading dot.");
860 return retval;
861 }
862
863 /* inet_pton is not available on all platforms. */
864 ip = a2i_IPADDRESS(server_hostname);
865 if (ip == NULL) {
866 ERR_clear_error();
867 }
868
Christian Heimes11a14932018-02-24 02:35:08 +0100869 hostname = PyUnicode_Decode(server_hostname, len, "ascii", "strict");
Christian Heimes61d478c2018-01-27 15:51:38 +0100870 if (hostname == NULL) {
871 goto error;
872 }
873 self->server_hostname = hostname;
874
875 /* Only send SNI extension for non-IP hostnames */
876 if (ip == NULL) {
877 if (!SSL_set_tlsext_host_name(self->ssl, server_hostname)) {
878 _setSSLError(NULL, 0, __FILE__, __LINE__);
879 }
880 }
881 if (self->ctx->check_hostname) {
882 X509_VERIFY_PARAM *param = SSL_get0_param(self->ssl);
883 if (ip == NULL) {
Christian Heimesd02ac252018-03-25 12:36:13 +0200884 if (!X509_VERIFY_PARAM_set1_host(param, server_hostname,
885 strlen(server_hostname))) {
Christian Heimes61d478c2018-01-27 15:51:38 +0100886 _setSSLError(NULL, 0, __FILE__, __LINE__);
887 goto error;
888 }
889 } else {
890 if (!X509_VERIFY_PARAM_set1_ip(param, ASN1_STRING_data(ip),
891 ASN1_STRING_length(ip))) {
892 _setSSLError(NULL, 0, __FILE__, __LINE__);
893 goto error;
894 }
895 }
896 }
897 retval = 0;
898 error:
899 if (ip != NULL) {
900 ASN1_OCTET_STRING_free(ip);
901 }
902 return retval;
903}
904
Antoine Pitrou152efa22010-05-16 18:19:27 +0000905static PySSLSocket *
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100906newPySSLSocket(PySSLContext *sslctx, PySocketSockObject *sock,
Antoine Pitroud5323212010-10-22 18:19:07 +0000907 enum py_ssl_server_or_client socket_type,
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200908 char *server_hostname,
Christian Heimes141c5e82018-02-24 21:10:57 +0100909 PyObject *owner, PyObject *session,
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200910 PySSLMemoryBIO *inbio, PySSLMemoryBIO *outbio)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000911{
Antoine Pitrou152efa22010-05-16 18:19:27 +0000912 PySSLSocket *self;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100913 SSL_CTX *ctx = sslctx->ctx;
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700914 _PySSLError err = { 0 };
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000915
Antoine Pitrou152efa22010-05-16 18:19:27 +0000916 self = PyObject_New(PySSLSocket, &PySSLSocket_Type);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000917 if (self == NULL)
918 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000919
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000920 self->ssl = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000921 self->Socket = NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100922 self->ctx = sslctx;
Nathaniel J. Smith65ece7c2017-06-07 23:30:43 -0700923 Py_INCREF(sslctx);
Antoine Pitrou860aee72013-09-29 19:52:45 +0200924 self->shutdown_seen_zero = 0;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200925 self->owner = NULL;
Benjamin Peterson81b9ecd2016-08-15 21:55:37 -0700926 self->server_hostname = NULL;
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700927 self->err = err;
Christian Heimesc7f70692019-05-31 11:44:05 +0200928 self->exc_type = NULL;
929 self->exc_value = NULL;
930 self->exc_tb = NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200931
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000932 /* Make sure the SSL error state is initialized */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000933 ERR_clear_error();
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000934
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000935 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitrou152efa22010-05-16 18:19:27 +0000936 self->ssl = SSL_new(ctx);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000937 PySSL_END_ALLOW_THREADS
Zackery Spytz4c49da02018-12-07 03:11:30 -0700938 if (self->ssl == NULL) {
939 Py_DECREF(self);
940 _setSSLError(NULL, 0, __FILE__, __LINE__);
941 return NULL;
942 }
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200943 SSL_set_app_data(self->ssl, self);
944 if (sock) {
945 SSL_set_fd(self->ssl, Py_SAFE_DOWNCAST(sock->sock_fd, SOCKET_T, int));
946 } else {
947 /* BIOs are reference counted and SSL_set_bio borrows our reference.
948 * To prevent a double free in memory_bio_dealloc() we need to take an
949 * extra reference here. */
Christian Heimes598894f2016-09-05 23:19:05 +0200950 BIO_up_ref(inbio->bio);
951 BIO_up_ref(outbio->bio);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200952 SSL_set_bio(self->ssl, inbio->bio, outbio->bio);
953 }
Alex Gaynorf0422422018-05-14 11:51:45 -0400954 SSL_set_mode(self->ssl,
955 SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER | SSL_MODE_AUTO_RETRY);
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000956
Christian Heimesf22c4cf2019-07-01 09:25:48 +0200957#ifdef TLS1_3_VERSION
958 if (sslctx->post_handshake_auth == 1) {
959 if (socket_type == PY_SSL_SERVER) {
960 /* bpo-37428: OpenSSL does not ignore SSL_VERIFY_POST_HANDSHAKE.
961 * Set SSL_VERIFY_POST_HANDSHAKE flag only for server sockets and
962 * only in combination with SSL_VERIFY_PEER flag. */
963 int mode = SSL_get_verify_mode(self->ssl);
964 if (mode & SSL_VERIFY_PEER) {
965 int (*verify_cb)(int, X509_STORE_CTX *) = NULL;
966 verify_cb = SSL_get_verify_callback(self->ssl);
967 mode |= SSL_VERIFY_POST_HANDSHAKE;
968 SSL_set_verify(self->ssl, mode, verify_cb);
969 }
970 } else {
971 /* client socket */
972 SSL_set_post_handshake_auth(self->ssl, 1);
973 }
974 }
975#endif
976
Christian Heimes61d478c2018-01-27 15:51:38 +0100977 if (server_hostname != NULL) {
978 if (_ssl_configure_hostname(self, server_hostname) < 0) {
979 Py_DECREF(self);
980 return NULL;
981 }
982 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000983 /* If the socket is in non-blocking mode or timeout mode, set the BIO
984 * to non-blocking mode (blocking is the default)
985 */
Victor Stinnere2452312015-03-28 03:00:46 +0100986 if (sock && sock->sock_timeout >= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000987 BIO_set_nbio(SSL_get_rbio(self->ssl), 1);
988 BIO_set_nbio(SSL_get_wbio(self->ssl), 1);
989 }
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000990
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000991 PySSL_BEGIN_ALLOW_THREADS
992 if (socket_type == PY_SSL_CLIENT)
993 SSL_set_connect_state(self->ssl);
994 else
995 SSL_set_accept_state(self->ssl);
996 PySSL_END_ALLOW_THREADS
Martin v. Löwis09c35f72002-07-28 09:57:45 +0000997
Antoine Pitroud6494802011-07-21 01:11:30 +0200998 self->socket_type = socket_type;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200999 if (sock != NULL) {
1000 self->Socket = PyWeakref_NewRef((PyObject *) sock, NULL);
1001 if (self->Socket == NULL) {
1002 Py_DECREF(self);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001003 return NULL;
1004 }
Victor Stinnera9eb38f2013-10-31 16:35:38 +01001005 }
Christian Heimes141c5e82018-02-24 21:10:57 +01001006 if (owner && owner != Py_None) {
1007 if (PySSL_set_owner(self, owner, NULL) == -1) {
1008 Py_DECREF(self);
1009 return NULL;
1010 }
1011 }
1012 if (session && session != Py_None) {
1013 if (PySSL_set_session(self, session, NULL) == -1) {
1014 Py_DECREF(self);
1015 return NULL;
1016 }
1017 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001018 return self;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001019}
1020
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001021/* SSL object methods */
1022
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001023/*[clinic input]
1024_ssl._SSLSocket.do_handshake
1025[clinic start generated code]*/
1026
1027static PyObject *
1028_ssl__SSLSocket_do_handshake_impl(PySSLSocket *self)
1029/*[clinic end generated code: output=6c0898a8936548f6 input=d2d737de3df018c8]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001030{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001031 int ret;
Steve Dowerc6fd1c12018-09-17 11:34:47 -07001032 _PySSLError err;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001033 int sockstate, nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001034 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02001035 _PyTime_t timeout, deadline = 0;
1036 int has_timeout;
Antoine Pitroud3f8ab82010-04-24 21:26:44 +00001037
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001038 if (sock) {
1039 if (((PyObject*)sock) == Py_None) {
1040 _setSSLError("Underlying socket connection gone",
1041 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1042 return NULL;
1043 }
1044 Py_INCREF(sock);
1045
1046 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01001047 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001048 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1049 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001050 }
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001051
Victor Stinner14690702015-04-06 22:46:13 +02001052 timeout = GET_SOCKET_TIMEOUT(sock);
1053 has_timeout = (timeout > 0);
1054 if (has_timeout)
1055 deadline = _PyTime_GetMonotonicClock() + timeout;
1056
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001057 /* Actually negotiate SSL connection */
1058 /* XXX If SSL_do_handshake() returns 0, it's also a failure. */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001059 do {
Bill Janssen6e027db2007-11-15 22:23:56 +00001060 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001061 ret = SSL_do_handshake(self->ssl);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07001062 err = _PySSL_errno(ret < 1, self->ssl, ret);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001063 PySSL_END_ALLOW_THREADS
Steve Dowerc6fd1c12018-09-17 11:34:47 -07001064 self->err = err;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001065
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001066 if (PyErr_CheckSignals())
1067 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001068
Victor Stinner14690702015-04-06 22:46:13 +02001069 if (has_timeout)
1070 timeout = deadline - _PyTime_GetMonotonicClock();
1071
Steve Dowerc6fd1c12018-09-17 11:34:47 -07001072 if (err.ssl == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +02001073 sockstate = PySSL_select(sock, 0, timeout);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07001074 } else if (err.ssl == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +02001075 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001076 } else {
1077 sockstate = SOCKET_OPERATION_OK;
1078 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001079
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001080 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001081 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitrou525807b2010-05-12 14:05:24 +00001082 ERRSTR("The handshake operation timed out"));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001083 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001084 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1085 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +00001086 ERRSTR("Underlying socket has been closed."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001087 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001088 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1089 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +00001090 ERRSTR("Underlying socket too large for select()."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001091 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001092 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1093 break;
1094 }
Steve Dowerc6fd1c12018-09-17 11:34:47 -07001095 } while (err.ssl == SSL_ERROR_WANT_READ ||
1096 err.ssl == SSL_ERROR_WANT_WRITE);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001097 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001098 if (ret < 1)
1099 return PySSL_SetError(self, ret, __FILE__, __LINE__);
Christian Heimesc7f70692019-05-31 11:44:05 +02001100 if (PySSL_ChainExceptions(self) < 0)
1101 return NULL;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001102 Py_RETURN_NONE;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001103error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001104 Py_XDECREF(sock);
Christian Heimesc7f70692019-05-31 11:44:05 +02001105 PySSL_ChainExceptions(self);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001106 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001107}
1108
Thomas Woutersed03b412007-08-28 21:37:11 +00001109static PyObject *
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001110_asn1obj2py(const ASN1_OBJECT *name, int no_name)
1111{
1112 char buf[X509_NAME_MAXLEN];
1113 char *namebuf = buf;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001114 int buflen;
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001115 PyObject *name_obj = NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001116
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001117 buflen = OBJ_obj2txt(namebuf, X509_NAME_MAXLEN, name, no_name);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001118 if (buflen < 0) {
1119 _setSSLError(NULL, 0, __FILE__, __LINE__);
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001120 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001121 }
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001122 /* initial buffer is too small for oid + terminating null byte */
1123 if (buflen > X509_NAME_MAXLEN - 1) {
1124 /* make OBJ_obj2txt() calculate the required buflen */
1125 buflen = OBJ_obj2txt(NULL, 0, name, no_name);
1126 /* allocate len + 1 for terminating NULL byte */
1127 namebuf = PyMem_Malloc(buflen + 1);
1128 if (namebuf == NULL) {
1129 PyErr_NoMemory();
1130 return NULL;
1131 }
1132 buflen = OBJ_obj2txt(namebuf, buflen + 1, name, no_name);
1133 if (buflen < 0) {
1134 _setSSLError(NULL, 0, __FILE__, __LINE__);
1135 goto done;
1136 }
1137 }
1138 if (!buflen && no_name) {
1139 Py_INCREF(Py_None);
1140 name_obj = Py_None;
1141 }
1142 else {
1143 name_obj = PyUnicode_FromStringAndSize(namebuf, buflen);
1144 }
1145
1146 done:
1147 if (buf != namebuf) {
1148 PyMem_Free(namebuf);
1149 }
1150 return name_obj;
1151}
1152
1153static PyObject *
1154_create_tuple_for_attribute(ASN1_OBJECT *name, ASN1_STRING *value)
1155{
1156 Py_ssize_t buflen;
1157 unsigned char *valuebuf = NULL;
1158 PyObject *attr;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001159
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001160 buflen = ASN1_STRING_to_UTF8(&valuebuf, value);
1161 if (buflen < 0) {
1162 _setSSLError(NULL, 0, __FILE__, __LINE__);
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001163 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001164 }
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001165 attr = Py_BuildValue("Ns#", _asn1obj2py(name, 0), valuebuf, buflen);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001166 OPENSSL_free(valuebuf);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001167 return attr;
Thomas Woutersed03b412007-08-28 21:37:11 +00001168}
1169
1170static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001171_create_tuple_for_X509_NAME (X509_NAME *xname)
Thomas Woutersed03b412007-08-28 21:37:11 +00001172{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001173 PyObject *dn = NULL; /* tuple which represents the "distinguished name" */
1174 PyObject *rdn = NULL; /* tuple to hold a "relative distinguished name" */
1175 PyObject *rdnt;
1176 PyObject *attr = NULL; /* tuple to hold an attribute */
1177 int entry_count = X509_NAME_entry_count(xname);
1178 X509_NAME_ENTRY *entry;
1179 ASN1_OBJECT *name;
1180 ASN1_STRING *value;
1181 int index_counter;
1182 int rdn_level = -1;
1183 int retcode;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001184
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001185 dn = PyList_New(0);
1186 if (dn == NULL)
1187 return NULL;
1188 /* now create another tuple to hold the top-level RDN */
1189 rdn = PyList_New(0);
1190 if (rdn == NULL)
1191 goto fail0;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001192
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001193 for (index_counter = 0;
1194 index_counter < entry_count;
1195 index_counter++)
1196 {
1197 entry = X509_NAME_get_entry(xname, index_counter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001198
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001199 /* check to see if we've gotten to a new RDN */
1200 if (rdn_level >= 0) {
Christian Heimes598894f2016-09-05 23:19:05 +02001201 if (rdn_level != X509_NAME_ENTRY_set(entry)) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001202 /* yes, new RDN */
1203 /* add old RDN to DN */
1204 rdnt = PyList_AsTuple(rdn);
1205 Py_DECREF(rdn);
1206 if (rdnt == NULL)
1207 goto fail0;
1208 retcode = PyList_Append(dn, rdnt);
1209 Py_DECREF(rdnt);
1210 if (retcode < 0)
1211 goto fail0;
1212 /* create new RDN */
1213 rdn = PyList_New(0);
1214 if (rdn == NULL)
1215 goto fail0;
1216 }
1217 }
Christian Heimes598894f2016-09-05 23:19:05 +02001218 rdn_level = X509_NAME_ENTRY_set(entry);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001219
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001220 /* now add this attribute to the current RDN */
1221 name = X509_NAME_ENTRY_get_object(entry);
1222 value = X509_NAME_ENTRY_get_data(entry);
1223 attr = _create_tuple_for_attribute(name, value);
1224 /*
1225 fprintf(stderr, "RDN level %d, attribute %s: %s\n",
1226 entry->set,
1227 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 0)),
1228 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 1)));
1229 */
1230 if (attr == NULL)
1231 goto fail1;
1232 retcode = PyList_Append(rdn, attr);
1233 Py_DECREF(attr);
1234 if (retcode < 0)
1235 goto fail1;
1236 }
1237 /* now, there's typically a dangling RDN */
Antoine Pitrou2f5a1632012-02-15 22:25:27 +01001238 if (rdn != NULL) {
1239 if (PyList_GET_SIZE(rdn) > 0) {
1240 rdnt = PyList_AsTuple(rdn);
1241 Py_DECREF(rdn);
1242 if (rdnt == NULL)
1243 goto fail0;
1244 retcode = PyList_Append(dn, rdnt);
1245 Py_DECREF(rdnt);
1246 if (retcode < 0)
1247 goto fail0;
1248 }
1249 else {
1250 Py_DECREF(rdn);
1251 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001252 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001253
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001254 /* convert list to tuple */
1255 rdnt = PyList_AsTuple(dn);
1256 Py_DECREF(dn);
1257 if (rdnt == NULL)
1258 return NULL;
1259 return rdnt;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001260
1261 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001262 Py_XDECREF(rdn);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001263
1264 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001265 Py_XDECREF(dn);
1266 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001267}
1268
1269static PyObject *
1270_get_peer_alt_names (X509 *certificate) {
Guido van Rossumf06628b2007-11-21 20:01:53 +00001271
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001272 /* this code follows the procedure outlined in
1273 OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print()
1274 function to extract the STACK_OF(GENERAL_NAME),
1275 then iterates through the stack to add the
1276 names. */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001277
Alex Gaynorb87c0df2017-06-06 07:53:11 -04001278 int j;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001279 PyObject *peer_alt_names = Py_None;
Christian Heimes60bf2fc2013-09-05 16:04:35 +02001280 PyObject *v = NULL, *t;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001281 GENERAL_NAMES *names = NULL;
1282 GENERAL_NAME *name;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001283 BIO *biobuf = NULL;
1284 char buf[2048];
1285 char *vptr;
1286 int len;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001287
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001288 if (certificate == NULL)
1289 return peer_alt_names;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001290
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001291 /* get a memory buffer */
1292 biobuf = BIO_new(BIO_s_mem());
Zackery Spytz4c49da02018-12-07 03:11:30 -07001293 if (biobuf == NULL) {
1294 PyErr_SetString(PySSLErrorObject, "failed to allocate BIO");
1295 return NULL;
1296 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001297
Alex Gaynorb87c0df2017-06-06 07:53:11 -04001298 names = (GENERAL_NAMES *)X509_get_ext_d2i(
1299 certificate, NID_subject_alt_name, NULL, NULL);
1300 if (names != NULL) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001301 if (peer_alt_names == Py_None) {
1302 peer_alt_names = PyList_New(0);
1303 if (peer_alt_names == NULL)
1304 goto fail;
1305 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001306
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001307 for(j = 0; j < sk_GENERAL_NAME_num(names); j++) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001308 /* get a rendering of each name in the set of names */
Christian Heimes824f7f32013-08-17 00:54:47 +02001309 int gntype;
1310 ASN1_STRING *as = NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001311
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001312 name = sk_GENERAL_NAME_value(names, j);
Christian Heimes474afdd2013-08-17 17:18:56 +02001313 gntype = name->type;
Christian Heimes824f7f32013-08-17 00:54:47 +02001314 switch (gntype) {
1315 case GEN_DIRNAME:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001316 /* we special-case DirName as a tuple of
1317 tuples of attributes */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001318
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001319 t = PyTuple_New(2);
1320 if (t == NULL) {
1321 goto fail;
1322 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001323
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001324 v = PyUnicode_FromString("DirName");
1325 if (v == NULL) {
1326 Py_DECREF(t);
1327 goto fail;
1328 }
1329 PyTuple_SET_ITEM(t, 0, v);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001330
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001331 v = _create_tuple_for_X509_NAME (name->d.dirn);
1332 if (v == NULL) {
1333 Py_DECREF(t);
1334 goto fail;
1335 }
1336 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +02001337 break;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001338
Christian Heimes824f7f32013-08-17 00:54:47 +02001339 case GEN_EMAIL:
1340 case GEN_DNS:
1341 case GEN_URI:
1342 /* GENERAL_NAME_print() doesn't handle NULL bytes in ASN1_string
1343 correctly, CVE-2013-4238 */
1344 t = PyTuple_New(2);
1345 if (t == NULL)
1346 goto fail;
1347 switch (gntype) {
1348 case GEN_EMAIL:
1349 v = PyUnicode_FromString("email");
1350 as = name->d.rfc822Name;
1351 break;
1352 case GEN_DNS:
1353 v = PyUnicode_FromString("DNS");
1354 as = name->d.dNSName;
1355 break;
1356 case GEN_URI:
1357 v = PyUnicode_FromString("URI");
1358 as = name->d.uniformResourceIdentifier;
1359 break;
1360 }
1361 if (v == NULL) {
1362 Py_DECREF(t);
1363 goto fail;
1364 }
1365 PyTuple_SET_ITEM(t, 0, v);
1366 v = PyUnicode_FromStringAndSize((char *)ASN1_STRING_data(as),
1367 ASN1_STRING_length(as));
1368 if (v == NULL) {
1369 Py_DECREF(t);
1370 goto fail;
1371 }
1372 PyTuple_SET_ITEM(t, 1, v);
1373 break;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001374
Christian Heimes1c03abd2016-09-06 23:25:35 +02001375 case GEN_RID:
1376 t = PyTuple_New(2);
1377 if (t == NULL)
1378 goto fail;
1379
1380 v = PyUnicode_FromString("Registered ID");
1381 if (v == NULL) {
1382 Py_DECREF(t);
1383 goto fail;
1384 }
1385 PyTuple_SET_ITEM(t, 0, v);
1386
1387 len = i2t_ASN1_OBJECT(buf, sizeof(buf)-1, name->d.rid);
1388 if (len < 0) {
1389 Py_DECREF(t);
1390 _setSSLError(NULL, 0, __FILE__, __LINE__);
1391 goto fail;
1392 } else if (len >= (int)sizeof(buf)) {
1393 v = PyUnicode_FromString("<INVALID>");
1394 } else {
1395 v = PyUnicode_FromStringAndSize(buf, len);
1396 }
1397 if (v == NULL) {
1398 Py_DECREF(t);
1399 goto fail;
1400 }
1401 PyTuple_SET_ITEM(t, 1, v);
1402 break;
1403
Miss Islington (bot)9d3cacd2019-12-07 09:20:27 -08001404 case GEN_IPADD:
1405 /* OpenSSL < 3.0.0 adds a trailing \n to IPv6. 3.0.0 removed
1406 * the trailing newline. Remove it in all versions
1407 */
1408 t = PyTuple_New(2);
1409 if (t == NULL)
1410 goto fail;
1411
1412 v = PyUnicode_FromString("IP Address");
1413 if (v == NULL) {
1414 Py_DECREF(t);
1415 goto fail;
1416 }
1417 PyTuple_SET_ITEM(t, 0, v);
1418
1419 if (name->d.ip->length == 4) {
1420 unsigned char *p = name->d.ip->data;
1421 v = PyUnicode_FromFormat(
1422 "%d.%d.%d.%d",
1423 p[0], p[1], p[2], p[3]
1424 );
1425 } else if (name->d.ip->length == 16) {
1426 /* PyUnicode_FromFormat() does not support %X */
1427 unsigned char *p = name->d.ip->data;
1428 len = sprintf(
1429 buf,
1430 "%X:%X:%X:%X:%X:%X:%X:%X",
1431 p[0] << 8 | p[1],
1432 p[2] << 8 | p[3],
1433 p[4] << 8 | p[5],
1434 p[6] << 8 | p[7],
1435 p[8] << 8 | p[9],
1436 p[10] << 8 | p[11],
1437 p[12] << 8 | p[13],
1438 p[14] << 8 | p[15]
1439 );
1440 v = PyUnicode_FromStringAndSize(buf, len);
1441 } else {
1442 v = PyUnicode_FromString("<invalid>");
1443 }
1444
1445 if (v == NULL) {
1446 Py_DECREF(t);
1447 goto fail;
1448 }
1449 PyTuple_SET_ITEM(t, 1, v);
1450 break;
1451
Christian Heimes824f7f32013-08-17 00:54:47 +02001452 default:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001453 /* for everything else, we use the OpenSSL print form */
Christian Heimes824f7f32013-08-17 00:54:47 +02001454 switch (gntype) {
1455 /* check for new general name type */
1456 case GEN_OTHERNAME:
1457 case GEN_X400:
1458 case GEN_EDIPARTY:
Christian Heimes824f7f32013-08-17 00:54:47 +02001459 case GEN_RID:
1460 break;
1461 default:
1462 if (PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
1463 "Unknown general name type %d",
1464 gntype) == -1) {
1465 goto fail;
1466 }
1467 break;
1468 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001469 (void) BIO_reset(biobuf);
1470 GENERAL_NAME_print(biobuf, name);
1471 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1472 if (len < 0) {
1473 _setSSLError(NULL, 0, __FILE__, __LINE__);
1474 goto fail;
1475 }
1476 vptr = strchr(buf, ':');
Christian Heimes1c03abd2016-09-06 23:25:35 +02001477 if (vptr == NULL) {
1478 PyErr_Format(PyExc_ValueError,
1479 "Invalid value %.200s",
1480 buf);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001481 goto fail;
Christian Heimes1c03abd2016-09-06 23:25:35 +02001482 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001483 t = PyTuple_New(2);
1484 if (t == NULL)
1485 goto fail;
1486 v = PyUnicode_FromStringAndSize(buf, (vptr - buf));
1487 if (v == NULL) {
1488 Py_DECREF(t);
1489 goto fail;
1490 }
1491 PyTuple_SET_ITEM(t, 0, v);
1492 v = PyUnicode_FromStringAndSize((vptr + 1),
1493 (len - (vptr - buf + 1)));
1494 if (v == NULL) {
1495 Py_DECREF(t);
1496 goto fail;
1497 }
1498 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +02001499 break;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001500 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001501
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001502 /* and add that rendering to the list */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001503
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001504 if (PyList_Append(peer_alt_names, t) < 0) {
1505 Py_DECREF(t);
1506 goto fail;
1507 }
1508 Py_DECREF(t);
1509 }
Antoine Pitrou116d6b92011-11-23 01:39:19 +01001510 sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001511 }
1512 BIO_free(biobuf);
1513 if (peer_alt_names != Py_None) {
1514 v = PyList_AsTuple(peer_alt_names);
1515 Py_DECREF(peer_alt_names);
1516 return v;
1517 } else {
1518 return peer_alt_names;
1519 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001520
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001521
1522 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001523 if (biobuf != NULL)
1524 BIO_free(biobuf);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001525
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001526 if (peer_alt_names != Py_None) {
1527 Py_XDECREF(peer_alt_names);
1528 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001529
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001530 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001531}
1532
1533static PyObject *
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001534_get_aia_uri(X509 *certificate, int nid) {
1535 PyObject *lst = NULL, *ostr = NULL;
1536 int i, result;
1537 AUTHORITY_INFO_ACCESS *info;
1538
1539 info = X509_get_ext_d2i(certificate, NID_info_access, NULL, NULL);
Benjamin Petersonf0c90382015-11-14 15:12:18 -08001540 if (info == NULL)
1541 return Py_None;
1542 if (sk_ACCESS_DESCRIPTION_num(info) == 0) {
1543 AUTHORITY_INFO_ACCESS_free(info);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001544 return Py_None;
1545 }
1546
1547 if ((lst = PyList_New(0)) == NULL) {
1548 goto fail;
1549 }
1550
1551 for (i = 0; i < sk_ACCESS_DESCRIPTION_num(info); i++) {
1552 ACCESS_DESCRIPTION *ad = sk_ACCESS_DESCRIPTION_value(info, i);
1553 ASN1_IA5STRING *uri;
1554
1555 if ((OBJ_obj2nid(ad->method) != nid) ||
1556 (ad->location->type != GEN_URI)) {
1557 continue;
1558 }
1559 uri = ad->location->d.uniformResourceIdentifier;
1560 ostr = PyUnicode_FromStringAndSize((char *)uri->data,
1561 uri->length);
1562 if (ostr == NULL) {
1563 goto fail;
1564 }
1565 result = PyList_Append(lst, ostr);
1566 Py_DECREF(ostr);
1567 if (result < 0) {
1568 goto fail;
1569 }
1570 }
1571 AUTHORITY_INFO_ACCESS_free(info);
1572
1573 /* convert to tuple or None */
1574 if (PyList_Size(lst) == 0) {
1575 Py_DECREF(lst);
1576 return Py_None;
1577 } else {
1578 PyObject *tup;
1579 tup = PyList_AsTuple(lst);
1580 Py_DECREF(lst);
1581 return tup;
1582 }
1583
1584 fail:
1585 AUTHORITY_INFO_ACCESS_free(info);
Christian Heimes18fc7be2013-11-21 23:57:49 +01001586 Py_XDECREF(lst);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001587 return NULL;
1588}
1589
1590static PyObject *
1591_get_crl_dp(X509 *certificate) {
1592 STACK_OF(DIST_POINT) *dps;
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001593 int i, j;
1594 PyObject *lst, *res = NULL;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001595
Christian Heimes598894f2016-09-05 23:19:05 +02001596 dps = X509_get_ext_d2i(certificate, NID_crl_distribution_points, NULL, NULL);
Christian Heimes949ec142013-11-21 16:26:51 +01001597
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001598 if (dps == NULL)
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001599 return Py_None;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001600
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001601 lst = PyList_New(0);
1602 if (lst == NULL)
1603 goto done;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001604
1605 for (i=0; i < sk_DIST_POINT_num(dps); i++) {
1606 DIST_POINT *dp;
1607 STACK_OF(GENERAL_NAME) *gns;
1608
1609 dp = sk_DIST_POINT_value(dps, i);
Christian Heimesa37f5242019-01-15 23:47:42 +01001610 if (dp->distpoint == NULL) {
1611 /* Ignore empty DP value, CVE-2019-5010 */
1612 continue;
1613 }
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001614 gns = dp->distpoint->name.fullname;
1615
1616 for (j=0; j < sk_GENERAL_NAME_num(gns); j++) {
1617 GENERAL_NAME *gn;
1618 ASN1_IA5STRING *uri;
1619 PyObject *ouri;
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001620 int err;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001621
1622 gn = sk_GENERAL_NAME_value(gns, j);
1623 if (gn->type != GEN_URI) {
1624 continue;
1625 }
1626 uri = gn->d.uniformResourceIdentifier;
1627 ouri = PyUnicode_FromStringAndSize((char *)uri->data,
1628 uri->length);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001629 if (ouri == NULL)
1630 goto done;
1631
1632 err = PyList_Append(lst, ouri);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001633 Py_DECREF(ouri);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001634 if (err < 0)
1635 goto done;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001636 }
1637 }
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001638
1639 /* Convert to tuple. */
1640 res = (PyList_GET_SIZE(lst) > 0) ? PyList_AsTuple(lst) : Py_None;
1641
1642 done:
1643 Py_XDECREF(lst);
Olivier Vielpeau2849cc32017-04-14 21:06:07 -04001644 CRL_DIST_POINTS_free(dps);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001645 return res;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001646}
1647
1648static PyObject *
Antoine Pitroufb046912010-11-09 20:21:19 +00001649_decode_certificate(X509 *certificate) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001650
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001651 PyObject *retval = NULL;
1652 BIO *biobuf = NULL;
1653 PyObject *peer;
1654 PyObject *peer_alt_names = NULL;
1655 PyObject *issuer;
1656 PyObject *version;
1657 PyObject *sn_obj;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001658 PyObject *obj;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001659 ASN1_INTEGER *serialNumber;
1660 char buf[2048];
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001661 int len, result;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001662 ASN1_TIME *notBefore, *notAfter;
1663 PyObject *pnotBefore, *pnotAfter;
Thomas Woutersed03b412007-08-28 21:37:11 +00001664
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001665 retval = PyDict_New();
1666 if (retval == NULL)
1667 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001668
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001669 peer = _create_tuple_for_X509_NAME(
1670 X509_get_subject_name(certificate));
1671 if (peer == NULL)
1672 goto fail0;
1673 if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) {
1674 Py_DECREF(peer);
1675 goto fail0;
1676 }
1677 Py_DECREF(peer);
Thomas Woutersed03b412007-08-28 21:37:11 +00001678
Antoine Pitroufb046912010-11-09 20:21:19 +00001679 issuer = _create_tuple_for_X509_NAME(
1680 X509_get_issuer_name(certificate));
1681 if (issuer == NULL)
1682 goto fail0;
1683 if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001684 Py_DECREF(issuer);
Antoine Pitroufb046912010-11-09 20:21:19 +00001685 goto fail0;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001686 }
Antoine Pitroufb046912010-11-09 20:21:19 +00001687 Py_DECREF(issuer);
1688
1689 version = PyLong_FromLong(X509_get_version(certificate) + 1);
Christian Heimes5962bef2013-07-26 15:51:18 +02001690 if (version == NULL)
1691 goto fail0;
Antoine Pitroufb046912010-11-09 20:21:19 +00001692 if (PyDict_SetItemString(retval, "version", version) < 0) {
1693 Py_DECREF(version);
1694 goto fail0;
1695 }
1696 Py_DECREF(version);
Guido van Rossumf06628b2007-11-21 20:01:53 +00001697
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001698 /* get a memory buffer */
1699 biobuf = BIO_new(BIO_s_mem());
Zackery Spytz4c49da02018-12-07 03:11:30 -07001700 if (biobuf == NULL) {
1701 PyErr_SetString(PySSLErrorObject, "failed to allocate BIO");
1702 goto fail0;
1703 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001704
Antoine Pitroufb046912010-11-09 20:21:19 +00001705 (void) BIO_reset(biobuf);
1706 serialNumber = X509_get_serialNumber(certificate);
1707 /* should not exceed 20 octets, 160 bits, so buf is big enough */
1708 i2a_ASN1_INTEGER(biobuf, serialNumber);
1709 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1710 if (len < 0) {
1711 _setSSLError(NULL, 0, __FILE__, __LINE__);
1712 goto fail1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001713 }
Antoine Pitroufb046912010-11-09 20:21:19 +00001714 sn_obj = PyUnicode_FromStringAndSize(buf, len);
1715 if (sn_obj == NULL)
1716 goto fail1;
1717 if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) {
1718 Py_DECREF(sn_obj);
1719 goto fail1;
1720 }
1721 Py_DECREF(sn_obj);
1722
1723 (void) BIO_reset(biobuf);
1724 notBefore = X509_get_notBefore(certificate);
1725 ASN1_TIME_print(biobuf, notBefore);
1726 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1727 if (len < 0) {
1728 _setSSLError(NULL, 0, __FILE__, __LINE__);
1729 goto fail1;
1730 }
1731 pnotBefore = PyUnicode_FromStringAndSize(buf, len);
1732 if (pnotBefore == NULL)
1733 goto fail1;
1734 if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) {
1735 Py_DECREF(pnotBefore);
1736 goto fail1;
1737 }
1738 Py_DECREF(pnotBefore);
Thomas Woutersed03b412007-08-28 21:37:11 +00001739
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001740 (void) BIO_reset(biobuf);
1741 notAfter = X509_get_notAfter(certificate);
1742 ASN1_TIME_print(biobuf, notAfter);
1743 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1744 if (len < 0) {
1745 _setSSLError(NULL, 0, __FILE__, __LINE__);
1746 goto fail1;
1747 }
1748 pnotAfter = PyUnicode_FromStringAndSize(buf, len);
1749 if (pnotAfter == NULL)
1750 goto fail1;
1751 if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) {
1752 Py_DECREF(pnotAfter);
1753 goto fail1;
1754 }
1755 Py_DECREF(pnotAfter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001756
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001757 /* Now look for subjectAltName */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001758
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001759 peer_alt_names = _get_peer_alt_names(certificate);
1760 if (peer_alt_names == NULL)
1761 goto fail1;
1762 else if (peer_alt_names != Py_None) {
1763 if (PyDict_SetItemString(retval, "subjectAltName",
1764 peer_alt_names) < 0) {
1765 Py_DECREF(peer_alt_names);
1766 goto fail1;
1767 }
1768 Py_DECREF(peer_alt_names);
1769 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001770
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001771 /* Authority Information Access: OCSP URIs */
1772 obj = _get_aia_uri(certificate, NID_ad_OCSP);
1773 if (obj == NULL) {
1774 goto fail1;
1775 } else if (obj != Py_None) {
1776 result = PyDict_SetItemString(retval, "OCSP", obj);
1777 Py_DECREF(obj);
1778 if (result < 0) {
1779 goto fail1;
1780 }
1781 }
1782
1783 obj = _get_aia_uri(certificate, NID_ad_ca_issuers);
1784 if (obj == NULL) {
1785 goto fail1;
1786 } else if (obj != Py_None) {
1787 result = PyDict_SetItemString(retval, "caIssuers", obj);
1788 Py_DECREF(obj);
1789 if (result < 0) {
1790 goto fail1;
1791 }
1792 }
1793
1794 /* CDP (CRL distribution points) */
1795 obj = _get_crl_dp(certificate);
1796 if (obj == NULL) {
1797 goto fail1;
1798 } else if (obj != Py_None) {
1799 result = PyDict_SetItemString(retval, "crlDistributionPoints", obj);
1800 Py_DECREF(obj);
1801 if (result < 0) {
1802 goto fail1;
1803 }
1804 }
1805
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001806 BIO_free(biobuf);
1807 return retval;
Thomas Woutersed03b412007-08-28 21:37:11 +00001808
1809 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001810 if (biobuf != NULL)
1811 BIO_free(biobuf);
Thomas Woutersed03b412007-08-28 21:37:11 +00001812 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001813 Py_XDECREF(retval);
1814 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001815}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001816
Christian Heimes9a5395a2013-06-17 15:44:12 +02001817static PyObject *
1818_certificate_to_der(X509 *certificate)
1819{
1820 unsigned char *bytes_buf = NULL;
1821 int len;
1822 PyObject *retval;
1823
1824 bytes_buf = NULL;
1825 len = i2d_X509(certificate, &bytes_buf);
1826 if (len < 0) {
1827 _setSSLError(NULL, 0, __FILE__, __LINE__);
1828 return NULL;
1829 }
1830 /* this is actually an immutable bytes sequence */
1831 retval = PyBytes_FromStringAndSize((const char *) bytes_buf, len);
1832 OPENSSL_free(bytes_buf);
1833 return retval;
1834}
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001835
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001836/*[clinic input]
1837_ssl._test_decode_cert
1838 path: object(converter="PyUnicode_FSConverter")
1839 /
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001840
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001841[clinic start generated code]*/
1842
1843static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001844_ssl__test_decode_cert_impl(PyObject *module, PyObject *path)
1845/*[clinic end generated code: output=96becb9abb23c091 input=cdeaaf02d4346628]*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001846{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001847 PyObject *retval = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001848 X509 *x=NULL;
1849 BIO *cert;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001850
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001851 if ((cert=BIO_new(BIO_s_file())) == NULL) {
1852 PyErr_SetString(PySSLErrorObject,
1853 "Can't malloc memory to read file");
1854 goto fail0;
1855 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001856
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001857 if (BIO_read_filename(cert, PyBytes_AsString(path)) <= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001858 PyErr_SetString(PySSLErrorObject,
1859 "Can't open file");
1860 goto fail0;
1861 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001862
Miss Islington (bot)f7812832019-08-15 05:52:51 -07001863 x = PEM_read_bio_X509(cert, NULL, NULL, NULL);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001864 if (x == NULL) {
1865 PyErr_SetString(PySSLErrorObject,
1866 "Error decoding PEM-encoded file");
1867 goto fail0;
1868 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001869
Antoine Pitroufb046912010-11-09 20:21:19 +00001870 retval = _decode_certificate(x);
Mark Dickinsonee55df52010-08-03 18:31:54 +00001871 X509_free(x);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001872
1873 fail0:
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001874 Py_DECREF(path);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001875 if (cert != NULL) BIO_free(cert);
1876 return retval;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001877}
1878
1879
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001880/*[clinic input]
Christian Heimes141c5e82018-02-24 21:10:57 +01001881_ssl._SSLSocket.getpeercert
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001882 der as binary_mode: bool = False
1883 /
1884
1885Returns the certificate for the peer.
1886
1887If no certificate was provided, returns None. If a certificate was
1888provided, but not validated, returns an empty dictionary. Otherwise
1889returns a dict containing information about the peer certificate.
1890
1891If the optional argument is True, returns a DER-encoded copy of the
1892peer certificate, or None if no certificate was provided. This will
1893return the certificate even if it wasn't validated.
1894[clinic start generated code]*/
1895
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001896static PyObject *
Christian Heimes141c5e82018-02-24 21:10:57 +01001897_ssl__SSLSocket_getpeercert_impl(PySSLSocket *self, int binary_mode)
1898/*[clinic end generated code: output=1f0ab66dfb693c88 input=c0fbe802e57629b7]*/
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001899{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001900 int verification;
Christian Heimes66dc33b2017-05-23 16:02:02 -07001901 X509 *peer_cert;
1902 PyObject *result;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001903
Christian Heimes66dc33b2017-05-23 16:02:02 -07001904 if (!SSL_is_init_finished(self->ssl)) {
Antoine Pitrou20b85552013-09-29 19:50:53 +02001905 PyErr_SetString(PyExc_ValueError,
1906 "handshake not done yet");
1907 return NULL;
1908 }
Christian Heimes66dc33b2017-05-23 16:02:02 -07001909 peer_cert = SSL_get_peer_certificate(self->ssl);
1910 if (peer_cert == NULL)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001911 Py_RETURN_NONE;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001912
Antoine Pitrou721738f2012-08-15 23:20:39 +02001913 if (binary_mode) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001914 /* return cert in DER-encoded format */
Christian Heimes66dc33b2017-05-23 16:02:02 -07001915 result = _certificate_to_der(peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001916 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00001917 verification = SSL_CTX_get_verify_mode(SSL_get_SSL_CTX(self->ssl));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001918 if ((verification & SSL_VERIFY_PEER) == 0)
Christian Heimes66dc33b2017-05-23 16:02:02 -07001919 result = PyDict_New();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001920 else
Christian Heimes66dc33b2017-05-23 16:02:02 -07001921 result = _decode_certificate(peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001922 }
Christian Heimes66dc33b2017-05-23 16:02:02 -07001923 X509_free(peer_cert);
1924 return result;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001925}
1926
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001927static PyObject *
1928cipher_to_tuple(const SSL_CIPHER *cipher)
1929{
1930 const char *cipher_name, *cipher_protocol;
1931 PyObject *v, *retval = PyTuple_New(3);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001932 if (retval == NULL)
1933 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001934
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001935 cipher_name = SSL_CIPHER_get_name(cipher);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001936 if (cipher_name == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001937 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001938 PyTuple_SET_ITEM(retval, 0, Py_None);
1939 } else {
1940 v = PyUnicode_FromString(cipher_name);
1941 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001942 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001943 PyTuple_SET_ITEM(retval, 0, v);
1944 }
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001945
1946 cipher_protocol = SSL_CIPHER_get_version(cipher);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001947 if (cipher_protocol == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001948 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001949 PyTuple_SET_ITEM(retval, 1, Py_None);
1950 } else {
1951 v = PyUnicode_FromString(cipher_protocol);
1952 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001953 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001954 PyTuple_SET_ITEM(retval, 1, v);
1955 }
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001956
1957 v = PyLong_FromLong(SSL_CIPHER_get_bits(cipher, NULL));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001958 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001959 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001960 PyTuple_SET_ITEM(retval, 2, v);
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001961
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001962 return retval;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001963
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001964 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001965 Py_DECREF(retval);
1966 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001967}
1968
Christian Heimes25bfcd52016-09-06 00:04:45 +02001969#if OPENSSL_VERSION_NUMBER >= 0x10002000UL
1970static PyObject *
1971cipher_to_dict(const SSL_CIPHER *cipher)
1972{
1973 const char *cipher_name, *cipher_protocol;
1974
1975 unsigned long cipher_id;
1976 int alg_bits, strength_bits, len;
1977 char buf[512] = {0};
1978#if OPENSSL_VERSION_1_1
1979 int aead, nid;
1980 const char *skcipher = NULL, *digest = NULL, *kx = NULL, *auth = NULL;
1981#endif
Christian Heimes25bfcd52016-09-06 00:04:45 +02001982
1983 /* can be NULL */
1984 cipher_name = SSL_CIPHER_get_name(cipher);
1985 cipher_protocol = SSL_CIPHER_get_version(cipher);
1986 cipher_id = SSL_CIPHER_get_id(cipher);
1987 SSL_CIPHER_description(cipher, buf, sizeof(buf) - 1);
Segev Finer5cff6372017-07-27 01:19:17 +03001988 /* Downcast to avoid a warning. Safe since buf is always 512 bytes */
1989 len = (int)strlen(buf);
Christian Heimes25bfcd52016-09-06 00:04:45 +02001990 if (len > 1 && buf[len-1] == '\n')
1991 buf[len-1] = '\0';
1992 strength_bits = SSL_CIPHER_get_bits(cipher, &alg_bits);
1993
1994#if OPENSSL_VERSION_1_1
1995 aead = SSL_CIPHER_is_aead(cipher);
1996 nid = SSL_CIPHER_get_cipher_nid(cipher);
1997 skcipher = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1998 nid = SSL_CIPHER_get_digest_nid(cipher);
1999 digest = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
2000 nid = SSL_CIPHER_get_kx_nid(cipher);
2001 kx = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
2002 nid = SSL_CIPHER_get_auth_nid(cipher);
2003 auth = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
2004#endif
2005
Victor Stinner410b9882016-09-12 12:00:23 +02002006 return Py_BuildValue(
Christian Heimes25bfcd52016-09-06 00:04:45 +02002007 "{sksssssssisi"
2008#if OPENSSL_VERSION_1_1
2009 "sOssssssss"
2010#endif
2011 "}",
2012 "id", cipher_id,
2013 "name", cipher_name,
2014 "protocol", cipher_protocol,
2015 "description", buf,
2016 "strength_bits", strength_bits,
2017 "alg_bits", alg_bits
2018#if OPENSSL_VERSION_1_1
2019 ,"aead", aead ? Py_True : Py_False,
2020 "symmetric", skcipher,
2021 "digest", digest,
2022 "kea", kx,
2023 "auth", auth
2024#endif
2025 );
Christian Heimes25bfcd52016-09-06 00:04:45 +02002026}
2027#endif
2028
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002029/*[clinic input]
2030_ssl._SSLSocket.shared_ciphers
2031[clinic start generated code]*/
2032
2033static PyObject *
2034_ssl__SSLSocket_shared_ciphers_impl(PySSLSocket *self)
2035/*[clinic end generated code: output=3d174ead2e42c4fd input=0bfe149da8fe6306]*/
Benjamin Peterson4cb17812015-01-07 11:14:26 -06002036{
2037 STACK_OF(SSL_CIPHER) *ciphers;
2038 int i;
2039 PyObject *res;
2040
Christian Heimes598894f2016-09-05 23:19:05 +02002041 ciphers = SSL_get_ciphers(self->ssl);
2042 if (!ciphers)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06002043 Py_RETURN_NONE;
Benjamin Peterson4cb17812015-01-07 11:14:26 -06002044 res = PyList_New(sk_SSL_CIPHER_num(ciphers));
2045 if (!res)
2046 return NULL;
2047 for (i = 0; i < sk_SSL_CIPHER_num(ciphers); i++) {
2048 PyObject *tup = cipher_to_tuple(sk_SSL_CIPHER_value(ciphers, i));
2049 if (!tup) {
2050 Py_DECREF(res);
2051 return NULL;
2052 }
2053 PyList_SET_ITEM(res, i, tup);
2054 }
2055 return res;
2056}
2057
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002058/*[clinic input]
2059_ssl._SSLSocket.cipher
2060[clinic start generated code]*/
2061
2062static PyObject *
2063_ssl__SSLSocket_cipher_impl(PySSLSocket *self)
2064/*[clinic end generated code: output=376417c16d0e5815 input=548fb0e27243796d]*/
Benjamin Peterson4cb17812015-01-07 11:14:26 -06002065{
2066 const SSL_CIPHER *current;
2067
2068 if (self->ssl == NULL)
2069 Py_RETURN_NONE;
2070 current = SSL_get_current_cipher(self->ssl);
2071 if (current == NULL)
2072 Py_RETURN_NONE;
2073 return cipher_to_tuple(current);
2074}
2075
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002076/*[clinic input]
2077_ssl._SSLSocket.version
2078[clinic start generated code]*/
2079
2080static PyObject *
2081_ssl__SSLSocket_version_impl(PySSLSocket *self)
2082/*[clinic end generated code: output=178aed33193b2cdb input=900186a503436fd6]*/
Antoine Pitrou47e40422014-09-04 21:00:10 +02002083{
2084 const char *version;
2085
2086 if (self->ssl == NULL)
2087 Py_RETURN_NONE;
Christian Heimes68771112017-09-05 21:55:40 -07002088 if (!SSL_is_init_finished(self->ssl)) {
2089 /* handshake not finished */
2090 Py_RETURN_NONE;
2091 }
Antoine Pitrou47e40422014-09-04 21:00:10 +02002092 version = SSL_get_version(self->ssl);
2093 if (!strcmp(version, "unknown"))
2094 Py_RETURN_NONE;
2095 return PyUnicode_FromString(version);
2096}
2097
Christian Heimes29eab552018-02-25 12:31:33 +01002098#if HAVE_NPN
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002099/*[clinic input]
2100_ssl._SSLSocket.selected_npn_protocol
2101[clinic start generated code]*/
2102
2103static PyObject *
2104_ssl__SSLSocket_selected_npn_protocol_impl(PySSLSocket *self)
2105/*[clinic end generated code: output=b91d494cd207ecf6 input=c28fde139204b826]*/
2106{
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002107 const unsigned char *out;
2108 unsigned int outlen;
2109
Victor Stinner4569cd52013-06-23 14:58:43 +02002110 SSL_get0_next_proto_negotiated(self->ssl,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002111 &out, &outlen);
2112
2113 if (out == NULL)
2114 Py_RETURN_NONE;
Benjamin Petersoncca27322015-01-23 16:35:37 -05002115 return PyUnicode_FromStringAndSize((char *)out, outlen);
2116}
2117#endif
2118
Christian Heimes29eab552018-02-25 12:31:33 +01002119#if HAVE_ALPN
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002120/*[clinic input]
2121_ssl._SSLSocket.selected_alpn_protocol
2122[clinic start generated code]*/
2123
2124static PyObject *
2125_ssl__SSLSocket_selected_alpn_protocol_impl(PySSLSocket *self)
2126/*[clinic end generated code: output=ec33688b303d250f input=442de30e35bc2913]*/
2127{
Benjamin Petersoncca27322015-01-23 16:35:37 -05002128 const unsigned char *out;
2129 unsigned int outlen;
2130
2131 SSL_get0_alpn_selected(self->ssl, &out, &outlen);
2132
2133 if (out == NULL)
2134 Py_RETURN_NONE;
2135 return PyUnicode_FromStringAndSize((char *)out, outlen);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002136}
2137#endif
2138
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002139/*[clinic input]
2140_ssl._SSLSocket.compression
2141[clinic start generated code]*/
2142
2143static PyObject *
2144_ssl__SSLSocket_compression_impl(PySSLSocket *self)
2145/*[clinic end generated code: output=bd16cb1bb4646ae7 input=5d059d0a2bbc32c8]*/
2146{
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01002147#ifdef OPENSSL_NO_COMP
2148 Py_RETURN_NONE;
2149#else
2150 const COMP_METHOD *comp_method;
2151 const char *short_name;
2152
2153 if (self->ssl == NULL)
2154 Py_RETURN_NONE;
2155 comp_method = SSL_get_current_compression(self->ssl);
Christian Heimes598894f2016-09-05 23:19:05 +02002156 if (comp_method == NULL || COMP_get_type(comp_method) == NID_undef)
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01002157 Py_RETURN_NONE;
Christian Heimes281e5f82016-09-06 01:10:39 +02002158 short_name = OBJ_nid2sn(COMP_get_type(comp_method));
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01002159 if (short_name == NULL)
2160 Py_RETURN_NONE;
2161 return PyUnicode_DecodeFSDefault(short_name);
2162#endif
2163}
2164
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002165static PySSLContext *PySSL_get_context(PySSLSocket *self, void *closure) {
2166 Py_INCREF(self->ctx);
2167 return self->ctx;
2168}
2169
2170static int PySSL_set_context(PySSLSocket *self, PyObject *value,
2171 void *closure) {
2172
2173 if (PyObject_TypeCheck(value, &PySSLContext_Type)) {
Antoine Pitrou912fbff2013-03-30 16:29:32 +01002174#if !HAVE_SNI
2175 PyErr_SetString(PyExc_NotImplementedError, "setting a socket's "
2176 "context is not supported by your OpenSSL library");
Antoine Pitrou41f8c4f2013-03-30 16:36:54 +01002177 return -1;
Antoine Pitrou912fbff2013-03-30 16:29:32 +01002178#else
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002179 Py_INCREF(value);
Serhiy Storchaka57a01d32016-04-10 18:05:40 +03002180 Py_SETREF(self->ctx, (PySSLContext *)value);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002181 SSL_set_SSL_CTX(self->ssl, self->ctx->ctx);
Antoine Pitrou912fbff2013-03-30 16:29:32 +01002182#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002183 } else {
Ned Deily4531ec72018-06-11 20:26:28 -04002184 PyErr_SetString(PyExc_TypeError, "The value must be a SSLContext");
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002185 return -1;
2186 }
2187
2188 return 0;
2189}
2190
2191PyDoc_STRVAR(PySSL_set_context_doc,
2192"_setter_context(ctx)\n\
2193\
2194This changes the context associated with the SSLSocket. This is typically\n\
Christian Heimes11a14932018-02-24 02:35:08 +01002195used from within a callback function set by the sni_callback\n\
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002196on the SSLContext to change the certificate information associated with the\n\
2197SSLSocket before the cryptographic exchange handshake messages\n");
2198
2199
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002200static PyObject *
2201PySSL_get_server_side(PySSLSocket *self, void *c)
2202{
2203 return PyBool_FromLong(self->socket_type == PY_SSL_SERVER);
2204}
2205
2206PyDoc_STRVAR(PySSL_get_server_side_doc,
2207"Whether this is a server-side socket.");
2208
2209static PyObject *
2210PySSL_get_server_hostname(PySSLSocket *self, void *c)
2211{
2212 if (self->server_hostname == NULL)
2213 Py_RETURN_NONE;
2214 Py_INCREF(self->server_hostname);
2215 return self->server_hostname;
2216}
2217
2218PyDoc_STRVAR(PySSL_get_server_hostname_doc,
2219"The currently set server hostname (for SNI).");
2220
2221static PyObject *
2222PySSL_get_owner(PySSLSocket *self, void *c)
2223{
2224 PyObject *owner;
2225
2226 if (self->owner == NULL)
2227 Py_RETURN_NONE;
2228
2229 owner = PyWeakref_GetObject(self->owner);
2230 Py_INCREF(owner);
2231 return owner;
2232}
2233
2234static int
2235PySSL_set_owner(PySSLSocket *self, PyObject *value, void *c)
2236{
Serhiy Storchaka48842712016-04-06 09:45:48 +03002237 Py_XSETREF(self->owner, PyWeakref_NewRef(value, NULL));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002238 if (self->owner == NULL)
2239 return -1;
2240 return 0;
2241}
2242
2243PyDoc_STRVAR(PySSL_get_owner_doc,
2244"The Python-level owner of this object.\
2245Passed as \"self\" in servername callback.");
2246
Christian Heimesc7f70692019-05-31 11:44:05 +02002247static int
2248PySSL_traverse(PySSLSocket *self, visitproc visit, void *arg)
2249{
2250 Py_VISIT(self->exc_type);
2251 Py_VISIT(self->exc_value);
2252 Py_VISIT(self->exc_tb);
2253 return 0;
2254}
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002255
Christian Heimesc7f70692019-05-31 11:44:05 +02002256static int
2257PySSL_clear(PySSLSocket *self)
2258{
2259 Py_CLEAR(self->exc_type);
2260 Py_CLEAR(self->exc_value);
2261 Py_CLEAR(self->exc_tb);
2262 return 0;
2263}
2264
2265static void
2266PySSL_dealloc(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002267{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002268 if (self->ssl)
2269 SSL_free(self->ssl);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002270 Py_XDECREF(self->Socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002271 Py_XDECREF(self->ctx);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002272 Py_XDECREF(self->server_hostname);
2273 Py_XDECREF(self->owner);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002274 PyObject_Del(self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002275}
2276
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002277/* If the socket has a timeout, do a select()/poll() on the socket.
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002278 The argument writing indicates the direction.
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00002279 Returns one of the possibilities in the timeout_state enum (above).
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002280 */
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00002281
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002282static int
Victor Stinner14690702015-04-06 22:46:13 +02002283PySSL_select(PySocketSockObject *s, int writing, _PyTime_t timeout)
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002284{
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002285 int rc;
2286#ifdef HAVE_POLL
2287 struct pollfd pollfd;
2288 _PyTime_t ms;
2289#else
2290 int nfds;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002291 fd_set fds;
2292 struct timeval tv;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002293#endif
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002294
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002295 /* Nothing to do unless we're in timeout mode (not non-blocking) */
Victor Stinner14690702015-04-06 22:46:13 +02002296 if ((s == NULL) || (timeout == 0))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002297 return SOCKET_IS_NONBLOCKING;
Victor Stinner14690702015-04-06 22:46:13 +02002298 else if (timeout < 0) {
2299 if (s->sock_timeout > 0)
2300 return SOCKET_HAS_TIMED_OUT;
2301 else
2302 return SOCKET_IS_BLOCKING;
2303 }
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002304
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002305 /* Guard against closed socket */
Victor Stinner524714e2016-07-22 17:43:59 +02002306 if (s->sock_fd == INVALID_SOCKET)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002307 return SOCKET_HAS_BEEN_CLOSED;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002308
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002309 /* Prefer poll, if available, since you can poll() any fd
2310 * which can't be done with select(). */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002311#ifdef HAVE_POLL
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002312 pollfd.fd = s->sock_fd;
2313 pollfd.events = writing ? POLLOUT : POLLIN;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002314
Victor Stinner14690702015-04-06 22:46:13 +02002315 /* timeout is in seconds, poll() uses milliseconds */
2316 ms = (int)_PyTime_AsMilliseconds(timeout, _PyTime_ROUND_CEILING);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002317 assert(ms <= INT_MAX);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002318
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002319 PySSL_BEGIN_ALLOW_THREADS
2320 rc = poll(&pollfd, 1, (int)ms);
2321 PySSL_END_ALLOW_THREADS
2322#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002323 /* Guard against socket too large for select*/
Charles-François Nataliaa26b272011-08-28 17:51:43 +02002324 if (!_PyIsSelectable_fd(s->sock_fd))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002325 return SOCKET_TOO_LARGE_FOR_SELECT;
Neal Norwitz082b2df2006-02-07 07:04:46 +00002326
Victor Stinner14690702015-04-06 22:46:13 +02002327 _PyTime_AsTimeval_noraise(timeout, &tv, _PyTime_ROUND_CEILING);
Victor Stinnere2452312015-03-28 03:00:46 +01002328
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002329 FD_ZERO(&fds);
2330 FD_SET(s->sock_fd, &fds);
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002331
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002332 /* Wait until the socket becomes ready */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002333 PySSL_BEGIN_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002334 nfds = Py_SAFE_DOWNCAST(s->sock_fd+1, SOCKET_T, int);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002335 if (writing)
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002336 rc = select(nfds, NULL, &fds, NULL, &tv);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002337 else
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002338 rc = select(nfds, &fds, NULL, NULL, &tv);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002339 PySSL_END_ALLOW_THREADS
Bill Janssen6e027db2007-11-15 22:23:56 +00002340#endif
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002341
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002342 /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
2343 (when we are able to write or when there's something to read) */
2344 return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002345}
2346
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002347/*[clinic input]
2348_ssl._SSLSocket.write
2349 b: Py_buffer
2350 /
2351
2352Writes the bytes-like object b into the SSL object.
2353
2354Returns the number of bytes written.
2355[clinic start generated code]*/
2356
2357static PyObject *
2358_ssl__SSLSocket_write_impl(PySSLSocket *self, Py_buffer *b)
2359/*[clinic end generated code: output=aa7a6be5527358d8 input=77262d994fe5100a]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002360{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002361 int len;
2362 int sockstate;
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002363 _PySSLError err;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002364 int nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002365 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002366 _PyTime_t timeout, deadline = 0;
2367 int has_timeout;
Bill Janssen54cc54c2007-12-14 22:08:56 +00002368
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002369 if (sock != NULL) {
2370 if (((PyObject*)sock) == Py_None) {
2371 _setSSLError("Underlying socket connection gone",
2372 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2373 return NULL;
2374 }
2375 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002376 }
2377
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002378 if (b->len > INT_MAX) {
Victor Stinner6efa9652013-06-25 00:42:31 +02002379 PyErr_Format(PyExc_OverflowError,
2380 "string longer than %d bytes", INT_MAX);
2381 goto error;
2382 }
2383
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002384 if (sock != NULL) {
2385 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002386 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002387 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2388 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
2389 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002390
Victor Stinner14690702015-04-06 22:46:13 +02002391 timeout = GET_SOCKET_TIMEOUT(sock);
2392 has_timeout = (timeout > 0);
2393 if (has_timeout)
2394 deadline = _PyTime_GetMonotonicClock() + timeout;
2395
2396 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002397 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002398 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002399 "The write operation timed out");
2400 goto error;
2401 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
2402 PyErr_SetString(PySSLErrorObject,
2403 "Underlying socket has been closed.");
2404 goto error;
2405 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
2406 PyErr_SetString(PySSLErrorObject,
2407 "Underlying socket too large for select().");
2408 goto error;
2409 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002410
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002411 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002412 PySSL_BEGIN_ALLOW_THREADS
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002413 len = SSL_write(self->ssl, b->buf, (int)b->len);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002414 err = _PySSL_errno(len <= 0, self->ssl, len);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002415 PySSL_END_ALLOW_THREADS
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002416 self->err = err;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002417
2418 if (PyErr_CheckSignals())
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002419 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002420
Victor Stinner14690702015-04-06 22:46:13 +02002421 if (has_timeout)
2422 timeout = deadline - _PyTime_GetMonotonicClock();
2423
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002424 if (err.ssl == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +02002425 sockstate = PySSL_select(sock, 0, timeout);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002426 } else if (err.ssl == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +02002427 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002428 } else {
2429 sockstate = SOCKET_OPERATION_OK;
2430 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002431
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002432 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002433 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002434 "The write operation timed out");
2435 goto error;
2436 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
2437 PyErr_SetString(PySSLErrorObject,
2438 "Underlying socket has been closed.");
2439 goto error;
2440 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
2441 break;
2442 }
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002443 } while (err.ssl == SSL_ERROR_WANT_READ ||
2444 err.ssl == SSL_ERROR_WANT_WRITE);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002445
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002446 Py_XDECREF(sock);
Christian Heimesc7f70692019-05-31 11:44:05 +02002447 if (len <= 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002448 return PySSL_SetError(self, len, __FILE__, __LINE__);
Christian Heimesc7f70692019-05-31 11:44:05 +02002449 if (PySSL_ChainExceptions(self) < 0)
2450 return NULL;
2451 return PyLong_FromLong(len);
Antoine Pitrou7d7aede2009-11-25 18:55:32 +00002452error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002453 Py_XDECREF(sock);
Christian Heimesc7f70692019-05-31 11:44:05 +02002454 PySSL_ChainExceptions(self);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002455 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002456}
2457
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002458/*[clinic input]
2459_ssl._SSLSocket.pending
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002460
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002461Returns the number of already decrypted bytes available for read, pending on the connection.
2462[clinic start generated code]*/
2463
2464static PyObject *
2465_ssl__SSLSocket_pending_impl(PySSLSocket *self)
2466/*[clinic end generated code: output=983d9fecdc308a83 input=2b77487d6dfd597f]*/
Bill Janssen6e027db2007-11-15 22:23:56 +00002467{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002468 int count = 0;
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002469 _PySSLError err;
Bill Janssen6e027db2007-11-15 22:23:56 +00002470
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002471 PySSL_BEGIN_ALLOW_THREADS
2472 count = SSL_pending(self->ssl);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002473 err = _PySSL_errno(count < 0, self->ssl, count);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002474 PySSL_END_ALLOW_THREADS
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002475 self->err = err;
2476
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002477 if (count < 0)
2478 return PySSL_SetError(self, count, __FILE__, __LINE__);
2479 else
2480 return PyLong_FromLong(count);
Bill Janssen6e027db2007-11-15 22:23:56 +00002481}
2482
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002483/*[clinic input]
2484_ssl._SSLSocket.read
2485 size as len: int
2486 [
Larry Hastingsdbfdc382015-05-04 06:59:46 -07002487 buffer: Py_buffer(accept={rwbuffer})
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002488 ]
2489 /
Bill Janssen6e027db2007-11-15 22:23:56 +00002490
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002491Read up to size bytes from the SSL socket.
2492[clinic start generated code]*/
2493
2494static PyObject *
2495_ssl__SSLSocket_read_impl(PySSLSocket *self, int len, int group_right_1,
2496 Py_buffer *buffer)
Larry Hastingsdbfdc382015-05-04 06:59:46 -07002497/*[clinic end generated code: output=00097776cec2a0af input=ff157eb918d0905b]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002498{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002499 PyObject *dest = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002500 char *mem;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002501 int count;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002502 int sockstate;
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002503 _PySSLError err;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002504 int nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002505 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002506 _PyTime_t timeout, deadline = 0;
2507 int has_timeout;
Bill Janssen54cc54c2007-12-14 22:08:56 +00002508
Martin Panter5503d472016-03-27 05:35:19 +00002509 if (!group_right_1 && len < 0) {
2510 PyErr_SetString(PyExc_ValueError, "size should not be negative");
2511 return NULL;
2512 }
2513
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002514 if (sock != NULL) {
2515 if (((PyObject*)sock) == Py_None) {
2516 _setSSLError("Underlying socket connection gone",
2517 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2518 return NULL;
2519 }
2520 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002521 }
2522
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002523 if (!group_right_1) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002524 dest = PyBytes_FromStringAndSize(NULL, len);
2525 if (dest == NULL)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002526 goto error;
Martin Panterbed7f1a2016-07-11 00:17:13 +00002527 if (len == 0) {
2528 Py_XDECREF(sock);
2529 return dest;
2530 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002531 mem = PyBytes_AS_STRING(dest);
2532 }
2533 else {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002534 mem = buffer->buf;
2535 if (len <= 0 || len > buffer->len) {
2536 len = (int) buffer->len;
2537 if (buffer->len != len) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002538 PyErr_SetString(PyExc_OverflowError,
2539 "maximum length can't fit in a C 'int'");
2540 goto error;
2541 }
Martin Panterbed7f1a2016-07-11 00:17:13 +00002542 if (len == 0) {
2543 count = 0;
2544 goto done;
2545 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002546 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002547 }
2548
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002549 if (sock != NULL) {
2550 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002551 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002552 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2553 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
2554 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002555
Victor Stinner14690702015-04-06 22:46:13 +02002556 timeout = GET_SOCKET_TIMEOUT(sock);
2557 has_timeout = (timeout > 0);
2558 if (has_timeout)
2559 deadline = _PyTime_GetMonotonicClock() + timeout;
2560
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002561 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002562 PySSL_BEGIN_ALLOW_THREADS
2563 count = SSL_read(self->ssl, mem, len);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002564 err = _PySSL_errno(count <= 0, self->ssl, count);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002565 PySSL_END_ALLOW_THREADS
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002566 self->err = err;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002567
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002568 if (PyErr_CheckSignals())
2569 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002570
Victor Stinner14690702015-04-06 22:46:13 +02002571 if (has_timeout)
2572 timeout = deadline - _PyTime_GetMonotonicClock();
2573
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002574 if (err.ssl == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +02002575 sockstate = PySSL_select(sock, 0, timeout);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002576 } else if (err.ssl == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +02002577 sockstate = PySSL_select(sock, 1, timeout);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002578 } else if (err.ssl == SSL_ERROR_ZERO_RETURN &&
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002579 SSL_get_shutdown(self->ssl) == SSL_RECEIVED_SHUTDOWN)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002580 {
2581 count = 0;
2582 goto done;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002583 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002584 else
2585 sockstate = SOCKET_OPERATION_OK;
2586
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002587 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002588 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002589 "The read operation timed out");
2590 goto error;
2591 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
2592 break;
2593 }
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002594 } while (err.ssl == SSL_ERROR_WANT_READ ||
2595 err.ssl == SSL_ERROR_WANT_WRITE);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002596
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002597 if (count <= 0) {
2598 PySSL_SetError(self, count, __FILE__, __LINE__);
2599 goto error;
2600 }
Christian Heimesc7f70692019-05-31 11:44:05 +02002601 if (self->exc_type != NULL)
2602 goto error;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002603
2604done:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002605 Py_XDECREF(sock);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002606 if (!group_right_1) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002607 _PyBytes_Resize(&dest, count);
2608 return dest;
2609 }
2610 else {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002611 return PyLong_FromLong(count);
2612 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002613
2614error:
Christian Heimesc7f70692019-05-31 11:44:05 +02002615 PySSL_ChainExceptions(self);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002616 Py_XDECREF(sock);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002617 if (!group_right_1)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002618 Py_XDECREF(dest);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002619 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002620}
2621
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002622/*[clinic input]
2623_ssl._SSLSocket.shutdown
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002624
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002625Does the SSL shutdown handshake with the remote end.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002626[clinic start generated code]*/
2627
2628static PyObject *
2629_ssl__SSLSocket_shutdown_impl(PySSLSocket *self)
Christian Heimes141c5e82018-02-24 21:10:57 +01002630/*[clinic end generated code: output=ca1aa7ed9d25ca42 input=11d39e69b0a2bf4a]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00002631{
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002632 _PySSLError err;
2633 int sockstate, nonblocking, ret;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002634 int zeros = 0;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002635 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002636 _PyTime_t timeout, deadline = 0;
2637 int has_timeout;
Bill Janssen40a0f662008-08-12 16:56:25 +00002638
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002639 if (sock != NULL) {
2640 /* Guard against closed socket */
Victor Stinner524714e2016-07-22 17:43:59 +02002641 if ((((PyObject*)sock) == Py_None) || (sock->sock_fd == INVALID_SOCKET)) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002642 _setSSLError("Underlying socket connection gone",
2643 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2644 return NULL;
2645 }
2646 Py_INCREF(sock);
2647
2648 /* Just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002649 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002650 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2651 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002652 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002653
Victor Stinner14690702015-04-06 22:46:13 +02002654 timeout = GET_SOCKET_TIMEOUT(sock);
2655 has_timeout = (timeout > 0);
2656 if (has_timeout)
2657 deadline = _PyTime_GetMonotonicClock() + timeout;
2658
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002659 while (1) {
2660 PySSL_BEGIN_ALLOW_THREADS
2661 /* Disable read-ahead so that unwrap can work correctly.
2662 * Otherwise OpenSSL might read in too much data,
2663 * eating clear text data that happens to be
2664 * transmitted after the SSL shutdown.
Ezio Melotti85a86292013-08-17 16:57:41 +03002665 * Should be safe to call repeatedly every time this
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002666 * function is used and the shutdown_seen_zero != 0
2667 * condition is met.
2668 */
2669 if (self->shutdown_seen_zero)
2670 SSL_set_read_ahead(self->ssl, 0);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002671 ret = SSL_shutdown(self->ssl);
2672 err = _PySSL_errno(ret < 0, self->ssl, ret);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002673 PySSL_END_ALLOW_THREADS
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002674 self->err = err;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002675
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002676 /* If err == 1, a secure shutdown with SSL_shutdown() is complete */
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002677 if (ret > 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002678 break;
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002679 if (ret == 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002680 /* Don't loop endlessly; instead preserve legacy
2681 behaviour of trying SSL_shutdown() only twice.
2682 This looks necessary for OpenSSL < 0.9.8m */
2683 if (++zeros > 1)
2684 break;
2685 /* Shutdown was sent, now try receiving */
2686 self->shutdown_seen_zero = 1;
2687 continue;
Bill Janssen40a0f662008-08-12 16:56:25 +00002688 }
2689
Victor Stinner14690702015-04-06 22:46:13 +02002690 if (has_timeout)
2691 timeout = deadline - _PyTime_GetMonotonicClock();
2692
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002693 /* Possibly retry shutdown until timeout or failure */
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002694 if (err.ssl == SSL_ERROR_WANT_READ)
Victor Stinner14690702015-04-06 22:46:13 +02002695 sockstate = PySSL_select(sock, 0, timeout);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002696 else if (err.ssl == SSL_ERROR_WANT_WRITE)
Victor Stinner14690702015-04-06 22:46:13 +02002697 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002698 else
2699 break;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002700
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002701 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002702 if (err.ssl == SSL_ERROR_WANT_READ)
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002703 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002704 "The read operation timed out");
2705 else
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002706 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002707 "The write operation timed out");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002708 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002709 }
2710 else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
2711 PyErr_SetString(PySSLErrorObject,
2712 "Underlying socket too large for select().");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002713 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002714 }
2715 else if (sockstate != SOCKET_OPERATION_OK)
2716 /* Retain the SSL error code */
2717 break;
2718 }
Nathaniel J. Smithc0da5822018-09-21 21:44:12 -07002719 if (ret < 0) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002720 Py_XDECREF(sock);
Christian Heimesc7f70692019-05-31 11:44:05 +02002721 PySSL_SetError(self, ret, __FILE__, __LINE__);
2722 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002723 }
Christian Heimesc7f70692019-05-31 11:44:05 +02002724 if (self->exc_type != NULL)
2725 goto error;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002726 if (sock)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002727 /* It's already INCREF'ed */
2728 return (PyObject *) sock;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002729 else
2730 Py_RETURN_NONE;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002731
2732error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002733 Py_XDECREF(sock);
Christian Heimesc7f70692019-05-31 11:44:05 +02002734 PySSL_ChainExceptions(self);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002735 return NULL;
Bill Janssen40a0f662008-08-12 16:56:25 +00002736}
2737
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002738/*[clinic input]
Christian Heimes141c5e82018-02-24 21:10:57 +01002739_ssl._SSLSocket.get_channel_binding
2740 cb_type: str = "tls-unique"
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002741
Christian Heimes141c5e82018-02-24 21:10:57 +01002742Get channel binding data for current connection.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002743
Christian Heimes141c5e82018-02-24 21:10:57 +01002744Raise ValueError if the requested `cb_type` is not supported. Return bytes
2745of the data or None if the data is not available (e.g. before the handshake).
2746Only 'tls-unique' channel binding data from RFC 5929 is supported.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002747[clinic start generated code]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00002748
Antoine Pitroud6494802011-07-21 01:11:30 +02002749static PyObject *
Christian Heimes141c5e82018-02-24 21:10:57 +01002750_ssl__SSLSocket_get_channel_binding_impl(PySSLSocket *self,
2751 const char *cb_type)
2752/*[clinic end generated code: output=34bac9acb6a61d31 input=08b7e43b99c17d41]*/
Antoine Pitroud6494802011-07-21 01:11:30 +02002753{
Antoine Pitroud6494802011-07-21 01:11:30 +02002754 char buf[PySSL_CB_MAXLEN];
Victor Stinner9ee02032013-06-23 15:08:23 +02002755 size_t len;
Antoine Pitroud6494802011-07-21 01:11:30 +02002756
Christian Heimes141c5e82018-02-24 21:10:57 +01002757 if (strcmp(cb_type, "tls-unique") == 0) {
2758 if (SSL_session_reused(self->ssl) ^ !self->socket_type) {
2759 /* if session is resumed XOR we are the client */
2760 len = SSL_get_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2761 }
2762 else {
2763 /* if a new session XOR we are the server */
2764 len = SSL_get_peer_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2765 }
Antoine Pitroud6494802011-07-21 01:11:30 +02002766 }
2767 else {
Christian Heimes141c5e82018-02-24 21:10:57 +01002768 PyErr_Format(
2769 PyExc_ValueError,
2770 "'%s' channel binding type not implemented",
2771 cb_type
2772 );
2773 return NULL;
Antoine Pitroud6494802011-07-21 01:11:30 +02002774 }
2775
2776 /* It cannot be negative in current OpenSSL version as of July 2011 */
Antoine Pitroud6494802011-07-21 01:11:30 +02002777 if (len == 0)
2778 Py_RETURN_NONE;
2779
Christian Heimes141c5e82018-02-24 21:10:57 +01002780 return PyBytes_FromStringAndSize(buf, len);
Antoine Pitroud6494802011-07-21 01:11:30 +02002781}
2782
Christian Heimes9fb051f2018-09-23 08:32:31 +02002783/*[clinic input]
2784_ssl._SSLSocket.verify_client_post_handshake
2785
2786Initiate TLS 1.3 post-handshake authentication
2787[clinic start generated code]*/
2788
2789static PyObject *
2790_ssl__SSLSocket_verify_client_post_handshake_impl(PySSLSocket *self)
2791/*[clinic end generated code: output=532147f3b1341425 input=6bfa874810a3d889]*/
2792{
2793#ifdef TLS1_3_VERSION
2794 int err = SSL_verify_client_post_handshake(self->ssl);
2795 if (err == 0)
2796 return _setSSLError(NULL, 0, __FILE__, __LINE__);
2797 else
2798 Py_RETURN_NONE;
2799#else
2800 PyErr_SetString(PyExc_NotImplementedError,
2801 "Post-handshake auth is not supported by your "
2802 "OpenSSL version.");
2803 return NULL;
2804#endif
2805}
2806
Christian Heimes99a65702016-09-10 23:44:53 +02002807#ifdef OPENSSL_VERSION_1_1
2808
2809static SSL_SESSION*
2810_ssl_session_dup(SSL_SESSION *session) {
2811 SSL_SESSION *newsession = NULL;
2812 int slen;
2813 unsigned char *senc = NULL, *p;
2814 const unsigned char *const_p;
2815
2816 if (session == NULL) {
2817 PyErr_SetString(PyExc_ValueError, "Invalid session");
2818 goto error;
2819 }
2820
2821 /* get length */
2822 slen = i2d_SSL_SESSION(session, NULL);
2823 if (slen == 0 || slen > 0xFF00) {
2824 PyErr_SetString(PyExc_ValueError, "i2d() failed.");
2825 goto error;
2826 }
2827 if ((senc = PyMem_Malloc(slen)) == NULL) {
2828 PyErr_NoMemory();
2829 goto error;
2830 }
2831 p = senc;
2832 if (!i2d_SSL_SESSION(session, &p)) {
2833 PyErr_SetString(PyExc_ValueError, "i2d() failed.");
2834 goto error;
2835 }
2836 const_p = senc;
2837 newsession = d2i_SSL_SESSION(NULL, &const_p, slen);
2838 if (session == NULL) {
2839 goto error;
2840 }
2841 PyMem_Free(senc);
2842 return newsession;
2843 error:
2844 if (senc != NULL) {
2845 PyMem_Free(senc);
2846 }
2847 return NULL;
2848}
2849#endif
2850
2851static PyObject *
2852PySSL_get_session(PySSLSocket *self, void *closure) {
2853 /* get_session can return sessions from a server-side connection,
2854 * it does not check for handshake done or client socket. */
2855 PySSLSession *pysess;
2856 SSL_SESSION *session;
2857
2858#ifdef OPENSSL_VERSION_1_1
2859 /* duplicate session as workaround for session bug in OpenSSL 1.1.0,
2860 * https://github.com/openssl/openssl/issues/1550 */
2861 session = SSL_get0_session(self->ssl); /* borrowed reference */
2862 if (session == NULL) {
2863 Py_RETURN_NONE;
2864 }
2865 if ((session = _ssl_session_dup(session)) == NULL) {
2866 return NULL;
2867 }
2868#else
2869 session = SSL_get1_session(self->ssl);
2870 if (session == NULL) {
2871 Py_RETURN_NONE;
2872 }
2873#endif
Christian Heimesa5d07652016-09-24 10:48:05 +02002874 pysess = PyObject_GC_New(PySSLSession, &PySSLSession_Type);
Christian Heimes99a65702016-09-10 23:44:53 +02002875 if (pysess == NULL) {
2876 SSL_SESSION_free(session);
2877 return NULL;
2878 }
2879
2880 assert(self->ctx);
2881 pysess->ctx = self->ctx;
2882 Py_INCREF(pysess->ctx);
2883 pysess->session = session;
Christian Heimesa5d07652016-09-24 10:48:05 +02002884 PyObject_GC_Track(pysess);
Christian Heimes99a65702016-09-10 23:44:53 +02002885 return (PyObject *)pysess;
2886}
2887
2888static int PySSL_set_session(PySSLSocket *self, PyObject *value,
2889 void *closure)
2890 {
2891 PySSLSession *pysess;
2892#ifdef OPENSSL_VERSION_1_1
2893 SSL_SESSION *session;
2894#endif
2895 int result;
2896
2897 if (!PySSLSession_Check(value)) {
Ned Deily4531ec72018-06-11 20:26:28 -04002898 PyErr_SetString(PyExc_TypeError, "Value is not a SSLSession.");
Christian Heimes99a65702016-09-10 23:44:53 +02002899 return -1;
2900 }
2901 pysess = (PySSLSession *)value;
2902
2903 if (self->ctx->ctx != pysess->ctx->ctx) {
2904 PyErr_SetString(PyExc_ValueError,
2905 "Session refers to a different SSLContext.");
2906 return -1;
2907 }
2908 if (self->socket_type != PY_SSL_CLIENT) {
2909 PyErr_SetString(PyExc_ValueError,
2910 "Cannot set session for server-side SSLSocket.");
2911 return -1;
2912 }
Christian Heimes66dc33b2017-05-23 16:02:02 -07002913 if (SSL_is_init_finished(self->ssl)) {
Christian Heimes99a65702016-09-10 23:44:53 +02002914 PyErr_SetString(PyExc_ValueError,
2915 "Cannot set session after handshake.");
2916 return -1;
2917 }
2918#ifdef OPENSSL_VERSION_1_1
2919 /* duplicate session */
2920 if ((session = _ssl_session_dup(pysess->session)) == NULL) {
2921 return -1;
2922 }
2923 result = SSL_set_session(self->ssl, session);
2924 /* free duplicate, SSL_set_session() bumps ref count */
2925 SSL_SESSION_free(session);
2926#else
2927 result = SSL_set_session(self->ssl, pysess->session);
2928#endif
2929 if (result == 0) {
2930 _setSSLError(NULL, 0, __FILE__, __LINE__);
2931 return -1;
2932 }
2933 return 0;
2934}
2935
2936PyDoc_STRVAR(PySSL_set_session_doc,
2937"_setter_session(session)\n\
2938\
2939Get / set SSLSession.");
2940
2941static PyObject *
2942PySSL_get_session_reused(PySSLSocket *self, void *closure) {
2943 if (SSL_session_reused(self->ssl)) {
2944 Py_RETURN_TRUE;
2945 } else {
2946 Py_RETURN_FALSE;
2947 }
2948}
2949
2950PyDoc_STRVAR(PySSL_get_session_reused_doc,
2951"Was the client session reused during handshake?");
2952
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002953static PyGetSetDef ssl_getsetlist[] = {
2954 {"context", (getter) PySSL_get_context,
2955 (setter) PySSL_set_context, PySSL_set_context_doc},
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002956 {"server_side", (getter) PySSL_get_server_side, NULL,
2957 PySSL_get_server_side_doc},
2958 {"server_hostname", (getter) PySSL_get_server_hostname, NULL,
2959 PySSL_get_server_hostname_doc},
2960 {"owner", (getter) PySSL_get_owner, (setter) PySSL_set_owner,
2961 PySSL_get_owner_doc},
Christian Heimes99a65702016-09-10 23:44:53 +02002962 {"session", (getter) PySSL_get_session,
2963 (setter) PySSL_set_session, PySSL_set_session_doc},
2964 {"session_reused", (getter) PySSL_get_session_reused, NULL,
2965 PySSL_get_session_reused_doc},
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002966 {NULL}, /* sentinel */
2967};
2968
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002969static PyMethodDef PySSLMethods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002970 _SSL__SSLSOCKET_DO_HANDSHAKE_METHODDEF
2971 _SSL__SSLSOCKET_WRITE_METHODDEF
2972 _SSL__SSLSOCKET_READ_METHODDEF
2973 _SSL__SSLSOCKET_PENDING_METHODDEF
Christian Heimes141c5e82018-02-24 21:10:57 +01002974 _SSL__SSLSOCKET_GETPEERCERT_METHODDEF
2975 _SSL__SSLSOCKET_GET_CHANNEL_BINDING_METHODDEF
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002976 _SSL__SSLSOCKET_CIPHER_METHODDEF
2977 _SSL__SSLSOCKET_SHARED_CIPHERS_METHODDEF
2978 _SSL__SSLSOCKET_VERSION_METHODDEF
2979 _SSL__SSLSOCKET_SELECTED_NPN_PROTOCOL_METHODDEF
2980 _SSL__SSLSOCKET_SELECTED_ALPN_PROTOCOL_METHODDEF
2981 _SSL__SSLSOCKET_COMPRESSION_METHODDEF
2982 _SSL__SSLSOCKET_SHUTDOWN_METHODDEF
Christian Heimes9fb051f2018-09-23 08:32:31 +02002983 _SSL__SSLSOCKET_VERIFY_CLIENT_POST_HANDSHAKE_METHODDEF
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002984 {NULL, NULL}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002985};
2986
Antoine Pitrou152efa22010-05-16 18:19:27 +00002987static PyTypeObject PySSLSocket_Type = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002988 PyVarObject_HEAD_INIT(NULL, 0)
Antoine Pitrou152efa22010-05-16 18:19:27 +00002989 "_ssl._SSLSocket", /*tp_name*/
2990 sizeof(PySSLSocket), /*tp_basicsize*/
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002991 0, /*tp_itemsize*/
2992 /* methods */
2993 (destructor)PySSL_dealloc, /*tp_dealloc*/
Jeroen Demeyer530f5062019-05-31 04:13:39 +02002994 0, /*tp_vectorcall_offset*/
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002995 0, /*tp_getattr*/
2996 0, /*tp_setattr*/
Jeroen Demeyer530f5062019-05-31 04:13:39 +02002997 0, /*tp_as_async*/
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002998 0, /*tp_repr*/
2999 0, /*tp_as_number*/
3000 0, /*tp_as_sequence*/
3001 0, /*tp_as_mapping*/
3002 0, /*tp_hash*/
3003 0, /*tp_call*/
3004 0, /*tp_str*/
3005 0, /*tp_getattro*/
3006 0, /*tp_setattro*/
3007 0, /*tp_as_buffer*/
3008 Py_TPFLAGS_DEFAULT, /*tp_flags*/
3009 0, /*tp_doc*/
Christian Heimesc7f70692019-05-31 11:44:05 +02003010 (traverseproc) PySSL_traverse, /*tp_traverse*/
3011 (inquiry) PySSL_clear, /*tp_clear*/
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003012 0, /*tp_richcompare*/
3013 0, /*tp_weaklistoffset*/
3014 0, /*tp_iter*/
3015 0, /*tp_iternext*/
3016 PySSLMethods, /*tp_methods*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003017 0, /*tp_members*/
3018 ssl_getsetlist, /*tp_getset*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003019};
3020
Antoine Pitrou152efa22010-05-16 18:19:27 +00003021
3022/*
3023 * _SSLContext objects
3024 */
3025
Christian Heimes5fe668c2016-09-12 00:01:11 +02003026static int
Christian Heimes9fb051f2018-09-23 08:32:31 +02003027_set_verify_mode(PySSLContext *self, enum py_ssl_cert_requirements n)
Christian Heimes5fe668c2016-09-12 00:01:11 +02003028{
3029 int mode;
3030 int (*verify_cb)(int, X509_STORE_CTX *) = NULL;
3031
3032 switch(n) {
3033 case PY_SSL_CERT_NONE:
3034 mode = SSL_VERIFY_NONE;
3035 break;
3036 case PY_SSL_CERT_OPTIONAL:
3037 mode = SSL_VERIFY_PEER;
3038 break;
3039 case PY_SSL_CERT_REQUIRED:
3040 mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
3041 break;
3042 default:
3043 PyErr_SetString(PyExc_ValueError,
3044 "invalid value for verify_mode");
3045 return -1;
3046 }
Christian Heimesf22c4cf2019-07-01 09:25:48 +02003047
3048 /* bpo-37428: newPySSLSocket() sets SSL_VERIFY_POST_HANDSHAKE flag for
3049 * server sockets and SSL_set_post_handshake_auth() for client. */
3050
Christian Heimes5fe668c2016-09-12 00:01:11 +02003051 /* keep current verify cb */
Christian Heimes9fb051f2018-09-23 08:32:31 +02003052 verify_cb = SSL_CTX_get_verify_callback(self->ctx);
3053 SSL_CTX_set_verify(self->ctx, mode, verify_cb);
Christian Heimes5fe668c2016-09-12 00:01:11 +02003054 return 0;
3055}
3056
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003057/*[clinic input]
3058@classmethod
3059_ssl._SSLContext.__new__
3060 protocol as proto_version: int
3061 /
3062[clinic start generated code]*/
3063
Antoine Pitrou152efa22010-05-16 18:19:27 +00003064static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003065_ssl__SSLContext_impl(PyTypeObject *type, int proto_version)
3066/*[clinic end generated code: output=2cf0d7a0741b6bd1 input=8d58a805b95fc534]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003067{
Antoine Pitrou152efa22010-05-16 18:19:27 +00003068 PySSLContext *self;
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01003069 long options;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003070 SSL_CTX *ctx = NULL;
Christian Heimes61d478c2018-01-27 15:51:38 +01003071 X509_VERIFY_PARAM *params;
Christian Heimes358cfd42016-09-10 22:43:48 +02003072 int result;
Berker Peksagdfcb0412016-04-14 16:48:48 +03003073#if defined(SSL_MODE_RELEASE_BUFFERS)
Benjamin Peterson3b1a8b32016-01-07 21:37:37 -08003074 unsigned long libver;
Berker Peksagdfcb0412016-04-14 16:48:48 +03003075#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00003076
Antoine Pitrou152efa22010-05-16 18:19:27 +00003077 PySSL_BEGIN_ALLOW_THREADS
Miss Islington (bot)a6694432020-05-16 01:33:42 -07003078 switch(proto_version) {
3079#if defined(SSL3_VERSION) && !defined(OPENSSL_NO_SSL3)
3080 case PY_SSL_VERSION_SSL3:
Antoine Pitrou152efa22010-05-16 18:19:27 +00003081 ctx = SSL_CTX_new(SSLv3_method());
Miss Islington (bot)a6694432020-05-16 01:33:42 -07003082 break;
Benjamin Petersone32467c2014-12-05 21:59:35 -05003083#endif
Miss Islington (bot)a6694432020-05-16 01:33:42 -07003084#if defined(TLS1_VERSION) && !defined(OPENSSL_NO_TLS1)
3085 case PY_SSL_VERSION_TLS1:
3086 ctx = SSL_CTX_new(TLSv1_method());
3087 break;
Victor Stinner3de49192011-05-09 00:42:58 +02003088#endif
Miss Islington (bot)a6694432020-05-16 01:33:42 -07003089#if defined(TLS1_1_VERSION) && !defined(OPENSSL_NO_TLS1_1)
3090 case PY_SSL_VERSION_TLS1_1:
3091 ctx = SSL_CTX_new(TLSv1_1_method());
3092 break;
3093#endif
3094#if defined(TLS1_2_VERSION) && !defined(OPENSSL_NO_TLS1_2)
3095 case PY_SSL_VERSION_TLS1_2:
3096 ctx = SSL_CTX_new(TLSv1_2_method());
3097 break;
3098#endif
3099 case PY_SSL_VERSION_TLS:
3100 /* SSLv23 */
Christian Heimes598894f2016-09-05 23:19:05 +02003101 ctx = SSL_CTX_new(TLS_method());
Miss Islington (bot)a6694432020-05-16 01:33:42 -07003102 break;
3103 case PY_SSL_VERSION_TLS_CLIENT:
Christian Heimes5fe668c2016-09-12 00:01:11 +02003104 ctx = SSL_CTX_new(TLS_client_method());
Miss Islington (bot)a6694432020-05-16 01:33:42 -07003105 break;
3106 case PY_SSL_VERSION_TLS_SERVER:
Christian Heimes5fe668c2016-09-12 00:01:11 +02003107 ctx = SSL_CTX_new(TLS_server_method());
Miss Islington (bot)a6694432020-05-16 01:33:42 -07003108 break;
3109 default:
Antoine Pitrou152efa22010-05-16 18:19:27 +00003110 proto_version = -1;
Miss Islington (bot)a6694432020-05-16 01:33:42 -07003111 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003112 PySSL_END_ALLOW_THREADS
3113
3114 if (proto_version == -1) {
3115 PyErr_SetString(PyExc_ValueError,
Miss Islington (bot)a6694432020-05-16 01:33:42 -07003116 "invalid or unsupported protocol version");
Antoine Pitrou152efa22010-05-16 18:19:27 +00003117 return NULL;
3118 }
3119 if (ctx == NULL) {
Christian Heimes17c9ac92017-09-07 14:14:00 -07003120 _setSSLError(NULL, 0, __FILE__, __LINE__);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003121 return NULL;
3122 }
3123
3124 assert(type != NULL && type->tp_alloc != NULL);
3125 self = (PySSLContext *) type->tp_alloc(type, 0);
3126 if (self == NULL) {
3127 SSL_CTX_free(ctx);
3128 return NULL;
3129 }
3130 self->ctx = ctx;
Christian Heimes61d478c2018-01-27 15:51:38 +01003131 self->hostflags = X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS;
Christian Heimes11a14932018-02-24 02:35:08 +01003132 self->protocol = proto_version;
Christian Heimesc7f70692019-05-31 11:44:05 +02003133 self->msg_cb = NULL;
3134#ifdef HAVE_OPENSSL_KEYLOG
3135 self->keylog_filename = NULL;
3136 self->keylog_bio = NULL;
3137#endif
Christian Heimes29eab552018-02-25 12:31:33 +01003138#if HAVE_NPN
Christian Heimes5cb31c92012-09-20 12:42:54 +02003139 self->npn_protocols = NULL;
3140#endif
Christian Heimes29eab552018-02-25 12:31:33 +01003141#if HAVE_ALPN
Benjamin Petersoncca27322015-01-23 16:35:37 -05003142 self->alpn_protocols = NULL;
3143#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003144#ifndef OPENSSL_NO_TLSEXT
Christian Heimes11a14932018-02-24 02:35:08 +01003145 self->set_sni_cb = NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003146#endif
Christian Heimes1aa9a752013-12-02 02:41:19 +01003147 /* Don't check host name by default */
Christian Heimes5fe668c2016-09-12 00:01:11 +02003148 if (proto_version == PY_SSL_VERSION_TLS_CLIENT) {
3149 self->check_hostname = 1;
Christian Heimes9fb051f2018-09-23 08:32:31 +02003150 if (_set_verify_mode(self, PY_SSL_CERT_REQUIRED) == -1) {
Christian Heimes5fe668c2016-09-12 00:01:11 +02003151 Py_DECREF(self);
3152 return NULL;
3153 }
3154 } else {
3155 self->check_hostname = 0;
Christian Heimes9fb051f2018-09-23 08:32:31 +02003156 if (_set_verify_mode(self, PY_SSL_CERT_NONE) == -1) {
Christian Heimes5fe668c2016-09-12 00:01:11 +02003157 Py_DECREF(self);
3158 return NULL;
3159 }
3160 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003161 /* Defaults */
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01003162 options = SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
3163 if (proto_version != PY_SSL_VERSION_SSL2)
3164 options |= SSL_OP_NO_SSLv2;
Benjamin Petersona9dcdab2015-11-11 22:38:41 -08003165 if (proto_version != PY_SSL_VERSION_SSL3)
3166 options |= SSL_OP_NO_SSLv3;
Christian Heimes358cfd42016-09-10 22:43:48 +02003167 /* Minimal security flags for server and client side context.
3168 * Client sockets ignore server-side parameters. */
3169#ifdef SSL_OP_NO_COMPRESSION
3170 options |= SSL_OP_NO_COMPRESSION;
3171#endif
3172#ifdef SSL_OP_CIPHER_SERVER_PREFERENCE
3173 options |= SSL_OP_CIPHER_SERVER_PREFERENCE;
3174#endif
3175#ifdef SSL_OP_SINGLE_DH_USE
3176 options |= SSL_OP_SINGLE_DH_USE;
3177#endif
3178#ifdef SSL_OP_SINGLE_ECDH_USE
3179 options |= SSL_OP_SINGLE_ECDH_USE;
3180#endif
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01003181 SSL_CTX_set_options(self->ctx, options);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003182
Semen Zhydenko1295e112017-10-15 21:28:31 +02003183 /* A bare minimum cipher list without completely broken cipher suites.
Christian Heimes358cfd42016-09-10 22:43:48 +02003184 * It's far from perfect but gives users a better head start. */
3185 if (proto_version != PY_SSL_VERSION_SSL2) {
Christian Heimes892d66e2018-01-29 14:10:18 +01003186#if PY_SSL_DEFAULT_CIPHERS == 2
3187 /* stick to OpenSSL's default settings */
3188 result = 1;
3189#else
3190 result = SSL_CTX_set_cipher_list(ctx, PY_SSL_DEFAULT_CIPHER_STRING);
3191#endif
Christian Heimes358cfd42016-09-10 22:43:48 +02003192 } else {
3193 /* SSLv2 needs MD5 */
3194 result = SSL_CTX_set_cipher_list(ctx, "HIGH:!aNULL:!eNULL");
3195 }
3196 if (result == 0) {
3197 Py_DECREF(self);
3198 ERR_clear_error();
3199 PyErr_SetString(PySSLErrorObject,
3200 "No cipher can be selected.");
3201 return NULL;
3202 }
3203
Benjamin Peterson3b1a8b32016-01-07 21:37:37 -08003204#if defined(SSL_MODE_RELEASE_BUFFERS)
3205 /* Set SSL_MODE_RELEASE_BUFFERS. This potentially greatly reduces memory
3206 usage for no cost at all. However, don't do this for OpenSSL versions
3207 between 1.0.1 and 1.0.1h or 1.0.0 and 1.0.0m, which are affected by CVE
3208 2014-0198. I can't find exactly which beta fixed this CVE, so be
3209 conservative and assume it wasn't fixed until release. We do this check
3210 at runtime to avoid problems from the dynamic linker.
3211 See #25672 for more on this. */
3212 libver = SSLeay();
3213 if (!(libver >= 0x10001000UL && libver < 0x1000108fUL) &&
3214 !(libver >= 0x10000000UL && libver < 0x100000dfUL)) {
3215 SSL_CTX_set_mode(self->ctx, SSL_MODE_RELEASE_BUFFERS);
3216 }
3217#endif
3218
3219
Donald Stufft8ae264c2017-03-02 11:45:29 -05003220#if !defined(OPENSSL_NO_ECDH) && !defined(OPENSSL_VERSION_1_1)
Antoine Pitrou0bebbc32014-03-22 18:13:50 +01003221 /* Allow automatic ECDH curve selection (on OpenSSL 1.0.2+), or use
3222 prime256v1 by default. This is Apache mod_ssl's initialization
Christian Heimes598894f2016-09-05 23:19:05 +02003223 policy, so we should be safe. OpenSSL 1.1 has it enabled by default.
3224 */
Donald Stufft8ae264c2017-03-02 11:45:29 -05003225#if defined(SSL_CTX_set_ecdh_auto)
Antoine Pitrou0bebbc32014-03-22 18:13:50 +01003226 SSL_CTX_set_ecdh_auto(self->ctx, 1);
3227#else
3228 {
3229 EC_KEY *key = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
3230 SSL_CTX_set_tmp_ecdh(self->ctx, key);
3231 EC_KEY_free(key);
3232 }
3233#endif
3234#endif
3235
Antoine Pitroufc113ee2010-10-13 12:46:13 +00003236#define SID_CTX "Python"
3237 SSL_CTX_set_session_id_context(self->ctx, (const unsigned char *) SID_CTX,
3238 sizeof(SID_CTX));
3239#undef SID_CTX
3240
Christian Heimes61d478c2018-01-27 15:51:38 +01003241 params = SSL_CTX_get0_param(self->ctx);
Benjamin Petersonfdb19712015-03-04 22:11:12 -05003242#ifdef X509_V_FLAG_TRUSTED_FIRST
Christian Heimes61d478c2018-01-27 15:51:38 +01003243 /* Improve trust chain building when cross-signed intermediate
3244 certificates are present. See https://bugs.python.org/issue23476. */
3245 X509_VERIFY_PARAM_set_flags(params, X509_V_FLAG_TRUSTED_FIRST);
Benjamin Petersonfdb19712015-03-04 22:11:12 -05003246#endif
Christian Heimes61d478c2018-01-27 15:51:38 +01003247 X509_VERIFY_PARAM_set_hostflags(params, self->hostflags);
Benjamin Petersonfdb19712015-03-04 22:11:12 -05003248
Christian Heimes9fb051f2018-09-23 08:32:31 +02003249#ifdef TLS1_3_VERSION
3250 self->post_handshake_auth = 0;
3251 SSL_CTX_set_post_handshake_auth(self->ctx, self->post_handshake_auth);
3252#endif
3253
Antoine Pitrou152efa22010-05-16 18:19:27 +00003254 return (PyObject *)self;
3255}
3256
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003257static int
3258context_traverse(PySSLContext *self, visitproc visit, void *arg)
3259{
3260#ifndef OPENSSL_NO_TLSEXT
Christian Heimes11a14932018-02-24 02:35:08 +01003261 Py_VISIT(self->set_sni_cb);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003262#endif
Christian Heimesc7f70692019-05-31 11:44:05 +02003263 Py_VISIT(self->msg_cb);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003264 return 0;
3265}
3266
3267static int
3268context_clear(PySSLContext *self)
3269{
3270#ifndef OPENSSL_NO_TLSEXT
Christian Heimes11a14932018-02-24 02:35:08 +01003271 Py_CLEAR(self->set_sni_cb);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003272#endif
Christian Heimesc7f70692019-05-31 11:44:05 +02003273 Py_CLEAR(self->msg_cb);
3274#ifdef HAVE_OPENSSL_KEYLOG
3275 Py_CLEAR(self->keylog_filename);
3276 if (self->keylog_bio != NULL) {
3277 PySSL_BEGIN_ALLOW_THREADS
3278 BIO_free_all(self->keylog_bio);
3279 PySSL_END_ALLOW_THREADS
3280 self->keylog_bio = NULL;
3281 }
3282#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003283 return 0;
3284}
3285
Antoine Pitrou152efa22010-05-16 18:19:27 +00003286static void
3287context_dealloc(PySSLContext *self)
3288{
INADA Naokia6296d32017-08-24 14:55:17 +09003289 /* bpo-31095: UnTrack is needed before calling any callbacks */
3290 PyObject_GC_UnTrack(self);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003291 context_clear(self);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003292 SSL_CTX_free(self->ctx);
Christian Heimes29eab552018-02-25 12:31:33 +01003293#if HAVE_NPN
Benjamin Petersoncca27322015-01-23 16:35:37 -05003294 PyMem_FREE(self->npn_protocols);
3295#endif
Christian Heimes29eab552018-02-25 12:31:33 +01003296#if HAVE_ALPN
Benjamin Petersoncca27322015-01-23 16:35:37 -05003297 PyMem_FREE(self->alpn_protocols);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003298#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00003299 Py_TYPE(self)->tp_free(self);
3300}
3301
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003302/*[clinic input]
3303_ssl._SSLContext.set_ciphers
3304 cipherlist: str
3305 /
3306[clinic start generated code]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003307
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003308static PyObject *
3309_ssl__SSLContext_set_ciphers_impl(PySSLContext *self, const char *cipherlist)
3310/*[clinic end generated code: output=3a3162f3557c0f3f input=a7ac931b9f3ca7fc]*/
3311{
3312 int ret = SSL_CTX_set_cipher_list(self->ctx, cipherlist);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003313 if (ret == 0) {
Antoine Pitrou65ec8ae2010-05-16 19:56:32 +00003314 /* Clearing the error queue is necessary on some OpenSSL versions,
3315 otherwise the error will be reported again when another SSL call
3316 is done. */
3317 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00003318 PyErr_SetString(PySSLErrorObject,
3319 "No cipher can be selected.");
3320 return NULL;
3321 }
3322 Py_RETURN_NONE;
3323}
3324
Christian Heimes25bfcd52016-09-06 00:04:45 +02003325#if OPENSSL_VERSION_NUMBER >= 0x10002000UL
3326/*[clinic input]
3327_ssl._SSLContext.get_ciphers
3328[clinic start generated code]*/
3329
3330static PyObject *
3331_ssl__SSLContext_get_ciphers_impl(PySSLContext *self)
3332/*[clinic end generated code: output=a56e4d68a406dfc4 input=a2aadc9af89b79c5]*/
3333{
3334 SSL *ssl = NULL;
3335 STACK_OF(SSL_CIPHER) *sk = NULL;
Christian Heimes99a65702016-09-10 23:44:53 +02003336 const SSL_CIPHER *cipher;
Christian Heimes25bfcd52016-09-06 00:04:45 +02003337 int i=0;
3338 PyObject *result = NULL, *dct;
3339
3340 ssl = SSL_new(self->ctx);
3341 if (ssl == NULL) {
3342 _setSSLError(NULL, 0, __FILE__, __LINE__);
3343 goto exit;
3344 }
3345 sk = SSL_get_ciphers(ssl);
3346
3347 result = PyList_New(sk_SSL_CIPHER_num(sk));
3348 if (result == NULL) {
3349 goto exit;
3350 }
3351
3352 for (i = 0; i < sk_SSL_CIPHER_num(sk); i++) {
3353 cipher = sk_SSL_CIPHER_value(sk, i);
3354 dct = cipher_to_dict(cipher);
3355 if (dct == NULL) {
3356 Py_CLEAR(result);
3357 goto exit;
3358 }
3359 PyList_SET_ITEM(result, i, dct);
3360 }
3361
3362 exit:
3363 if (ssl != NULL)
3364 SSL_free(ssl);
3365 return result;
3366
3367}
3368#endif
3369
3370
Christian Heimes29eab552018-02-25 12:31:33 +01003371#if HAVE_NPN || HAVE_ALPN
Benjamin Petersoncca27322015-01-23 16:35:37 -05003372static int
Benjamin Peterson88615022015-01-23 17:30:26 -05003373do_protocol_selection(int alpn, unsigned char **out, unsigned char *outlen,
3374 const unsigned char *server_protocols, unsigned int server_protocols_len,
3375 const unsigned char *client_protocols, unsigned int client_protocols_len)
Benjamin Petersoncca27322015-01-23 16:35:37 -05003376{
Benjamin Peterson88615022015-01-23 17:30:26 -05003377 int ret;
3378 if (client_protocols == NULL) {
3379 client_protocols = (unsigned char *)"";
3380 client_protocols_len = 0;
3381 }
3382 if (server_protocols == NULL) {
3383 server_protocols = (unsigned char *)"";
3384 server_protocols_len = 0;
Benjamin Petersoncca27322015-01-23 16:35:37 -05003385 }
3386
Benjamin Peterson88615022015-01-23 17:30:26 -05003387 ret = SSL_select_next_proto(out, outlen,
3388 server_protocols, server_protocols_len,
3389 client_protocols, client_protocols_len);
3390 if (alpn && ret != OPENSSL_NPN_NEGOTIATED)
3391 return SSL_TLSEXT_ERR_NOACK;
Benjamin Petersoncca27322015-01-23 16:35:37 -05003392
3393 return SSL_TLSEXT_ERR_OK;
3394}
Melvyn Sopacuab2d096b2017-09-04 23:35:15 +02003395#endif
Benjamin Petersoncca27322015-01-23 16:35:37 -05003396
Christian Heimes29eab552018-02-25 12:31:33 +01003397#if HAVE_NPN
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003398/* this callback gets passed to SSL_CTX_set_next_protos_advertise_cb */
3399static int
Victor Stinner4569cd52013-06-23 14:58:43 +02003400_advertiseNPN_cb(SSL *s,
3401 const unsigned char **data, unsigned int *len,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003402 void *args)
3403{
3404 PySSLContext *ssl_ctx = (PySSLContext *) args;
3405
3406 if (ssl_ctx->npn_protocols == NULL) {
Benjamin Petersoncca27322015-01-23 16:35:37 -05003407 *data = (unsigned char *)"";
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003408 *len = 0;
3409 } else {
Benjamin Petersoncca27322015-01-23 16:35:37 -05003410 *data = ssl_ctx->npn_protocols;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003411 *len = ssl_ctx->npn_protocols_len;
3412 }
3413
3414 return SSL_TLSEXT_ERR_OK;
3415}
3416/* this callback gets passed to SSL_CTX_set_next_proto_select_cb */
3417static int
Victor Stinner4569cd52013-06-23 14:58:43 +02003418_selectNPN_cb(SSL *s,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003419 unsigned char **out, unsigned char *outlen,
3420 const unsigned char *server, unsigned int server_len,
3421 void *args)
3422{
Benjamin Petersoncca27322015-01-23 16:35:37 -05003423 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Peterson88615022015-01-23 17:30:26 -05003424 return do_protocol_selection(0, out, outlen, server, server_len,
Benjamin Petersoncca27322015-01-23 16:35:37 -05003425 ctx->npn_protocols, ctx->npn_protocols_len);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003426}
3427#endif
3428
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003429/*[clinic input]
3430_ssl._SSLContext._set_npn_protocols
3431 protos: Py_buffer
3432 /
3433[clinic start generated code]*/
3434
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003435static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003436_ssl__SSLContext__set_npn_protocols_impl(PySSLContext *self,
3437 Py_buffer *protos)
3438/*[clinic end generated code: output=72b002c3324390c6 input=319fcb66abf95bd7]*/
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003439{
Christian Heimes29eab552018-02-25 12:31:33 +01003440#if HAVE_NPN
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003441 PyMem_Free(self->npn_protocols);
3442 self->npn_protocols = PyMem_Malloc(protos->len);
3443 if (self->npn_protocols == NULL)
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003444 return PyErr_NoMemory();
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003445 memcpy(self->npn_protocols, protos->buf, protos->len);
3446 self->npn_protocols_len = (int) protos->len;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003447
3448 /* set both server and client callbacks, because the context can
3449 * be used to create both types of sockets */
3450 SSL_CTX_set_next_protos_advertised_cb(self->ctx,
3451 _advertiseNPN_cb,
3452 self);
3453 SSL_CTX_set_next_proto_select_cb(self->ctx,
3454 _selectNPN_cb,
3455 self);
3456
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003457 Py_RETURN_NONE;
3458#else
3459 PyErr_SetString(PyExc_NotImplementedError,
3460 "The NPN extension requires OpenSSL 1.0.1 or later.");
3461 return NULL;
3462#endif
3463}
3464
Christian Heimes29eab552018-02-25 12:31:33 +01003465#if HAVE_ALPN
Benjamin Petersoncca27322015-01-23 16:35:37 -05003466static int
3467_selectALPN_cb(SSL *s,
3468 const unsigned char **out, unsigned char *outlen,
3469 const unsigned char *client_protocols, unsigned int client_protocols_len,
3470 void *args)
3471{
3472 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Peterson88615022015-01-23 17:30:26 -05003473 return do_protocol_selection(1, (unsigned char **)out, outlen,
3474 ctx->alpn_protocols, ctx->alpn_protocols_len,
3475 client_protocols, client_protocols_len);
Benjamin Petersoncca27322015-01-23 16:35:37 -05003476}
3477#endif
3478
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003479/*[clinic input]
3480_ssl._SSLContext._set_alpn_protocols
3481 protos: Py_buffer
3482 /
3483[clinic start generated code]*/
3484
Benjamin Petersoncca27322015-01-23 16:35:37 -05003485static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003486_ssl__SSLContext__set_alpn_protocols_impl(PySSLContext *self,
3487 Py_buffer *protos)
3488/*[clinic end generated code: output=87599a7f76651a9b input=9bba964595d519be]*/
Benjamin Petersoncca27322015-01-23 16:35:37 -05003489{
Christian Heimes29eab552018-02-25 12:31:33 +01003490#if HAVE_ALPN
Victor Stinner5a615592017-09-14 01:10:30 -07003491 if ((size_t)protos->len > UINT_MAX) {
Segev Finer5cff6372017-07-27 01:19:17 +03003492 PyErr_Format(PyExc_OverflowError,
Serhiy Storchakad53fe5f2019-03-13 22:59:55 +02003493 "protocols longer than %u bytes", UINT_MAX);
Segev Finer5cff6372017-07-27 01:19:17 +03003494 return NULL;
3495 }
3496
Benjamin Petersoncca27322015-01-23 16:35:37 -05003497 PyMem_FREE(self->alpn_protocols);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003498 self->alpn_protocols = PyMem_Malloc(protos->len);
Benjamin Petersoncca27322015-01-23 16:35:37 -05003499 if (!self->alpn_protocols)
3500 return PyErr_NoMemory();
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003501 memcpy(self->alpn_protocols, protos->buf, protos->len);
Segev Finer5cff6372017-07-27 01:19:17 +03003502 self->alpn_protocols_len = (unsigned int)protos->len;
Benjamin Petersoncca27322015-01-23 16:35:37 -05003503
3504 if (SSL_CTX_set_alpn_protos(self->ctx, self->alpn_protocols, self->alpn_protocols_len))
3505 return PyErr_NoMemory();
3506 SSL_CTX_set_alpn_select_cb(self->ctx, _selectALPN_cb, self);
3507
Benjamin Petersoncca27322015-01-23 16:35:37 -05003508 Py_RETURN_NONE;
3509#else
3510 PyErr_SetString(PyExc_NotImplementedError,
3511 "The ALPN extension requires OpenSSL 1.0.2 or later.");
3512 return NULL;
3513#endif
3514}
3515
Antoine Pitrou152efa22010-05-16 18:19:27 +00003516static PyObject *
3517get_verify_mode(PySSLContext *self, void *c)
3518{
Christian Heimes9fb051f2018-09-23 08:32:31 +02003519 /* ignore SSL_VERIFY_CLIENT_ONCE and SSL_VERIFY_POST_HANDSHAKE */
3520 int mask = (SSL_VERIFY_NONE | SSL_VERIFY_PEER |
3521 SSL_VERIFY_FAIL_IF_NO_PEER_CERT);
3522 switch (SSL_CTX_get_verify_mode(self->ctx) & mask) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003523 case SSL_VERIFY_NONE:
3524 return PyLong_FromLong(PY_SSL_CERT_NONE);
3525 case SSL_VERIFY_PEER:
3526 return PyLong_FromLong(PY_SSL_CERT_OPTIONAL);
3527 case SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT:
3528 return PyLong_FromLong(PY_SSL_CERT_REQUIRED);
3529 }
3530 PyErr_SetString(PySSLErrorObject,
3531 "invalid return value from SSL_CTX_get_verify_mode");
3532 return NULL;
3533}
3534
3535static int
3536set_verify_mode(PySSLContext *self, PyObject *arg, void *c)
3537{
Christian Heimes5fe668c2016-09-12 00:01:11 +02003538 int n;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003539 if (!PyArg_Parse(arg, "i", &n))
3540 return -1;
Christian Heimes5fe668c2016-09-12 00:01:11 +02003541 if (n == PY_SSL_CERT_NONE && self->check_hostname) {
Christian Heimes1aa9a752013-12-02 02:41:19 +01003542 PyErr_SetString(PyExc_ValueError,
3543 "Cannot set verify_mode to CERT_NONE when "
3544 "check_hostname is enabled.");
3545 return -1;
3546 }
Christian Heimes9fb051f2018-09-23 08:32:31 +02003547 return _set_verify_mode(self, n);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003548}
3549
3550static PyObject *
Christian Heimes22587792013-11-21 23:56:13 +01003551get_verify_flags(PySSLContext *self, void *c)
3552{
Christian Heimes598894f2016-09-05 23:19:05 +02003553 X509_VERIFY_PARAM *param;
Christian Heimes22587792013-11-21 23:56:13 +01003554 unsigned long flags;
3555
Christian Heimes61d478c2018-01-27 15:51:38 +01003556 param = SSL_CTX_get0_param(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02003557 flags = X509_VERIFY_PARAM_get_flags(param);
Christian Heimes22587792013-11-21 23:56:13 +01003558 return PyLong_FromUnsignedLong(flags);
3559}
3560
3561static int
3562set_verify_flags(PySSLContext *self, PyObject *arg, void *c)
3563{
Christian Heimes598894f2016-09-05 23:19:05 +02003564 X509_VERIFY_PARAM *param;
Christian Heimes22587792013-11-21 23:56:13 +01003565 unsigned long new_flags, flags, set, clear;
3566
3567 if (!PyArg_Parse(arg, "k", &new_flags))
3568 return -1;
Christian Heimes61d478c2018-01-27 15:51:38 +01003569 param = SSL_CTX_get0_param(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02003570 flags = X509_VERIFY_PARAM_get_flags(param);
Christian Heimes22587792013-11-21 23:56:13 +01003571 clear = flags & ~new_flags;
3572 set = ~flags & new_flags;
3573 if (clear) {
Christian Heimes598894f2016-09-05 23:19:05 +02003574 if (!X509_VERIFY_PARAM_clear_flags(param, clear)) {
Christian Heimes22587792013-11-21 23:56:13 +01003575 _setSSLError(NULL, 0, __FILE__, __LINE__);
3576 return -1;
3577 }
3578 }
3579 if (set) {
Christian Heimes598894f2016-09-05 23:19:05 +02003580 if (!X509_VERIFY_PARAM_set_flags(param, set)) {
Christian Heimes22587792013-11-21 23:56:13 +01003581 _setSSLError(NULL, 0, __FILE__, __LINE__);
3582 return -1;
3583 }
3584 }
3585 return 0;
3586}
3587
Christian Heimes698dde12018-02-27 11:54:43 +01003588/* Getter and setter for protocol version */
3589#if defined(SSL_CTRL_GET_MAX_PROTO_VERSION)
3590
3591
3592static int
3593set_min_max_proto_version(PySSLContext *self, PyObject *arg, int what)
3594{
3595 long v;
3596 int result;
3597
3598 if (!PyArg_Parse(arg, "l", &v))
3599 return -1;
3600 if (v > INT_MAX) {
3601 PyErr_SetString(PyExc_OverflowError, "Option is too long");
3602 return -1;
3603 }
3604
3605 switch(self->protocol) {
3606 case PY_SSL_VERSION_TLS_CLIENT: /* fall through */
3607 case PY_SSL_VERSION_TLS_SERVER: /* fall through */
3608 case PY_SSL_VERSION_TLS:
3609 break;
3610 default:
3611 PyErr_SetString(
3612 PyExc_ValueError,
3613 "The context's protocol doesn't support modification of "
3614 "highest and lowest version."
3615 );
3616 return -1;
3617 }
3618
3619 if (what == 0) {
3620 switch(v) {
3621 case PY_PROTO_MINIMUM_SUPPORTED:
3622 v = 0;
3623 break;
3624 case PY_PROTO_MAXIMUM_SUPPORTED:
3625 /* Emulate max for set_min_proto_version */
3626 v = PY_PROTO_MAXIMUM_AVAILABLE;
3627 break;
3628 default:
3629 break;
3630 }
3631 result = SSL_CTX_set_min_proto_version(self->ctx, v);
3632 }
3633 else {
3634 switch(v) {
3635 case PY_PROTO_MAXIMUM_SUPPORTED:
3636 v = 0;
3637 break;
3638 case PY_PROTO_MINIMUM_SUPPORTED:
3639 /* Emulate max for set_min_proto_version */
3640 v = PY_PROTO_MINIMUM_AVAILABLE;
3641 break;
3642 default:
3643 break;
3644 }
3645 result = SSL_CTX_set_max_proto_version(self->ctx, v);
3646 }
3647 if (result == 0) {
3648 PyErr_Format(PyExc_ValueError,
3649 "Unsupported protocol version 0x%x", v);
3650 return -1;
3651 }
3652 return 0;
3653}
3654
3655static PyObject *
3656get_minimum_version(PySSLContext *self, void *c)
3657{
3658 int v = SSL_CTX_ctrl(self->ctx, SSL_CTRL_GET_MIN_PROTO_VERSION, 0, NULL);
3659 if (v == 0) {
3660 v = PY_PROTO_MINIMUM_SUPPORTED;
3661 }
3662 return PyLong_FromLong(v);
3663}
3664
3665static int
3666set_minimum_version(PySSLContext *self, PyObject *arg, void *c)
3667{
3668 return set_min_max_proto_version(self, arg, 0);
3669}
3670
3671static PyObject *
3672get_maximum_version(PySSLContext *self, void *c)
3673{
3674 int v = SSL_CTX_ctrl(self->ctx, SSL_CTRL_GET_MAX_PROTO_VERSION, 0, NULL);
3675 if (v == 0) {
3676 v = PY_PROTO_MAXIMUM_SUPPORTED;
3677 }
3678 return PyLong_FromLong(v);
3679}
3680
3681static int
3682set_maximum_version(PySSLContext *self, PyObject *arg, void *c)
3683{
3684 return set_min_max_proto_version(self, arg, 1);
3685}
3686#endif /* SSL_CTRL_GET_MAX_PROTO_VERSION */
3687
Christian Heimes78c7d522019-06-03 21:00:10 +02003688#if (OPENSSL_VERSION_NUMBER >= 0x10101000L) && !defined(LIBRESSL_VERSION_NUMBER)
3689static PyObject *
3690get_num_tickets(PySSLContext *self, void *c)
3691{
Miss Islington (bot)bbad6952019-07-09 05:42:49 -07003692 return PyLong_FromSize_t(SSL_CTX_get_num_tickets(self->ctx));
Christian Heimes78c7d522019-06-03 21:00:10 +02003693}
3694
3695static int
3696set_num_tickets(PySSLContext *self, PyObject *arg, void *c)
3697{
3698 long num;
3699 if (!PyArg_Parse(arg, "l", &num))
3700 return -1;
3701 if (num < 0) {
3702 PyErr_SetString(PyExc_ValueError, "value must be non-negative");
3703 return -1;
3704 }
3705 if (self->protocol != PY_SSL_VERSION_TLS_SERVER) {
3706 PyErr_SetString(PyExc_ValueError,
3707 "SSLContext is not a server context.");
3708 return -1;
3709 }
3710 if (SSL_CTX_set_num_tickets(self->ctx, num) != 1) {
3711 PyErr_SetString(PyExc_ValueError, "failed to set num tickets.");
3712 return -1;
3713 }
3714 return 0;
3715}
3716
3717PyDoc_STRVAR(PySSLContext_num_tickets_doc,
3718"Control the number of TLSv1.3 session tickets");
3719#endif /* OpenSSL 1.1.1 */
3720
Christian Heimes22587792013-11-21 23:56:13 +01003721static PyObject *
Antoine Pitroub5218772010-05-21 09:56:06 +00003722get_options(PySSLContext *self, void *c)
3723{
3724 return PyLong_FromLong(SSL_CTX_get_options(self->ctx));
3725}
3726
3727static int
3728set_options(PySSLContext *self, PyObject *arg, void *c)
3729{
3730 long new_opts, opts, set, clear;
3731 if (!PyArg_Parse(arg, "l", &new_opts))
3732 return -1;
3733 opts = SSL_CTX_get_options(self->ctx);
3734 clear = opts & ~new_opts;
3735 set = ~opts & new_opts;
3736 if (clear) {
3737#ifdef HAVE_SSL_CTX_CLEAR_OPTIONS
3738 SSL_CTX_clear_options(self->ctx, clear);
3739#else
3740 PyErr_SetString(PyExc_ValueError,
3741 "can't clear options before OpenSSL 0.9.8m");
3742 return -1;
3743#endif
3744 }
3745 if (set)
3746 SSL_CTX_set_options(self->ctx, set);
3747 return 0;
3748}
3749
Christian Heimes1aa9a752013-12-02 02:41:19 +01003750static PyObject *
Christian Heimes61d478c2018-01-27 15:51:38 +01003751get_host_flags(PySSLContext *self, void *c)
3752{
3753 return PyLong_FromUnsignedLong(self->hostflags);
3754}
3755
3756static int
3757set_host_flags(PySSLContext *self, PyObject *arg, void *c)
3758{
3759 X509_VERIFY_PARAM *param;
3760 unsigned int new_flags = 0;
3761
3762 if (!PyArg_Parse(arg, "I", &new_flags))
3763 return -1;
3764
3765 param = SSL_CTX_get0_param(self->ctx);
3766 self->hostflags = new_flags;
3767 X509_VERIFY_PARAM_set_hostflags(param, new_flags);
3768 return 0;
3769}
3770
3771static PyObject *
Christian Heimes1aa9a752013-12-02 02:41:19 +01003772get_check_hostname(PySSLContext *self, void *c)
3773{
3774 return PyBool_FromLong(self->check_hostname);
3775}
3776
3777static int
3778set_check_hostname(PySSLContext *self, PyObject *arg, void *c)
3779{
3780 int check_hostname;
3781 if (!PyArg_Parse(arg, "p", &check_hostname))
3782 return -1;
3783 if (check_hostname &&
3784 SSL_CTX_get_verify_mode(self->ctx) == SSL_VERIFY_NONE) {
Christian Heimese82c0342017-09-15 20:29:57 +02003785 /* check_hostname = True sets verify_mode = CERT_REQUIRED */
Christian Heimes9fb051f2018-09-23 08:32:31 +02003786 if (_set_verify_mode(self, PY_SSL_CERT_REQUIRED) == -1) {
Christian Heimese82c0342017-09-15 20:29:57 +02003787 return -1;
3788 }
Christian Heimes1aa9a752013-12-02 02:41:19 +01003789 }
3790 self->check_hostname = check_hostname;
3791 return 0;
3792}
3793
Christian Heimes11a14932018-02-24 02:35:08 +01003794static PyObject *
Christian Heimes9fb051f2018-09-23 08:32:31 +02003795get_post_handshake_auth(PySSLContext *self, void *c) {
3796#if TLS1_3_VERSION
3797 return PyBool_FromLong(self->post_handshake_auth);
3798#else
3799 Py_RETURN_NONE;
3800#endif
3801}
3802
3803#if TLS1_3_VERSION
3804static int
3805set_post_handshake_auth(PySSLContext *self, PyObject *arg, void *c) {
Zackery Spytz842acaa2018-12-17 07:52:45 -07003806 if (arg == NULL) {
3807 PyErr_SetString(PyExc_AttributeError, "cannot delete attribute");
3808 return -1;
3809 }
Christian Heimes9fb051f2018-09-23 08:32:31 +02003810 int pha = PyObject_IsTrue(arg);
3811
3812 if (pha == -1) {
3813 return -1;
3814 }
3815 self->post_handshake_auth = pha;
3816
Christian Heimesf22c4cf2019-07-01 09:25:48 +02003817 /* bpo-37428: newPySSLSocket() sets SSL_VERIFY_POST_HANDSHAKE flag for
3818 * server sockets and SSL_set_post_handshake_auth() for client. */
Christian Heimes9fb051f2018-09-23 08:32:31 +02003819
3820 return 0;
3821}
3822#endif
3823
3824static PyObject *
Christian Heimes11a14932018-02-24 02:35:08 +01003825get_protocol(PySSLContext *self, void *c) {
3826 return PyLong_FromLong(self->protocol);
3827}
Christian Heimes1aa9a752013-12-02 02:41:19 +01003828
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003829typedef struct {
3830 PyThreadState *thread_state;
3831 PyObject *callable;
3832 char *password;
Victor Stinner9ee02032013-06-23 15:08:23 +02003833 int size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003834 int error;
3835} _PySSLPasswordInfo;
3836
3837static int
3838_pwinfo_set(_PySSLPasswordInfo *pw_info, PyObject* password,
3839 const char *bad_type_error)
3840{
3841 /* Set the password and size fields of a _PySSLPasswordInfo struct
3842 from a unicode, bytes, or byte array object.
3843 The password field will be dynamically allocated and must be freed
3844 by the caller */
3845 PyObject *password_bytes = NULL;
3846 const char *data = NULL;
3847 Py_ssize_t size;
3848
3849 if (PyUnicode_Check(password)) {
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03003850 password_bytes = PyUnicode_AsUTF8String(password);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003851 if (!password_bytes) {
3852 goto error;
3853 }
3854 data = PyBytes_AS_STRING(password_bytes);
3855 size = PyBytes_GET_SIZE(password_bytes);
3856 } else if (PyBytes_Check(password)) {
3857 data = PyBytes_AS_STRING(password);
3858 size = PyBytes_GET_SIZE(password);
3859 } else if (PyByteArray_Check(password)) {
3860 data = PyByteArray_AS_STRING(password);
3861 size = PyByteArray_GET_SIZE(password);
3862 } else {
3863 PyErr_SetString(PyExc_TypeError, bad_type_error);
3864 goto error;
3865 }
3866
Victor Stinner9ee02032013-06-23 15:08:23 +02003867 if (size > (Py_ssize_t)INT_MAX) {
3868 PyErr_Format(PyExc_ValueError,
3869 "password cannot be longer than %d bytes", INT_MAX);
3870 goto error;
3871 }
3872
Victor Stinner11ebff22013-07-07 17:07:52 +02003873 PyMem_Free(pw_info->password);
3874 pw_info->password = PyMem_Malloc(size);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003875 if (!pw_info->password) {
3876 PyErr_SetString(PyExc_MemoryError,
3877 "unable to allocate password buffer");
3878 goto error;
3879 }
3880 memcpy(pw_info->password, data, size);
Victor Stinner9ee02032013-06-23 15:08:23 +02003881 pw_info->size = (int)size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003882
3883 Py_XDECREF(password_bytes);
3884 return 1;
3885
3886error:
3887 Py_XDECREF(password_bytes);
3888 return 0;
3889}
3890
3891static int
3892_password_callback(char *buf, int size, int rwflag, void *userdata)
3893{
3894 _PySSLPasswordInfo *pw_info = (_PySSLPasswordInfo*) userdata;
3895 PyObject *fn_ret = NULL;
3896
3897 PySSL_END_ALLOW_THREADS_S(pw_info->thread_state);
3898
3899 if (pw_info->callable) {
Victor Stinnerf17c3de2016-12-06 18:46:19 +01003900 fn_ret = _PyObject_CallNoArg(pw_info->callable);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003901 if (!fn_ret) {
3902 /* TODO: It would be nice to move _ctypes_add_traceback() into the
3903 core python API, so we could use it to add a frame here */
3904 goto error;
3905 }
3906
3907 if (!_pwinfo_set(pw_info, fn_ret,
3908 "password callback must return a string")) {
3909 goto error;
3910 }
3911 Py_CLEAR(fn_ret);
3912 }
3913
3914 if (pw_info->size > size) {
3915 PyErr_Format(PyExc_ValueError,
3916 "password cannot be longer than %d bytes", size);
3917 goto error;
3918 }
3919
3920 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
3921 memcpy(buf, pw_info->password, pw_info->size);
3922 return pw_info->size;
3923
3924error:
3925 Py_XDECREF(fn_ret);
3926 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
3927 pw_info->error = 1;
3928 return -1;
3929}
3930
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003931/*[clinic input]
3932_ssl._SSLContext.load_cert_chain
3933 certfile: object
Serhiy Storchakad322abb2019-09-14 13:31:50 +03003934 keyfile: object = None
3935 password: object = None
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003936
3937[clinic start generated code]*/
3938
Antoine Pitroub5218772010-05-21 09:56:06 +00003939static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003940_ssl__SSLContext_load_cert_chain_impl(PySSLContext *self, PyObject *certfile,
3941 PyObject *keyfile, PyObject *password)
Serhiy Storchakad322abb2019-09-14 13:31:50 +03003942/*[clinic end generated code: output=9480bc1c380e2095 input=30bc7e967ea01a58]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003943{
Antoine Pitrou152efa22010-05-16 18:19:27 +00003944 PyObject *certfile_bytes = NULL, *keyfile_bytes = NULL;
Christian Heimes598894f2016-09-05 23:19:05 +02003945 pem_password_cb *orig_passwd_cb = SSL_CTX_get_default_passwd_cb(self->ctx);
3946 void *orig_passwd_userdata = SSL_CTX_get_default_passwd_cb_userdata(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003947 _PySSLPasswordInfo pw_info = { NULL, NULL, NULL, 0, 0 };
Antoine Pitrou152efa22010-05-16 18:19:27 +00003948 int r;
3949
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003950 errno = 0;
Antoine Pitrou67e8e562010-09-01 20:55:41 +00003951 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00003952 if (keyfile == Py_None)
3953 keyfile = NULL;
3954 if (!PyUnicode_FSConverter(certfile, &certfile_bytes)) {
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03003955 if (PyErr_ExceptionMatches(PyExc_TypeError)) {
3956 PyErr_SetString(PyExc_TypeError,
3957 "certfile should be a valid filesystem path");
3958 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003959 return NULL;
3960 }
3961 if (keyfile && !PyUnicode_FSConverter(keyfile, &keyfile_bytes)) {
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03003962 if (PyErr_ExceptionMatches(PyExc_TypeError)) {
3963 PyErr_SetString(PyExc_TypeError,
3964 "keyfile should be a valid filesystem path");
3965 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003966 goto error;
3967 }
Serhiy Storchakad322abb2019-09-14 13:31:50 +03003968 if (password != Py_None) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003969 if (PyCallable_Check(password)) {
3970 pw_info.callable = password;
3971 } else if (!_pwinfo_set(&pw_info, password,
3972 "password should be a string or callable")) {
3973 goto error;
3974 }
3975 SSL_CTX_set_default_passwd_cb(self->ctx, _password_callback);
3976 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, &pw_info);
3977 }
3978 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003979 r = SSL_CTX_use_certificate_chain_file(self->ctx,
3980 PyBytes_AS_STRING(certfile_bytes));
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003981 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003982 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003983 if (pw_info.error) {
3984 ERR_clear_error();
3985 /* the password callback has already set the error information */
3986 }
3987 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00003988 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03003989 PyErr_SetFromErrno(PyExc_OSError);
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003990 }
3991 else {
3992 _setSSLError(NULL, 0, __FILE__, __LINE__);
3993 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003994 goto error;
3995 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003996 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou9c254862011-04-03 18:15:34 +02003997 r = SSL_CTX_use_PrivateKey_file(self->ctx,
Antoine Pitrou152efa22010-05-16 18:19:27 +00003998 PyBytes_AS_STRING(keyfile ? keyfile_bytes : certfile_bytes),
3999 SSL_FILETYPE_PEM);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02004000 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
4001 Py_CLEAR(keyfile_bytes);
4002 Py_CLEAR(certfile_bytes);
Antoine Pitrou152efa22010-05-16 18:19:27 +00004003 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02004004 if (pw_info.error) {
4005 ERR_clear_error();
4006 /* the password callback has already set the error information */
4007 }
4008 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00004009 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03004010 PyErr_SetFromErrno(PyExc_OSError);
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00004011 }
4012 else {
4013 _setSSLError(NULL, 0, __FILE__, __LINE__);
4014 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02004015 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004016 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02004017 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00004018 r = SSL_CTX_check_private_key(self->ctx);
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) {
4021 _setSSLError(NULL, 0, __FILE__, __LINE__);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02004022 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004023 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02004024 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
4025 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02004026 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00004027 Py_RETURN_NONE;
4028
4029error:
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02004030 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
4031 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02004032 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00004033 Py_XDECREF(keyfile_bytes);
4034 Py_XDECREF(certfile_bytes);
4035 return NULL;
4036}
4037
Christian Heimesefff7062013-11-21 03:35:02 +01004038/* internal helper function, returns -1 on error
4039 */
4040static int
4041_add_ca_certs(PySSLContext *self, void *data, Py_ssize_t len,
4042 int filetype)
4043{
4044 BIO *biobuf = NULL;
4045 X509_STORE *store;
4046 int retval = 0, err, loaded = 0;
4047
4048 assert(filetype == SSL_FILETYPE_ASN1 || filetype == SSL_FILETYPE_PEM);
4049
4050 if (len <= 0) {
4051 PyErr_SetString(PyExc_ValueError,
4052 "Empty certificate data");
4053 return -1;
4054 } else if (len > INT_MAX) {
4055 PyErr_SetString(PyExc_OverflowError,
4056 "Certificate data is too long.");
4057 return -1;
4058 }
4059
Christian Heimes1dbf61f2013-11-22 00:34:18 +01004060 biobuf = BIO_new_mem_buf(data, (int)len);
Christian Heimesefff7062013-11-21 03:35:02 +01004061 if (biobuf == NULL) {
4062 _setSSLError("Can't allocate buffer", 0, __FILE__, __LINE__);
4063 return -1;
4064 }
4065
4066 store = SSL_CTX_get_cert_store(self->ctx);
4067 assert(store != NULL);
4068
4069 while (1) {
4070 X509 *cert = NULL;
4071 int r;
4072
4073 if (filetype == SSL_FILETYPE_ASN1) {
4074 cert = d2i_X509_bio(biobuf, NULL);
4075 } else {
4076 cert = PEM_read_bio_X509(biobuf, NULL,
Christian Heimes598894f2016-09-05 23:19:05 +02004077 SSL_CTX_get_default_passwd_cb(self->ctx),
4078 SSL_CTX_get_default_passwd_cb_userdata(self->ctx)
4079 );
Christian Heimesefff7062013-11-21 03:35:02 +01004080 }
4081 if (cert == NULL) {
4082 break;
4083 }
4084 r = X509_STORE_add_cert(store, cert);
4085 X509_free(cert);
4086 if (!r) {
4087 err = ERR_peek_last_error();
4088 if ((ERR_GET_LIB(err) == ERR_LIB_X509) &&
4089 (ERR_GET_REASON(err) == X509_R_CERT_ALREADY_IN_HASH_TABLE)) {
4090 /* cert already in hash table, not an error */
4091 ERR_clear_error();
4092 } else {
4093 break;
4094 }
4095 }
4096 loaded++;
4097 }
4098
4099 err = ERR_peek_last_error();
4100 if ((filetype == SSL_FILETYPE_ASN1) &&
4101 (loaded > 0) &&
4102 (ERR_GET_LIB(err) == ERR_LIB_ASN1) &&
4103 (ERR_GET_REASON(err) == ASN1_R_HEADER_TOO_LONG)) {
4104 /* EOF ASN1 file, not an error */
4105 ERR_clear_error();
4106 retval = 0;
4107 } else if ((filetype == SSL_FILETYPE_PEM) &&
4108 (loaded > 0) &&
4109 (ERR_GET_LIB(err) == ERR_LIB_PEM) &&
4110 (ERR_GET_REASON(err) == PEM_R_NO_START_LINE)) {
4111 /* EOF PEM file, not an error */
4112 ERR_clear_error();
4113 retval = 0;
4114 } else {
4115 _setSSLError(NULL, 0, __FILE__, __LINE__);
4116 retval = -1;
4117 }
4118
4119 BIO_free(biobuf);
4120 return retval;
4121}
4122
4123
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004124/*[clinic input]
4125_ssl._SSLContext.load_verify_locations
Serhiy Storchakad322abb2019-09-14 13:31:50 +03004126 cafile: object = None
4127 capath: object = None
4128 cadata: object = None
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004129
4130[clinic start generated code]*/
4131
Antoine Pitrou152efa22010-05-16 18:19:27 +00004132static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004133_ssl__SSLContext_load_verify_locations_impl(PySSLContext *self,
4134 PyObject *cafile,
4135 PyObject *capath,
4136 PyObject *cadata)
Serhiy Storchakad322abb2019-09-14 13:31:50 +03004137/*[clinic end generated code: output=454c7e41230ca551 input=42ecfe258233e194]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004138{
Antoine Pitrou152efa22010-05-16 18:19:27 +00004139 PyObject *cafile_bytes = NULL, *capath_bytes = NULL;
4140 const char *cafile_buf = NULL, *capath_buf = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01004141 int r = 0, ok = 1;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004142
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00004143 errno = 0;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004144 if (cafile == Py_None)
4145 cafile = NULL;
4146 if (capath == Py_None)
4147 capath = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01004148 if (cadata == Py_None)
4149 cadata = NULL;
4150
4151 if (cafile == NULL && capath == NULL && cadata == NULL) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00004152 PyErr_SetString(PyExc_TypeError,
Christian Heimesefff7062013-11-21 03:35:02 +01004153 "cafile, capath and cadata cannot be all omitted");
4154 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004155 }
4156 if (cafile && !PyUnicode_FSConverter(cafile, &cafile_bytes)) {
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03004157 if (PyErr_ExceptionMatches(PyExc_TypeError)) {
4158 PyErr_SetString(PyExc_TypeError,
4159 "cafile should be a valid filesystem path");
4160 }
Christian Heimesefff7062013-11-21 03:35:02 +01004161 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004162 }
4163 if (capath && !PyUnicode_FSConverter(capath, &capath_bytes)) {
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03004164 if (PyErr_ExceptionMatches(PyExc_TypeError)) {
4165 PyErr_SetString(PyExc_TypeError,
4166 "capath should be a valid filesystem path");
4167 }
Christian Heimesefff7062013-11-21 03:35:02 +01004168 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004169 }
Christian Heimesefff7062013-11-21 03:35:02 +01004170
4171 /* validata cadata type and load cadata */
4172 if (cadata) {
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03004173 if (PyUnicode_Check(cadata)) {
4174 PyObject *cadata_ascii = PyUnicode_AsASCIIString(cadata);
4175 if (cadata_ascii == NULL) {
4176 if (PyErr_ExceptionMatches(PyExc_UnicodeEncodeError)) {
4177 goto invalid_cadata;
4178 }
4179 goto error;
4180 }
4181 r = _add_ca_certs(self,
4182 PyBytes_AS_STRING(cadata_ascii),
4183 PyBytes_GET_SIZE(cadata_ascii),
4184 SSL_FILETYPE_PEM);
4185 Py_DECREF(cadata_ascii);
4186 if (r == -1) {
4187 goto error;
4188 }
4189 }
4190 else if (PyObject_CheckBuffer(cadata)) {
4191 Py_buffer buf;
4192 if (PyObject_GetBuffer(cadata, &buf, PyBUF_SIMPLE)) {
4193 goto error;
4194 }
Christian Heimesefff7062013-11-21 03:35:02 +01004195 if (!PyBuffer_IsContiguous(&buf, 'C') || buf.ndim > 1) {
4196 PyBuffer_Release(&buf);
4197 PyErr_SetString(PyExc_TypeError,
4198 "cadata should be a contiguous buffer with "
4199 "a single dimension");
4200 goto error;
4201 }
4202 r = _add_ca_certs(self, buf.buf, buf.len, SSL_FILETYPE_ASN1);
4203 PyBuffer_Release(&buf);
4204 if (r == -1) {
4205 goto error;
4206 }
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03004207 }
4208 else {
4209 invalid_cadata:
4210 PyErr_SetString(PyExc_TypeError,
4211 "cadata should be an ASCII string or a "
4212 "bytes-like object");
4213 goto error;
Christian Heimesefff7062013-11-21 03:35:02 +01004214 }
4215 }
4216
4217 /* load cafile or capath */
4218 if (cafile || capath) {
4219 if (cafile)
4220 cafile_buf = PyBytes_AS_STRING(cafile_bytes);
4221 if (capath)
4222 capath_buf = PyBytes_AS_STRING(capath_bytes);
4223 PySSL_BEGIN_ALLOW_THREADS
4224 r = SSL_CTX_load_verify_locations(self->ctx, cafile_buf, capath_buf);
4225 PySSL_END_ALLOW_THREADS
4226 if (r != 1) {
4227 ok = 0;
4228 if (errno != 0) {
4229 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03004230 PyErr_SetFromErrno(PyExc_OSError);
Christian Heimesefff7062013-11-21 03:35:02 +01004231 }
4232 else {
4233 _setSSLError(NULL, 0, __FILE__, __LINE__);
4234 }
4235 goto error;
4236 }
4237 }
4238 goto end;
4239
4240 error:
4241 ok = 0;
4242 end:
Antoine Pitrou152efa22010-05-16 18:19:27 +00004243 Py_XDECREF(cafile_bytes);
4244 Py_XDECREF(capath_bytes);
Christian Heimesefff7062013-11-21 03:35:02 +01004245 if (ok) {
4246 Py_RETURN_NONE;
4247 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00004248 return NULL;
4249 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00004250}
4251
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004252/*[clinic input]
4253_ssl._SSLContext.load_dh_params
4254 path as filepath: object
4255 /
4256
4257[clinic start generated code]*/
4258
Antoine Pitrou152efa22010-05-16 18:19:27 +00004259static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004260_ssl__SSLContext_load_dh_params(PySSLContext *self, PyObject *filepath)
4261/*[clinic end generated code: output=1c8e57a38e055af0 input=c8871f3c796ae1d6]*/
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004262{
4263 FILE *f;
4264 DH *dh;
4265
Victor Stinnerdaf45552013-08-28 00:53:59 +02004266 f = _Py_fopen_obj(filepath, "rb");
Victor Stinnere42ccd22015-03-18 01:39:23 +01004267 if (f == NULL)
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004268 return NULL;
Victor Stinnere42ccd22015-03-18 01:39:23 +01004269
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004270 errno = 0;
4271 PySSL_BEGIN_ALLOW_THREADS
4272 dh = PEM_read_DHparams(f, NULL, NULL, NULL);
Antoine Pitrou457a2292013-01-12 21:43:45 +01004273 fclose(f);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004274 PySSL_END_ALLOW_THREADS
4275 if (dh == NULL) {
4276 if (errno != 0) {
4277 ERR_clear_error();
4278 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
4279 }
4280 else {
4281 _setSSLError(NULL, 0, __FILE__, __LINE__);
4282 }
4283 return NULL;
4284 }
4285 if (SSL_CTX_set_tmp_dh(self->ctx, dh) == 0)
4286 _setSSLError(NULL, 0, __FILE__, __LINE__);
4287 DH_free(dh);
4288 Py_RETURN_NONE;
4289}
4290
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004291/*[clinic input]
4292_ssl._SSLContext._wrap_socket
4293 sock: object(subclass_of="PySocketModule.Sock_Type")
4294 server_side: int
4295 server_hostname as hostname_obj: object = None
Christian Heimes141c5e82018-02-24 21:10:57 +01004296 *
4297 owner: object = None
4298 session: object = None
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004299
4300[clinic start generated code]*/
4301
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004302static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004303_ssl__SSLContext__wrap_socket_impl(PySSLContext *self, PyObject *sock,
Christian Heimes141c5e82018-02-24 21:10:57 +01004304 int server_side, PyObject *hostname_obj,
4305 PyObject *owner, PyObject *session)
4306/*[clinic end generated code: output=f103f238633940b4 input=957d5006183d1894]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004307{
Antoine Pitroud5323212010-10-22 18:19:07 +00004308 char *hostname = NULL;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004309 PyObject *res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004310
Antoine Pitroud5323212010-10-22 18:19:07 +00004311 /* server_hostname is either None (or absent), or to be encoded
Christian Heimesd02ac252018-03-25 12:36:13 +02004312 as IDN A-label (ASCII str) without NULL bytes. */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004313 if (hostname_obj != Py_None) {
Christian Heimes11a14932018-02-24 02:35:08 +01004314 if (!PyArg_Parse(hostname_obj, "es", "ascii", &hostname))
Antoine Pitroud5323212010-10-22 18:19:07 +00004315 return NULL;
Antoine Pitroud5323212010-10-22 18:19:07 +00004316 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00004317
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004318 res = (PyObject *) newPySSLSocket(self, (PySocketSockObject *)sock,
4319 server_side, hostname,
Christian Heimes141c5e82018-02-24 21:10:57 +01004320 owner, session,
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004321 NULL, NULL);
Antoine Pitroud5323212010-10-22 18:19:07 +00004322 if (hostname != NULL)
4323 PyMem_Free(hostname);
4324 return res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004325}
4326
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004327/*[clinic input]
4328_ssl._SSLContext._wrap_bio
4329 incoming: object(subclass_of="&PySSLMemoryBIO_Type", type="PySSLMemoryBIO *")
4330 outgoing: object(subclass_of="&PySSLMemoryBIO_Type", type="PySSLMemoryBIO *")
4331 server_side: int
4332 server_hostname as hostname_obj: object = None
Christian Heimes141c5e82018-02-24 21:10:57 +01004333 *
4334 owner: object = None
4335 session: object = None
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004336
4337[clinic start generated code]*/
4338
Antoine Pitroub0182c82010-10-12 20:09:02 +00004339static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004340_ssl__SSLContext__wrap_bio_impl(PySSLContext *self, PySSLMemoryBIO *incoming,
4341 PySSLMemoryBIO *outgoing, int server_side,
Christian Heimes141c5e82018-02-24 21:10:57 +01004342 PyObject *hostname_obj, PyObject *owner,
4343 PyObject *session)
4344/*[clinic end generated code: output=5c5d6d9b41f99332 input=8cf22f4d586ac56a]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004345{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004346 char *hostname = NULL;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004347 PyObject *res;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004348
4349 /* server_hostname is either None (or absent), or to be encoded
Christian Heimesd02ac252018-03-25 12:36:13 +02004350 as IDN A-label (ASCII str) without NULL bytes. */
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004351 if (hostname_obj != Py_None) {
Christian Heimes11a14932018-02-24 02:35:08 +01004352 if (!PyArg_Parse(hostname_obj, "es", "ascii", &hostname))
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004353 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004354 }
4355
4356 res = (PyObject *) newPySSLSocket(self, NULL, server_side, hostname,
Christian Heimes141c5e82018-02-24 21:10:57 +01004357 owner, session,
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004358 incoming, outgoing);
4359
4360 PyMem_Free(hostname);
4361 return res;
4362}
4363
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004364/*[clinic input]
4365_ssl._SSLContext.session_stats
4366[clinic start generated code]*/
4367
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004368static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004369_ssl__SSLContext_session_stats_impl(PySSLContext *self)
4370/*[clinic end generated code: output=0d96411c42893bfb input=7e0a81fb11102c8b]*/
Antoine Pitroub0182c82010-10-12 20:09:02 +00004371{
4372 int r;
4373 PyObject *value, *stats = PyDict_New();
4374 if (!stats)
4375 return NULL;
4376
4377#define ADD_STATS(SSL_NAME, KEY_NAME) \
4378 value = PyLong_FromLong(SSL_CTX_sess_ ## SSL_NAME (self->ctx)); \
4379 if (value == NULL) \
4380 goto error; \
4381 r = PyDict_SetItemString(stats, KEY_NAME, value); \
4382 Py_DECREF(value); \
4383 if (r < 0) \
4384 goto error;
4385
4386 ADD_STATS(number, "number");
4387 ADD_STATS(connect, "connect");
4388 ADD_STATS(connect_good, "connect_good");
4389 ADD_STATS(connect_renegotiate, "connect_renegotiate");
4390 ADD_STATS(accept, "accept");
4391 ADD_STATS(accept_good, "accept_good");
4392 ADD_STATS(accept_renegotiate, "accept_renegotiate");
4393 ADD_STATS(accept, "accept");
4394 ADD_STATS(hits, "hits");
4395 ADD_STATS(misses, "misses");
4396 ADD_STATS(timeouts, "timeouts");
4397 ADD_STATS(cache_full, "cache_full");
4398
4399#undef ADD_STATS
4400
4401 return stats;
4402
4403error:
4404 Py_DECREF(stats);
4405 return NULL;
4406}
4407
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004408/*[clinic input]
4409_ssl._SSLContext.set_default_verify_paths
4410[clinic start generated code]*/
4411
Antoine Pitrou664c2d12010-11-17 20:29:42 +00004412static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004413_ssl__SSLContext_set_default_verify_paths_impl(PySSLContext *self)
4414/*[clinic end generated code: output=0bee74e6e09deaaa input=35f3408021463d74]*/
Antoine Pitrou664c2d12010-11-17 20:29:42 +00004415{
4416 if (!SSL_CTX_set_default_verify_paths(self->ctx)) {
4417 _setSSLError(NULL, 0, __FILE__, __LINE__);
4418 return NULL;
4419 }
4420 Py_RETURN_NONE;
4421}
4422
Antoine Pitrou501da612011-12-21 09:27:41 +01004423#ifndef OPENSSL_NO_ECDH
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004424/*[clinic input]
4425_ssl._SSLContext.set_ecdh_curve
4426 name: object
4427 /
4428
4429[clinic start generated code]*/
4430
Antoine Pitrou923df6f2011-12-19 17:16:51 +01004431static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004432_ssl__SSLContext_set_ecdh_curve(PySSLContext *self, PyObject *name)
4433/*[clinic end generated code: output=23022c196e40d7d2 input=c2bafb6f6e34726b]*/
Antoine Pitrou923df6f2011-12-19 17:16:51 +01004434{
4435 PyObject *name_bytes;
4436 int nid;
4437 EC_KEY *key;
4438
4439 if (!PyUnicode_FSConverter(name, &name_bytes))
4440 return NULL;
4441 assert(PyBytes_Check(name_bytes));
4442 nid = OBJ_sn2nid(PyBytes_AS_STRING(name_bytes));
4443 Py_DECREF(name_bytes);
4444 if (nid == 0) {
4445 PyErr_Format(PyExc_ValueError,
4446 "unknown elliptic curve name %R", name);
4447 return NULL;
4448 }
4449 key = EC_KEY_new_by_curve_name(nid);
4450 if (key == NULL) {
4451 _setSSLError(NULL, 0, __FILE__, __LINE__);
4452 return NULL;
4453 }
4454 SSL_CTX_set_tmp_ecdh(self->ctx, key);
4455 EC_KEY_free(key);
4456 Py_RETURN_NONE;
4457}
Antoine Pitrou501da612011-12-21 09:27:41 +01004458#endif
Antoine Pitrou923df6f2011-12-19 17:16:51 +01004459
Antoine Pitrou912fbff2013-03-30 16:29:32 +01004460#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004461static int
4462_servername_callback(SSL *s, int *al, void *args)
4463{
4464 int ret;
4465 PySSLContext *ssl_ctx = (PySSLContext *) args;
4466 PySSLSocket *ssl;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004467 PyObject *result;
4468 /* The high-level ssl.SSLSocket object */
4469 PyObject *ssl_socket;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004470 const char *servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
Stefan Krah20d60802013-01-17 17:07:17 +01004471 PyGILState_STATE gstate = PyGILState_Ensure();
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004472
Christian Heimes11a14932018-02-24 02:35:08 +01004473 if (ssl_ctx->set_sni_cb == NULL) {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004474 /* remove race condition in this the call back while if removing the
4475 * callback is in progress */
4476 PyGILState_Release(gstate);
Antoine Pitrou5dd12a52013-01-06 15:25:36 +01004477 return SSL_TLSEXT_ERR_OK;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004478 }
4479
4480 ssl = SSL_get_app_data(s);
4481 assert(PySSLSocket_Check(ssl));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004482
Serhiy Storchakaf51d7152015-11-02 14:40:41 +02004483 /* The servername callback expects an argument that represents the current
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004484 * SSL connection and that has a .context attribute that can be changed to
4485 * identify the requested hostname. Since the official API is the Python
4486 * level API we want to pass the callback a Python level object rather than
4487 * a _ssl.SSLSocket instance. If there's an "owner" (typically an
4488 * SSLObject) that will be passed. Otherwise if there's a socket then that
4489 * will be passed. If both do not exist only then the C-level object is
4490 * passed. */
4491 if (ssl->owner)
4492 ssl_socket = PyWeakref_GetObject(ssl->owner);
4493 else if (ssl->Socket)
4494 ssl_socket = PyWeakref_GetObject(ssl->Socket);
4495 else
4496 ssl_socket = (PyObject *) ssl;
4497
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004498 Py_INCREF(ssl_socket);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004499 if (ssl_socket == Py_None)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004500 goto error;
Victor Stinner7e001512013-06-25 00:44:31 +02004501
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004502 if (servername == NULL) {
Christian Heimes11a14932018-02-24 02:35:08 +01004503 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_sni_cb, ssl_socket,
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004504 Py_None, ssl_ctx, NULL);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004505 }
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004506 else {
Christian Heimes11a14932018-02-24 02:35:08 +01004507 PyObject *servername_bytes;
4508 PyObject *servername_str;
4509
4510 servername_bytes = PyBytes_FromString(servername);
4511 if (servername_bytes == NULL) {
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004512 PyErr_WriteUnraisable((PyObject *) ssl_ctx);
4513 goto error;
4514 }
Christian Heimes11a14932018-02-24 02:35:08 +01004515 /* server_hostname was encoded to an A-label by our caller; put it
4516 * back into a str object, but still as an A-label (bpo-28414)
4517 */
4518 servername_str = PyUnicode_FromEncodedObject(servername_bytes, "ascii", NULL);
4519 Py_DECREF(servername_bytes);
4520 if (servername_str == NULL) {
4521 PyErr_WriteUnraisable(servername_bytes);
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004522 goto error;
4523 }
Christian Heimes11a14932018-02-24 02:35:08 +01004524 result = PyObject_CallFunctionObjArgs(
4525 ssl_ctx->set_sni_cb, ssl_socket, servername_str,
4526 ssl_ctx, NULL);
4527 Py_DECREF(servername_str);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004528 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004529 Py_DECREF(ssl_socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004530
4531 if (result == NULL) {
Christian Heimes11a14932018-02-24 02:35:08 +01004532 PyErr_WriteUnraisable(ssl_ctx->set_sni_cb);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004533 *al = SSL_AD_HANDSHAKE_FAILURE;
4534 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
4535 }
4536 else {
Christian Heimes11a14932018-02-24 02:35:08 +01004537 /* Result may be None, a SSLContext or an integer
4538 * None and SSLContext are OK, integer or other values are an error.
4539 */
4540 if (result == Py_None) {
4541 ret = SSL_TLSEXT_ERR_OK;
4542 } else {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004543 *al = (int) PyLong_AsLong(result);
4544 if (PyErr_Occurred()) {
4545 PyErr_WriteUnraisable(result);
4546 *al = SSL_AD_INTERNAL_ERROR;
4547 }
4548 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
4549 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004550 Py_DECREF(result);
4551 }
4552
4553 PyGILState_Release(gstate);
4554 return ret;
4555
4556error:
4557 Py_DECREF(ssl_socket);
4558 *al = SSL_AD_INTERNAL_ERROR;
4559 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
4560 PyGILState_Release(gstate);
4561 return ret;
4562}
Antoine Pitroua5963382013-03-30 16:39:00 +01004563#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004564
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004565static PyObject *
Christian Heimes11a14932018-02-24 02:35:08 +01004566get_sni_callback(PySSLContext *self, void *c)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004567{
Christian Heimes11a14932018-02-24 02:35:08 +01004568 PyObject *cb = self->set_sni_cb;
4569 if (cb == NULL) {
4570 Py_RETURN_NONE;
4571 }
4572 Py_INCREF(cb);
4573 return cb;
4574}
4575
4576static int
4577set_sni_callback(PySSLContext *self, PyObject *arg, void *c)
4578{
4579 if (self->protocol == PY_SSL_VERSION_TLS_CLIENT) {
4580 PyErr_SetString(PyExc_ValueError,
4581 "sni_callback cannot be set on TLS_CLIENT context");
4582 return -1;
4583 }
Antoine Pitrou912fbff2013-03-30 16:29:32 +01004584#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Christian Heimes11a14932018-02-24 02:35:08 +01004585 Py_CLEAR(self->set_sni_cb);
4586 if (arg == Py_None) {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004587 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
4588 }
4589 else {
Christian Heimes11a14932018-02-24 02:35:08 +01004590 if (!PyCallable_Check(arg)) {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004591 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
4592 PyErr_SetString(PyExc_TypeError,
4593 "not a callable object");
Christian Heimes11a14932018-02-24 02:35:08 +01004594 return -1;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004595 }
Christian Heimes11a14932018-02-24 02:35:08 +01004596 Py_INCREF(arg);
4597 self->set_sni_cb = arg;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004598 SSL_CTX_set_tlsext_servername_callback(self->ctx, _servername_callback);
4599 SSL_CTX_set_tlsext_servername_arg(self->ctx, self);
4600 }
Christian Heimes11a14932018-02-24 02:35:08 +01004601 return 0;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004602#else
4603 PyErr_SetString(PyExc_NotImplementedError,
4604 "The TLS extension servername callback, "
4605 "SSL_CTX_set_tlsext_servername_callback, "
4606 "is not in the current OpenSSL library.");
Christian Heimes11a14932018-02-24 02:35:08 +01004607 return -1;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004608#endif
4609}
4610
Christian Heimes11a14932018-02-24 02:35:08 +01004611PyDoc_STRVAR(PySSLContext_sni_callback_doc,
4612"Set a callback that will be called when a server name is provided by the SSL/TLS client in the SNI extension.\n\
4613\n\
4614If the argument is None then the callback is disabled. The method is called\n\
4615with the SSLSocket, the server name as a string, and the SSLContext object.\n\
4616See RFC 6066 for details of the SNI extension.");
4617
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004618/*[clinic input]
4619_ssl._SSLContext.cert_store_stats
4620
4621Returns quantities of loaded X.509 certificates.
4622
4623X.509 certificates with a CA extension and certificate revocation lists
4624inside the context's cert store.
4625
4626NOTE: Certificates in a capath directory aren't loaded unless they have
4627been used at least once.
4628[clinic start generated code]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004629
4630static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004631_ssl__SSLContext_cert_store_stats_impl(PySSLContext *self)
4632/*[clinic end generated code: output=5f356f4d9cca874d input=eb40dd0f6d0e40cf]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004633{
4634 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02004635 STACK_OF(X509_OBJECT) *objs;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004636 X509_OBJECT *obj;
Christian Heimes598894f2016-09-05 23:19:05 +02004637 int x509 = 0, crl = 0, ca = 0, i;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004638
4639 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02004640 objs = X509_STORE_get0_objects(store);
4641 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
4642 obj = sk_X509_OBJECT_value(objs, i);
4643 switch (X509_OBJECT_get_type(obj)) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004644 case X509_LU_X509:
4645 x509++;
Christian Heimes598894f2016-09-05 23:19:05 +02004646 if (X509_check_ca(X509_OBJECT_get0_X509(obj))) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004647 ca++;
4648 }
4649 break;
4650 case X509_LU_CRL:
4651 crl++;
4652 break;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004653 default:
4654 /* Ignore X509_LU_FAIL, X509_LU_RETRY, X509_LU_PKEY.
4655 * As far as I can tell they are internal states and never
4656 * stored in a cert store */
4657 break;
4658 }
4659 }
4660 return Py_BuildValue("{sisisi}", "x509", x509, "crl", crl,
4661 "x509_ca", ca);
4662}
4663
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004664/*[clinic input]
4665_ssl._SSLContext.get_ca_certs
4666 binary_form: bool = False
4667
4668Returns a list of dicts with information of loaded CA certs.
4669
4670If the optional argument is True, returns a DER-encoded copy of the CA
4671certificate.
4672
4673NOTE: Certificates in a capath directory aren't loaded unless they have
4674been used at least once.
4675[clinic start generated code]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004676
4677static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004678_ssl__SSLContext_get_ca_certs_impl(PySSLContext *self, int binary_form)
4679/*[clinic end generated code: output=0d58f148f37e2938 input=6887b5a09b7f9076]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004680{
4681 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02004682 STACK_OF(X509_OBJECT) *objs;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004683 PyObject *ci = NULL, *rlist = NULL;
4684 int i;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004685
4686 if ((rlist = PyList_New(0)) == NULL) {
4687 return NULL;
4688 }
4689
4690 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02004691 objs = X509_STORE_get0_objects(store);
4692 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004693 X509_OBJECT *obj;
4694 X509 *cert;
4695
Christian Heimes598894f2016-09-05 23:19:05 +02004696 obj = sk_X509_OBJECT_value(objs, i);
4697 if (X509_OBJECT_get_type(obj) != X509_LU_X509) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004698 /* not a x509 cert */
4699 continue;
4700 }
4701 /* CA for any purpose */
Christian Heimes598894f2016-09-05 23:19:05 +02004702 cert = X509_OBJECT_get0_X509(obj);
Christian Heimes9a5395a2013-06-17 15:44:12 +02004703 if (!X509_check_ca(cert)) {
4704 continue;
4705 }
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004706 if (binary_form) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004707 ci = _certificate_to_der(cert);
4708 } else {
4709 ci = _decode_certificate(cert);
4710 }
4711 if (ci == NULL) {
4712 goto error;
4713 }
4714 if (PyList_Append(rlist, ci) == -1) {
4715 goto error;
4716 }
4717 Py_CLEAR(ci);
4718 }
4719 return rlist;
4720
4721 error:
4722 Py_XDECREF(ci);
4723 Py_XDECREF(rlist);
4724 return NULL;
4725}
4726
4727
Antoine Pitrou152efa22010-05-16 18:19:27 +00004728static PyGetSetDef context_getsetlist[] = {
Christian Heimes1aa9a752013-12-02 02:41:19 +01004729 {"check_hostname", (getter) get_check_hostname,
4730 (setter) set_check_hostname, NULL},
Christian Heimes61d478c2018-01-27 15:51:38 +01004731 {"_host_flags", (getter) get_host_flags,
4732 (setter) set_host_flags, NULL},
Christian Heimes698dde12018-02-27 11:54:43 +01004733#if SSL_CTRL_GET_MAX_PROTO_VERSION
4734 {"minimum_version", (getter) get_minimum_version,
4735 (setter) set_minimum_version, NULL},
4736 {"maximum_version", (getter) get_maximum_version,
4737 (setter) set_maximum_version, NULL},
4738#endif
Christian Heimesc7f70692019-05-31 11:44:05 +02004739#ifdef HAVE_OPENSSL_KEYLOG
4740 {"keylog_filename", (getter) _PySSLContext_get_keylog_filename,
4741 (setter) _PySSLContext_set_keylog_filename, NULL},
4742#endif
4743 {"_msg_callback", (getter) _PySSLContext_get_msg_callback,
4744 (setter) _PySSLContext_set_msg_callback, NULL},
Christian Heimes11a14932018-02-24 02:35:08 +01004745 {"sni_callback", (getter) get_sni_callback,
Christian Heimes698dde12018-02-27 11:54:43 +01004746 (setter) set_sni_callback, PySSLContext_sni_callback_doc},
Christian Heimes78c7d522019-06-03 21:00:10 +02004747#if (OPENSSL_VERSION_NUMBER >= 0x10101000L) && !defined(LIBRESSL_VERSION_NUMBER)
4748 {"num_tickets", (getter) get_num_tickets,
4749 (setter) set_num_tickets, PySSLContext_num_tickets_doc},
4750#endif
Antoine Pitroub5218772010-05-21 09:56:06 +00004751 {"options", (getter) get_options,
4752 (setter) set_options, NULL},
Christian Heimes9fb051f2018-09-23 08:32:31 +02004753 {"post_handshake_auth", (getter) get_post_handshake_auth,
4754#ifdef TLS1_3_VERSION
4755 (setter) set_post_handshake_auth,
4756#else
4757 NULL,
4758#endif
4759 NULL},
Christian Heimes11a14932018-02-24 02:35:08 +01004760 {"protocol", (getter) get_protocol,
4761 NULL, NULL},
Christian Heimes22587792013-11-21 23:56:13 +01004762 {"verify_flags", (getter) get_verify_flags,
4763 (setter) set_verify_flags, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00004764 {"verify_mode", (getter) get_verify_mode,
4765 (setter) set_verify_mode, NULL},
4766 {NULL}, /* sentinel */
4767};
4768
4769static struct PyMethodDef context_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004770 _SSL__SSLCONTEXT__WRAP_SOCKET_METHODDEF
4771 _SSL__SSLCONTEXT__WRAP_BIO_METHODDEF
4772 _SSL__SSLCONTEXT_SET_CIPHERS_METHODDEF
4773 _SSL__SSLCONTEXT__SET_ALPN_PROTOCOLS_METHODDEF
4774 _SSL__SSLCONTEXT__SET_NPN_PROTOCOLS_METHODDEF
4775 _SSL__SSLCONTEXT_LOAD_CERT_CHAIN_METHODDEF
4776 _SSL__SSLCONTEXT_LOAD_DH_PARAMS_METHODDEF
4777 _SSL__SSLCONTEXT_LOAD_VERIFY_LOCATIONS_METHODDEF
4778 _SSL__SSLCONTEXT_SESSION_STATS_METHODDEF
4779 _SSL__SSLCONTEXT_SET_DEFAULT_VERIFY_PATHS_METHODDEF
4780 _SSL__SSLCONTEXT_SET_ECDH_CURVE_METHODDEF
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004781 _SSL__SSLCONTEXT_CERT_STORE_STATS_METHODDEF
4782 _SSL__SSLCONTEXT_GET_CA_CERTS_METHODDEF
Christian Heimes25bfcd52016-09-06 00:04:45 +02004783 _SSL__SSLCONTEXT_GET_CIPHERS_METHODDEF
Antoine Pitrou152efa22010-05-16 18:19:27 +00004784 {NULL, NULL} /* sentinel */
4785};
4786
4787static PyTypeObject PySSLContext_Type = {
4788 PyVarObject_HEAD_INIT(NULL, 0)
4789 "_ssl._SSLContext", /*tp_name*/
4790 sizeof(PySSLContext), /*tp_basicsize*/
4791 0, /*tp_itemsize*/
4792 (destructor)context_dealloc, /*tp_dealloc*/
Jeroen Demeyer530f5062019-05-31 04:13:39 +02004793 0, /*tp_vectorcall_offset*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004794 0, /*tp_getattr*/
4795 0, /*tp_setattr*/
Jeroen Demeyer530f5062019-05-31 04:13:39 +02004796 0, /*tp_as_async*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004797 0, /*tp_repr*/
4798 0, /*tp_as_number*/
4799 0, /*tp_as_sequence*/
4800 0, /*tp_as_mapping*/
4801 0, /*tp_hash*/
4802 0, /*tp_call*/
4803 0, /*tp_str*/
4804 0, /*tp_getattro*/
4805 0, /*tp_setattro*/
4806 0, /*tp_as_buffer*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004807 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004808 0, /*tp_doc*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004809 (traverseproc) context_traverse, /*tp_traverse*/
4810 (inquiry) context_clear, /*tp_clear*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004811 0, /*tp_richcompare*/
4812 0, /*tp_weaklistoffset*/
4813 0, /*tp_iter*/
4814 0, /*tp_iternext*/
4815 context_methods, /*tp_methods*/
4816 0, /*tp_members*/
4817 context_getsetlist, /*tp_getset*/
4818 0, /*tp_base*/
4819 0, /*tp_dict*/
4820 0, /*tp_descr_get*/
4821 0, /*tp_descr_set*/
4822 0, /*tp_dictoffset*/
4823 0, /*tp_init*/
4824 0, /*tp_alloc*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004825 _ssl__SSLContext, /*tp_new*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004826};
4827
4828
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004829/*
4830 * MemoryBIO objects
4831 */
4832
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004833/*[clinic input]
4834@classmethod
4835_ssl.MemoryBIO.__new__
4836
4837[clinic start generated code]*/
4838
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004839static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004840_ssl_MemoryBIO_impl(PyTypeObject *type)
4841/*[clinic end generated code: output=8820a58db78330ac input=26d22e4909ecb1b5]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004842{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004843 BIO *bio;
4844 PySSLMemoryBIO *self;
4845
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004846 bio = BIO_new(BIO_s_mem());
4847 if (bio == NULL) {
4848 PyErr_SetString(PySSLErrorObject,
4849 "failed to allocate BIO");
4850 return NULL;
4851 }
4852 /* Since our BIO is non-blocking an empty read() does not indicate EOF,
4853 * just that no data is currently available. The SSL routines should retry
4854 * the read, which we can achieve by calling BIO_set_retry_read(). */
4855 BIO_set_retry_read(bio);
4856 BIO_set_mem_eof_return(bio, -1);
4857
4858 assert(type != NULL && type->tp_alloc != NULL);
4859 self = (PySSLMemoryBIO *) type->tp_alloc(type, 0);
4860 if (self == NULL) {
4861 BIO_free(bio);
4862 return NULL;
4863 }
4864 self->bio = bio;
4865 self->eof_written = 0;
4866
4867 return (PyObject *) self;
4868}
4869
4870static void
4871memory_bio_dealloc(PySSLMemoryBIO *self)
4872{
4873 BIO_free(self->bio);
4874 Py_TYPE(self)->tp_free(self);
4875}
4876
4877static PyObject *
4878memory_bio_get_pending(PySSLMemoryBIO *self, void *c)
4879{
Segev Finer5cff6372017-07-27 01:19:17 +03004880 return PyLong_FromSize_t(BIO_ctrl_pending(self->bio));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004881}
4882
4883PyDoc_STRVAR(PySSL_memory_bio_pending_doc,
4884"The number of bytes pending in the memory BIO.");
4885
4886static PyObject *
4887memory_bio_get_eof(PySSLMemoryBIO *self, void *c)
4888{
4889 return PyBool_FromLong((BIO_ctrl_pending(self->bio) == 0)
4890 && self->eof_written);
4891}
4892
4893PyDoc_STRVAR(PySSL_memory_bio_eof_doc,
4894"Whether the memory BIO is at EOF.");
4895
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004896/*[clinic input]
4897_ssl.MemoryBIO.read
4898 size as len: int = -1
4899 /
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004900
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004901Read up to size bytes from the memory BIO.
4902
4903If size is not specified, read the entire buffer.
4904If the return value is an empty bytes instance, this means either
4905EOF or that no data is available. Use the "eof" property to
4906distinguish between the two.
4907[clinic start generated code]*/
4908
4909static PyObject *
4910_ssl_MemoryBIO_read_impl(PySSLMemoryBIO *self, int len)
4911/*[clinic end generated code: output=a657aa1e79cd01b3 input=574d7be06a902366]*/
4912{
4913 int avail, nbytes;
4914 PyObject *result;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004915
Segev Finer5cff6372017-07-27 01:19:17 +03004916 avail = (int)Py_MIN(BIO_ctrl_pending(self->bio), INT_MAX);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004917 if ((len < 0) || (len > avail))
4918 len = avail;
4919
4920 result = PyBytes_FromStringAndSize(NULL, len);
4921 if ((result == NULL) || (len == 0))
4922 return result;
4923
4924 nbytes = BIO_read(self->bio, PyBytes_AS_STRING(result), len);
Zackery Spytz365ad2e2018-10-06 11:41:45 -06004925 if (nbytes < 0) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004926 Py_DECREF(result);
Zackery Spytz365ad2e2018-10-06 11:41:45 -06004927 _setSSLError(NULL, 0, __FILE__, __LINE__);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004928 return NULL;
4929 }
4930
Zackery Spytz365ad2e2018-10-06 11:41:45 -06004931 /* There should never be any short reads but check anyway. */
4932 if (nbytes < len) {
4933 _PyBytes_Resize(&result, nbytes);
4934 }
4935
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004936 return result;
4937}
4938
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004939/*[clinic input]
4940_ssl.MemoryBIO.write
4941 b: Py_buffer
4942 /
4943
4944Writes the bytes b into the memory BIO.
4945
4946Returns the number of bytes written.
4947[clinic start generated code]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004948
4949static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004950_ssl_MemoryBIO_write_impl(PySSLMemoryBIO *self, Py_buffer *b)
4951/*[clinic end generated code: output=156ec59110d75935 input=e45757b3e17c4808]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004952{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004953 int nbytes;
4954
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004955 if (b->len > INT_MAX) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004956 PyErr_Format(PyExc_OverflowError,
4957 "string longer than %d bytes", INT_MAX);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004958 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004959 }
4960
4961 if (self->eof_written) {
4962 PyErr_SetString(PySSLErrorObject,
4963 "cannot write() after write_eof()");
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004964 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004965 }
4966
Segev Finer5cff6372017-07-27 01:19:17 +03004967 nbytes = BIO_write(self->bio, b->buf, (int)b->len);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004968 if (nbytes < 0) {
4969 _setSSLError(NULL, 0, __FILE__, __LINE__);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004970 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004971 }
4972
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004973 return PyLong_FromLong(nbytes);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004974}
4975
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004976/*[clinic input]
4977_ssl.MemoryBIO.write_eof
4978
4979Write an EOF marker to the memory BIO.
4980
4981When all data has been read, the "eof" property will be True.
4982[clinic start generated code]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004983
4984static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004985_ssl_MemoryBIO_write_eof_impl(PySSLMemoryBIO *self)
4986/*[clinic end generated code: output=d4106276ccd1ed34 input=56a945f1d29e8bd6]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004987{
4988 self->eof_written = 1;
4989 /* After an EOF is written, a zero return from read() should be a real EOF
4990 * i.e. it should not be retried. Clear the SHOULD_RETRY flag. */
4991 BIO_clear_retry_flags(self->bio);
4992 BIO_set_mem_eof_return(self->bio, 0);
4993
4994 Py_RETURN_NONE;
4995}
4996
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004997static PyGetSetDef memory_bio_getsetlist[] = {
4998 {"pending", (getter) memory_bio_get_pending, NULL,
4999 PySSL_memory_bio_pending_doc},
5000 {"eof", (getter) memory_bio_get_eof, NULL,
5001 PySSL_memory_bio_eof_doc},
5002 {NULL}, /* sentinel */
5003};
5004
5005static struct PyMethodDef memory_bio_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005006 _SSL_MEMORYBIO_READ_METHODDEF
5007 _SSL_MEMORYBIO_WRITE_METHODDEF
5008 _SSL_MEMORYBIO_WRITE_EOF_METHODDEF
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005009 {NULL, NULL} /* sentinel */
5010};
5011
5012static PyTypeObject PySSLMemoryBIO_Type = {
5013 PyVarObject_HEAD_INIT(NULL, 0)
5014 "_ssl.MemoryBIO", /*tp_name*/
5015 sizeof(PySSLMemoryBIO), /*tp_basicsize*/
5016 0, /*tp_itemsize*/
5017 (destructor)memory_bio_dealloc, /*tp_dealloc*/
Jeroen Demeyer530f5062019-05-31 04:13:39 +02005018 0, /*tp_vectorcall_offset*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005019 0, /*tp_getattr*/
5020 0, /*tp_setattr*/
Jeroen Demeyer530f5062019-05-31 04:13:39 +02005021 0, /*tp_as_async*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005022 0, /*tp_repr*/
5023 0, /*tp_as_number*/
5024 0, /*tp_as_sequence*/
5025 0, /*tp_as_mapping*/
5026 0, /*tp_hash*/
5027 0, /*tp_call*/
5028 0, /*tp_str*/
5029 0, /*tp_getattro*/
5030 0, /*tp_setattro*/
5031 0, /*tp_as_buffer*/
5032 Py_TPFLAGS_DEFAULT, /*tp_flags*/
5033 0, /*tp_doc*/
5034 0, /*tp_traverse*/
5035 0, /*tp_clear*/
5036 0, /*tp_richcompare*/
5037 0, /*tp_weaklistoffset*/
5038 0, /*tp_iter*/
5039 0, /*tp_iternext*/
5040 memory_bio_methods, /*tp_methods*/
5041 0, /*tp_members*/
5042 memory_bio_getsetlist, /*tp_getset*/
5043 0, /*tp_base*/
5044 0, /*tp_dict*/
5045 0, /*tp_descr_get*/
5046 0, /*tp_descr_set*/
5047 0, /*tp_dictoffset*/
5048 0, /*tp_init*/
5049 0, /*tp_alloc*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005050 _ssl_MemoryBIO, /*tp_new*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005051};
5052
Antoine Pitrou152efa22010-05-16 18:19:27 +00005053
Christian Heimes99a65702016-09-10 23:44:53 +02005054/*
5055 * SSL Session object
5056 */
5057
5058static void
5059PySSLSession_dealloc(PySSLSession *self)
5060{
INADA Naokia6296d32017-08-24 14:55:17 +09005061 /* bpo-31095: UnTrack is needed before calling any callbacks */
Christian Heimesa5d07652016-09-24 10:48:05 +02005062 PyObject_GC_UnTrack(self);
Christian Heimes99a65702016-09-10 23:44:53 +02005063 Py_XDECREF(self->ctx);
5064 if (self->session != NULL) {
5065 SSL_SESSION_free(self->session);
5066 }
Christian Heimesa5d07652016-09-24 10:48:05 +02005067 PyObject_GC_Del(self);
Christian Heimes99a65702016-09-10 23:44:53 +02005068}
5069
5070static PyObject *
5071PySSLSession_richcompare(PyObject *left, PyObject *right, int op)
5072{
5073 int result;
5074
5075 if (left == NULL || right == NULL) {
5076 PyErr_BadInternalCall();
5077 return NULL;
5078 }
5079
5080 if (!PySSLSession_Check(left) || !PySSLSession_Check(right)) {
5081 Py_RETURN_NOTIMPLEMENTED;
5082 }
5083
5084 if (left == right) {
5085 result = 0;
5086 } else {
5087 const unsigned char *left_id, *right_id;
5088 unsigned int left_len, right_len;
5089 left_id = SSL_SESSION_get_id(((PySSLSession *)left)->session,
5090 &left_len);
5091 right_id = SSL_SESSION_get_id(((PySSLSession *)right)->session,
5092 &right_len);
5093 if (left_len == right_len) {
5094 result = memcmp(left_id, right_id, left_len);
5095 } else {
5096 result = 1;
5097 }
5098 }
5099
5100 switch (op) {
5101 case Py_EQ:
5102 if (result == 0) {
5103 Py_RETURN_TRUE;
5104 } else {
5105 Py_RETURN_FALSE;
5106 }
5107 break;
5108 case Py_NE:
5109 if (result != 0) {
5110 Py_RETURN_TRUE;
5111 } else {
5112 Py_RETURN_FALSE;
5113 }
5114 break;
5115 case Py_LT:
5116 case Py_LE:
5117 case Py_GT:
5118 case Py_GE:
5119 Py_RETURN_NOTIMPLEMENTED;
5120 break;
5121 default:
5122 PyErr_BadArgument();
5123 return NULL;
5124 }
5125}
5126
5127static int
5128PySSLSession_traverse(PySSLSession *self, visitproc visit, void *arg)
5129{
5130 Py_VISIT(self->ctx);
5131 return 0;
5132}
5133
5134static int
5135PySSLSession_clear(PySSLSession *self)
5136{
5137 Py_CLEAR(self->ctx);
5138 return 0;
5139}
5140
5141
5142static PyObject *
5143PySSLSession_get_time(PySSLSession *self, void *closure) {
5144 return PyLong_FromLong(SSL_SESSION_get_time(self->session));
5145}
5146
5147PyDoc_STRVAR(PySSLSession_get_time_doc,
5148"Session creation time (seconds since epoch).");
5149
5150
5151static PyObject *
5152PySSLSession_get_timeout(PySSLSession *self, void *closure) {
5153 return PyLong_FromLong(SSL_SESSION_get_timeout(self->session));
5154}
5155
5156PyDoc_STRVAR(PySSLSession_get_timeout_doc,
5157"Session timeout (delta in seconds).");
5158
5159
5160static PyObject *
5161PySSLSession_get_ticket_lifetime_hint(PySSLSession *self, void *closure) {
5162 unsigned long hint = SSL_SESSION_get_ticket_lifetime_hint(self->session);
5163 return PyLong_FromUnsignedLong(hint);
5164}
5165
5166PyDoc_STRVAR(PySSLSession_get_ticket_lifetime_hint_doc,
5167"Ticket life time hint.");
5168
5169
5170static PyObject *
5171PySSLSession_get_session_id(PySSLSession *self, void *closure) {
5172 const unsigned char *id;
5173 unsigned int len;
5174 id = SSL_SESSION_get_id(self->session, &len);
5175 return PyBytes_FromStringAndSize((const char *)id, len);
5176}
5177
5178PyDoc_STRVAR(PySSLSession_get_session_id_doc,
5179"Session id");
5180
5181
5182static PyObject *
5183PySSLSession_get_has_ticket(PySSLSession *self, void *closure) {
5184 if (SSL_SESSION_has_ticket(self->session)) {
5185 Py_RETURN_TRUE;
5186 } else {
5187 Py_RETURN_FALSE;
5188 }
5189}
5190
5191PyDoc_STRVAR(PySSLSession_get_has_ticket_doc,
5192"Does the session contain a ticket?");
5193
5194
5195static PyGetSetDef PySSLSession_getsetlist[] = {
5196 {"has_ticket", (getter) PySSLSession_get_has_ticket, NULL,
5197 PySSLSession_get_has_ticket_doc},
5198 {"id", (getter) PySSLSession_get_session_id, NULL,
5199 PySSLSession_get_session_id_doc},
5200 {"ticket_lifetime_hint", (getter) PySSLSession_get_ticket_lifetime_hint,
5201 NULL, PySSLSession_get_ticket_lifetime_hint_doc},
5202 {"time", (getter) PySSLSession_get_time, NULL,
5203 PySSLSession_get_time_doc},
5204 {"timeout", (getter) PySSLSession_get_timeout, NULL,
5205 PySSLSession_get_timeout_doc},
5206 {NULL}, /* sentinel */
5207};
5208
5209static PyTypeObject PySSLSession_Type = {
5210 PyVarObject_HEAD_INIT(NULL, 0)
5211 "_ssl.Session", /*tp_name*/
5212 sizeof(PySSLSession), /*tp_basicsize*/
5213 0, /*tp_itemsize*/
5214 (destructor)PySSLSession_dealloc, /*tp_dealloc*/
Jeroen Demeyer530f5062019-05-31 04:13:39 +02005215 0, /*tp_vectorcall_offset*/
Christian Heimes99a65702016-09-10 23:44:53 +02005216 0, /*tp_getattr*/
5217 0, /*tp_setattr*/
Jeroen Demeyer530f5062019-05-31 04:13:39 +02005218 0, /*tp_as_async*/
Christian Heimes99a65702016-09-10 23:44:53 +02005219 0, /*tp_repr*/
5220 0, /*tp_as_number*/
5221 0, /*tp_as_sequence*/
5222 0, /*tp_as_mapping*/
5223 0, /*tp_hash*/
5224 0, /*tp_call*/
5225 0, /*tp_str*/
5226 0, /*tp_getattro*/
5227 0, /*tp_setattro*/
5228 0, /*tp_as_buffer*/
Christian Heimesa5d07652016-09-24 10:48:05 +02005229 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
Christian Heimes99a65702016-09-10 23:44:53 +02005230 0, /*tp_doc*/
5231 (traverseproc)PySSLSession_traverse, /*tp_traverse*/
5232 (inquiry)PySSLSession_clear, /*tp_clear*/
5233 PySSLSession_richcompare, /*tp_richcompare*/
5234 0, /*tp_weaklistoffset*/
5235 0, /*tp_iter*/
5236 0, /*tp_iternext*/
5237 0, /*tp_methods*/
5238 0, /*tp_members*/
5239 PySSLSession_getsetlist, /*tp_getset*/
5240};
5241
5242
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005243/* helper routines for seeding the SSL PRNG */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005244/*[clinic input]
5245_ssl.RAND_add
Larry Hastingsdbfdc382015-05-04 06:59:46 -07005246 string as view: Py_buffer(accept={str, buffer})
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005247 entropy: double
5248 /
5249
5250Mix string into the OpenSSL PRNG state.
5251
5252entropy (a float) is a lower bound on the entropy contained in
Chandan Kumar63c2c8a2017-06-09 15:13:58 +05305253string. See RFC 4086.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005254[clinic start generated code]*/
5255
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005256static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005257_ssl_RAND_add_impl(PyObject *module, Py_buffer *view, double entropy)
Serhiy Storchaka5f31d5c2017-06-10 13:13:51 +03005258/*[clinic end generated code: output=e6dd48df9c9024e9 input=5c33017422828f5c]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005259{
Serhiy Storchaka8490f5a2015-03-20 09:00:36 +02005260 const char *buf;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02005261 Py_ssize_t len, written;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005262
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005263 buf = (const char *)view->buf;
5264 len = view->len;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02005265 do {
5266 written = Py_MIN(len, INT_MAX);
5267 RAND_add(buf, (int)written, entropy);
5268 buf += written;
5269 len -= written;
5270 } while (len);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02005271 Py_RETURN_NONE;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005272}
5273
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005274static PyObject *
Victor Stinner99c8b162011-05-24 12:05:19 +02005275PySSL_RAND(int len, int pseudo)
5276{
5277 int ok;
5278 PyObject *bytes;
5279 unsigned long err;
5280 const char *errstr;
5281 PyObject *v;
5282
Victor Stinner1e81a392013-12-19 16:47:04 +01005283 if (len < 0) {
5284 PyErr_SetString(PyExc_ValueError, "num must be positive");
5285 return NULL;
5286 }
5287
Victor Stinner99c8b162011-05-24 12:05:19 +02005288 bytes = PyBytes_FromStringAndSize(NULL, len);
5289 if (bytes == NULL)
5290 return NULL;
5291 if (pseudo) {
5292 ok = RAND_pseudo_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
5293 if (ok == 0 || ok == 1)
5294 return Py_BuildValue("NO", bytes, ok == 1 ? Py_True : Py_False);
5295 }
5296 else {
5297 ok = RAND_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
5298 if (ok == 1)
5299 return bytes;
5300 }
5301 Py_DECREF(bytes);
5302
5303 err = ERR_get_error();
5304 errstr = ERR_reason_error_string(err);
5305 v = Py_BuildValue("(ks)", err, errstr);
5306 if (v != NULL) {
5307 PyErr_SetObject(PySSLErrorObject, v);
5308 Py_DECREF(v);
5309 }
5310 return NULL;
5311}
5312
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005313/*[clinic input]
5314_ssl.RAND_bytes
5315 n: int
5316 /
5317
5318Generate n cryptographically strong pseudo-random bytes.
5319[clinic start generated code]*/
5320
Victor Stinner99c8b162011-05-24 12:05:19 +02005321static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005322_ssl_RAND_bytes_impl(PyObject *module, int n)
5323/*[clinic end generated code: output=977da635e4838bc7 input=678ddf2872dfebfc]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02005324{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005325 return PySSL_RAND(n, 0);
Victor Stinner99c8b162011-05-24 12:05:19 +02005326}
5327
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005328/*[clinic input]
5329_ssl.RAND_pseudo_bytes
5330 n: int
5331 /
5332
5333Generate n pseudo-random bytes.
5334
5335Return a pair (bytes, is_cryptographic). is_cryptographic is True
5336if the bytes generated are cryptographically strong.
5337[clinic start generated code]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02005338
5339static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005340_ssl_RAND_pseudo_bytes_impl(PyObject *module, int n)
5341/*[clinic end generated code: output=b1509e937000e52d input=58312bd53f9bbdd0]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02005342{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005343 return PySSL_RAND(n, 1);
Victor Stinner99c8b162011-05-24 12:05:19 +02005344}
5345
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005346/*[clinic input]
5347_ssl.RAND_status
5348
5349Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.
5350
5351It is necessary to seed the PRNG with RAND_add() on some platforms before
5352using the ssl() function.
5353[clinic start generated code]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02005354
5355static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005356_ssl_RAND_status_impl(PyObject *module)
5357/*[clinic end generated code: output=7e0aaa2d39fdc1ad input=8a774b02d1dc81f3]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005358{
Christian Heimes217cfd12007-12-02 14:31:20 +00005359 return PyLong_FromLong(RAND_status());
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005360}
5361
Benjamin Petersonb8a2f512016-07-06 23:55:15 -07005362#ifndef OPENSSL_NO_EGD
Christian Heimesa5d07652016-09-24 10:48:05 +02005363/* LCOV_EXCL_START */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005364/*[clinic input]
5365_ssl.RAND_egd
5366 path: object(converter="PyUnicode_FSConverter")
5367 /
5368
5369Queries the entropy gather daemon (EGD) on the socket named by 'path'.
5370
5371Returns number of bytes read. Raises SSLError if connection to EGD
5372fails or if it does not provide enough data to seed PRNG.
5373[clinic start generated code]*/
5374
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005375static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005376_ssl_RAND_egd_impl(PyObject *module, PyObject *path)
5377/*[clinic end generated code: output=02a67c7c367f52fa input=1aeb7eb948312195]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005378{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005379 int bytes = RAND_egd(PyBytes_AsString(path));
Victor Stinnerf9faaad2010-05-16 21:36:37 +00005380 Py_DECREF(path);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005381 if (bytes == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00005382 PyErr_SetString(PySSLErrorObject,
5383 "EGD connection failed or EGD did not return "
5384 "enough data to seed the PRNG");
5385 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005386 }
Christian Heimes217cfd12007-12-02 14:31:20 +00005387 return PyLong_FromLong(bytes);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005388}
Christian Heimesa5d07652016-09-24 10:48:05 +02005389/* LCOV_EXCL_STOP */
Benjamin Petersonb8a2f512016-07-06 23:55:15 -07005390#endif /* OPENSSL_NO_EGD */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005391
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005392
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005393
5394/*[clinic input]
5395_ssl.get_default_verify_paths
5396
5397Return search paths and environment vars that are used by SSLContext's set_default_verify_paths() to load default CAs.
5398
5399The values are 'cert_file_env', 'cert_file', 'cert_dir_env', 'cert_dir'.
5400[clinic start generated code]*/
Christian Heimes6d7ad132013-06-09 18:02:55 +02005401
5402static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005403_ssl_get_default_verify_paths_impl(PyObject *module)
5404/*[clinic end generated code: output=e5b62a466271928b input=5210c953d98c3eb5]*/
Christian Heimes6d7ad132013-06-09 18:02:55 +02005405{
5406 PyObject *ofile_env = NULL;
5407 PyObject *ofile = NULL;
5408 PyObject *odir_env = NULL;
5409 PyObject *odir = NULL;
5410
Benjamin Petersond113c962015-07-18 10:59:13 -07005411#define CONVERT(info, target) { \
Christian Heimes6d7ad132013-06-09 18:02:55 +02005412 const char *tmp = (info); \
5413 target = NULL; \
5414 if (!tmp) { Py_INCREF(Py_None); target = Py_None; } \
5415 else if ((target = PyUnicode_DecodeFSDefault(tmp)) == NULL) { \
5416 target = PyBytes_FromString(tmp); } \
5417 if (!target) goto error; \
Benjamin Peterson025a1fd2015-11-14 15:12:38 -08005418 }
Christian Heimes6d7ad132013-06-09 18:02:55 +02005419
Benjamin Petersond113c962015-07-18 10:59:13 -07005420 CONVERT(X509_get_default_cert_file_env(), ofile_env);
5421 CONVERT(X509_get_default_cert_file(), ofile);
5422 CONVERT(X509_get_default_cert_dir_env(), odir_env);
5423 CONVERT(X509_get_default_cert_dir(), odir);
5424#undef CONVERT
Christian Heimes6d7ad132013-06-09 18:02:55 +02005425
Christian Heimes200bb1b2013-06-14 15:14:29 +02005426 return Py_BuildValue("NNNN", ofile_env, ofile, odir_env, odir);
Christian Heimes6d7ad132013-06-09 18:02:55 +02005427
5428 error:
5429 Py_XDECREF(ofile_env);
5430 Py_XDECREF(ofile);
5431 Py_XDECREF(odir_env);
5432 Py_XDECREF(odir);
5433 return NULL;
5434}
5435
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005436static PyObject*
5437asn1obj2py(ASN1_OBJECT *obj)
5438{
5439 int nid;
5440 const char *ln, *sn;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005441
5442 nid = OBJ_obj2nid(obj);
5443 if (nid == NID_undef) {
5444 PyErr_Format(PyExc_ValueError, "Unknown object");
5445 return NULL;
5446 }
5447 sn = OBJ_nid2sn(nid);
5448 ln = OBJ_nid2ln(nid);
Serhiy Storchakae503ca52017-09-05 01:28:53 +03005449 return Py_BuildValue("issN", nid, sn, ln, _asn1obj2py(obj, 1));
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005450}
5451
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005452/*[clinic input]
5453_ssl.txt2obj
5454 txt: str
5455 name: bool = False
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005456
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005457Lookup NID, short name, long name and OID of an ASN1_OBJECT.
5458
5459By default objects are looked up by OID. With name=True short and
5460long name are also matched.
5461[clinic start generated code]*/
5462
5463static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005464_ssl_txt2obj_impl(PyObject *module, const char *txt, int name)
5465/*[clinic end generated code: output=c38e3991347079c1 input=1c1e7d0aa7c48602]*/
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005466{
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005467 PyObject *result = NULL;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005468 ASN1_OBJECT *obj;
5469
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005470 obj = OBJ_txt2obj(txt, name ? 0 : 1);
5471 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01005472 PyErr_Format(PyExc_ValueError, "unknown object '%.100s'", txt);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005473 return NULL;
5474 }
5475 result = asn1obj2py(obj);
5476 ASN1_OBJECT_free(obj);
5477 return result;
5478}
5479
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005480/*[clinic input]
5481_ssl.nid2obj
5482 nid: int
5483 /
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005484
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005485Lookup NID, short name, long name and OID of an ASN1_OBJECT by NID.
5486[clinic start generated code]*/
5487
5488static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005489_ssl_nid2obj_impl(PyObject *module, int nid)
5490/*[clinic end generated code: output=4a98ab691cd4f84a input=51787a3bee7d8f98]*/
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005491{
5492 PyObject *result = NULL;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005493 ASN1_OBJECT *obj;
5494
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005495 if (nid < NID_undef) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01005496 PyErr_SetString(PyExc_ValueError, "NID must be positive.");
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005497 return NULL;
5498 }
5499 obj = OBJ_nid2obj(nid);
5500 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01005501 PyErr_Format(PyExc_ValueError, "unknown NID %i", nid);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005502 return NULL;
5503 }
5504 result = asn1obj2py(obj);
5505 ASN1_OBJECT_free(obj);
5506 return result;
5507}
5508
Christian Heimes46bebee2013-06-09 19:03:31 +02005509#ifdef _MSC_VER
Christian Heimes44109d72013-11-22 01:51:30 +01005510
5511static PyObject*
5512certEncodingType(DWORD encodingType)
5513{
5514 static PyObject *x509_asn = NULL;
5515 static PyObject *pkcs_7_asn = NULL;
5516
5517 if (x509_asn == NULL) {
5518 x509_asn = PyUnicode_InternFromString("x509_asn");
5519 if (x509_asn == NULL)
5520 return NULL;
5521 }
5522 if (pkcs_7_asn == NULL) {
5523 pkcs_7_asn = PyUnicode_InternFromString("pkcs_7_asn");
5524 if (pkcs_7_asn == NULL)
5525 return NULL;
5526 }
5527 switch(encodingType) {
5528 case X509_ASN_ENCODING:
5529 Py_INCREF(x509_asn);
5530 return x509_asn;
5531 case PKCS_7_ASN_ENCODING:
5532 Py_INCREF(pkcs_7_asn);
5533 return pkcs_7_asn;
5534 default:
5535 return PyLong_FromLong(encodingType);
5536 }
5537}
5538
5539static PyObject*
5540parseKeyUsage(PCCERT_CONTEXT pCertCtx, DWORD flags)
5541{
5542 CERT_ENHKEY_USAGE *usage;
5543 DWORD size, error, i;
5544 PyObject *retval;
5545
5546 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, NULL, &size)) {
5547 error = GetLastError();
5548 if (error == CRYPT_E_NOT_FOUND) {
5549 Py_RETURN_TRUE;
5550 }
5551 return PyErr_SetFromWindowsErr(error);
5552 }
5553
5554 usage = (CERT_ENHKEY_USAGE*)PyMem_Malloc(size);
5555 if (usage == NULL) {
5556 return PyErr_NoMemory();
5557 }
5558
5559 /* Now get the actual enhanced usage property */
5560 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, usage, &size)) {
5561 PyMem_Free(usage);
5562 error = GetLastError();
5563 if (error == CRYPT_E_NOT_FOUND) {
5564 Py_RETURN_TRUE;
5565 }
5566 return PyErr_SetFromWindowsErr(error);
5567 }
Steve Dowerfdd17ab2019-09-10 02:02:04 -07005568 retval = PyFrozenSet_New(NULL);
Christian Heimes44109d72013-11-22 01:51:30 +01005569 if (retval == NULL) {
5570 goto error;
5571 }
5572 for (i = 0; i < usage->cUsageIdentifier; ++i) {
5573 if (usage->rgpszUsageIdentifier[i]) {
5574 PyObject *oid;
5575 int err;
5576 oid = PyUnicode_FromString(usage->rgpszUsageIdentifier[i]);
5577 if (oid == NULL) {
5578 Py_CLEAR(retval);
5579 goto error;
5580 }
5581 err = PySet_Add(retval, oid);
5582 Py_DECREF(oid);
5583 if (err == -1) {
5584 Py_CLEAR(retval);
5585 goto error;
5586 }
5587 }
5588 }
5589 error:
5590 PyMem_Free(usage);
5591 return retval;
5592}
5593
kctherookied93fbbf2019-03-29 00:59:06 +07005594static HCERTSTORE
5595ssl_collect_certificates(const char *store_name)
5596{
5597/* this function collects the system certificate stores listed in
5598 * system_stores into a collection certificate store for being
5599 * enumerated. The store must be readable to be added to the
5600 * store collection.
5601 */
5602
5603 HCERTSTORE hCollectionStore = NULL, hSystemStore = NULL;
5604 static DWORD system_stores[] = {
5605 CERT_SYSTEM_STORE_LOCAL_MACHINE,
5606 CERT_SYSTEM_STORE_LOCAL_MACHINE_ENTERPRISE,
5607 CERT_SYSTEM_STORE_LOCAL_MACHINE_GROUP_POLICY,
5608 CERT_SYSTEM_STORE_CURRENT_USER,
5609 CERT_SYSTEM_STORE_CURRENT_USER_GROUP_POLICY,
5610 CERT_SYSTEM_STORE_SERVICES,
5611 CERT_SYSTEM_STORE_USERS};
5612 size_t i, storesAdded;
5613 BOOL result;
5614
5615 hCollectionStore = CertOpenStore(CERT_STORE_PROV_COLLECTION, 0,
5616 (HCRYPTPROV)NULL, 0, NULL);
5617 if (!hCollectionStore) {
5618 return NULL;
5619 }
5620 storesAdded = 0;
5621 for (i = 0; i < sizeof(system_stores) / sizeof(DWORD); i++) {
5622 hSystemStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0,
5623 (HCRYPTPROV)NULL,
5624 CERT_STORE_READONLY_FLAG |
5625 system_stores[i], store_name);
5626 if (hSystemStore) {
5627 result = CertAddStoreToCollection(hCollectionStore, hSystemStore,
5628 CERT_PHYSICAL_STORE_ADD_ENABLE_FLAG, 0);
5629 if (result) {
5630 ++storesAdded;
5631 }
Steve Dower5d695b62019-09-09 06:48:22 -07005632 CertCloseStore(hSystemStore, 0); /* flag must be 0 */
kctherookied93fbbf2019-03-29 00:59:06 +07005633 }
5634 }
5635 if (storesAdded == 0) {
5636 CertCloseStore(hCollectionStore, CERT_CLOSE_STORE_FORCE_FLAG);
5637 return NULL;
5638 }
5639
5640 return hCollectionStore;
5641}
5642
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005643/*[clinic input]
5644_ssl.enum_certificates
5645 store_name: str
5646
5647Retrieve certificates from Windows' cert store.
5648
5649store_name may be one of 'CA', 'ROOT' or 'MY'. The system may provide
5650more cert storages, too. The function returns a list of (bytes,
5651encoding_type, trust) tuples. The encoding_type flag can be interpreted
5652with X509_ASN_ENCODING or PKCS_7_ASN_ENCODING. The trust setting is either
5653a set of OIDs or the boolean True.
5654[clinic start generated code]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00005655
Christian Heimes46bebee2013-06-09 19:03:31 +02005656static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005657_ssl_enum_certificates_impl(PyObject *module, const char *store_name)
5658/*[clinic end generated code: output=5134dc8bb3a3c893 input=915f60d70461ea4e]*/
Christian Heimes46bebee2013-06-09 19:03:31 +02005659{
kctherookied93fbbf2019-03-29 00:59:06 +07005660 HCERTSTORE hCollectionStore = NULL;
Christian Heimes44109d72013-11-22 01:51:30 +01005661 PCCERT_CONTEXT pCertCtx = NULL;
5662 PyObject *keyusage = NULL, *cert = NULL, *enc = NULL, *tup = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02005663 PyObject *result = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02005664
Steve Dowerfdd17ab2019-09-10 02:02:04 -07005665 result = PySet_New(NULL);
Christian Heimes44109d72013-11-22 01:51:30 +01005666 if (result == NULL) {
5667 return NULL;
5668 }
kctherookied93fbbf2019-03-29 00:59:06 +07005669 hCollectionStore = ssl_collect_certificates(store_name);
5670 if (hCollectionStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02005671 Py_DECREF(result);
5672 return PyErr_SetFromWindowsErr(GetLastError());
5673 }
5674
kctherookied93fbbf2019-03-29 00:59:06 +07005675 while (pCertCtx = CertEnumCertificatesInStore(hCollectionStore, pCertCtx)) {
Christian Heimes44109d72013-11-22 01:51:30 +01005676 cert = PyBytes_FromStringAndSize((const char*)pCertCtx->pbCertEncoded,
5677 pCertCtx->cbCertEncoded);
5678 if (!cert) {
5679 Py_CLEAR(result);
5680 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02005681 }
Christian Heimes44109d72013-11-22 01:51:30 +01005682 if ((enc = certEncodingType(pCertCtx->dwCertEncodingType)) == NULL) {
5683 Py_CLEAR(result);
5684 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02005685 }
Christian Heimes44109d72013-11-22 01:51:30 +01005686 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG);
5687 if (keyusage == Py_True) {
5688 Py_DECREF(keyusage);
5689 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_EXT_ONLY_ENHKEY_USAGE_FLAG);
Christian Heimes46bebee2013-06-09 19:03:31 +02005690 }
Christian Heimes44109d72013-11-22 01:51:30 +01005691 if (keyusage == NULL) {
5692 Py_CLEAR(result);
5693 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02005694 }
Christian Heimes44109d72013-11-22 01:51:30 +01005695 if ((tup = PyTuple_New(3)) == NULL) {
5696 Py_CLEAR(result);
5697 break;
5698 }
5699 PyTuple_SET_ITEM(tup, 0, cert);
5700 cert = NULL;
5701 PyTuple_SET_ITEM(tup, 1, enc);
5702 enc = NULL;
5703 PyTuple_SET_ITEM(tup, 2, keyusage);
5704 keyusage = NULL;
Steve Dowerfdd17ab2019-09-10 02:02:04 -07005705 if (PySet_Add(result, tup) == -1) {
5706 Py_CLEAR(result);
5707 Py_CLEAR(tup);
5708 break;
Christian Heimes44109d72013-11-22 01:51:30 +01005709 }
5710 Py_CLEAR(tup);
5711 }
5712 if (pCertCtx) {
5713 /* loop ended with an error, need to clean up context manually */
5714 CertFreeCertificateContext(pCertCtx);
Christian Heimes46bebee2013-06-09 19:03:31 +02005715 }
5716
5717 /* In error cases cert, enc and tup may not be NULL */
5718 Py_XDECREF(cert);
5719 Py_XDECREF(enc);
Christian Heimes44109d72013-11-22 01:51:30 +01005720 Py_XDECREF(keyusage);
Christian Heimes46bebee2013-06-09 19:03:31 +02005721 Py_XDECREF(tup);
5722
kctherookied93fbbf2019-03-29 00:59:06 +07005723 /* CERT_CLOSE_STORE_FORCE_FLAG forces freeing of memory for all contexts
5724 associated with the store, in this case our collection store and the
5725 associated system stores. */
5726 if (!CertCloseStore(hCollectionStore, CERT_CLOSE_STORE_FORCE_FLAG)) {
Christian Heimes46bebee2013-06-09 19:03:31 +02005727 /* This error case might shadow another exception.*/
Christian Heimes44109d72013-11-22 01:51:30 +01005728 Py_XDECREF(result);
5729 return PyErr_SetFromWindowsErr(GetLastError());
5730 }
kctherookied93fbbf2019-03-29 00:59:06 +07005731
Steve Dowerfdd17ab2019-09-10 02:02:04 -07005732 /* convert set to list */
5733 if (result == NULL) {
5734 return NULL;
5735 } else {
5736 PyObject *lst = PySequence_List(result);
5737 Py_DECREF(result);
5738 return lst;
5739 }
Christian Heimes44109d72013-11-22 01:51:30 +01005740}
5741
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005742/*[clinic input]
5743_ssl.enum_crls
5744 store_name: str
5745
5746Retrieve CRLs from Windows' cert store.
5747
5748store_name may be one of 'CA', 'ROOT' or 'MY'. The system may provide
5749more cert storages, too. The function returns a list of (bytes,
5750encoding_type) tuples. The encoding_type flag can be interpreted with
5751X509_ASN_ENCODING or PKCS_7_ASN_ENCODING.
5752[clinic start generated code]*/
Christian Heimes44109d72013-11-22 01:51:30 +01005753
5754static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005755_ssl_enum_crls_impl(PyObject *module, const char *store_name)
5756/*[clinic end generated code: output=bce467f60ccd03b6 input=a1f1d7629f1c5d3d]*/
Christian Heimes44109d72013-11-22 01:51:30 +01005757{
kctherookied93fbbf2019-03-29 00:59:06 +07005758 HCERTSTORE hCollectionStore = NULL;
Christian Heimes44109d72013-11-22 01:51:30 +01005759 PCCRL_CONTEXT pCrlCtx = NULL;
5760 PyObject *crl = NULL, *enc = NULL, *tup = NULL;
5761 PyObject *result = NULL;
5762
Steve Dowerfdd17ab2019-09-10 02:02:04 -07005763 result = PySet_New(NULL);
Christian Heimes44109d72013-11-22 01:51:30 +01005764 if (result == NULL) {
5765 return NULL;
5766 }
kctherookied93fbbf2019-03-29 00:59:06 +07005767 hCollectionStore = ssl_collect_certificates(store_name);
5768 if (hCollectionStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02005769 Py_DECREF(result);
5770 return PyErr_SetFromWindowsErr(GetLastError());
5771 }
Christian Heimes44109d72013-11-22 01:51:30 +01005772
kctherookied93fbbf2019-03-29 00:59:06 +07005773 while (pCrlCtx = CertEnumCRLsInStore(hCollectionStore, pCrlCtx)) {
Christian Heimes44109d72013-11-22 01:51:30 +01005774 crl = PyBytes_FromStringAndSize((const char*)pCrlCtx->pbCrlEncoded,
5775 pCrlCtx->cbCrlEncoded);
5776 if (!crl) {
5777 Py_CLEAR(result);
5778 break;
5779 }
5780 if ((enc = certEncodingType(pCrlCtx->dwCertEncodingType)) == NULL) {
5781 Py_CLEAR(result);
5782 break;
5783 }
5784 if ((tup = PyTuple_New(2)) == NULL) {
5785 Py_CLEAR(result);
5786 break;
5787 }
5788 PyTuple_SET_ITEM(tup, 0, crl);
5789 crl = NULL;
5790 PyTuple_SET_ITEM(tup, 1, enc);
5791 enc = NULL;
5792
Steve Dowerfdd17ab2019-09-10 02:02:04 -07005793 if (PySet_Add(result, tup) == -1) {
5794 Py_CLEAR(result);
5795 Py_CLEAR(tup);
5796 break;
Christian Heimes44109d72013-11-22 01:51:30 +01005797 }
5798 Py_CLEAR(tup);
Christian Heimes46bebee2013-06-09 19:03:31 +02005799 }
Christian Heimes44109d72013-11-22 01:51:30 +01005800 if (pCrlCtx) {
5801 /* loop ended with an error, need to clean up context manually */
5802 CertFreeCRLContext(pCrlCtx);
5803 }
5804
5805 /* In error cases cert, enc and tup may not be NULL */
5806 Py_XDECREF(crl);
5807 Py_XDECREF(enc);
5808 Py_XDECREF(tup);
5809
kctherookied93fbbf2019-03-29 00:59:06 +07005810 /* CERT_CLOSE_STORE_FORCE_FLAG forces freeing of memory for all contexts
5811 associated with the store, in this case our collection store and the
5812 associated system stores. */
5813 if (!CertCloseStore(hCollectionStore, CERT_CLOSE_STORE_FORCE_FLAG)) {
Christian Heimes44109d72013-11-22 01:51:30 +01005814 /* This error case might shadow another exception.*/
5815 Py_XDECREF(result);
5816 return PyErr_SetFromWindowsErr(GetLastError());
5817 }
Steve Dowerfdd17ab2019-09-10 02:02:04 -07005818 /* convert set to list */
5819 if (result == NULL) {
5820 return NULL;
5821 } else {
5822 PyObject *lst = PySequence_List(result);
5823 Py_DECREF(result);
5824 return lst;
5825 }
Christian Heimes46bebee2013-06-09 19:03:31 +02005826}
Christian Heimes44109d72013-11-22 01:51:30 +01005827
5828#endif /* _MSC_VER */
Bill Janssen40a0f662008-08-12 16:56:25 +00005829
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005830/* List of functions exported by this module. */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005831static PyMethodDef PySSL_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005832 _SSL__TEST_DECODE_CERT_METHODDEF
5833 _SSL_RAND_ADD_METHODDEF
5834 _SSL_RAND_BYTES_METHODDEF
5835 _SSL_RAND_PSEUDO_BYTES_METHODDEF
5836 _SSL_RAND_EGD_METHODDEF
5837 _SSL_RAND_STATUS_METHODDEF
5838 _SSL_GET_DEFAULT_VERIFY_PATHS_METHODDEF
5839 _SSL_ENUM_CERTIFICATES_METHODDEF
5840 _SSL_ENUM_CRLS_METHODDEF
5841 _SSL_TXT2OBJ_METHODDEF
5842 _SSL_NID2OBJ_METHODDEF
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005843 {NULL, NULL} /* Sentinel */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005844};
5845
5846
Christian Heimes598894f2016-09-05 23:19:05 +02005847#ifdef HAVE_OPENSSL_CRYPTO_LOCK
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005848
5849/* an implementation of OpenSSL threading operations in terms
Christian Heimes598894f2016-09-05 23:19:05 +02005850 * of the Python C thread library
5851 * Only used up to 1.0.2. OpenSSL 1.1.0+ has its own locking code.
5852 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005853
5854static PyThread_type_lock *_ssl_locks = NULL;
5855
Christian Heimes4d98ca92013-08-19 17:36:29 +02005856#if OPENSSL_VERSION_NUMBER >= 0x10000000
5857/* use new CRYPTO_THREADID API. */
5858static void
5859_ssl_threadid_callback(CRYPTO_THREADID *id)
5860{
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +02005861 CRYPTO_THREADID_set_numeric(id, PyThread_get_thread_ident());
Christian Heimes4d98ca92013-08-19 17:36:29 +02005862}
5863#else
5864/* deprecated CRYPTO_set_id_callback() API. */
5865static unsigned long
5866_ssl_thread_id_function (void) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005867 return PyThread_get_thread_ident();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005868}
Christian Heimes4d98ca92013-08-19 17:36:29 +02005869#endif
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005870
Bill Janssen6e027db2007-11-15 22:23:56 +00005871static void _ssl_thread_locking_function
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005872 (int mode, int n, const char *file, int line) {
5873 /* this function is needed to perform locking on shared data
5874 structures. (Note that OpenSSL uses a number of global data
5875 structures that will be implicitly shared whenever multiple
5876 threads use OpenSSL.) Multi-threaded applications will
5877 crash at random if it is not set.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005878
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005879 locking_function() must be able to handle up to
5880 CRYPTO_num_locks() different mutex locks. It sets the n-th
5881 lock if mode & CRYPTO_LOCK, and releases it otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005882
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005883 file and line are the file number of the function setting the
5884 lock. They can be useful for debugging.
5885 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005886
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005887 if ((_ssl_locks == NULL) ||
5888 (n < 0) || ((unsigned)n >= _ssl_locks_count))
5889 return;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005890
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005891 if (mode & CRYPTO_LOCK) {
5892 PyThread_acquire_lock(_ssl_locks[n], 1);
5893 } else {
5894 PyThread_release_lock(_ssl_locks[n]);
5895 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005896}
5897
5898static int _setup_ssl_threads(void) {
5899
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005900 unsigned int i;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005901
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005902 if (_ssl_locks == NULL) {
5903 _ssl_locks_count = CRYPTO_num_locks();
Christian Heimesf6365e32016-09-13 20:48:13 +02005904 _ssl_locks = PyMem_Calloc(_ssl_locks_count,
5905 sizeof(PyThread_type_lock));
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02005906 if (_ssl_locks == NULL) {
5907 PyErr_NoMemory();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005908 return 0;
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02005909 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005910 for (i = 0; i < _ssl_locks_count; i++) {
5911 _ssl_locks[i] = PyThread_allocate_lock();
5912 if (_ssl_locks[i] == NULL) {
5913 unsigned int j;
5914 for (j = 0; j < i; j++) {
5915 PyThread_free_lock(_ssl_locks[j]);
5916 }
Victor Stinnerb6404912013-07-07 16:21:41 +02005917 PyMem_Free(_ssl_locks);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005918 return 0;
5919 }
5920 }
5921 CRYPTO_set_locking_callback(_ssl_thread_locking_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02005922#if OPENSSL_VERSION_NUMBER >= 0x10000000
5923 CRYPTO_THREADID_set_callback(_ssl_threadid_callback);
5924#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005925 CRYPTO_set_id_callback(_ssl_thread_id_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02005926#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005927 }
5928 return 1;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005929}
5930
Antoine Pitroua6a4dc82017-09-07 18:56:24 +02005931#endif /* HAVE_OPENSSL_CRYPTO_LOCK for OpenSSL < 1.1.0 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005932
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005933PyDoc_STRVAR(module_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005934"Implementation module for SSL socket operations. See the socket module\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005935for documentation.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005936
Martin v. Löwis1a214512008-06-11 05:26:20 +00005937
5938static struct PyModuleDef _sslmodule = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005939 PyModuleDef_HEAD_INIT,
5940 "_ssl",
5941 module_doc,
5942 -1,
5943 PySSL_methods,
5944 NULL,
5945 NULL,
5946 NULL,
5947 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00005948};
5949
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02005950
5951static void
5952parse_openssl_version(unsigned long libver,
5953 unsigned int *major, unsigned int *minor,
5954 unsigned int *fix, unsigned int *patch,
5955 unsigned int *status)
5956{
5957 *status = libver & 0xF;
5958 libver >>= 4;
5959 *patch = libver & 0xFF;
5960 libver >>= 8;
5961 *fix = libver & 0xFF;
5962 libver >>= 8;
5963 *minor = libver & 0xFF;
5964 libver >>= 8;
5965 *major = libver & 0xFF;
5966}
5967
Mark Hammondfe51c6d2002-08-02 02:27:13 +00005968PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00005969PyInit__ssl(void)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005970{
Christian Heimesb3ad0e52017-09-08 12:00:19 -07005971 PyObject *m, *d, *r, *bases;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005972 unsigned long libver;
5973 unsigned int major, minor, fix, patch, status;
5974 PySocketModule_APIObject *socket_api;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02005975 struct py_ssl_error_code *errcode;
5976 struct py_ssl_library_code *libcode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005977
Antoine Pitrou152efa22010-05-16 18:19:27 +00005978 if (PyType_Ready(&PySSLContext_Type) < 0)
5979 return NULL;
5980 if (PyType_Ready(&PySSLSocket_Type) < 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005981 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005982 if (PyType_Ready(&PySSLMemoryBIO_Type) < 0)
5983 return NULL;
Christian Heimes99a65702016-09-10 23:44:53 +02005984 if (PyType_Ready(&PySSLSession_Type) < 0)
5985 return NULL;
5986
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005987
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005988 m = PyModule_Create(&_sslmodule);
5989 if (m == NULL)
5990 return NULL;
5991 d = PyModule_GetDict(m);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005992
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005993 /* Load _socket module and its C API */
5994 socket_api = PySocketModule_ImportModuleAndAPI();
5995 if (!socket_api)
5996 return NULL;
5997 PySocketModule = *socket_api;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005998
Christian Heimesc941e622017-09-05 15:47:11 +02005999#ifndef OPENSSL_VERSION_1_1
6000 /* Load all algorithms and initialize cpuid */
6001 OPENSSL_add_all_algorithms_noconf();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006002 /* Init OpenSSL */
6003 SSL_load_error_strings();
6004 SSL_library_init();
Christian Heimesc941e622017-09-05 15:47:11 +02006005#endif
6006
Christian Heimes598894f2016-09-05 23:19:05 +02006007#ifdef HAVE_OPENSSL_CRYPTO_LOCK
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006008 /* note that this will start threading if not already started */
6009 if (!_setup_ssl_threads()) {
6010 return NULL;
6011 }
Christian Heimes387c7442020-05-15 22:36:51 +02006012#elif OPENSSL_VERSION_1_1
Christian Heimes598894f2016-09-05 23:19:05 +02006013 /* OpenSSL 1.1.0 builtin thread support is enabled */
6014 _ssl_locks_count++;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00006015#endif
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00006016
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006017 /* Add symbols to module dict */
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02006018 sslerror_type_slots[0].pfunc = PyExc_OSError;
6019 PySSLErrorObject = PyType_FromSpec(&sslerror_type_spec);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006020 if (PySSLErrorObject == NULL)
6021 return NULL;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02006022
Christian Heimesb3ad0e52017-09-08 12:00:19 -07006023 /* ssl.CertificateError used to be a subclass of ValueError */
6024 bases = Py_BuildValue("OO", PySSLErrorObject, PyExc_ValueError);
6025 if (bases == NULL)
6026 return NULL;
6027 PySSLCertVerificationErrorObject = PyErr_NewExceptionWithDoc(
6028 "ssl.SSLCertVerificationError", SSLCertVerificationError_doc,
6029 bases, NULL);
6030 Py_DECREF(bases);
Antoine Pitrou41032a62011-10-27 23:56:55 +02006031 PySSLZeroReturnErrorObject = PyErr_NewExceptionWithDoc(
6032 "ssl.SSLZeroReturnError", SSLZeroReturnError_doc,
6033 PySSLErrorObject, NULL);
6034 PySSLWantReadErrorObject = PyErr_NewExceptionWithDoc(
6035 "ssl.SSLWantReadError", SSLWantReadError_doc,
6036 PySSLErrorObject, NULL);
6037 PySSLWantWriteErrorObject = PyErr_NewExceptionWithDoc(
6038 "ssl.SSLWantWriteError", SSLWantWriteError_doc,
6039 PySSLErrorObject, NULL);
6040 PySSLSyscallErrorObject = PyErr_NewExceptionWithDoc(
6041 "ssl.SSLSyscallError", SSLSyscallError_doc,
6042 PySSLErrorObject, NULL);
6043 PySSLEOFErrorObject = PyErr_NewExceptionWithDoc(
6044 "ssl.SSLEOFError", SSLEOFError_doc,
6045 PySSLErrorObject, NULL);
Christian Heimesb3ad0e52017-09-08 12:00:19 -07006046 if (PySSLCertVerificationErrorObject == NULL
6047 || PySSLZeroReturnErrorObject == NULL
Antoine Pitrou41032a62011-10-27 23:56:55 +02006048 || PySSLWantReadErrorObject == NULL
6049 || PySSLWantWriteErrorObject == NULL
6050 || PySSLSyscallErrorObject == NULL
6051 || PySSLEOFErrorObject == NULL)
6052 return NULL;
6053 if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0
Christian Heimesb3ad0e52017-09-08 12:00:19 -07006054 || PyDict_SetItemString(d, "SSLCertVerificationError",
6055 PySSLCertVerificationErrorObject) != 0
Antoine Pitrou41032a62011-10-27 23:56:55 +02006056 || PyDict_SetItemString(d, "SSLZeroReturnError", PySSLZeroReturnErrorObject) != 0
6057 || PyDict_SetItemString(d, "SSLWantReadError", PySSLWantReadErrorObject) != 0
6058 || PyDict_SetItemString(d, "SSLWantWriteError", PySSLWantWriteErrorObject) != 0
6059 || PyDict_SetItemString(d, "SSLSyscallError", PySSLSyscallErrorObject) != 0
6060 || PyDict_SetItemString(d, "SSLEOFError", PySSLEOFErrorObject) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006061 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00006062 if (PyDict_SetItemString(d, "_SSLContext",
6063 (PyObject *)&PySSLContext_Type) != 0)
6064 return NULL;
6065 if (PyDict_SetItemString(d, "_SSLSocket",
6066 (PyObject *)&PySSLSocket_Type) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006067 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02006068 if (PyDict_SetItemString(d, "MemoryBIO",
6069 (PyObject *)&PySSLMemoryBIO_Type) != 0)
6070 return NULL;
Christian Heimes99a65702016-09-10 23:44:53 +02006071 if (PyDict_SetItemString(d, "SSLSession",
6072 (PyObject *)&PySSLSession_Type) != 0)
6073 return NULL;
6074
Christian Heimes892d66e2018-01-29 14:10:18 +01006075 PyModule_AddStringConstant(m, "_DEFAULT_CIPHERS",
6076 PY_SSL_DEFAULT_CIPHER_STRING);
6077
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006078 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
6079 PY_SSL_ERROR_ZERO_RETURN);
6080 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
6081 PY_SSL_ERROR_WANT_READ);
6082 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
6083 PY_SSL_ERROR_WANT_WRITE);
6084 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
6085 PY_SSL_ERROR_WANT_X509_LOOKUP);
6086 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
6087 PY_SSL_ERROR_SYSCALL);
6088 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
6089 PY_SSL_ERROR_SSL);
6090 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
6091 PY_SSL_ERROR_WANT_CONNECT);
6092 /* non ssl.h errorcodes */
6093 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
6094 PY_SSL_ERROR_EOF);
6095 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
6096 PY_SSL_ERROR_INVALID_ERROR_CODE);
6097 /* cert requirements */
6098 PyModule_AddIntConstant(m, "CERT_NONE",
6099 PY_SSL_CERT_NONE);
6100 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
6101 PY_SSL_CERT_OPTIONAL);
6102 PyModule_AddIntConstant(m, "CERT_REQUIRED",
6103 PY_SSL_CERT_REQUIRED);
Christian Heimes22587792013-11-21 23:56:13 +01006104 /* CRL verification for verification_flags */
6105 PyModule_AddIntConstant(m, "VERIFY_DEFAULT",
6106 0);
6107 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_LEAF",
6108 X509_V_FLAG_CRL_CHECK);
6109 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_CHAIN",
6110 X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
6111 PyModule_AddIntConstant(m, "VERIFY_X509_STRICT",
6112 X509_V_FLAG_X509_STRICT);
Benjamin Peterson990fcaa2015-03-04 22:49:41 -05006113#ifdef X509_V_FLAG_TRUSTED_FIRST
6114 PyModule_AddIntConstant(m, "VERIFY_X509_TRUSTED_FIRST",
6115 X509_V_FLAG_TRUSTED_FIRST);
6116#endif
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00006117
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01006118 /* Alert Descriptions from ssl.h */
6119 /* note RESERVED constants no longer intended for use have been removed */
6120 /* http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-6 */
6121
6122#define ADD_AD_CONSTANT(s) \
6123 PyModule_AddIntConstant(m, "ALERT_DESCRIPTION_"#s, \
6124 SSL_AD_##s)
6125
6126 ADD_AD_CONSTANT(CLOSE_NOTIFY);
6127 ADD_AD_CONSTANT(UNEXPECTED_MESSAGE);
6128 ADD_AD_CONSTANT(BAD_RECORD_MAC);
6129 ADD_AD_CONSTANT(RECORD_OVERFLOW);
6130 ADD_AD_CONSTANT(DECOMPRESSION_FAILURE);
6131 ADD_AD_CONSTANT(HANDSHAKE_FAILURE);
6132 ADD_AD_CONSTANT(BAD_CERTIFICATE);
6133 ADD_AD_CONSTANT(UNSUPPORTED_CERTIFICATE);
6134 ADD_AD_CONSTANT(CERTIFICATE_REVOKED);
6135 ADD_AD_CONSTANT(CERTIFICATE_EXPIRED);
6136 ADD_AD_CONSTANT(CERTIFICATE_UNKNOWN);
6137 ADD_AD_CONSTANT(ILLEGAL_PARAMETER);
6138 ADD_AD_CONSTANT(UNKNOWN_CA);
6139 ADD_AD_CONSTANT(ACCESS_DENIED);
6140 ADD_AD_CONSTANT(DECODE_ERROR);
6141 ADD_AD_CONSTANT(DECRYPT_ERROR);
6142 ADD_AD_CONSTANT(PROTOCOL_VERSION);
6143 ADD_AD_CONSTANT(INSUFFICIENT_SECURITY);
6144 ADD_AD_CONSTANT(INTERNAL_ERROR);
6145 ADD_AD_CONSTANT(USER_CANCELLED);
6146 ADD_AD_CONSTANT(NO_RENEGOTIATION);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01006147 /* Not all constants are in old OpenSSL versions */
Antoine Pitrou912fbff2013-03-30 16:29:32 +01006148#ifdef SSL_AD_UNSUPPORTED_EXTENSION
6149 ADD_AD_CONSTANT(UNSUPPORTED_EXTENSION);
6150#endif
6151#ifdef SSL_AD_CERTIFICATE_UNOBTAINABLE
6152 ADD_AD_CONSTANT(CERTIFICATE_UNOBTAINABLE);
6153#endif
6154#ifdef SSL_AD_UNRECOGNIZED_NAME
6155 ADD_AD_CONSTANT(UNRECOGNIZED_NAME);
6156#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01006157#ifdef SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE
6158 ADD_AD_CONSTANT(BAD_CERTIFICATE_STATUS_RESPONSE);
6159#endif
6160#ifdef SSL_AD_BAD_CERTIFICATE_HASH_VALUE
6161 ADD_AD_CONSTANT(BAD_CERTIFICATE_HASH_VALUE);
6162#endif
6163#ifdef SSL_AD_UNKNOWN_PSK_IDENTITY
6164 ADD_AD_CONSTANT(UNKNOWN_PSK_IDENTITY);
6165#endif
6166
6167#undef ADD_AD_CONSTANT
6168
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006169 /* protocol versions */
Victor Stinner3de49192011-05-09 00:42:58 +02006170#ifndef OPENSSL_NO_SSL2
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006171 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
6172 PY_SSL_VERSION_SSL2);
Victor Stinner3de49192011-05-09 00:42:58 +02006173#endif
Benjamin Petersone32467c2014-12-05 21:59:35 -05006174#ifndef OPENSSL_NO_SSL3
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006175 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
6176 PY_SSL_VERSION_SSL3);
Benjamin Petersone32467c2014-12-05 21:59:35 -05006177#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006178 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
Christian Heimes598894f2016-09-05 23:19:05 +02006179 PY_SSL_VERSION_TLS);
6180 PyModule_AddIntConstant(m, "PROTOCOL_TLS",
6181 PY_SSL_VERSION_TLS);
Christian Heimes5fe668c2016-09-12 00:01:11 +02006182 PyModule_AddIntConstant(m, "PROTOCOL_TLS_CLIENT",
6183 PY_SSL_VERSION_TLS_CLIENT);
6184 PyModule_AddIntConstant(m, "PROTOCOL_TLS_SERVER",
6185 PY_SSL_VERSION_TLS_SERVER);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006186 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
6187 PY_SSL_VERSION_TLS1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01006188 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_1",
6189 PY_SSL_VERSION_TLS1_1);
6190 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_2",
6191 PY_SSL_VERSION_TLS1_2);
Antoine Pitrou04f6a322010-04-05 21:40:07 +00006192
Antoine Pitroub5218772010-05-21 09:56:06 +00006193 /* protocol options */
Antoine Pitrou3f366312012-01-27 09:50:45 +01006194 PyModule_AddIntConstant(m, "OP_ALL",
6195 SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
Antoine Pitroub5218772010-05-21 09:56:06 +00006196 PyModule_AddIntConstant(m, "OP_NO_SSLv2", SSL_OP_NO_SSLv2);
6197 PyModule_AddIntConstant(m, "OP_NO_SSLv3", SSL_OP_NO_SSLv3);
6198 PyModule_AddIntConstant(m, "OP_NO_TLSv1", SSL_OP_NO_TLSv1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01006199 PyModule_AddIntConstant(m, "OP_NO_TLSv1_1", SSL_OP_NO_TLSv1_1);
6200 PyModule_AddIntConstant(m, "OP_NO_TLSv1_2", SSL_OP_NO_TLSv1_2);
Christian Heimescb5b68a2017-09-07 18:07:00 -07006201#ifdef SSL_OP_NO_TLSv1_3
6202 PyModule_AddIntConstant(m, "OP_NO_TLSv1_3", SSL_OP_NO_TLSv1_3);
6203#else
6204 PyModule_AddIntConstant(m, "OP_NO_TLSv1_3", 0);
6205#endif
Antoine Pitrou6db49442011-12-19 13:27:11 +01006206 PyModule_AddIntConstant(m, "OP_CIPHER_SERVER_PREFERENCE",
6207 SSL_OP_CIPHER_SERVER_PREFERENCE);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01006208 PyModule_AddIntConstant(m, "OP_SINGLE_DH_USE", SSL_OP_SINGLE_DH_USE);
Christian Heimes99a65702016-09-10 23:44:53 +02006209 PyModule_AddIntConstant(m, "OP_NO_TICKET", SSL_OP_NO_TICKET);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01006210#ifdef SSL_OP_SINGLE_ECDH_USE
Antoine Pitrou923df6f2011-12-19 17:16:51 +01006211 PyModule_AddIntConstant(m, "OP_SINGLE_ECDH_USE", SSL_OP_SINGLE_ECDH_USE);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01006212#endif
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01006213#ifdef SSL_OP_NO_COMPRESSION
6214 PyModule_AddIntConstant(m, "OP_NO_COMPRESSION",
6215 SSL_OP_NO_COMPRESSION);
6216#endif
Christian Heimes05d9fe32018-02-27 08:55:39 +01006217#ifdef SSL_OP_ENABLE_MIDDLEBOX_COMPAT
6218 PyModule_AddIntConstant(m, "OP_ENABLE_MIDDLEBOX_COMPAT",
6219 SSL_OP_ENABLE_MIDDLEBOX_COMPAT);
6220#endif
Christian Heimes67c48012018-05-15 16:25:40 -04006221#ifdef SSL_OP_NO_RENEGOTIATION
6222 PyModule_AddIntConstant(m, "OP_NO_RENEGOTIATION",
6223 SSL_OP_NO_RENEGOTIATION);
6224#endif
Antoine Pitroub5218772010-05-21 09:56:06 +00006225
Christian Heimes61d478c2018-01-27 15:51:38 +01006226#ifdef X509_CHECK_FLAG_ALWAYS_CHECK_SUBJECT
6227 PyModule_AddIntConstant(m, "HOSTFLAG_ALWAYS_CHECK_SUBJECT",
6228 X509_CHECK_FLAG_ALWAYS_CHECK_SUBJECT);
6229#endif
6230#ifdef X509_CHECK_FLAG_NEVER_CHECK_SUBJECT
6231 PyModule_AddIntConstant(m, "HOSTFLAG_NEVER_CHECK_SUBJECT",
6232 X509_CHECK_FLAG_NEVER_CHECK_SUBJECT);
6233#endif
6234#ifdef X509_CHECK_FLAG_NO_WILDCARDS
6235 PyModule_AddIntConstant(m, "HOSTFLAG_NO_WILDCARDS",
6236 X509_CHECK_FLAG_NO_WILDCARDS);
6237#endif
6238#ifdef X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS
6239 PyModule_AddIntConstant(m, "HOSTFLAG_NO_PARTIAL_WILDCARDS",
6240 X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS);
6241#endif
6242#ifdef X509_CHECK_FLAG_MULTI_LABEL_WILDCARDS
6243 PyModule_AddIntConstant(m, "HOSTFLAG_MULTI_LABEL_WILDCARDS",
6244 X509_CHECK_FLAG_MULTI_LABEL_WILDCARDS);
6245#endif
6246#ifdef X509_CHECK_FLAG_SINGLE_LABEL_SUBDOMAINS
6247 PyModule_AddIntConstant(m, "HOSTFLAG_SINGLE_LABEL_SUBDOMAINS",
6248 X509_CHECK_FLAG_SINGLE_LABEL_SUBDOMAINS);
6249#endif
6250
Christian Heimes698dde12018-02-27 11:54:43 +01006251 /* protocol versions */
6252 PyModule_AddIntConstant(m, "PROTO_MINIMUM_SUPPORTED",
6253 PY_PROTO_MINIMUM_SUPPORTED);
6254 PyModule_AddIntConstant(m, "PROTO_MAXIMUM_SUPPORTED",
6255 PY_PROTO_MAXIMUM_SUPPORTED);
6256 PyModule_AddIntConstant(m, "PROTO_SSLv3", PY_PROTO_SSLv3);
6257 PyModule_AddIntConstant(m, "PROTO_TLSv1", PY_PROTO_TLSv1);
6258 PyModule_AddIntConstant(m, "PROTO_TLSv1_1", PY_PROTO_TLSv1_1);
6259 PyModule_AddIntConstant(m, "PROTO_TLSv1_2", PY_PROTO_TLSv1_2);
6260 PyModule_AddIntConstant(m, "PROTO_TLSv1_3", PY_PROTO_TLSv1_3);
Antoine Pitroud5323212010-10-22 18:19:07 +00006261
Victor Stinnerb37672d2018-11-22 03:37:50 +01006262#define addbool(m, key, value) \
6263 do { \
6264 PyObject *bool_obj = (value) ? Py_True : Py_False; \
6265 Py_INCREF(bool_obj); \
6266 PyModule_AddObject((m), (key), bool_obj); \
6267 } while (0)
Christian Heimes698dde12018-02-27 11:54:43 +01006268
6269#if HAVE_SNI
6270 addbool(m, "HAS_SNI", 1);
Antoine Pitrou501da612011-12-21 09:27:41 +01006271#else
Christian Heimes698dde12018-02-27 11:54:43 +01006272 addbool(m, "HAS_SNI", 0);
Antoine Pitrou501da612011-12-21 09:27:41 +01006273#endif
Christian Heimes698dde12018-02-27 11:54:43 +01006274
6275 addbool(m, "HAS_TLS_UNIQUE", 1);
6276
6277#ifndef OPENSSL_NO_ECDH
6278 addbool(m, "HAS_ECDH", 1);
6279#else
6280 addbool(m, "HAS_ECDH", 0);
6281#endif
Antoine Pitrou501da612011-12-21 09:27:41 +01006282
Christian Heimes29eab552018-02-25 12:31:33 +01006283#if HAVE_NPN
Christian Heimes698dde12018-02-27 11:54:43 +01006284 addbool(m, "HAS_NPN", 1);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01006285#else
Christian Heimes698dde12018-02-27 11:54:43 +01006286 addbool(m, "HAS_NPN", 0);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01006287#endif
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01006288
Christian Heimes29eab552018-02-25 12:31:33 +01006289#if HAVE_ALPN
Christian Heimes698dde12018-02-27 11:54:43 +01006290 addbool(m, "HAS_ALPN", 1);
Benjamin Petersoncca27322015-01-23 16:35:37 -05006291#else
Christian Heimes698dde12018-02-27 11:54:43 +01006292 addbool(m, "HAS_ALPN", 0);
Benjamin Petersoncca27322015-01-23 16:35:37 -05006293#endif
Christian Heimes698dde12018-02-27 11:54:43 +01006294
6295#if defined(SSL2_VERSION) && !defined(OPENSSL_NO_SSL2)
6296 addbool(m, "HAS_SSLv2", 1);
6297#else
6298 addbool(m, "HAS_SSLv2", 0);
6299#endif
6300
6301#if defined(SSL3_VERSION) && !defined(OPENSSL_NO_SSL3)
6302 addbool(m, "HAS_SSLv3", 1);
6303#else
6304 addbool(m, "HAS_SSLv3", 0);
6305#endif
6306
6307#if defined(TLS1_VERSION) && !defined(OPENSSL_NO_TLS1)
6308 addbool(m, "HAS_TLSv1", 1);
6309#else
6310 addbool(m, "HAS_TLSv1", 0);
6311#endif
6312
6313#if defined(TLS1_1_VERSION) && !defined(OPENSSL_NO_TLS1_1)
6314 addbool(m, "HAS_TLSv1_1", 1);
6315#else
6316 addbool(m, "HAS_TLSv1_1", 0);
6317#endif
6318
6319#if defined(TLS1_2_VERSION) && !defined(OPENSSL_NO_TLS1_2)
6320 addbool(m, "HAS_TLSv1_2", 1);
6321#else
6322 addbool(m, "HAS_TLSv1_2", 0);
6323#endif
Benjamin Petersoncca27322015-01-23 16:35:37 -05006324
Christian Heimescb5b68a2017-09-07 18:07:00 -07006325#if defined(TLS1_3_VERSION) && !defined(OPENSSL_NO_TLS1_3)
Christian Heimes698dde12018-02-27 11:54:43 +01006326 addbool(m, "HAS_TLSv1_3", 1);
Christian Heimescb5b68a2017-09-07 18:07:00 -07006327#else
Christian Heimes698dde12018-02-27 11:54:43 +01006328 addbool(m, "HAS_TLSv1_3", 0);
Christian Heimescb5b68a2017-09-07 18:07:00 -07006329#endif
Christian Heimescb5b68a2017-09-07 18:07:00 -07006330
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02006331 /* Mappings for error codes */
6332 err_codes_to_names = PyDict_New();
6333 err_names_to_codes = PyDict_New();
6334 if (err_codes_to_names == NULL || err_names_to_codes == NULL)
6335 return NULL;
6336 errcode = error_codes;
6337 while (errcode->mnemonic != NULL) {
6338 PyObject *mnemo, *key;
6339 mnemo = PyUnicode_FromString(errcode->mnemonic);
6340 key = Py_BuildValue("ii", errcode->library, errcode->reason);
6341 if (mnemo == NULL || key == NULL)
6342 return NULL;
6343 if (PyDict_SetItem(err_codes_to_names, key, mnemo))
6344 return NULL;
6345 if (PyDict_SetItem(err_names_to_codes, mnemo, key))
6346 return NULL;
6347 Py_DECREF(key);
6348 Py_DECREF(mnemo);
6349 errcode++;
6350 }
6351 if (PyModule_AddObject(m, "err_codes_to_names", err_codes_to_names))
6352 return NULL;
6353 if (PyModule_AddObject(m, "err_names_to_codes", err_names_to_codes))
6354 return NULL;
6355
6356 lib_codes_to_names = PyDict_New();
6357 if (lib_codes_to_names == NULL)
6358 return NULL;
6359 libcode = library_codes;
6360 while (libcode->library != NULL) {
6361 PyObject *mnemo, *key;
6362 key = PyLong_FromLong(libcode->code);
6363 mnemo = PyUnicode_FromString(libcode->library);
6364 if (key == NULL || mnemo == NULL)
6365 return NULL;
6366 if (PyDict_SetItem(lib_codes_to_names, key, mnemo))
6367 return NULL;
6368 Py_DECREF(key);
6369 Py_DECREF(mnemo);
6370 libcode++;
6371 }
6372 if (PyModule_AddObject(m, "lib_codes_to_names", lib_codes_to_names))
6373 return NULL;
Victor Stinner4569cd52013-06-23 14:58:43 +02006374
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006375 /* OpenSSL version */
6376 /* SSLeay() gives us the version of the library linked against,
6377 which could be different from the headers version.
6378 */
6379 libver = SSLeay();
6380 r = PyLong_FromUnsignedLong(libver);
6381 if (r == NULL)
6382 return NULL;
6383 if (PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r))
6384 return NULL;
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02006385 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006386 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
6387 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r))
6388 return NULL;
6389 r = PyUnicode_FromString(SSLeay_version(SSLEAY_VERSION));
6390 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r))
6391 return NULL;
Antoine Pitrou04f6a322010-04-05 21:40:07 +00006392
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02006393 libver = OPENSSL_VERSION_NUMBER;
6394 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
6395 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
6396 if (r == NULL || PyModule_AddObject(m, "_OPENSSL_API_VERSION", r))
6397 return NULL;
6398
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006399 return m;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00006400}